Function Timeout in Python

In some code I’m working on I want to put a 10 second timeout on a function call. If the function doesn’t return in 10 seconds I just want to terminate the function and return None. Here’s the code I came up with using multiprocessing.Pool:

import multiprocessing as mp

pool = mp.Pool(1, maxtasksperchild=1)
result = pool.apply_async(function, (arg1,))

    s = result.get(10)
except mp.TimeoutError:
    return None

This seems to work but I’m curious if there’s a standard Python pattern for this sort of thing?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s