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.

buy Viagra said...

I would like to say that you really made my day, it's wonderful when you just look around the web
and find something like this, reminds me of that ''How to make a dinner for a romantic...'' by Elsa Thomas,
you're a wonderful writer let me tell you!!! ñ_ñ

James Maverick (
3453 Rardin Drive
San Mateo, CA 94403
Project Manager

Natural Viagra said...

Well as for me many kinds of commands that exist on all the SO's are a serious thing cause you need to know the events that happend in your computer. Thanks for sharing and keep posting!