Python循环遍历导入并检查变量
我已经成功地从一个文件夹里导入了一堆模块,使用了
from assets import *
现在我想要遍历这些导入的模块,检查里面是否有一个特定的变量或函数。我试着用 dir() 函数来获取导入模块的列表,然后查看它们,但因为我实际上是在遍历一个字符串数组,而不是模块数组,所以我无法查找模块里的变量。
for aModule in dir(assets):
if word in aModule.alt:
print "found it!"
如果在 aModule.alt 中找到 word:
AttributeError: 'str' 对象没有 'alt' 属性
1 个回答
3
我觉得你现在做的事情可以更简单地完成:
import assets
for aModule in vars(assets).values():
if hasattr(aModule, 'alt') and word in aModule.alt:
print "found it!"
print aModule.__name__