【问题标题】:concurrent.futures captures all exceptionsconcurrent.futures 捕获所有异常
【发布时间】:2022-11-23 09:20:54
【问题描述】:

我已经将自己编码到一个我不知道如何摆脱的有趣情况中。

我有许多函数在多个并行线程中运行,但是当其中一个线程中抛出异常时,代码继续运行而没有通知

    with concurrent.futures.ThreadPoolExecutor() as executor:
        # queue up the threads for parallel execution
        futureHost.update({executor.submit(infoCatalina, host): host for host in onlineHosts})
        futureHost.update({executor.submit(infoVersion, host): host for host in onlineHosts})
        futureHost.update({executor.submit(infoMount, host): host for host in onlineHosts})
        # go through the threads as they complete
        for _ in concurrent.futures.as_completed(futureHost):
            x = progress(x, progBarLength)

如果我将 1/0 放在 infoVersion 行之前或之后抛出 ZeroDivisionError,则会抛出正确的错误。

        1/0   # will throw an error
        futureHost.update({executor.submit(infoVersion, host): host for host in onlineHosts})
        1/0   # will throw an error

但是,如果我将 1/0 放在 infoVersion() 中,则在抛出错误并且函数退出时我不会收到任何消息。

def infoVersion(host):
    print('This statement prints')
    1/0      # does not throw an error
    print('This statement does not print')

我必须按照上面的方式放置消息,以找出我的代码死在哪里。

我怎样才能让错误再次出现在我的代码中?

【问题讨论】:

    标签: python exception error-handling concurrent.futures


    【解决方案1】:

    异常由 future 对象捕获:

           for future in concurrent.futures.as_completed(futureHost):
               if future.exception() is not None:
                   print(f'ERROR: {future}: {future.exception()}')
                   continue
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-01
      • 2011-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-05
      相关资源
      最近更新 更多