Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to override threading.excepthook in Python?

I am trying to handle uncaught exceptions that occur when I run a thread. The python documentation at docs.python.org states that "threading.excepthook() can be overridden to control how uncaught exceptions raised by Thread.run() are handled." However, I can't seem to do it properly. It doesn't appear that my excepthook function is ever excecuted. What is the correct way to do this?

import threading
import time

class MyThread(threading.Thread):
  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

  def excepthook(self, *args, **kwargs):
    print("In excepthook")

def error_soon(timeout):
  time.sleep(timeout)
  raise Exception("Time is up!")

my_thread = MyThread(target=error_soon, args=(3,))
my_thread.start()
time.sleep(7)
like image 414
bl5eebryce Avatar asked Apr 09 '20 18:04

bl5eebryce


People also ask

How do you override a thread in Python?

Given the Python documentation for Thread. run() : You may override this method in a subclass. The standard run() method invokes the callable object passed to the object's constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

How does Python handle thread exception?

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 ...

How do you stop a thread from threading in Python?

Using a hidden function _stop() : In order to kill a thread, we use hidden function _stop() this function is not documented but might disappear in the next version of python.


1 Answers

threading.excepthook is a function that belongs to the threading module, not a method of the threading.Thread class, so you should override threading.excepthook instead with your own function:

import threading
import time

def excepthook(args):
    print("In excepthook")

threading.excepthook = excepthook

class MyThread(threading.Thread):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

def error_soon(timeout):
    time.sleep(timeout)
    raise Exception("Time is up!")

my_thread = MyThread(target=error_soon, args=(3,))
my_thread.start()
time.sleep(7)
like image 113
blhsing Avatar answered Oct 04 '22 01:10

blhsing