在Python中重写threading.excepthook的正确方法是什么?

在Python中重写threading.excepthook的正确方法是什么?,python,multithreading,inheritance,exception,overloading,Python,Multithreading,Inheritance,Exception,Overloading,我试图处理运行线程时发生的未捕获异常。位于的python文档声明“threading.excepthook()可以被重写,以控制如何处理由Thread.run()引发的未捕获异常。”但是,我似乎无法正确执行此操作。我的excepthook函数似乎从未被执行过。正确的方法是什么 import threading import time class MyThread(threading.Thread): def __init__(self, *args, **kwargs): supe

我试图处理运行线程时发生的未捕获异常。位于的python文档声明“
threading.excepthook()
可以被重写,以控制如何处理由
Thread.run()
引发的未捕获异常。”但是,我似乎无法正确执行此操作。我的
excepthook
函数似乎从未被执行过。正确的方法是什么

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)

threading.excepthook
是属于
threading
模块的函数,而不是
threading.Thread
类的方法,因此您应该使用自己的函数重写
threading.excepthook

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)