Source From Here
QuestionI 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
- import random
- def message(name):
- greeting = random.choice(['Hi', 'Hello', 'Aloha'])
- return f"{greeting}, {name}"
- from xyz import *
- def say_hi(name):
- print(message(name))
- from haha import say_hi
- if __name__ == '__main__':
- say_hi('John')
Usage example1 - command line
You can refer to here for more usage. Below is a simple example to generate call graph:
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
- #!/usr/bin/env python
- from haha import say_hi
- from pycallgraph import PyCallGraph
- from pycallgraph import Config
- from pycallgraph import GlobbingFilter
- from pycallgraph.output import GraphvizOutput
- config = Config()
- config.trace_filter = GlobbingFilter(exclude=[
- # 'xyz.*',
- # '*.secret_function',
- ])
- if __name__ == '__main__':
- graphviz = GraphvizOutput(output_file='main_with_config.png')
- with PyCallGraph(output=graphviz, config=config):
- say_hi("John")
沒有留言:
張貼留言