使用Python ast模块访问语法树中的节点

时间:2023-01-25 09:00:22

I'm playing with python ast (abstract syntax tree).

我在玩python ast(抽象语法树)。

I wrote the following and it visited all nodes of the AST.

我编写了以下代码,它访问了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)

Then added some methods to Py2Neko class

然后向Py2Neko类添加了一些方法

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.

但当它遇到一个“打印”语句或一个赋值或表达式时,它似乎停止了,并没有更进一步。

It outputs:

输出:

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.

有人能告诉我我做错了什么吗?

I'm using Python 2.6.6

我使用Python 2.6.6

2 个解决方案

#1


11  

Since your visit_Assign method does not explicitly process the child nodes of the Assign node, traversal of the syntax tree stops there.

由于visit_Assign方法没有显式地处理赋值节点的子节点,因此对语法树的遍历将在这里停止。

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:

如果你看一下NodeVisitor(客人)就知道了。在ast.py的实现中,您将看到它循环遍历当前节点的子节点。因此,您可以从需要处理子类的每个方法中显式地调用基类generic_visit方法:

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)

#2


4  

For non-terminal nodes, your visit function has to visit the children. See Simple example of how to use ast.NodeVisitor? for some more information.

对于非终端节点,访问函数必须访问子节点。查看如何使用ast.NodeVisitor的简单示例?对于一些更多的信息。

#1


11  

Since your visit_Assign method does not explicitly process the child nodes of the Assign node, traversal of the syntax tree stops there.

由于visit_Assign方法没有显式地处理赋值节点的子节点,因此对语法树的遍历将在这里停止。

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:

如果你看一下NodeVisitor(客人)就知道了。在ast.py的实现中,您将看到它循环遍历当前节点的子节点。因此,您可以从需要处理子类的每个方法中显式地调用基类generic_visit方法:

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)

#2


4  

For non-terminal nodes, your visit function has to visit the children. See Simple example of how to use ast.NodeVisitor? for some more information.

对于非终端节点,访问函数必须访问子节点。查看如何使用ast.NodeVisitor的简单示例?对于一些更多的信息。