有时候,咱们很须要在程序运行的过程当中,根据变量或者配置动态的决定导入哪一个模块。ide
假设咱们须要导入的模块module_12定义在subPack1文件夹下面,内容以下。spa
- def funcA12():
- print('funcA12 in module_12')
- return
- import os
- print os.path.join(os.path.abspath(os.path.dirname(__file__)),('templates'))
- print os.path.join(os.path.relpath(os.path.dirname(__file__)),'..templates')
在这个模块的上层须要动态导入这个模块,可使用下面的代码。xml
使用importlib模块的import_module方法就能够实现动态的导入。string
- import importlib
- mo =importlib.import_module('subPack1.module_12')
- mo.funcA12()