Created
May 31, 2020 15:03
-
-
Save pvsune/79a3125375e2f1ea4e68618f8f063b8c to your computer and use it in GitHub Desktop.
A helper function to limit execution of a function in seconds.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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