线程中的异常处理
concurrent.futures — 启动并行任务 — Python 3.13.0 文档
from concurrent.futures import ThreadPoolExecutor
def task():
a = 1 / 0
print('任务执行中...')
with ThreadPoolExecutor(max_workers=5) as t:
for i in range(10):
worker = t.submit(task)
没有任任何打印, 有任务中的异常被吃掉了
打印线程中异常信息堆栈
from concurrent.futures import ThreadPoolExecutor
def task():
a = 1 / 0
print('任务执行中...')
def callback(future):
print('任务执行完毕')
# 打印异常信息
print(future.exception()) # division by zero
# 打印异常信息堆栈
future.result()
with ThreadPoolExecutor(max_workers=5) as t:
for i in range(10):
future = t.submit(task)
future.add_done_callback(callback)
处理线程中执行的异常
from concurrent.futures import ThreadPoolExecutor
def task():
a = 1 / 0
print('任务执行中...')
def callback(future):
print('任务执行完毕')
try:
future.result()
except Exception as e:
print("处理线程中执行的异常", e)
pass
with ThreadPoolExecutor(max_workers=5) as t:
for i in range(10):
future = t.submit(task)
future.add_done_callback(callback)
根据线程任务返回结果判断是否继续新增线程
from concurrent.futures import ThreadPoolExecutor
def task(pages):
for page in pages:
print('任务', page)
# 假设 第33页是最后一页
if page >= 33:
return True
def main():
with ThreadPoolExecutor(max_workers=10) as t:
# 根据任务返回结果判断是否继续新增线程
# 场景: 有个未知总页数的任务, 每次线程任务执行10页, 当任务返回结果为True时, 任务结束
over = False
page = 0
jump = 10
def callback(future):
nonlocal over
res = future.result()
print('任务返回结果', res)
if res:
print("任务结束")
over = True
while not over:
pages = list(range(page, page + jump))
f = t.submit(task, pages)
f.add_done_callback(callback)
page += jump
if __name__ == '__main__':
main()
多个参数的任务
from concurrent.futures import ThreadPoolExecutor
def task(a, b):
print(a, b)
def main():
with ThreadPoolExecutor(max_workers=10) as t:
for i in range(10):
t.submit(task, i, i * i)
if __name__ == '__main__':
main()
(max_workers=10) as t:
for i in range(10):
t.submit(task, i, i * i)
if name == ‘main’:
main()