我想在這裏做兩件事情,動態地導入目錄中的所有模塊(數量/名稱未知),然後對於找到的每個模塊調用一個名爲checkMe的函數)。 checkMe()保證在每個模塊中,所以不需要檢查。這是我到目前爲止有:從模塊的動態列表中調用方法
進口
import sys
import os
import glob
pathname = os.path.dirname(sys.argv[0]) + "/"
pathname = pathname + "/modules/"
__modules__ = [ os.path.basename(f)[:-3] for f in glob.glob(os.path.dirname(pathname)+"/*.py")]
for module in __modules__:
__import__(module)
調用checkMe()
for module in __modules__:
m = getattr(sys.modules[__name__], module)
getattr(m, 'checkMe').__call__()
但我得到這個錯誤:
AttributeError: 'module' object has no attribute 'sendme'
(sendme是第一個模塊)
任何幫助非常感謝...謝謝!
添加一些打印語句,以顯示你得到什麼'pathname','__modules__',等 –
我很確定導入工作...我已經調試了,我沒有得到這些線路的錯誤了。 – pdeuchler
如果可能仍然有助於查看'__module__'中的結果。每當你分配給一個變量時,我都會添加打印語句,這樣你就可以跟蹤整個應用程序的狀態並找出出錯的地方。 –