python 生成函数图_Python - 使用pycallgraph生成函数关系图

$ 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

819128-20181122232224263-337318869.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()

生成函数关系图

819128-20181122232332837-1209844356.png

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值