Joh*_*yDH 47 python static module function call-graph
我有一堆脚本来执行任务.我真的需要知道项目的调用图,因为它非常令人困惑.我无法执行代码,因为它需要额外的硬件和软件才能执行此操作.但是,我需要理解它背后的逻辑.所以,我需要知道是否有一个工具(不需要任何python文件执行)可以使用模块而不是trace或python解析器构建调用图.我有这样的工具用于C但不用于python.
谢谢.
Dav*_*ser 36
我发现的最好的工具叫做pyan,最初由Edmund Horner 编写,由他改进,然后由Juha Jeronen 给出着色和其他功能.该版本具有有用的命令行选项:
Usage: pyan.py FILENAME... [--dot|--tgf]
Analyse one or more Python source files and generate an approximate call graph
of the modules, classes and functions within them.
Options:
-h, --help show this help message and exit
--dot output in GraphViz dot format
--tgf output in Trivial Graph Format
-v, --verbose verbose output
-d, --defines add edges for 'defines' relationships [default]
-n, --no-defines do not add edges for 'defines' relationships
-u, --uses add edges for 'uses' relationships [default]
-N, --no-uses do not add edges for 'uses' relationships
-c, --colored color nodes according to namespace [dot only]
-g, --grouped group nodes (create subgraphs) according to namespace
[dot only]
-e, --nested-groups create nested groups (subgraphs) for nested namespaces
(implies -g) [dot only]
Run Code Online (Sandbox Code Playgroud)
这是运行的结果pyan.py --dot -c -e pyan.py | fdp -Tpng:
Edmund Horner的原始代码现在最好在他的github存储库中找到,而且有人也创建了两个版本的存储库,您可以从中下载Juha Jeronen的版本.我已经制作了一个干净的版本,将他们的贡献结合到我自己的存储库中,仅用于pyan,因为这两个存储库都有许多其他软件.
vko*_*ori 26
你可能想看一下pycallgraph:
此链接中还描述了一种更加手动的方法:
简而言之,不存在这样的工具。Python的语言过于动态,无法在不执行代码的情况下生成调用图。
以下代码清楚地展示了python的一些非常动态的功能:
class my_obj(object):
def __init__(self, item):
self.item = item
def item_to_power(self, power):
return self.item ** power
def strange_power_call(obj):
to_call = "item_to_power"
return getattr(obj, to_call)(4)
a = eval("my" + "_obj" + "(12)")
b = strange_power_call(a)
Run Code Online (Sandbox Code Playgroud)
请注意,我们eval用于创建的实例,my_obj也getattr用于调用其方法之一。这两种方法都使得为python创建静态调用图变得极为困难。此外,还有各种难以分析的模块导入方式。
我认为您最好的选择是坐在代码库和纸上,然后开始做笔记。这将具有使您更加熟悉代码库的双重好处,并且不会因难以解析的场景而容易被欺骗。
SourceTrail 将为您提供帮助。https://www.sourcetrail.com/
Sourcetrail 是一个免费的开源跨平台源代码浏览器,可帮助您高效地处理不熟悉的源代码。支持 C、C++、Java 和 Python
https://github.com/CoatiSoftware/Sourcetrail
这是文档的链接
https://www.sourcetrail.com/documentation/
请注意,Python 支持相对较新,因此请不要指望它能完美运行。