catching syntax errors via excepthook?

H

Hari Sekhon

I've written an except hook into a script as shown below which works
well for the most part and catches exceptions.

import sys
def myexcepthook(type,value,tb):
do something

sys.excepthook=myexcepthook
rest of script.... (now protected by catchall exception hook)


I've been intentionally introducing errors into the code to try to test
it and while it catches import errors and other things, it doesn't catch
syntax errors.

Is there a way to get it to catch syntax errors?
Or is there a better way?

-h
 
A

Alex Martelli

Hari Sekhon said:
I've written an except hook into a script as shown below which works
well for the most part and catches exceptions.

import sys
def myexcepthook(type,value,tb):
do something

sys.excepthook=myexcepthook
rest of script.... (now protected by catchall exception hook)


I've been intentionally introducing errors into the code to try to test
it and while it catches import errors and other things, it doesn't catch
syntax errors.

Is there a way to get it to catch syntax errors?

Python, of course, parses (and in fact compiles) a whole module before
executing any of it, so if you're talking about syntax error in the
source of the very module which (when executed) will install an
excepthook, no way. Apart from this, no problem, e.g.:
.... print 'error', value
.... .... print 2+
.... ''')error invalid syntax (za.py, line 2)

etc, etc, i.e., the hook does catch all syntax errors due to parsing
which occurs *after* the hook is installed (in interactive sessions or
other modules). Clearly the hook cannot catch any error which occur
*before* the hook is installed.

You can delay the detection of syntax errors, for example, by explicitly
calling the compile built-in function on string literals, rather than
relying on implicit compilation of sources; and/or you can strive to
have your excepthook installed ASAP, e.g. by playing with
sitecustomize.py and/or $PYTHONSTARTUP .


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top