利用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)
程序运行结果如下图