【问题标题】:Using multiprocessing.Pool with exception handling使用带有异常处理的 multiprocessing.Pool
【发布时间】:2017-12-02 12:08:52
【问题描述】:
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

【问题讨论】:

    标签: python-2.7 process parallel-processing multiprocessing pool


    【解决方案1】:

    你也可以只在工作函数中做错误处理

    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)
    

    【讨论】:

      【解决方案2】:

      您可以使用imap 函数。

      iterator = p.imap(f, (1,2,3,4,5))
      
      while True:
          try:
              print next(iterator)
          except StopIteration:
              break
          except Exception as error:
              print error
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-15
        • 1970-01-01
        • 2013-07-10
        • 2013-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多