Created
February 5, 2019 16:50
-
-
Save antonagestam/8e61e6a6bce2bd4f0fb38613b9c628a1 to your computer and use it in GitHub Desktop.
Decorator for time limiting function calls in Python
This file contains 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 multiprocessing | |
import functools | |
import logging | |
from typing import Callable | |
class TimeLimitExceeded(Exception): | |
pass | |
def time_limited(time_limit: int) -> Callable: | |
def decorator(fn: Callable) -> Callable: | |
""" | |
Run the decorated function in a separate process, and kill it after time | |
limit is exceeded. If the time limit is exceeded we raise an exception. | |
""" | |
@functools.wraps(fn) | |
def wrapper(*args, **kwargs): | |
p = multiprocessing.Process(target=fn, args=args, kwargs=kwargs) | |
p.start() | |
p.join(time_limit) | |
if p.is_alive(): | |
logging.error(f"{fn} is still running, terminating ...") | |
try: | |
p.terminate() | |
p.join() | |
finally: | |
raise TimeLimitExceeded( | |
f"{fn.__name__} exceeded time limit of {time_limit} " | |
f"seconds") | |
return wrapper | |
return decorator | |
instant = time_limited(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment