为了添加到我的程序(在python 2.7中)检查可用模块,我添加了以下代码来代替经典导入(这个想法是为了帮助某人找到并添加额外的模块):
mymodules = ['socket', 'requests', 'simplejson', 'pickle', 'IPy',
'pygeoip', 'urllib', 'time', 'urllib2', 'StringIO', 'gzip', 'os']
import sys, importlib # these ones should be available, otherwise bad luck :)
for module in mymodules:
try:
importlib.import_module(module)
print "importing ", module
except:
if module == "requests": info = "http://docs.python-requests.org/en/latest/user/install/#install or aptitude install python-requests"
elif module == "requests": info = "https://github.com/simplejson/simplejson or aptitude install python-simplejson"
elif module == "IPy": info = "https://github.com/haypo/python-ipy/wiki or aptitude install python-ipy"
elif module == "pygeoip": info = "https://github.com/appliedsec/pygeoip or pip install pygeoip"
else: info = "Oops, you should not see this - the description of the missing plugin is missing in the code"
print "module {} is missing, see {}".format(module,info)
sys.exit(0)
稍后我的程序在调用time.time()时遇到NameError崩溃(‘time’未定义).因此我尝试从头开始测试模块导入:
>>> import sys, importlib
>>> importlib.import_module("time")
>>> print sys.modules.keys()
['copy_reg', 'sre_compile', '_sre', 'encodings', 'site', '__builtin__', 'sysconfig', '__main__', 'encodings.encodings', 'abc', 'importlib.sys', 'posixpath', '_weakrefset', 'errno', 'encodings.codecs', 'sre_constants', 're', '_abcoll', 'types', '_codecs', 'encodings.__builtin__', '_warnings', 'genericpath', 'stat', 'zipimport', '_sysconfigdata', 'warnings', 'UserDict', 'encodings.utf_8', 'sys', 'codecs', 'readline', '_sysconfigdata_nd', 'os.path', 'importlib', 'sitecustomize', 'signal', 'traceback', 'linecache', 'posix', 'encodings.aliases', 'time', 'exceptions', 'sre_parse', 'os', '_weakref']
时间到了.然而:
>>> print time.time()
Traceback (most recent call last):
File "", line 1, in
NameError: name 'time' is not defined
现在有一个经典的导入:
>>> import time
>>> print time.time()
1380831191.08
为什么importlib.import_module(“time”)不会以调用time.time()的方式导入时间?
解决方法:
The specified module will be inserted into sys.modules and returned.
换句话说,import_module不会为您创建变量,您必须自己创建:
time = importlib.import_module('time')
或者,在你的“动态”案例中:
globals()['time'] = importlib.import_module('time')
另外,为什么你这样做呢?为什么不在try-except块中包装正常导入?
标签:python,python-2-7,python-import