将 AST 节点转换为 python 代码
convert AST node to python code
假设我有以下字符串:
code = """
if 1 == 1 and 2 == 2 and 3 == 3:
test = 1
"""
以下代码在 AST 中转换该字符串。
ast.parse(code)
然后我有这样一棵树:
Module(body=[<_ast.If object at 0x100747358>])
If(test=BoolOp(op=And(), values=[<_ast.Compare object at 0x100747438>, <_ast.Compare object at 0x100747a90>, <_ast.Compare object at 0x100747d68>]), body=[<_ast.Assign object at 0x100747e48>], orelse=[])
我想知道有没有办法把对象at.If
转换成字符串if 1 == 1 and 2 == 2 and 3 == 3:
我知道遍历子节点可以完成,但这样会变得太复杂了。
您可以使用 astunparse 库,它基本上只是核心代码,单独重新打包。
首先,安装库:
pip install astunparse
然后,运行 您的 AST 模块通过它获取源代码。所以运行宁:
import ast
import astunparse
code = """
if 1 == 1 and 2 == 2 and 3 == 3:
test = 1
"""
node = ast.parse(code)
astunparse.unparse(node)
将输出:
'\nif ((1 == 1) and (2 == 2) and (3 == 3)):\n test = 1\n'
ast.get_source_segment
添加到 python 3.8:
>>> import ast
>>> code = """
>>> if 1 == 1 and 2 == 2 and 3 == 3:
>>> test = 1
>>> """
>>> node = ast.parse(code)
>>> ast.get_source_segment(code, node.body[0])
'if 1 == 1 and 2 == 2 and 3 == 3:\n test = 1'
Python 3.9 引入了 ast.unparse,它正是这样做的,即它反转了 ast.parse
。使用您的示例:
import ast
code = """
if 1 == 1 and 2 == 2 and 3 == 3:
test = 1
"""
tree = ast.parse(code)
print(ast.unparse(tree))
这将打印出:
if 1 == 1 and 2 == 2 and (3 == 3):
test = 1
请注意,可能与原始输入略有不同。
假设我有以下字符串:
code = """
if 1 == 1 and 2 == 2 and 3 == 3:
test = 1
"""
以下代码在 AST 中转换该字符串。
ast.parse(code)
然后我有这样一棵树:
Module(body=[<_ast.If object at 0x100747358>])
If(test=BoolOp(op=And(), values=[<_ast.Compare object at 0x100747438>, <_ast.Compare object at 0x100747a90>, <_ast.Compare object at 0x100747d68>]), body=[<_ast.Assign object at 0x100747e48>], orelse=[])
我想知道有没有办法把对象at.If
转换成字符串if 1 == 1 and 2 == 2 and 3 == 3:
我知道遍历子节点可以完成,但这样会变得太复杂了。
您可以使用 astunparse 库,它基本上只是核心代码,单独重新打包。
首先,安装库:
pip install astunparse
然后,运行 您的 AST 模块通过它获取源代码。所以运行宁:
import ast
import astunparse
code = """
if 1 == 1 and 2 == 2 and 3 == 3:
test = 1
"""
node = ast.parse(code)
astunparse.unparse(node)
将输出:
'\nif ((1 == 1) and (2 == 2) and (3 == 3)):\n test = 1\n'
ast.get_source_segment
添加到 python 3.8:
>>> import ast
>>> code = """
>>> if 1 == 1 and 2 == 2 and 3 == 3:
>>> test = 1
>>> """
>>> node = ast.parse(code)
>>> ast.get_source_segment(code, node.body[0])
'if 1 == 1 and 2 == 2 and 3 == 3:\n test = 1'
Python 3.9 引入了 ast.unparse,它正是这样做的,即它反转了 ast.parse
。使用您的示例:
import ast
code = """
if 1 == 1 and 2 == 2 and 3 == 3:
test = 1
"""
tree = ast.parse(code)
print(ast.unparse(tree))
这将打印出:
if 1 == 1 and 2 == 2 and (3 == 3):
test = 1
请注意,可能与原始输入略有不同。