sys.excepthook and threads
Jonathan Ellis
jbellis at gmail.com
Tue Oct 5 00:13:52 EDT 2004
I'm running into the same problem Chuck did 1.5 years ago. Can anyone
shed any light on why threads ignore sys.excepthook? Is there a better
workaround than the following? (prefixing whitespace with . to prevent
google from munching it)
import sys
from threading import Thread
def MyHandler(typ, exc, tb):
. print 'caught exception'
run_old = getattr(Thread, 'run')
def run(self, *args, **kargs):
. try:
. run_old(self, *args, **kargs)
. except:
. MyHandler(*sys.exc_info())
setattr(Thread, 'run', run)
-Jonathan
Chuck Esterbrook wrote:
> Is there a reason why sys.excepthook does not get invoked by threads
> (other than the main thread)?
>
> The program below does not output 'caught exception', but will if
> Raise() is called directly. Tested on Python 2.2.2 and 2.3a2. A quick
> search of c.l.p showed mention of this, but no explanation. I'm just
> curious.
>
> BTW the docs for sys.excepthook don't mention this phenomena at all.
> They say "When an exception is raised and uncaught, the interpreter
> calls sys.excepthook with three arguments" so that's what I expected,
> threads or not.
>
> -----------------------------------------------
> def MyHandler(typ, exc, tb):
> print 'caught exception'
>
> import sys
> sys.excepthook = MyHandler
>
> from threading import Thread
>
> def Raise():
> assert 0
>
> if 1:
> Thread(target=Raise).start()
> else:
> Raise()
> -----------------------------------------------
>
>
> --
> Chuck
> http://ChuckEsterbrook.com
More information about the Python-list
mailing list