我想在这里做两件事情,动态地导入目录中的所有模块(数量/名称未知),然后对于找到的每个模块调用一个名为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__'中的结果。每当你分配给一个变量时,我都会添加打印语句,这样你就可以跟踪整个应用程序的状态并找出出错的地方。 –