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,))
pool.close()

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

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

Function Timeout in Python

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.