python提取ast,并以树绘图
时间: 2024-05-09 12:16:25 浏览: 9
要提取Python代码的AST(抽象语法树),可以使用Python标准库中的`ast`模块。下面是一个简单的例子:
```python
import ast
import pydot
code = """
def greet(name):
print(f'Hello, {name}!')
greet('world')
"""
tree = ast.parse(code)
graph = pydot.Dot(graph_type='graph')
def add_nodes(parent, node):
for child_node_name, child_node in ast.iter_fields(node):
if isinstance(child_node, ast.AST):
child_node_id = id(child_node)
child_node_label = type(child_node).__name__
child_node_shape = "ellipse"
child_node_color = "lightblue"
child_node_style = "filled"
child_node_fontcolor = "black"
child_node_fontsize = "10"
child_node_attributes = {
"label": child_node_label,
"shape": child_node_shape,
"color": child_node_color,
"style": child_node_style,
"fontcolor": child_node_fontcolor,
"fontsize": child_node_fontsize,
}
child_node_dot = pydot.Node(
child_node_id,
**child_node_attributes
)
graph.add_node(child_node_dot)
edge_attributes = {}
if isinstance(parent, ast.AST):
edge_attributes["label"] = child_node_name
graph.add_edge(pydot.Edge(parent, child_node_dot, **edge_attributes))
add_nodes(child_node_dot, child_node)
add_nodes(None, tree)
graph.write_png("ast.png")
```
这个例子会生成一张抽象语法树的图像,保存为`ast.png`。你可以用任何图像查看器打开它。
这个例子使用了`pydot`模块来绘制图形。如果你没有安装`pydot`,可以使用以下命令安装:
```
pip install pydot
```