【问题标题】:Catching exceptions in a multiprocessing loop在多处理循环中捕获异常
【发布时间】: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


    【解决方案1】:

    没关系,几天前就知道了。不确定这是否是完成这项工作的最佳/推荐方式,但似乎可以完成工作:

    with concurrent.futures.ThreadPoolExecutor(max_workers=num_cores) as executor:
        try:
            for i in range(step, len(items)):
                futures = {executor.submit(self.task, items[i])}
        except:
            self.task(items, i)
    
        concurrent.futures.wait(futures)
    

    仍然欢迎建议/建议

    【讨论】:

      猜你喜欢
      • 2017-05-08
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多