有時候,咱們很須要在程序運行的過程當中,根據變量或者配置動態的決定導入哪一個模塊。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()