parallel.futures.Executor.map中的异常处理 [英] Exception handling in concurrent.futures.Executor.map

查看:173
本文介绍了parallel.futures.Executor.map中的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 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),然后停止。这是否与上述陈述相抵触?我希望以下内容可以打印出循环中的所有异常。

The following snippet only outptus the first exeption (Exeption: 1), and stops. Does this contradict the above statement? I expect the following to print out all exceptions in the loop.

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)


推荐答案

map 方法返回一个生成器,该生成器允许在准备好结果后对其进行迭代。

The map method returns a generator which allows to iterate through the results once ready.

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

Unfortunately, it is not possible to resume a generator after an exception occurs. From PEP 255.


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

If an unhandled exception-- including, but not limited to, StopIteration --is raised by, or passes through, a generator function, then the exception is passed on to the caller in the usual way, and subsequent attempts to resume the generator function raise StopIteration. In other words, an unhandled exception terminates a generator's useful life.

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

这篇关于parallel.futures.Executor.map中的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆