You can only parse a complete valid python statement or expression. if True: is incomplete: if you were to attempt to parse it you would get a syntax error.
The solution is to first determine if you have a complete statement or expression; if you do not, buffer the line and keep reading new lines until you encounter a syntax error or a complete expression. Then use ast on your buffered input.
The compile_command function can distinguish between string of code which could be incomplete rather than incorrect. If the code appears incomplete, it returns None; otherwise it returns a code object (if valid) or raises a SyntaxError.
We can use this function to determine whether to buffer or parse a line. Untested code below:
linebuffer = []
while True:
line = raw_input()
linebuffer.append(line)
try:
compiled = code.compile_command(''.join(linebuffer))
except SyntaxError:
linebuffer = []
else:
if compiled is not None:
tree = ast.parse(''.join(linebuffer))
linebuffer = []
if True:is incomplete: if you were to attempt to parse it you would get a syntax error.