简体   繁体   中英

'sys.excepthook' and threading

I am using Python 2.5 and trying to use a self-defined excepthook in my program. In the main thread it works perfectly fine. But in a thread started with the threading module the usual excepthook is called.

Here is an example showing the problem. Uncommenting the comment shows the desired behaviour.

import threading, sys

def myexcepthook(type, value, tb):
    print 'myexcepthook'

class A(threading.Thread, object):

    def __init__(self):
        threading.Thread.__init__(self, verbose=True)
#       raise Exception('in main')
        self.start()

    def run(self):
        print 'A'
        raise Exception('in thread')            

if __name__ == "__main__":
    sys.excepthook = myexcepthook
    A()

So, how can I use my own excepthook in a thread?

It looks like this bug is still present in (at least) 3.4, and one of the workarounds in the discussion Nadia Alramli linked seems to work in Python 3.4 too.

For convenience and documentation sake, I'll post the code for (in my opinion) the best workaround here. I updated the coding style and comments slightly to make it more PEP8 and Pythonic.

import sys
import threading

def setup_thread_excepthook():
    """
    Workaround for `sys.excepthook` thread bug from:
    http://bugs.python.org/issue1230540

    Call once from the main thread before creating any threads.
    """

    init_original = threading.Thread.__init__

    def init(self, *args, **kwargs):

        init_original(self, *args, **kwargs)
        run_original = self.run

        def run_with_except_hook(*args2, **kwargs2):
            try:
                run_original(*args2, **kwargs2)
            except Exception:
                sys.excepthook(*sys.exc_info())

        self.run = run_with_except_hook

    threading.Thread.__init__ = init

It looks like there is a related bug reported here with workarounds. The suggested hacks basically wrap run in a try/catch and then call sys.excepthook(*sys.exc_info())

I just stumbled over this problem and as it turns out, it was the right time to do so.

New in version 3.8: threading.excepthook

Handle uncaught exception raised by Thread.run().

The args argument has the following attributes:

exc_type: Exception type.
exc_value: Exception value, can be None.
exc_traceback: Exception traceback, can be None.
thread: Thread which raised the exception, can be None.

I don't know why, but be aware, that unlike sys.excepthook , threading.excepthook receives the arguments as a namedtuple instead of multiple arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM