bl5*_*yce 5 python inheritance multithreading overloading exception
我正在尝试处理运行线程时发生的未捕获异常。docs.python.org 上的 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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)