Python - 使用pycallgraph生成函数关系图

1- pycallgraph简介

可用于创建python函数关系图,依赖于dot命令,需要先安装 graphviz;  

2- 安装pycallgraph

安装pycallgraph
$ pip3 install pycallgraph  --proxy=10.144.1.10:8080
Collecting pycallgraph
  Using cached https://files.pythonhosted.org/packages/ca/2e/fafa56316bc2c5fbfbda898f964137c8b5ef33a876cb1f35a54ff6afbd60/pycallgraph-1.0.1.tar.gz
Installing collected packages: pycallgraph
  Running setup.py install for pycallgraph ... done
Successfully installed pycallgraph-1.0.1
  安装graphviz graphviz(http://www.graphviz.org/)是一个图形可视化软件(Graph Visualization Software),使用dot文件生成关系图;

3- 运行pycallgraph

3-1 直接在命令行方式运行

$ pycallgraph graphviz -- ./test.py
默认将生成一个名为pycallgraph.png的函数关图

3-2 使用API在命令行运行

示例-1
$ cat TempTest.py
#! python3
# -*- coding: utf-8 -*-


def testStr(key):
    print("testStr is :", key)

$ cat CallGraphTest.py
#! python3
# -*- coding: utf-8 -*-
from pycallgraph import PyCallGraph
from pycallgraph.output import GraphvizOutput

import TempTest


def testNum(key):
    TempTest.testStr(key)
    print("testNum is :", key)


g = GraphvizOutput(output_file=r'./trace.png')
with PyCallGraph(output=g):
    TempTest.testStr("111")
    testNum(222)

$

$ py -3 CallGraphTest.py
testStr is : 111
testStr is : 222
testNum is : 222

$ ls -l
total 14
drwxr-xr-x 1 guowli 1049089    0 May 23 16:07 __pycache__/
-rwxr-xr-x 1 guowli 1049089  350 May 23 15:56 CallGraphTest.py*
-rwxr-xr-x 1 guowli 1049089   92 May 23 15:59 TempTest.py*
-rw-r--r-- 1 guowli 1049089 9141 May 23 16:07 trace.png

$

生成指定名称的函数关系图trace.png

Python - 使用pycallgraph生成函数关系图

 

示例-2

#! python3
# -*- coding: utf-8 -*-
from pycallgraph import PyCallGraph
from pycallgraph.output import GraphvizOutput
from pycallgraph import Config
from pycallgraph import GlobbingFilter


class Banana:

    def eat(self):
        pass


class Person:

    def __init__(self):
        self.no_bananas()

    def no_bananas(self):
        self.bananas = []

    def add_banana(self, banana):
        self.bananas.append(banana)

    def eat_bananas(self):
        [banana.eat() for banana in self.bananas]
        self.no_bananas()


def main():
    graphviz = GraphvizOutput()
    graphviz.output_file = 'basic.png'
    config = Config()
    config.max_depth = 5  # 控制最大追踪深度

    with PyCallGraph(output=graphviz, config=config):
        person = Person()
        for a in range(10):
            person.add_banana(Banana())
        person.eat_bananas()


if __name__ == '__main__':
    main()

生成函数关系图

Python - 使用pycallgraph生成函数关系图

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
上一篇:numpy存取数据(tofile/fromfile)


下一篇:python关于字典的常用方法