python之获取子线程异常信息

在这里插入图片描述

import queue
import sys
import threading
class ExcThread(threading.Thread):
    def __init__(self, bucket):
        super(ExcThread, self).__init__()
        self.bucket = bucket

    def run(self):
        try:
            raise Exception('thread error!!!')
        except Exception:
            # 异常信息元祖放入队列传递给父进程
            self.bucket.put(sys.exc_info())


def main():

    bucket = queue.Queue()
    thread_obj = ExcThread(bucket)
    thread_obj.start()

    # 循环获取子线程的异常信息
    while 1:
        try:
            exc = bucket.get(block=False)
        except queue.Empty:
            pass
        else:
            exc_type, exc_obj, exc_trace = exc
            # deal with the exception
            print(exc_type, exc_obj)
            print(exc_trace)

        # 防止阻塞
        thread_obj.join(0.2)
        if thread_obj.is_alive():
            continue
        else:
            break





# main函数:
if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/qq_45662588/article/details/127230557