Python ast到点图 [英] Python ast to dot graph

查看:31
本文介绍了Python ast到点图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在分析由 python 代码生成的乐趣和利润"的 AST,我想要比ast.dump"更图形化的东西来实际查看生成的 AST.

I'm analyzing the AST generated by python code for "fun and profit", and I would like to have something more graphical than "ast.dump" to actually see the AST generated.

理论上已经是一棵树了,所以创建一个图应该不会太难,但是我不明白我该怎么做.

In theory is already a tree, so it shouldn't be too hard to create a graph, but I don't understand how I could do it.

ast.walk 似乎走的是 BFS 策略,而visitX 方法我真的看不到父级或者我似乎没有找到创建图形的方法...

ast.walk seems to walk with a BFS strategy, and the visitX methods I can't really see the parent or I don't seem to find a way to create a graph...

好像只能自己写DFS walk函数了,有意义吗?

It seems like the only way is to write my own DFS walk function, is does it make sense?

推荐答案

如果你看看 ast.NodeVisitor,它是一个相当简单的类.您可以将其子类化,也可以根据需要重新实现其行走策略.例如,在访问节点时保持对父节点的引用很容易实现,只需添加一个 visit 方法,该方法也接受父节点作为参数,并从你自己的 传递它generic_visit.

If you look at ast.NodeVisitor, it's a fairly trivial class. You can either subclass it or just reimplement its walking strategy to whatever you need. For instance, keeping references to the parent when nodes are visited is very simple to implement this way, just add a visit method that also accepts the parent as an argument, and pass that from your own generic_visit.

附言顺便说一下,NodeVisitor.generic_visit 似乎实现了 DFS,所以你要做的就是添加父节点传递.

P.S. By the way, it appears that NodeVisitor.generic_visit implements DFS, so all you have to do is add the parent node passing.

这篇关于Python ast到点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆