在Python中重写threading.excepthook的正确方法是什么?
我试图处理运行线程时发生的未捕获异常。位于的python文档声明“在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
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)