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

标签 python concurrency concurrent.futures

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

If a func call raises an exception, then that exception will be raised when its value is retrieved from the iterator.

以下代码片段仅输出第一个异常(异常: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)

最佳答案

Ehsan 的解决方案很好,但在完成时获取结果比等待列表中的顺序项目完成可能稍微更有效。这是来自 library 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)))

关于python - concurrent.futures.Executor.map 中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51071378/

相关文章:

python - 从 concurrent.futures 使用 ThreadPoolExecutor 时的 max_workers 数量?

c - 这个 pthread_cond_wait() 示例如何工作?

java - EIP/Apache Camel - 如何同时处理消息,但按组原子处理?

python - 如何确保 concurrent.futures 迭代器中每个 Future 的超时?

python - [0]*x 语法在 Python 中有什么作用?

haskell - 可靠地等待多个异步?

python - Concurrent.futures - 返回导入模块未定义的错误

python - 我如何处理 pytrends 的结果?

python - scipy.stats 中 cdf 的精度

c# - 在页面上调用 javascript 方法