gpt4 book ai didi

python: importlib.import_module ("time") 但时间没有全局定义

转载 作者:太空宇宙 更新时间:2023-11-03 12:48:51 24 4
gpt4 key购买 nike

为了向我的程序(在 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 而崩溃(“时间”未定义)。因此,我尝试测试从头开始导入的模块:

>>> 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") 导入 timetime.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')

附带说明一下,您为什么要这样做?为什么不将普通的 import 包装在 try-except block 中?

关于python: importlib.import_module ("time") 但时间没有全局定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19179269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com