importlib模块

importlib.import_module(name, package=None)

动态引入引入一个模块。name可以是相对路径和绝对路径,如果是相对路径的话,这package就是相应的包名

foo.py文件
<pre>

coding:UTF-8

def main():
print(name)
</pre>

与foo.py同一文件夹下的文件
<pre>
import importlib
def dynamic_import(module):
return importlib.import_module(module)
if __name__ == '__main__':
module = dynamic_import('foo') #引入foo模块
module.main() #调用foo模块的main()方法
</pre>

importlib.util.find_spec(name, package=None)

模块导入检测

<pre>
import importlib
def check_module(module_name):
module_spec = importlib.util.find_spec(module_name)
if module_spec is None:
print('Module:{} not found'.format(module_name))
return None
else:
print('Module:{} can be imported!'.format(module_name))
return module_spec
def import_module_from_spec(module_spec):
module = importlib.util.module_from_spec(module_spec)
module_spec.loader.exec_module(module)
return module
if __name__ == '__main__':
module_spec = check_module('fake_module')
module_spec = check_module('collections')
if module_spec:
module = import_module_from_spec(module_spec)
print(module)

Module:fake_module not found
Module:collections can be imported!
<module 'collections' from 'C:\Program Files\Python36\lib\collections\init.py'>
</pre>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,323评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,052评论 6 342
  • /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home...
    光剑书架上的书阅读 9,386评论 2 8
  • 世间最美好的感情 是两情相悦 只可惜现在是爱人 以后是最熟悉的兄弟
    可爱mice阅读 1,852评论 0 0
  • 文'|M。 今天下午,一個人在圖書館複習望著窗外,想起昨天晚上錯過的那個黃昏於是帶著相機和iPad,跑到天台,迎來...
    Anni爱夏阅读 2,817评论 0 0