Ankur Agarwal
Ankur Agarwal

Reputation: 24778

Using multiprocessing.Pool with exception handling

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()

Consider this contrived example where I am creating a process pool of 4 workers and assigning work in f(). My question was:

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) ?

As is the code just gives me:

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

Upvotes: 3

Views: 4319

Answers (2)

jayflo
jayflo

Reputation: 1115

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)

Upvotes: 3

noxdafox
noxdafox

Reputation: 15060

You can use the imap function.

iterator = p.imap(f, (1,2,3,4,5))

while True:
    try:
        print next(iterator)
    except StopIteration:
        break
    except Exception as error:
        print error

Upvotes: 2

Related Questions