我试图在Windows 7上使用Python 3.6中的ThreadPoolExecutor
,但似乎异常被静默忽略或停止程序执行。以下是示例代码:
#!/usr/bin/env python3
from time import sleep
from concurrent.futures import ThreadPoolExecutor
EXECUTOR = ThreadPoolExecutor(2)
def run_jobs():
EXECUTOR.submit(some_long_task1)
EXECUTOR.submit(some_long_task2, 'hello', 123)
return 'Two jobs was launched in background!'
def some_long_task1():
print("Task #1 started!")
for i in range(10000000):
j = i + 1
1/0
print("Task #1 is done!")
def some_long_task2(arg1, arg2):
print("Task #2 started with args: %s %s!" % (arg1, arg2))
for i in range(10000000):
j = i + 1
print("Task #2 is done!")
if __name__ == '__main__':
run_jobs()
while True:
sleep(1)
输出结果:
Task #1 started!
Task #2 started with args: hello 123!
Task #2 is done!
我要按下Ctrl+C才能终止它的运行。
然而,当我从some_long_task1
函数中移除1/0
的代码时,任务#1就可以正常完成:
Task #1 started!
Task #2 started with args: hello 123!
Task #1 is done!
Task #2 is done!
我需要以某种方式捕获在运行于 ThreadPoolExecutor
中的函数引发的异常。
Python 3.6(Minconda),Windows 7 x64。