【发布时间】:2019-01-02 16:59:09
【问题描述】:
是否可以在来自concurrent.futures.Executor 的可调用对象中捕获循环引发的异常,例如这样? --
with concurrent.futures.ThreadPoolExecutor(max_workers=num_cores) as executor:
futures = {executor.submit(self._process_ticket, i) for i in items}
concurrent.futures.wait(futures)
我正在尝试遍历列表中的数千个对象以执行任务,并设置多处理以更快地处理它们。这很好用,但是由于我正在处理的对象,在此过程中可能会从for 循环中引发异常,并且因为它被concurrent.futures.Executor 调用,所以我无法以我的方式捕捉它之前就抓到了。
下面是一个简单的示例,说明我之前如何通过序列化过程捕获异常。我必须创建一个解决方法来强制迭代再次尝试处理对象并从该步骤继续向前,因为异常会导致循环停止:
def task(self, items, step=None):
# items = [list,of,many,objects]
try:
for i in range(0 if step is None else step, len(items)):
with app.app_context():
## do things with items[i]..
except Exception as e:
self.task(items, i)
如果循环被异常中断并从该步骤继续循环,我基本上想强制再次处理对象。
【问题讨论】:
标签: python python-3.x concurrency python-multiprocessing