Need Help Differentiating Bad Commands From Incomplete Commands

Jeff Epler jepler at
Mon Aug 2 04:08:34 CEST 2004

You may want to look at the codeop module

>>> from codeop import compile_command
>>> compile_command("a = 3")                      # Complete code
<code object ? at 0xf7054920, file "<input>", line 1>
>>> print compile_command("for x in range(10):")  # incomplete code
>>> print compile_command("fer x in ronge(10):")  # syntax error
Traceback (most recent call last):
  File "<input>", line 1
    fer x in ronge(10):
SyntaxError: invalid syntax

Note that this can detect invalid syntax ("fer" instead of "for") but
not undefined names (ronge instead of range)---that will only happen
when the code is executed, and range isn't found in anywhere.

PS _PyParser_Grammar is an internal symbol, so whoever wrote that FAQ
should be given 20 lashes with a short piece of string
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <>

More information about the Python-list mailing list