python - 在 python 文件夹中导入图表/结构(清理代码)

标签 python python-3.x python-import code-organization code-cleanup

我刚刚完成了一个中等大小的 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了。

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

最佳答案

您可以使用 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

关于python - 在 python 文件夹中导入图表/结构(清理代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60951469/

相关文章:

python-2.7 - Pandas 导入非常慢(Anaconda Python 2.7)

python - 为什么 ROS Publisher 不发布值?

python - 许多for在python生成器中的一行中

python 多处理悲情 - AuthenticationError : digest sent was rejected - Windows

python-3.x - 根据时间列来回计数行

python - Django基础模板 View 方法

python - Python 中的包路径错误

python - 如何在一个循环中比较两个列表的值是否相等?

python-3.x - TypeError : iteration over a 0-d array, 使用 numpy

python - 在 64 位 Windows 上从哪里获取和安装 crypto.dll