Python - 使用objgraph生成对象引用关系图
1- objgraph简介
- HomePage:https://mg.pov.lt/objgraph/
- PyPI:https://pypi.org/project/objgraph/
- 一般用于分析python对象相关问题,列出当前内存中存在的对象,定位内存泄露等;
- 还可以利用graphviz工具生成可视化的对象引用关系图;
2- 安装objgraph
这里以Window7 64bit为例。
通过pip安装objgraph:
$ pip3 install objgraph --proxy="10.144.1.10:8080" Collecting objgraph Downloading https://files.pythonhosted.org/packages/ec/3d/c1f0e827dd2df27c8080317d667cb555d264825d/objgraph-3.4.0-py2.py3-none-any.whl Collecting graphviz (from objgraph) Downloading https://files.pythonhosted.org/packages/84/44/21a7fdd50841aaaef224b943f7d10df87e473d48/graphviz-0.8.3-py2.py3-none-any.whl Installing collected packages: graphviz, objgraph Successfully installed graphviz-0.8.3 objgraph-3.4.0
安装graphviz
graphviz(http://www.graphviz.org/)是一个图形可视化软件(Graph Visualization Software),使用dot文件生成关系图;
- 下载:https://graphviz.gitlab.io/_pages/Download/windows/graphviz-2.38.msi
- 设置环境变量:Advanced System Settings--》Advanced (tab) ---》Environmental Variables then edit the PATH variable.---》"C:\Program Files (x86)\Graphviz2.38\bin"
3- 运行objgraph
示例:
$ ls -l total 1 -rwxr-xr-x 1 guowli 1049089 143 May 23 16:54 TempTest.py* $ cat TempTest.py #! python3 # -*- coding: utf-8 -*- import objgraph x = [] y = [x, [x], dict(x=x)] objgraph.show_refs([y], filename='sample-graph.png') $ py -3 TempTest.py Graph written to C:\Users\guowli\AppData\Local\Temp\objgraph-i96a8ww9.dot (4 nodes) Image generated as sample-graph.png $ ls -l total 13 -rw-r--r-- 1 guowli 1049089 10398 May 23 16:56 sample-graph.png -rwxr-xr-x 1 guowli 1049089 143 May 23 16:54 TempTest.py* $
生成对象引用关系图:
4- 在Pycharm运行objgraph
需要在Pycharm中设置Graphviz环境变量,否则可能报错:
'The command "{}" is required to be in your path.'.format(cmd)) pycallgraph.exceptions.PyCallGraphException: The command "dot" is required to be in your path.
设置Pycharm环境变量步骤:
Run --》Edit Configurations... --》Default --》Python --》Environment field group: Environment variables --》 ... --》+ --》
- Name: PATH
- Value: C:\Program Files (x86)\Graphviz2.38\bin
行动是绝望的解药!
欢迎转载和引用,但请在明显处保留原文链接和原作者信息!
本博客内容多为个人工作与学习的记录,少数内容来自于网络并略有修改,已尽力标明原文链接和转载说明。如有冒犯,即刻删除!
以所舍,求所得,有所获,方所成。