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

Dyl*_*ley 3 python tree parsing parse-tree

我希望能够将python代码(字符串)转换为解析树,在树级别修改它,然后将树转换为代码(字符串)。当转换为解析树并在没有任何树级修改的情况下返回代码时,生成的代码应该与原始输入代码完全匹配。

我想为此使用python。我找到了astparserpython 模块,但是 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 = ???
Run Code Online (Sandbox Code Playgroud)

小智 6

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

下面是一个例子示出了如何将代码从改变hi = 0hi = 2通过解析代码树中,突变的树和渲染树回源代码。更高级的用法可以在https://libcs​​t.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'
Run Code Online (Sandbox Code Playgroud)