python - 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)
解决方案
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)))
推荐阅读
- java - MultipartUpload 多个文件的附加信息
- python - 与 SIFT 匹配后如何应用 Delaunay 变换
- json - 如何在 Flutter 中初始化现有模型中的新变量
- swift - 以编程方式禁用标签栏故事板外观设置
- generics - 如何制作可以表现得像整数的自定义结构
- python - print(range(…)) 语句输出是“range(…)”而不是整数值
- traefik - 带有 Traefik 的码头软件
- ios - iOS:带有视频的神经风格迁移
- django - Django DurationField 和 00:00:00 与 NULL
- javascript - 正则表达式:如何跨多行/段落捕获“字符串”(字符串末尾可能有“锚”)