Skip to content

Instantly share code, notes, and snippets.

@ninjatrench
Created February 8, 2021 21:37
Show Gist options
  • Save ninjatrench/90134fe0a8467e98a501489062a561e5 to your computer and use it in GitHub Desktop.
Save ninjatrench/90134fe0a8467e98a501489062a561e5 to your computer and use it in GitHub Desktop.
Python timeout user input
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