有什么办法可以从树的转储文件中还原 AST 树?
is there any way to revert back the AST tree from the dump file of the tree?
c 是 python 代码的解析树:
c=ast.parse('''
for x in y:
print(x)
''')
d 是 tree-c 的转储文件
d=ast.dump(c)
d的内容为以下字符串:
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。
有什么建议吗?
谢谢
您可以使用 eval
从字符串中获取 ast
对象:
ast_obj = eval(d)
然后,存在各种可以转换回源代码的第三方库(Given an AST, is there a working library for getting the source?, Python ast (Abstract Syntax Trees): get back source string of subnode)
c 是 python 代码的解析树:
c=ast.parse('''
for x in y:
print(x)
''')
d 是 tree-c 的转储文件
d=ast.dump(c)
d的内容为以下字符串:
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。
有什么建议吗?
谢谢
您可以使用 eval
从字符串中获取 ast
对象:
ast_obj = eval(d)
然后,存在各种可以转换回源代码的第三方库(Given an AST, is there a working library for getting the source?, Python ast (Abstract Syntax Trees): get back source string of subnode)