首页 > 解决方案 > 在 python 文件夹中导入图表/结构(清理代码)

问题描述

我刚刚完成了一个中等大小的 python (3.6) 项目,我需要清理一下。我不是软件工程师,所以在开发过程中,我对项目的结构不太准确,所以现在我有几个模块不再(不再)由任何其他模块导入,或者由其他 .py 文件导入的模块实际上不需要。

例如,我有

Project/
├── __init__.py
├── main.py
├── foo.py
|
├── tools/
│   ├── __init__.py
│   ├── tool1.py
│   └── tool2.py
│   └── tool3.py
|
├── math/
│   ├── __init__.py
│   ├── math1.py
│   └── math2.py
├── graph/
│   ├── __init__.py
│   ├── graph1.py
│   ├── graph2.py
│

和里面

主文件

from math import math1
from tools import tool2

图1.py

from math import math1
from tools import tool1, tool2

foo.py

from tools import tool3

如果我一眼就能看出不是模块导入graph2math2,我可以删除它们,或者至少将它们添加为删除的候选对象(并以更好的方式重组项目)。或者我可能会考虑删除tool3,因为我知道我不再需要foo了。

是否有一种简单的方法可以以图表或其他某种结构化数据/可视化方式可视化所有“连接”(哪个模块导入哪个)?

标签: pythonpython-3.xpython-importcode-organizationcode-cleanup

解决方案


您可以使用 Python 为您完成工作:

将包含以下代码的 Python 文件放入与您的项目目录相同的目录中。

from pathlib import Path

# list all the modules you want to check:
modules = ["tool1", "tool2", "tool3", "math1", "math2", "graph1", "graph2"]

# find all the .py files within your Project directory (also searches subdirectories):
p = Path('./Project')
file_list = list(p.glob('**/*.py'))

# check, which modules are used in each .py file:
for file in file_list:
    with open(file, "r") as f:
        print('*'*10, file, ':')
        file_as_string = f.read()
        for module in modules:
            if module in file_as_string:
                print(module)

运行它会给你一个看起来像这样的输出:

********** Project\main.py :
tool1
tool2
graph1
********** Project\foo.py :
tool2
********** Project\math\math1.py :
tool2
math2

推荐阅读