如何将python代码转换为解析树,再转换回原始代码?

时间:2019-06-07 02:21:21

标签: python parsing tree parse-tree

我希望能够将python代码(字符串)转换为解析树,在树级别对其进行修改,然后将树转换为代码(字符串)。当转换为解析树并转换回未经任何树级修改的代码时,生成的代码应与原始输入代码完全匹配。

我想为此使用python。我找到了astparser python模块,但是ast树会丢失有关原始代码的信息。至于parser模块,我似乎无法弄清楚如何操作解析树或将其转换为代码。

这是我到目前为止所拥有的。

import ast
import astor # pip install astor
import parser

code = 'hi = 0'
ast_tree = ast.parse(code)
code_from_ast = astor.to_source(tree) # 'hi = 0\n'
parser_tree = parser.suite(code)
code_from_parser = ???

1 个答案:

答案 0 :(得分:3)

如您所述,内置ast模块不会保留许多格式信息(空格,注释等)。 在这种情况下,您需要一个具体的语法树(例如LibCST)而不是抽象语法树。 (您可以通过pip install libcst安装)

这是一个示例,展示了如何通过将代码解析为树,将树变异并渲染树为源代码来将代码从hi = 0更改为hi = 2。 在https://libcst.readthedocs.io/en/latest/usage.html

中可以找到更高级的用法
In [1]: import libcst as cst

In [2]: code = 'hi = 0'

In [3]: tree = cst.parse_module(code)

In [4]: print(tree)
Module(
    body=[
        SimpleStatementLine(
            body=[
                Assign(
                    targets=[
                        AssignTarget(
                            target=Name(
                                value='hi',
                                lpar=[],
                                rpar=[],
                            ),
                            whitespace_before_equal=SimpleWhitespace(
                                value=' ',
                            ),
                            whitespace_after_equal=SimpleWhitespace(
                                value=' ',
                            ),
                        ),
                    ],
                    value=Integer(
                        value='0',
                        lpar=[],
                        rpar=[],
                    ),
                    semicolon=MaybeSentinel.DEFAULT,
                ),
            ],
            leading_lines=[],
            trailing_whitespace=TrailingWhitespace(
                whitespace=SimpleWhitespace(
                    value='',
                ),
                comment=None,
                newline=Newline(
                    value=None,
                ),
            ),
        ),
    ],
    header=[],
    footer=[],
    encoding='utf-8',
    default_indent='    ',
    default_newline='\n',
    has_trailing_newline=False,
)

In [5]: class ModifyValueVisitor(cst.CSTTransformer):
   ...:     def leave_Assign(self, node, updated_node):
   ...:         return updated_node.with_changes(value=cst.Integer(value='2'))
   ...:

In [6]: modified_tree = tree.visit(ModifyValueVisitor())

In [7]: modified_tree.code
Out[7]: 'hi = 2'