【发布时间】:2021-12-23 21:32:33
【问题描述】:
使用 Python 多处理我想捕获进程丢弃它们并继续下一个进程。
在下面的示例中,我有一个 1 和 0 的列表作为输入。 0 将启动睡眠功能以触发超时错误。触发超时的进程会重新执行,因此脚本将永远运行。
如何捕获 TimeOut 错误、终止导致该错误的进程并防止该进程重新执行?重要的是我可以使用 imap 做到这一点。
import time
import multiprocessing as mp
def a_func(x):
print(x)
if x:
return x
# Function sleeps before returning
# to trigger timeout error
else:
time.sleep(2.0)
return x
if __name__ == "__main__":
solutions = []
# Inputs sum to 4
inputs = [1, 1, 0, 1, 1, 0]
with mp.get_context("spawn").Pool(1) as pool:
futures_res = pool.imap(a_func, inputs)
idx = 0
for s in (inputs):
try:
res = futures_res.next(timeout=0.1)
# If successful (no time out), append the result
solutions.append(res)
except mp.context.TimeoutError:
print(s, "err")
# Catch time out error
# I want this to also prevent the process from being executed again
# solutions.append(0.0)
# Should print 4
print(len(solutions))
print(solutions)
【问题讨论】:
标签: python python-3.x multiprocessing