1. こんな感じで使います。
$ python parser.py sample.py
import parser code = ''' a = 1 + 1 print(a) ''' graph = parser.create_graph(code) graph.render("sample")
import ast import sys import graphviz def create_graph(lines): graph = graphviz.Graph(format='png') root = ast.parse(lines) node_list = [root] _setup(graph, node_list) return graph def _setup(graph, node_list): # node node = node_list[-1] node_identity = str(len(node_list)) node_name = type(node).__name__ graph.node(node_identity, node_name) # children for child in ast.iter_child_nodes(node): node_list.append(child) child_identity = str(len(node_list)) graph.edge(node_identity, child_identity) _setup(graph, node_list) if __name__ == '__main__': file_name = sys.argv[1] with open(file_name) as file: lines = file.read() graph = create_graph(lines) graph.render(file_name)