469,925 Members | 1,485 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,925 developers. It's quick & easy.

catching syntax errors via excepthook?

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
Jul 3 '06 #1
1 1920
Hari Sekhon <se*********@googlemail.comwrote:
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.:
>>def myexcepthook(type,value,tb):
.... print 'error', value
....
>>sys.excepthook=myexcepthook
2+
error invalid syntax (<stdin>, line 1)
>>m=open('za.py', 'w')
m.writelines('''print "hello"
.... print 2+
.... ''')
>>m.close()
import za
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
Jul 3 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Peter A. Schott | last post: by
6 posts views Thread by Lunchtimemama | last post: by
1 post views Thread by Jesus Rivero - (Neurogeek) | last post: by
reply views Thread by Larry Bates | last post: by
1 post views Thread by Hari Sekhon | last post: by
1 post views Thread by ian | last post: by
5 posts views Thread by Stefan Bellon | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.