0
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()分配工作考慮這個人爲的例子。我的問題是:使用multiprocessing.Pool與異常處理

我怎樣才能檢索到這是對參數進行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 

回答

1

可以使用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