How to process syntax errors

Terry Reedy tjreedy at udel.edu
Tue Oct 11 00:58:03 EDT 2016


On 10/10/2016 11:24 AM, Chris Angelico wrote:
> On Tue, Oct 11, 2016 at 1:13 AM,  <mr.puneet.goyal at gmail.com> wrote:
>> Is there any way to capture syntax errors and process them ? I want to write a function which calls every time whenever there is syntax error in the program.

> However, you can catch this at some form of outer level. If you're
> using exec/eval to run the code, you can guard that:
>
> code = """
> obj = MyClass() # using PEP 8 names
> obj xyz
> """
> try:
>     exec(code)
> except SyntaxError:
>     print("Blah blah blah")

Far from being 'un-pythonic' (Puneet's response), this is essentially 
what the interpreter does, either without or with a separate explicit 
compile step.  IDLE splits the exec into two pieces in two processes. 
Except for the two process part, this either uses or copies 
code.InteractiveInterpreter in the stdlib.  The fact that the latter 
separates compile and exec is what allows IDLE to subclass it and run 
the code object elsewhere, by over-riding the runcode method.

# in IDLE process:

code = <user entry in shell or editor>

try:
     code_ob = compile(code, ....)
except (SyntaxError, <other compile errors>) as e:
     <display error to user>  # replace ^ with red background highlight
else:
     <ship code to user process>

# in user process

     exec(code, fake_main)
     # stdout, stderr connect to IDLE process



-- 
Terry Jan Reedy




More information about the Python-list mailing list