Skip to content

Instantly share code, notes, and snippets.

@giuliano-macedo
Created October 7, 2020 22:25
Show Gist options
  • Save giuliano-macedo/2191a1099d2cac32e106c8f92c2e0adb to your computer and use it in GitHub Desktop.
Save giuliano-macedo/2191a1099d2cac32e106c8f92c2e0adb to your computer and use it in GitHub Desktop.
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