$ 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
示例-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()
生成函数关系图
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