使用Python ast模块访问语法树中的节点 [英] Visiting nodes in a syntax tree with Python ast module
问题描述
我正在使用python ast(抽象语法树).
I'm playing with python ast (abstract syntax tree).
我写了以下内容,并访问了AST的所有节点.
I wrote the following and it visited all nodes of the AST.
import ast
class Py2Neko(ast.NodeVisitor):
def generic_visit(self, node):
print type(node).__name__
ast.NodeVisitor.generic_visit(self, node)
def visit_Name(self, node):
print 'Name :', node.id
def visit_Num(self, node):
print 'Num :', node.__dict__['n']
def visit_Str(self, node):
print "Str :", node.s
if __name__ == '__main__':
node = ast.parse("a = 1 + 2")
print ast.dump(node)
v = Py2Neko()
v.visit(node)
然后在Py2Neko类中添加了一些方法
Then added some methods to Py2Neko class
def visit_Print(self, node):
print "Print :"
def visit_Assign(self, node):
print "Assign :"
def visit_Expr(self, node):
print "Expr :"
但是,当它遇到打印"语句,赋值或表达式时,它似乎停止了并且不会继续前进.
But then when it encounters a "print" statement or an assignement or an expression it seems that it stops and isn't going further.
它输出:
Module(body=[Assign(targets=[Name(id='a', ctx=Store())], value=BinOp(left=Num(n=1), op=Add(), right=Num(n=2)))])
Module
Assign :
有人可以告诉我我做错了吗.
Can someone tell me what I did wrong.
我正在使用Python 2.6.6
I'm using Python 2.6.6
推荐答案
由于您的visit_Assign方法未显式处理Assign节点的子节点,因此语法树的遍历在那里停止.
Since your visit_Assign method does not explicitly process the child nodes of the Assign node, traversal of the syntax tree stops there.
如果您在ast.py的实现中查看NodeVisitor.generic_visit方法,则会看到它遍历当前节点的子代.因此,您可以从需要处理子级的每个方法中显式调用基类的generic_visit方法:
If you have a look at the NodeVisitor.generic_visit method in the implementation of ast.py, you'll see that it loops through the children of the current node. So, you can explicitly call the base class generic_visit method from each of your methods that needs to process children:
import ast
class Py2Neko(ast.NodeVisitor):
def generic_visit(self, node):
print type(node).__name__
ast.NodeVisitor.generic_visit(self, node)
def visit_Name(self, node):
print 'Name :', node.id
def visit_Num(self, node):
print 'Num :', node.__dict__['n']
def visit_Str(self, node):
print "Str :", node.s
def visit_Print(self, node):
print "Print :"
ast.NodeVisitor.generic_visit(self, node)
def visit_Assign(self, node):
print "Assign :"
ast.NodeVisitor.generic_visit(self, node)
def visit_Expr(self, node):
print "Expr :"
ast.NodeVisitor.generic_visit(self, node)
if __name__ == '__main__':
node = ast.parse("a = 1 + 2")
print ast.dump(node)
v = Py2Neko()
v.visit(node)
这篇关于使用Python ast模块访问语法树中的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!