Created
February 8, 2021 21:37
-
-
Save ninjatrench/90134fe0a8467e98a501489062a561e5 to your computer and use it in GitHub Desktop.
Python timeout user input
This file contains 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 | |
TIMEOUT = 2 # number of seconds your want for timeout | |
import sys | |
flag = 0 | |
def interrupted(signum, frame): | |
"called when read times out" | |
#raise RuntimeError() | |
sys.exit(1) | |
signal.signal(signal.SIGALRM, interrupted) | |
def som(): | |
print("insome") | |
def input(): | |
try: | |
print 'You have 2 seconds to type in your stuff...' | |
foo = raw_input() | |
return foo | |
except: | |
# timeout | |
return | |
import time | |
# set alarm | |
signal.alarm(TIMEOUT) | |
# disable the alarm after success | |
time.sleep(2) | |
signal.alarm(0) | |
print("ok") | |
som() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment