Python ThreadPoolExecutor 异常打印

利用ThreadPoolExecutor提交线程任务的时候,在线程里面发生异常,不会被主线程所捕抓,而是消无声息地死亡,非常不便于调试,尤其在我们写gui程序的时候。

我们可以新增一条线程帮我们把异常打印出来。

import time, traceback
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures._base import TimeoutError
from click import echo, style

pool = ThreadPoolExecutor(max_workers=3)
task_queue = []


def print_thread_pool_exception(tq):
    while True:
        if len(tq) > 0:
            for task in tq:
                try:
                    e = task.exception(timeout=0.1)
                    if e:
                        tq.remove(task)
                        raise e
                except TimeoutError:
                    pass
                except Exception:
                    echo(style(traceback.format_exc(), fg='red'))
                    echo(style("提示:程序遇到错误了,让程序作者给解决吧,以上是错误堆栈信息", fg='red'))

def pp(tag):
    for i in range(6):
        time.sleep(1)
        print("{}_{}".format(i, tag))
        if i == 4:
            raise Exception("测试")


task_queue.append(pool.submit(print_thread_pool_exception, task_queue))
task_queue.append(pool.submit(pp, "A"))
task_queue.append(pool.submit(pp, "B"))
task_queue.append(pool.submit(pp, "C"))
task_queue.append(pool.submit(pp, "D"))

time.sleep(50)

程序运行结果如下图
在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值