python importlib动态导入模块 reload重载模块
阅读目录
一般而言,当我们需要某些功能的模块时(无论是内置模块或自定义功能的模块),可以通过import module 或者 from * import module的方式导入,这属于静态导入,很容易理解。
而如果当我们需要在程序的运行过程时才能决定导入某个文件中的模块时,并且这些文件提供了同样的接口名字,上面说的方式就不适用了,这时候需要使用python 的动态导入。
importlib使用
如在scripts目录中保存着一些功能模块,向外提供类似的接口poc()和脚本描述信息description,需要传入一个参数target,当然脚本执行的功能是不一样的,以下只是举例:
[](javascript:void(0)😉
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
[](javascript:void(0)😉
而我们需要动态传入脚本名,来选用此时要执行的功能:
[](javascript:void(0)😉
#!/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) # 获取脚本描述信息
[](javascript:void(0)😉
[](javascript:void(0)😉
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
[](javascript:void(0)😉
当我们动态给定脚本名字时,就会动态的导入该模块,执行相应的功能。
importlib其他介绍
python doc: importlib
importlib中的几个函数:import、import_module、find_loader、invalidate_caches、reload
"Note Programmatic importing of modules should use import_module() instead of this function."
当进行编程时,使用import_module,如上使用该模块。
find_loader用来查找模块,reload重新载入模块,invalidate_caches不多介绍了。
出处:https://www.cnblogs.com/Hi-blog/
github:https://github.com/starnightcyber/
-------------------------------------------
个性签名:如果世上的事都按你说的道理走 世界就不是现在这样了!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)