python ast 语法分析
ast(Abstract Syntax Trees)是python中非常有用的一个模块,我们可以通过分析python的抽象语法树来对python的代码进行 分析和修改 。 ast作用在python代码的语法被解析后,被编译成字节码之前。 一. ast 1. 获取语法树 ast模块的基本使用是非常简单的,我们可以通过如下代码快速得到一棵抽象语法树: import ast root_node = ast.parse("print 'hello world'") root_node -> <_ast.Module object at 0x9e3df6c> 通过ast的parse方法得到ast tree的根节点root_node, 我看可以通过根节点来遍历语法树,从而对python代码进行分析和修改。 ast.parse(可以直接查看ast模块的源代码)方法实际上是调用内置函数compile进行编译,如下所示: def parse(source, filename='<unknown>', mode='exec'): """ Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). """ return compile(source, filename,