Skip to content

Instantly share code, notes, and snippets.

@thevickypedia
Last active May 26, 2022 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thevickypedia/7c36c1c47bd1413300c012220eb5f820 to your computer and use it in GitHub Desktop.
Save thevickypedia/7c36c1c47bd1413300c012220eb5f820 to your computer and use it in GitHub Desktop.
Handle timeout using context manager and singal (Linux and Darwin)
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