Thursday, June 14, 2007

A workaround for the sys.excepthook bug

About two years ago I reported the bug sys.excepthook doesn't work in threads. Then just recently someone asked in #utahpython if I had a workaround. Here it is (also added as a comment to the bug report) -- all we do is monkeypatch to run the excepthook manually if there is an uncaught exception:
def install_thread_excepthook():
    Workaround for sys.excepthook thread bug
    Call once from __main__ before creating any threads.
    If using psyco, call psyco.cannotcompile(
    since this replaces a new-style class method.
    import sys, threading
    run_old =
    def run(*args, **kwargs):
            run_old(*args, **kwargs)
        except (KeyboardInterrupt, SystemExit):
            sys.excepthook(*sys.exc_info()) = run


Anonymous said...

Actually, this won't work, at least not if you create your own subclasses of threading.Thread.

Jonathan Ellis said...

I would think it's obvious that it won't work if you override in a subclass, yes.

But there's usually no need to do that; good style is to just pass target and args options instead of subclassing.