现在的位置: 首页 > 综合 > 正文

[转]Python动态导入模块

2012年12月13日 ⁄ 综合 ⁄ 共 518字 ⁄ 字号 评论关闭

原文地址: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.

【上篇】
【下篇】

抱歉!评论已关闭.