python importlib动态导入模块

一、引入

一般而言,当我们需要某些功能的模块时(无论是内置模块或自定义功能的模块),可以通过import module 或者 from * import module的方式导入,这属于静态导入,很容易理解。

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

二、importlib使用

如在scripts目录中保存着一些功能模块,向外提供类似的接口port()和脚本描述信息description,需要传入一个参数target,当然脚本执行的功能是不一样的,以下只是举例:

---script

  ---test1.py

  ---test2.py

  ---test3.py

#test1.py

description = 'it is a test1'


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

    return True

而我们需要动态传入脚本名,来选用此时要执行的功能:

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

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

原文地址:https://www.cnblogs.com/fengchong/p/10079893.html