使用 multiprocessing.Pool 进行异常处理 [英] Using multiprocessing.Pool with exception handling
本文介绍了使用 multiprocessing.Pool 进行异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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()
中分配工作.我的问题是:
Consider this contrived example where I am creating a process pool of 4 workers and assigning work in f()
. My question was:
如何检索为参数 2、3、4 完成的成功工作(同时对参数 1 进行异常处理)?
How can I retrieve the successful work that was done for arguments 2,3,4 (and at the same time do exception handling for argument 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
推荐答案
你也可以只做工作函数中的错误处理
You can also just do the error handling in the work function
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)
这篇关于使用 multiprocessing.Pool 进行异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文