在使用python编程过程中,如果我们需要某些模块的功能时,通常使用import
语句导入。这种方式属于静态导入。
然而,在一些情况下我们需要在程序的运行过程中才能决定导入某个模块时,就无法使用静态导入了,这时需要python的动态导入模块importlib
。
importlib.import_module()
项目目录如下:
.
├── lib
│ └── test1.py
├── test2.py
└── test_importlib.py
test1.py如下:
# test1.py
name = "test1"
def getName():
print(name)
return name
test2.py如下:
# test2.py
name = "test2"
def getName():
print(name)
return name
test_importlib.py如下:
# test_importlib.py
import importlib
modelfilename1 = "lib.test1"
modellib1 = importlib.import_module(modelfilename1)
modellib1.getName()
modelfilename2 = "test2"
modellib2 = importlib.import_module(modelfilename2)
modellib2.getName()
运行test_importlib.py,结果如下:
test1
test2