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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM