2024-05-16 11:03:55 发布
网友
我的python项目具有以下文件结构:
/main.py /functions /functions/func1.py /functions/func2.py /functions/func3.py /funcitons/__init__.py
每职能部门文件有一个变量“CAN\u USE”。在一些文件中是真的,在另一些文件中是假的。 我怎么检查我的房间主.py哪个职能部门文件的“CAN\u USE”变量等于true?你知道吗
使用pkgutil可以找到包中的所有模块:
pkgutil
import pkgutil def usable_modules(package_name): modules = pkgutil.iter_modules([package_name]) usable = [] for importer, name, ispkg in modules: module = pkgutil.find_loader('{0}.{1}'.format(package_name, name)).\ load_module(name) if hasattr(module, 'CAN_USE') and module.CAN_USE: usable.append(module) return usable print(usable_modules('functions'))
注意,这还检查包中的其他模块(例如__init__.py)。如果愿意,可以在循环中过滤掉它们(例如if not name.startswith('func'): continue)。你知道吗
__init__.py
if not name.startswith('func'): continue
试试这个主.py你知道吗
from functions import func1, func2, func3 print func1.CAN_USE print func2.CAN_USE print func3.CAN_USE
使用
pkgutil
可以找到包中的所有模块:注意,这还检查包中的其他模块(例如
__init__.py
)。如果愿意,可以在循环中过滤掉它们(例如if not name.startswith('func'): continue
)。你知道吗试试这个主.py你知道吗
相关问题 更多 >
编程相关推荐