Skip to content

Instantly share code, notes, and snippets.

@pvsune
Created May 31, 2020 15:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pvsune/79a3125375e2f1ea4e68618f8f063b8c to your computer and use it in GitHub Desktop.
Save pvsune/79a3125375e2f1ea4e68618f8f063b8c to your computer and use it in GitHub Desktop.
A helper function to limit execution of a function in seconds.
import logging
from multiprocessing import Pool, TimeoutError
logging.basicConfig(level=logging.INFO)
def timeout(func, args=None, kwds=None, timeout=10):
"""Call function and wait until timeout.
Cannot make into a decorator, fails in pickling function.
"""
args = args or []
kwds = kwds or {}
with Pool(processes=1) as pool:
res = pool.apply_async(func, args, kwds)
try:
return res.get(timeout)
except TimeoutError:
logging.exception(
'Calling %s%s timed out after %ss',
func.__name__, tuple(args), timeout
)
raise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment