首页 > 解决方案 > concurrent.futures.Executor.map 中的异常处理

问题描述

来自https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.map

如果 func 调用引发异常,则在从迭代器中检索其值时将引发该异常。

以下代码段仅输出第一个异常(异常:1),然后停止。这是否与上述说法相矛盾?我希望以下内容能打印出循环中的所有异常。

def test_func(val):
  raise Exception(val)        

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:   
  for r in executor.map(test_func,[1,2,3,4,5]):
    try:
      print r
    except Exception as exc:
      print 'generated an exception: %s' % (exc)

标签: pythonconcurrencyconcurrent.futures

解决方案


Ehsan 的解决方案很好,但将结果作为完成而不是等待列表中的连续项目完成可能会更有效。这是图书馆文档中的一个示例。

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://some-made-up-domain.com/']

# 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)))

推荐阅读