python主线程捕获子线程异常

python内置threading.Thread类创建的子线程抛出的异常无法在主线程捕获,可以对该类进行优化,为子线程添加exit code属性,主线程通过获取子线程的返回状态,来判断子线程中是否发生了异常。

import threading
from traceback import format_exc

class ExcThread(threading.Thread):
    def __init__(self,targte, args, kwargs):
        super(ExcThread, self).__init__()
        self.function = target
        self.args = args
        self.kwargs = kwargs
        self.exit_code = 0
        self.exception = None
        self.exc_traceback = ''

    def run(self):
        try:
            self._run()
        except Exception as e:
            self.exit_code = 1
            self.exception = e
            self.exc_traceback = format_exc()

    def _run(self):
        try:
            self.function(*self.args, **self.kwargs)
        except Exception as e:
            raise e


def test_fn():
    raise Exception('test error')


t = ExcThread(target=test_fn, args=(), kwargs = {})
t.start()
t.join()
if t.exit_code != 0:
    raise t.exception

 

posted @ 2021-02-01 16:50  zcsh  阅读(2688)  评论(0编辑  收藏  举报