0

I use to run long independent jobs with multiprocessing.Pool.map

import multiprocessing
pool = multiprocessing.Pool(multiprocessing.cpu_count())
input_var = [1,2,3]
ris = pool.map(long_function,input_var)
pool.close()
pool.join()

This works well but if for example I get an error in long_function(2) I will lose all the information that I have obtained with long_function(1) and long_function(3).

is there a way to avoid this?

The best would be to obtain an output like ris=[long_function(1), ERROR, long_function(3)] Is there anyway to do that?

1 Answer 1

2
def safe_long_function(*args, **kwargs):
    try:
        return long_function(*args, **kwargs)
    except Exception as e:
        return e

You basically want to catch the exceptions thrown and then return them rather than raise them. For example

def long_function(x):
    if x == 2:
        raise Exception("This number is even")

import multiprocessing
pool = multiprocessing.Pool() # default is num CPUs
input_var = [1,2,3]
ris = pool.map(safe_long_function, input_var)
pool.close()
pool.join()

print ris

This will give [1, Exception("This number is even"), 3]

You can then do something like

for result in ris:
    if isinstance(result, Exception):
        print "Error: %s" % result
    else:
        print result
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.