gpt4 book ai didi

Python ThreadPoolExecutor 抑制异常

转载 作者:行者123 更新时间:2023-12-02 01:18:42 30 4
gpt4 key购买 nike

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED


def div_zero(x):
print('In div_zero')
return x / 0


with ThreadPoolExecutor(max_workers=4) as executor:
futures = executor.submit(div_zero, 1)

done, _ = wait([futures], return_when=ALL_COMPLETED)
# print(done.pop().result())

print('Done')

上面的程序将运行完成,不会出现任何错误消息。

只有显式调用 future.result()future.exception() 才能获得异常,就像我在注释掉的行中所做的那样。

我想知道为什么这个 Python 模块选择这种行为,即使它隐藏了问题。因此,我花了几个小时调试编程错误(引用类中不存在的属性),如果程序只是因异常而崩溃(例如 Java),那么该错误将非常明显。

最佳答案

我怀疑原因是整个池不会因为一个线程引发异常而崩溃。这样,池将处理所有任务,如果需要,您可以单独获取引发异常的线程。

关于Python ThreadPoolExecutor 抑制异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56075434/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com