爲了添加到我的程序(在Python 2.7中)檢查可用模塊,我添加了以下代碼來代替經典導入(想法是幫助別人找到&添加額外的模塊):python:importlib.import_module(「time」)但時間沒有全局定義
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
在那裏。然而:
現在有一個經典的進口:
>>> import time
>>> print time.time()
1380831191.08
爲什麼會以這樣的方式不importlib.import_module("time")
進口time
是time.time()
可以叫什麼名字?
你說得對,我可以重新創建它。它不限於'time'模塊,就好像import_module()返回模塊,而不是將其作爲全局導入('time = importlib.import_module(「time」)'將工作) – yuvi
你的代碼:把模塊的url放在一個字典中,這樣你可以查看它們,而不是用多個if語句來檢查名字。此外,不要在第一個失敗的模塊之後退出,但會將缺失的模塊累積在列表中,然後您可以一次通知用戶所有缺失的模塊。另外,應該不需要測試或_dynamically_導入內建模塊,如'os','socket'等 - 只需使用正常的導入語句,如果這些模塊失敗了,您可能會希望看到異常消息,因爲它可能表示嚴重使用python安裝的問題。 – l4mpi
@ l4mpi:感謝您的建設性意見。廣告1:我假設你的意思是一個字典,其中模塊名稱是關鍵字,值是要顯示的信息的值?好主意,我會嘗試。廣告2:也是一個好主意:)廣告3:我最初想到了這一點,然後將所有模塊放在一起以簡化操作。你對這個模塊上的實際失敗(有回溯)的評論是有道理的,也會這樣做。 – WoJ