【Python】利用graphviz和pycallgraph库自动生成Python函数调用关系图
一、下載并安裝graphviz
因為這個模塊依賴Graphviz2.38這個軟件,這個貝爾實驗室大牛為畫圖提供的一個命令行工具。
下載地址:https://graphviz.gitlab.io/_pages/Download/windows/graphviz-2.38.msi
安裝(路徑可任意選擇)
配置環境變量,在Path中添加graphviz的bin目錄所在路徑。
例如,我安裝在F:\Program Files (x86)
那么就添加環境變量F:\Program Files (x86)\Graphviz2.38\bin
二、安裝pycallgraph庫
pip install pycallgraph
三、使用
注意:只有你的操作使用了某個函數,才能顯示在流圖中。用戶沒有調用的函數則不會出現在流圖中。
(所以,使用的時候要考慮一下你此次調用的“測試覆蓋率”,盡可能全面的調用到每一個函數)
生成的圖片示例
代碼示例 1:在普通python程序中使用
# -*- coding: utf-8 -*-from pycallgraph import Config from pycallgraph import PyCallGraph from pycallgraph.output import GraphvizOutput from werkzeug.datastructures import ImmutableMultiDictfrom app.main.views import do_all_copydef main():# do something...if __name__ == "__main__":config = Config()# 關系圖中包括(include)哪些函數名。# 如果是某一類的函數,例如類gobang,則可以直接寫'gobang.*',表示以gobang.開頭的所有函數。(利用正則表達式)。# config.trace_filter = GlobbingFilter(include=[# 'draw_chessboard',# 'draw_chessman',# 'draw_chessboard_with_chessman',# 'choose_save',# 'choose_turn',# 'choose_mode',# 'choose_button',# 'save_chess',# 'load_chess',# 'play_chess',# 'pop_window',# 'tip',# 'get_score',# 'max_score',# 'win',# 'key_control'# ])# 該段作用是關系圖中不包括(exclude)哪些函數。(正則表達式規則)# config.trace_filter = GlobbingFilter(exclude=[# 'pycallgraph.*',# '*.secret_function',# 'FileFinder.*',# 'ModuleLockManager.*',# 'SourceFilLoader.*'# ])graphviz = GraphvizOutput()graphviz.output_file = 'graph.png'with PyCallGraph(output=graphviz, config=config):main()代碼示例 2:在Flask中使用
如果你開發的是web應用,同樣可以使用這個庫。
你只需要在你希望監測的函數中,添加如下代碼:
然后訪問你的web服務頁面,http://127.0.0.1:5000/example_mapping/即可。經過測試,此過程可能會比以往更慢一些。
附:報錯找不到dot的解決方式:
遇到錯誤 pycallgraph.exceptions.PyCallGraphException: The command “dot” is required to be in your path.
解決方式
You need to find dot.exe, which for me was in C:\Program Files (x86)\Graphviz2.38\bin so I went to the following: control panel > system > advanced system settings > Environment Variables... and then in the bottom box for System Variables, find Path, select it and select edit, then select new and paste the path in. Now close and reopen cmd.exe and see simple type in ‘dot’ and hit enter. If there’s no error, the path was setup properly.
簡單來說,就是你需要將C:\Program Files (x86)\Graphviz2.38\bin添加到環境變量的Path中,然后在cmd里面嘗試運行dot這個命令,如果不報錯,就可以正常使用了。
總結
以上是生活随笔為你收集整理的【Python】利用graphviz和pycallgraph库自动生成Python函数调用关系图的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【笔试题】C语言结构体中,不同的数据类型
- 下一篇: 【Python】忘记登录密码?遍历数字字