python importlib动态导入模块

  通常而言,当咱们须要某些功能的模块时(不管是内置模块或自定义功能的模块),能够经过import module 或者 from * import module的方式导入,这属于静态导入,很容易理解。html

  而若是当咱们须要在程序的运行过程时才能决定导入某个文件中的模块时,而且这些文件提供了一样的接口名字,上面说的方式就不适用了,这时候须要使用python 的动态导入。python

importlib使用

  如在scripts目录中保存着一些功能模块,向外提供相似的接口poc()和脚本描述信息description,须要传入一个参数target,固然脚本执行的功能是不同的,如下只是举例:编程

starnight:EXP-M starnight$ ls scripts/
__init__.py     __pycache__ test1.py test2.py test3.py starnight:EXP-M starnight$ cat scripts/test1.py #!/usr/bin/env python # -*- coding:utf-8 -*-
 description = 'it is a test1'


def poc(target): print('it is a test1') return True

  而咱们须要动态传入脚本名,来选用此时要执行的功能:函数

#!/usr/bin/env python # -*- coding:utf-8 -*-

import importlib script_name = input('please input script_name : ')     # 手动输入脚本名                module = importlib.import_module('scripts.{}'.format(script_name))    # 动态导入相应模块 func = module.poc('')      # 执行脚本功能 print(module.description)    # 获取脚本描述信息
please input script_name : test1 it is a test1 it is a test1 ... please input script_name : test3 it is a test3 it is a test3

  当咱们动态给定脚本名字时,就会动态的导入该模块,执行相应的功能。this

importlib其余介绍

  python doc: importlibspa

  importlib中的几个函数:__import__、import_module、find_loader、invalidate_caches、reloadcode

"Note Programmatic importing of modules should use import_module() instead of this function."

  当进行编程时,使用import_module,如上使用该模块。orm

  find_loader用来查找模块,reload从新载入模块,invalidate_caches很少介绍了。htm

相关文章
相关标签/搜索