简体   繁体   English

将Python解析为实例列表

[英]Parsing Python to a list of instances

I want to parse Pure-Python Code into something like a list of instances of certain classes that represent various parts of the original code.. 我想将Pure-Python代码解析成某些类的实例列表,这些类代表原始代码的各个部分。

An example: 一个例子:

>>> 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

The ast module has the tools you need: ast模块具有您需要的工具:

>>> 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=[])])"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM