为了向我的程序(在 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)
后来我的程序NameError
在调用time.time()
('时间'未定义)时崩溃。因此,我尝试从头开始测试模块导入:
>>> import sys, importlib
>>> importlib.import_module("time")
<module 'time' (built-in)>
>>> 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']
time
有没有。尽管如此:
>>> print time.time()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'time' is not defined
现在使用经典导入:
>>> import time
>>> print time.time()
1380831191.08
为什么不能以可以调用的方式importlib.import_module("time")
导入?time
time.time()