在python中实现动态导入模块importlib.import_module

 

有时候,咱们很须要在程序运行的过程当中,根据变量或者配置动态的决定导入哪一个模块。ide

 

假设咱们须要导入的模块module_12定义在subPack1文件夹下面,内容以下。spa

 

  
  
           
  
  
  1. def funcA12(): 
  2.     print('funcA12 in module_12'
  3.     return 
  4.  
  5.  
  6. import os 
  7. print  os.path.join(os.path.abspath(os.path.dirname(__file__)),('templates')) 
  8.  
  9. print os.path.join(os.path.relpath(os.path.dirname(__file__)),'..templates'

 

在这个模块的上层须要动态导入这个模块,可使用下面的代码。xml

使用importlib模块的import_module方法就能够实现动态的导入。string

  
  
           
  
  
  1. import importlib 
  2. mo =importlib.import_module('subPack1.module_12') 
  3. mo.funcA12() 
相关文章
相关标签/搜索