您的位置:首页 > 编程语言 > Python开发

[转]Python动态导入模块

2013-01-14 16:50 495 查看
原文地址:http://blog.csdn.net/huzhenwei/article/details/5393992

一 动态导入模块

Python的import不能接受变量,所以应该用 __import__函数来动态导入。

modules = ['OpenSSL', 'math', 'Crypto', 'MySQLdb', 'sqlite3', 'zope.interface', 'pyasn1', 'twisted', 'django']
for each in modules:
try:
__import__(each)
except Exception as e:
print(e)


 

二 检查模块是否安装

使用__import__函数也可以用来检查模块是否已安装,略微修改上面的代码即可。

 

使用imp.find_module()来检查不方便,如find_module('zope.interface')会抛出异常——因为这个函数无法查找子模块。

模块加载后,就可以在sys.module这个字典里找到加载的模块名了。

 

__import__

except in cases where you want to import a module whose name is only known at runtime.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: