python:importlib.import_module(“time”)但是时间没有全局定义
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python:importlib.import_module(“time”)但是时间没有全局定义,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2467字,纯文字阅读大概需要4分钟。
内容图文
为了添加到我的程序(在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")
<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']
时间到了.然而:
>>> 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()的方式导入时间?
解决方法:
从docs:
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:importlib.import_module(“time”)但是时间没有全局定义全部内容,希望文章能够帮你解决python:importlib.import_module(“time”)但是时间没有全局定义所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。