ThreadpoolExecutor处理task执行异常

文章讲述了在使用Python的concurrent.futures.ThreadPoolExecutor进行多线程任务执行时,如何通过future对象来检测并处理任务异常。当任务出现异常,不会自动抛出,需要通过future.exception()或future.result()检查。文章还提到了异常捕获后的两种重试策略:重新提交任务和保存失败任务参数以备后续重新执行。
摘要由CSDN通过智能技术生成

背景

日常开发中使用线程池时,发现线程池里的任务异常中断/失败是不会打印错误信息的,导致结果异常还不知道发生什么

原因

ThreadpoolExecutor线程池提交作业后,worker不会主动抛出异常。需要通过future对象的resultexceptionThreadpoolExecutor 对象submit()方法提交任务后后返回future对象。任务提交完后,得到future对象列表/字典*fn,通过futures.as_compose(*fn)遍历线程池中完成的task

future.expcection

遍历完成的task也就是future对象,通过 future.exception 是否为空判断该任务是否有异常信息。

import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://nonexistant-subdomain.python.org/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        if future.exception() is not None:
        	print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))
future.result

遍历完成的task也就是future对象,通过try except判断 future.result() 线程的执行结果是否异常。

import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://nonexistant-subdomain.python.org/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))
异常重试
  1. 捕获异常后,重新提交任务
....
for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            executor.sumbit(load_url, url)
        else:
            print('%r page is %d bytes' % (url, len(data)))
  1. 捕获异常后,把失败task的入参保存重新执行
pending_message = []
for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            pending_message.append(url)
        else:
            print('%r page is %d bytes' % (url, len(data)))
            
futures = [executor.sumbit(load_url, url) for url in pending_message]

参考文档:concurrent.futures - python 中文文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
ThreadPoolExecutorPython中的一个线程池实现,它可以用于管理和调度多个线程执行任务。当线程池中的线程执行任务时,如果任务异常,我们可以通过以下几种方式获取异常信息: 1. 使用submit()方法提交任务并返回一个Future对象,通过调用Future对象的result()方法获取任务执行的结果。如果任务异常,result()方法会将异常重新出,我们可以使用try-except语句捕获并处理异常。 ```python import concurrent.futures def task(): # 任务逻辑 raise Exception("Something went wrong") with concurrent.futures.ThreadPoolExecutor() as executor: future = executor.submit(task) try: result = future.result() except Exception as e: print("Exception:", e) ``` 2. 使用add_done_callback()方法注册一个回调函数,在任务执行完成后自动调用该函数。回调函数的参数是一个Future对象,我们可以通过调用Future对象的exception()方法获取任务执行过程中出的异常信息。 ```python import concurrent.futures def task(): # 任务逻辑 raise Exception("Something went wrong") def handle_exception(future): try: result = future.result() except Exception as e: print("Exception:", e) with concurrent.futures.ThreadPoolExecutor() as executor: future = executor.submit(task) future.add_done_callback(handle_exception) ``` 这样,当任务执行完成后,handle_exception()函数会被自动调用,并且可以获取到任务执行过程中出的异常信息。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值