Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 440
Ankur Agarwal Avatar asked Nov 27 '25 23:11

Ankur Agarwal


2 Answers

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)
like image 98
jayflo Avatar answered Nov 30 '25 23:11

jayflo


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
like image 33
noxdafox Avatar answered Dec 01 '25 01:12

noxdafox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!