Python 获取线程中的异常信息
通常情况下我们无法将多线程中的异常带回主线程,所以也就无法打印线程中的异常,而通过traceback模块,我们可以对线程做如下修改,从而实现捕获线程异常的目的1。 import threading import traceback def my_func(): raise BaseException("thread exception") class ExceptionThread(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): """ Redirect exceptions of thread to an exception handler. """ threading.Thread.__init__(self, group, target, name, args, kwargs, verbose) if kwargs is None: kwargs = {} self._target = target self._args = args self._kwargs = kwargs self._exc = None def run(self): try: if self._target: self._target() except BaseException as e: import sys self._exc = sys....