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..
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:
>>> 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=[])])"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.