Last active
May 26, 2022 14:29
-
-
Save thevickypedia/7c36c1c47bd1413300c012220eb5f820 to your computer and use it in GitHub Desktop.
Handle timeout using context manager and singal (Linux and Darwin)
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 signal | |
import time | |
from contextlib import contextmanager | |
from types import FrameType | |
from typing import Union, NoReturn | |
@contextmanager | |
def timeout(duration: Union[int, float]) -> NoReturn: | |
"""Creates a timeout handler. | |
Args: | |
duration: Takes the duration as an argument. | |
""" | |
def timeout_handler(signum: int, frame: FrameType): | |
"""Raises a TimeoutError. | |
Args: | |
signum: Takes the signal number as an argument. | |
frame: Takes the trigger frame as an argument. | |
Raises: | |
TimeoutError | |
""" | |
raise TimeoutError( | |
f'Block timed out after {duration} seconds\nSignal Number: {signum}\nFrame: {frame}' | |
) | |
signal.signal(signalnum=signal.SIGALRM, handler=timeout_handler) | |
signal.alarm(duration) | |
yield | |
signal.alarm(0) | |
def sleeper(duration: Union[int, float]): | |
start = time.time() | |
time.sleep(duration) | |
print(f'Task Finished in {int(time.time() - start)}s') | |
if __name__ == '__main__': | |
# Test1: Fails with a TimeoutError | |
with timeout(2): | |
try: | |
sleeper(5) | |
except TimeoutError as error: | |
print(error) | |
# Test2: Passes | |
with timeout(5): | |
sleeper(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment