import signal
import time
from contextlib import contextmanager
@contextmanager
def timeout_after(seconds: int):
# Register a function to raise a TimeoutError on the signal.
signal.signal(signal.SIGALRM, raise_timeout)
# Schedule the signal to be sent after `seconds`.
signal.alarm(seconds)
try:
yield
finally:
# Unregister the signal, so it won't be triggered if the timeout is not reached.
signal.signal(signal.SIGALRM, signal.SIG_IGN)
def raise_timeout(_, __):
raise TimeoutError
# Used as such:
@timeout_after(3)
def hello():
time.sleep(5)
print("hello")
if __name__ == '__main__':
with timeout_after(3):
time.sleep(5)
# hello()
# time.sleep(10)