簡體   English   中英

python:importlib.import_module(“time”)但是時間沒有全局定義

[英]python: importlib.import_module(“time”) but time is not defined globally

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

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

來自文檔

指定的模塊將插入sys.modules並返回。

換句話說, import_module不會為您創建變量,您必須自己創建:

time = importlib.import_module('time')

或者,在你的“動態”案例中:

globals()['time'] = importlib.import_module('time')

另外,為什么你這樣做呢? 為什么不在try - except塊中包裝正常import

我認為importlib.import_module("time")返回一個對象,我們需要將它分配給一個變量。 使用該變量來調用所有時間方法。

嘗試:

import sys, importlib

var_name = importlib.import_module("time")
print var_name.time()

請為上帝的愛不要這樣做,它浪費代碼行,它的另一個地方可以存在錯誤,而且導入系統也會發生變化。 如果你只是更好

import requests

讓它失敗然后我知道請求丟失了,我可以自己查看或安裝它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM