Created
October 7, 2020 22:25
-
-
Save giuliano-macedo/2191a1099d2cac32e106c8f92c2e0adb to your computer and use it in GitHub Desktop.
using contextlib+signals to make a with timeout with statement
This file contains hidden or 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 | |
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