Python: assert 没有打印出错误信息

Python: assert does not print out error message

我在多线程环境中使用断言来帮助我发现早期错误。但事实证明,当断言失败时,python3.7 只是静默终止,而没有打印我想看到的错误消息。感谢您提前提供帮助。

示例代码如下:

from concurrent.futures import ThreadPoolExecutor
import threading
import random
from time import sleep
def task():
    assert False, "no assertion output, why?"
    print("Executing our Task")
    sleep(5)
    result = 0
    i = 0
    for i in range(10):
        result = result + i
    print("I: {}".format(result))
    print("Task Executed {}".format(threading.current_thread()))

if __name__ == '__main__':
    executor = ThreadPoolExecutor(max_workers=3)
    task1 = executor.submit(task,1)
    task2 = executor.submit(task,1)
    #task(), directly calling and the assertion failure message will be printed out.

我运行它使用命令python3.7 test.py

我认为我以错误的方式使用了 python 断言,因为我认为它是 c++ 中的断言函数。如果我将断言更改为抛出异常,则上面的代码也不会打印出来。我应该捕捉异常吗?

顺便说一句,直接调用它,虽然会显示断言失败消息。

问题是您正在检索期货(将 return 值分配给 task1task2),但没有对它们进行任何操作。尝试这样的事情。

for future in futures.as_completed([task1, task2]):
    if future.exception() is not None
        # Process the results here.

这将删除您当前拥有的种族。