2024-03-28 11:41:41 发布
网友
有没有一种方法可以将给定的Python抽象语法树(AST)转换为源代码?在
Here是一个很好的例子,说明了如何使用Python的ast模块,特别是NodeTransformer。我正在寻找一种方法将得到的AST转换回源代码,这样可以直观地检查更改。在
ast
NodeTransformer
看看http://pypi.python.org/pypi/sourcecodegen/0.6.14
我发现了一个不错的第三方库:^{},它基于Ned在his answer中建议的unparse.py。示例:
unparse.py
import ast import astunparse code = ''' class C: def f(self, arg): return f'{arg}' print(C().f("foo" + 'bar')) ''' print(astunparse.unparse(ast.parse(code)))
运行中产生
另一个简洁的函数是astunparse.dump,它漂亮地打印了代码对象:
astunparse.dump
astunparse.dump(ast.parse(code))
输出:
Module(body=[ ClassDef( name='C', bases=[], keywords=[], body=[FunctionDef( name='f', args=arguments( args=[ arg( arg='self', annotation=None), arg( arg='arg', annotation=None)], vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, defaults=[]), body=[Return(value=JoinedStr(values=[FormattedValue( value=Name( id='arg', ctx=Load()), conversion=-1, format_spec=None)]))], decorator_list=[], returns=None)], decorator_list=[]), Expr(value=Call( func=Name( id='print', ctx=Load()), args=[Call( func=Attribute( value=Call( func=Name( id='C', ctx=Load()), args=[], keywords=[]), attr='f', ctx=Load()), args=[BinOp( left=Str(s='foo'), op=Add(), right=Str(s='bar'))], keywords=[])], keywords=[]))])
Python源代码树包含以下实现:解列.py在Demo/parser目录中:https://github.com/python/cpython/blob/master/Tools/parser/unparse.py
看看http://pypi.python.org/pypi/sourcecodegen/0.6.14
我发现了一个不错的第三方库:^{} ,它基于Ned在his answer中建议的
unparse.py
。示例:运行中产生
^{pr2}$另一个简洁的函数是
astunparse.dump
,它漂亮地打印了代码对象:输出:
Python源代码树包含以下实现:解列.py在Demo/parser目录中:https://github.com/python/cpython/blob/master/Tools/parser/unparse.py
相关问题 更多 >
编程相关推荐