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?
For catching and handling a thread's exception in the caller thread we use a variable that stores the raised exception (if any) in the called thread, and when the called thread is joined, the join function checks whether the value of exc is None, if it is then no exception is generated, otherwise, the generated ...
A lock allows you to force multiple threads to access a resource one at a time, rather than all of them trying to access the resource simultaneously.
A threading. Event object wraps a boolean variable that can either be “set” (True) or “not set” (False). Threads sharing the event instance can check if the event is set, set the event, clear the event (make it not set), or wait for the event to be set.
The condition occurs when one thread tries to modify a shared resource at the same time that another thread is modifying that resource – this leads to garbled output, which is why threads need to be synchronized. The threading module of Python includes locks as a synchronization tool. A lock has two states: locked.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With