Parsing python file by statement in python

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Sep 11 06:57:52 EDT 2003


Tim <fukawitribe at netscape.net> wrote in news:3F605192.5010405 at netscape.net:

> don't really want to compile the statement until have a top level block 
>   - have seen some scripts that do incremental command_compiles() on 
> readlines until they get back non-None but these obviously balls up on 
> statements like
> 
> for i in range(n) :
>     foo(i)
>     bar(i)

code.compile_command handles this like the interactive interpreter, the 
trick is to make sure you have newlines separating the lines, but no 
trailing newline. This simulates the interactive thing of needing a blank 
line to terminate the block.

>>> import code
>>> code.compile_command("x=3")
<code object ? at 00917340, file "<input>", line 1>
>>> code.compile_command("for i in range(n):")
>>> code.compile_command("for i in range(n):\n  foo(i)")
>>> code.compile_command("for i in range(n):\n  foo(i)\n  bar(i)")
>>> code.compile_command("for i in range(n):\n  foo(i)\n  bar(i)\n")
<code object ? at 00927FF0, file "<input>", line 1>
>>> 

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list