我有一个像这样的 ast.dump :
"Module(body=[Assign(targets=[Name(id='i', ctx=Store())], value=Num(n=0)), While(test=Compare(left=Name(id='i', ctx=Load()), ops=[Lt()], comparators=[Num(n=10)]), body=[Print(dest=None, values=[Name(id='i', ctx=Load())], nl=True), AugAssign(target=Name(id='i', ctx=Store()), op=Add(), value=Num(n=1))], orelse=[]), For(target=Name(id='x', ctx=Store()), iter=Call(func=Name(id='range', ctx=Load()), args=[Num(n=10)], keywords=[], starargs=None, kwargs=None), body=[Print(dest=None, values=[Name(id='x', ctx=Load())], nl=True)], orelse=[])])"
我如何(漂亮地)以更易读的形式打印它,如下所示?
Module(
body=[Assign(targets=[Name(id='i',
ctx=Store())],
value=Num(n=0)),
While(test=Compare(left=Name(id='i',
ctx=Load()),
ops=[Lt()],
comparators=[Num(n=10)]),
body=[Print(dest=None,
values=[Name(id='i',
ctx=Load())],
nl=True),
AugAssign(target=Name(id='i',
ctx=Store()),
op=Add(),
value=Num(n=1))],
orelse=[]),
For(target=Name(id='x',
ctx=Store()),
iter=Call(func=Name(id='range',
ctx=Load()),
args=[Num(n=10)],
keywords=[],
starargs=None,
kwargs=None),
body=[Print(dest=None,
values=[Name(id='x',
ctx=Load())],
nl=True)],
orelse=[])])
如果您想知道是什么代码生成了这个:
text = '''
i = 0
while i < 10:
print i
i += 1
for x in range(10):
print x
'''
ast.dump(ast.parse(text))