from multiprocessing import Pool
def f(arg):
if arg == 1:
raise Exception("exception")
return "hello %s" % arg
p = Pool(4)
res = p.map_async(f,(1,2,3,4))
p.close()
p.join()
res.get()
考虑这个人为的例子,我正在创建一个由 4 个工作人员组成的进程池,并在 f()
中分配工作。我的问题是:
如何检索对参数 2、3、4 完成的成功工作(同时对参数 1 进行异常处理)?
代码只是给我:
Traceback (most recent call last):
File "process_test.py", line 13, in <module>
res.get()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py", line 567, in get
raise self._value
Exception: exception
最佳答案
您也可以只在工作函数中进行错误处理
def do_work(x):
try:
return (None, something_with(x))
except Exception as e:
return (e, None)
output = Pool(n).map(do_work, input)
for exc, result in output:
if exc:
handle_exc(exc)
else:
handle_result(result)
关于python-2.7 - 将 multiprocessing.Pool 与异常处理结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44814142/