The ast module contains the necessary tools:
>>> 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=[])])"
source share