将AST节点转换为python代码 [英] convert AST node to python code
本文介绍了将AST节点转换为python代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下字符串:
code = """
if 1 == 1 and 2 == 2 and 3 == 3:
test = 1
"""
以下代码在 AST 中转换该字符串.
The following code converts that string in a 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:代码>
I want to know if there is a way to convert the object at.If
into the string if 1 == 1 and 2 == 2 and 3 == 3:
我知道可以通过遍历子节点来完成,但是那样太复杂了.
I know it can be done traversing the children node, but it's getting too complicated that way.
推荐答案
ast.get_source_segment
已在 python 3.8 中添加:
ast.get_source_segment
was added in 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'
这篇关于将AST节点转换为python代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文