python import time什么意思_python:importlib.import_module(“time”)但是时间没有全局定义...

为了添加到我的程序(在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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值