Skip to main content
 首页 » 编程设计

python之获取所有动态和二级导入的名称

2024年11月24日13bonelee

我从事一个包含许多子目录/包的复杂项目。

有没有办法打印给定项目目录中使用的所有second+ level/dynamic modules

例如,如果我使用以下导入:from core.dependency.checkpoints_dependency.checkpoints_manager import CheckpointsManagerimport scipy,我希望 core.dependency .checkpoints_dependency.checkpoints_managerscipy 被打印。

请您参考如下方法:

尝试使用 os.walk 解析目录,然后检查系统模块中的目录:

import sys 
import os 
 
all_modules = [] 
 
for dirpath, dirnames, filenames in os.walk(YOUR_PROJECT_DIRECTORY): 
    module_names = set(sys.modules) 
    modules_in_file = [sys.modules[name] for name in module_names] 
    all_modules.extend(modules_in_file) 
 
print(set(all_modules))