有什么办法可以从树的转储文件中还原AST树? [英] is there any way to revert back the AST tree from the dump file of the tree?
问题描述
c是经过解析的python代码树:
c is a parsed tree of a python code:
c = ast.parse('''
for x in y:
print(x)
''')
d是tree-c的转储文件
d is the dump file of tree-c
d=ast.dump(c)
d的内容为以下字符串:
the content of d is the following string:
Module(
body=[For(target=Name(id='x', ctx=Store()), iter=Name(id='y', ctx=Load()),
body=[Expr(value=Call(func=Name(id='print', ctx=Load()),
args=[Name(id='x', ctx=Load())], keywords=[]))], orelse=[])])
我环顾四周,看看是否可以找到方法使用d的内容,返回到树c。
I've looked around the net to see if I could find a method to use the content of d, to revert back to the tree c.
有什么建议吗?
谢谢
推荐答案
您可以使用 eval
来获取 ast
字符串中的对象:
You can use eval
to get the ast
object from the string:
ast_obj = eval(d)
然后,存在第三种可以转换回源代码的第三方库(使用AST,是否有一个可用的库来获取源代码?, Python ast(抽象语法树):获取子节点的源字符串)
Then, there exist various third party libraries that can convert back to source (Given an AST, is there a working library for getting the source?, Python ast (Abstract Syntax Trees): get back source string of subnode)
这篇关于有什么办法可以从树的转储文件中还原AST树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!