检查packag中模块的变量

2024-04-16 18:33:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我的python项目具有以下文件结构:

/main.py
/functions
/functions/func1.py
/functions/func2.py
/functions/func3.py
/funcitons/__init__.py

每职能部门文件有一个变量“CAN\u USE”。在一些文件中是真的,在另一些文件中是假的。 我怎么检查我的房间主.py哪个职能部门文件的“CAN\u USE”变量等于true?你知道吗


Tags: 文件项目pyinitusemainfunctions结构
2条回答

使用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)。你知道吗

试试这个主.py你知道吗

from functions import func1, func2, func3
print func1.CAN_USE
print func2.CAN_USE
print func3.CAN_USE

相关问题 更多 >