concurrent.futures.Executor.map 中的异常处理

use*_*636 17 python concurrency concurrent.futures

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

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

以下代码段仅输出第一个例外 (Exeption: 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)
Run Code Online (Sandbox Code Playgroud)

lea*_*eal 14

Ehsan 的解决方案很好,但在完成时获取结果而不是等待列表中的顺序项目完成可能会更有效。这是库 docs 中的一个示例。

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)))
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的精彩解释 (2认同)

Ehs*_*Kia 10

如上所述,不幸的是 executor.map 的 API 是有限的,只能让您获得第一个异常。此外,在迭代结果时,您只会获得第一个异常的值。

要回答您的问题,如果您不想使用不同的库,您可以展开地图并手动应用每个功能:

future_list = []
with concurrent.futures.ThreadPoolExecutor() as executor:
  for arg in range(10):
    future = executor.submit(test_func, arg)
    future_list.append(future)

for future in future_list:
  try:
    print(future.result())
  except Exception as e:
    print(e)
Run Code Online (Sandbox Code Playgroud)

这允许您单独处理每个未来。


Ten*_*rye 6

尽管其他人对于捕获多个异常的正确方法给出了很好的答案,但我想回答为什么问题中捕获异常的方法是错误的。以下片段:

class ExceptionA(Exception):
    pass


def test_func(val):
    raise ExceptionA(val)


with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    try:
        for r in executor.map(test_func, [1, 2, 3, 4, 5]):
            try:
                print(r)
            except ExceptionA as exc:
                print(f'Catch inside: {exc}')

    except ExceptionA as exc:
        print(f'Catch outside: {exc}')
Run Code Online (Sandbox Code Playgroud)

给出输出Catch outside: 1.

python 文档如下:

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

这意味着如果您想捕获异常,则需要在循环之外捕获它,因为该值是在循环语句而不是打印语句中检索的。


nox*_*fox 5

map方法返回一个生成器,它允许在准备好后迭代结果。

不幸的是,发生异常后无法恢复生成器。来自PEP 255

如果未处理的异常——包括但不限于 StopIteration——由生成器函数引发或通过,则异常以通常的方式传递给调用者,并随后尝试恢复生成器函数引发停止迭代。换句话说,未处理的异常会终止生成器的使用寿命。

还有其他库,例如pebble允许在发生错误后继续迭代。检查文档中的示例