将Python解析为实例列表

时间:2013-05-10 05:38:08

标签: python parsing

我想将Pure-Python代码解析成某些类的实例列表,这些类代表原始代码的各个部分。

一个例子:

>>> text = '''
... for x in range(100):
...     print x
... '''
>>> tree = parse(text)
>>> print tree
Tree( ForLoop(x,Range(100), [Stmt(Print(x))]) )
# here ForLoop, Range, Stmt, Print are all custom classes

1 个答案:

答案 0 :(得分:4)

ast module拥有您需要的工具:

>>> import ast
>>> text = '''
for x in range(100):
    print x
'''

>>> m = ast.parse(text)
>>> ast.dump(m)
"Module(body=[For(target=Name(id='x', ctx=Store()), iter=Call(func=Name(id='range', ctx=Load()),
       args=[Num(n=100)], keywords=[], starargs=None, kwargs=None), 
       body=[Print(dest=None, values=[Name(id='x', ctx=Load())], nl=True)], orelse=[])])"