Ask Your Question
2

Catch exception from forked subprocess

asked 2021-07-06 15:10:22 +0100

philipp7 gravatar image

I use fork to give certain methods only a fixed time for execution. These methods might, however, raise an exception and I don't know how to catch these. The code:

@fork
def test() :
    raise ValueError("Found a value error")

try :
    test()
except ValueError :
    print("Value error caught")

does not catch the error. Is there a way to do this?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-07-07 09:50:40 +0100

philipp7 gravatar image

My, not so nice, solution is the following: The idea is that we catch the exception e in the forked process and just return it as the object e. Then, after calling this forked process, we check whether the returned value is in fact an exception. If so, we raise it. Of course this has several drawbacks (what if a function really wants to return an exception? also the traceback gets more complicated) but seems to work okay for me. If anyone has a nicer solution, I would be very interested to learn about it!

def encode_exceptions(func, *args, **kwargs) :
    try :
        ret = func(*args, **kwargs)
        return ret
    except Exception as e:
        return e

def decode_exceptions(ret) :
    if isinstance(ret, Exception) :
        raise ret
    else :
        return ret

def fork_func(func, *args, **kwargs) :
    @fork
    def forked_func():
        return encode_exceptions(func, *args, **kwargs)
    ret = forked_func()
    return decode_exceptions(ret) 

def test() :
    raise ValueError("Found a value error")

print(fork_func(test))
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2021-07-06 15:10:22 +0100

Seen: 329 times

Last updated: Jul 07 '21