程式化匯入
Python 2.x >= 2.7
要通過函式呼叫匯入模組,請使用 importlib 模組(從 2.7 版開始包含在 Python 中):
import importlib
random = importlib.import_module("random")
importlib.import_module() 函式還將直接匯入包的子模組:
collections_abc = importlib.import_module("collections.abc")
對於舊版本的 Python,請使用 imp 模組。
Python 2.x <= 2.7
使用 imp.find_module 和 imp.load_module 函式執行程式設計匯入。
取自標準庫文件
import imp, sys
def import_module(name):
    fp, pathname, description = imp.find_module(name)
    try:
        return imp.load_module(name, fp, pathname, description)
    finally:
        if fp:
            fp.close()
千萬不要使用 __import__() 以程式設計方式匯入模組! 有一些微妙的細節涉及 sys.modules,fromlist 引數等等,很容易忽略 importlib.import_module() 為你處理。