Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using contextlib+signals to make a with timeout with statement
import signal
from contextlib import contextmanager
class TimeOutError(RuntimeError):pass
@contextmanager
def timeout(duration):
def timeout_handler(signum, frame):
raise TimeOutError()
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(duration)
try:
yield None
except TimeOutError:pass
finally:
signal.alarm(0)
u=None
with timeout(1):
u=input("high five:")
if u==None:
print("\npsyche")
else:
print("wow, nice")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment