2021年7月2日 星期五

[ Python 常見問題 ] Build a Call graph in python including modules and functions?

 Source From Here

Question
I have a bunch of scripts to perform a task. And I really need to know the call graph of the project because it is very confusing. I am not able to execute the code because it needs extra HW and SW to do so. However, I need to understand the logic behind it. So, I need to know if there is a tool (which does not require any python file execution) that can build a call graph using the modules instead of the trace or python parser.

I have such tools for C but not for python. Thank you.

HowTo
You might want to check out pycallgraph: pycallgraph

Also in this link a more manual approach is described:
generating-call-graphs-for-understanding-and-refactoring-python-code

Let's look at a few examples to learn how. Consider we have below python files:
xyz.py
  1. import random  
  2.   
  3. def message(name):  
  4.   greeting = random.choice(['Hi''Hello''Aloha'])  
  5.   return f"{greeting}, {name}"  
haha.py
  1. from xyz import *  
  2.   
  3. def say_hi(name):  
  4.   print(message(name))  
main.py
  1. from haha import say_hi  
  2.   
  3. if __name__ == '__main__':  
  4.   say_hi('John')  

Usage example1 - command line
You can refer to here for more usage. Below is a simple example to generate call graph:
# pycallgraph graphviz --output-file=main.png -- ./main.py
Hello, John

Below graph will be generated:


Usage example2 - exclude unwanted nodes
Let's create a py file to list unwanted nodes as below:
main_with_config.py
  1. #!/usr/bin/env python  
  2. from haha import say_hi  
  3. from pycallgraph import PyCallGraph  
  4. from pycallgraph import Config  
  5. from pycallgraph import GlobbingFilter  
  6. from pycallgraph.output import GraphvizOutput  
  7.   
  8. config = Config()  
  9. config.trace_filter = GlobbingFilter(exclude=[  
  10.     # 'xyz.*',  
  11.     # '*.secret_function',  
  12. ])  
  13.   
  14. if __name__ == '__main__':  
  15.   graphviz = GraphvizOutput(output_file='main_with_config.png')  
  16.   
  17.   with PyCallGraph(output=graphviz, config=config):  
  18.     say_hi("John")  
This time you can obtain a clean chart:



沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...