在 Python 中覆盖 threading.excepthook 的正确方法是什么?
What is the proper way to override threading.excepthook in Python?
我正在尝试处理 运行 线程时发生的未捕获异常。 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)
threading.excepthook
是属于threading
模块的函数,不是threading.Thread
class的方法,所以你应该覆盖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)
我正在尝试处理 运行 线程时发生的未捕获异常。 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)
threading.excepthook
是属于threading
模块的函数,不是threading.Thread
class的方法,所以你应该覆盖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)