2013-05-10 58 views
2

我有像這樣一個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)) 

回答

2

它已經完成,例如by this functionastpp module

從這個代碼後一個:

import ast 
import astpp 

tree = ast.parse(
""" 
print "Hello World!" 
s = "I'm a string!" 
print s 
""") 
print astpp.dump(tree) 

應該產生這樣的輸出:

Module(body=[ 
    Print(dest=None, values=[ 
     Str(s='Hello World!'), 
     ], nl=True), 
    Assign(targets=[ 
     Name(id='s', ctx=Store()), 
     ], value=Str(s="I'm a string!")), 
    Print(dest=None, values=[ 
     Name(id='s', ctx=Load()), 
     ], nl=True), 
    ]) 
+0

感謝我需要的.. – pradyunsg 2013-05-10 06:50:29