Skip to content

Instantly share code, notes, and snippets.

@erikson1970
Forked from atupal/select_input.py
Last active October 8, 2018 21:12
Show Gist options
  • Save erikson1970/6794349437ddd053934293b5b812f84e to your computer and use it in GitHub Desktop.
Save erikson1970/6794349437ddd053934293b5b812f84e to your computer and use it in GitHub Desktop.
Keyboard input with timeout in Python
import sys, select
print "You have ten seconds to answer!"
i, o, e = select.select( [sys.stdin], [], [], 10 )
if (i):
print "You said", sys.stdin.readline().strip()
else:
print "You said nothing!"
import signal
TIMEOUT = 5 # number of seconds your want for timeout
def interrupted(signum, frame):
"called when read times out"
print 'interrupted!'
signal.signal(signal.SIGALRM, interrupted)
def input():
try:
print 'You have 5 seconds to type in your stuff...'
foo = raw_input()
return foo
except:
# timeout
return
# set alarm
signal.alarm(TIMEOUT)
s = input()
# disable the alarm after success
signal.alarm(0)
print 'You typed', s
import threading, msvcrt
import sys
def readInput(caption, default, timeout = 5):
class KeyboardThread(threading.Thread):
def run(self):
self.timedout = False
self.input = ''
while True:
if msvcrt.kbhit():
chr = msvcrt.getche()
if ord(chr) == 13:
break
elif ord(chr) >= 32:
self.input += chr
if len(self.input) == 0 and self.timedout:
break
sys.stdout.write('%s(%s):'%(caption, default));
result = default
it = KeyboardThread()
it.start()
it.join(timeout)
it.timedout = True
if len(it.input) > 0:
# wait for rest of input
it.join()
result = it.input
print '' # needed to move to next line
return result
# and some examples of usage
ans = readInput('Please type a name', 'john')
print 'The name is %s' % ans
ans = readInput('Please enter a number', 10 )
print 'The number is %s' % ans
import signal
import sys, select
def GetInputWithSignal(TIMEOUT=10):
print "running GetInputWithSignal"
#TIMEOUT = 5 # number of seconds your want for timeout
def interrupted(signum, frame):
"called when read times out"
print 'interrupted!'
signal.signal(signal.SIGALRM, interrupted)
def input():
try:
print 'You have 5 seconds to type in your stuff...'
foo = raw_input()
return foo
except:
# timeout
return
# set alarm
signal.alarm(TIMEOUT)
s = input()
# disable the alarm after success
signal.alarm(0)
print 'You typed', s
def GetInputWithSelect():
print "You have ten seconds to answer!"
i, o, e = select.select( [sys.stdin], [], [], 10 )
if (i):
print "You said", sys.stdin.readline().strip()
else:
print "You said nothing!"
def prompt_with_timeout(timeout=10):
from time import sleep
print "running prompt_with_timeout"
Intd=False
inputSTR="MT"
while inputSTR!="DONE":
print('Waiting %d secs... please press Ctrl-C when you wish to proceed.'%timeout)
try:
for i in range(0, timeout): # 30 minutes is 30*60 seconds
sleep(1)
print("Oops, sorry, no input was received today. Come back tomorrow.")
inputSTR="DONE"
except KeyboardInterrupt:
print "...interrupted..."
inputSTR = raw_input("Time to log the daily weigh-in! How much today? ['DONE' exits] ")
print ("Thanks for logging: " + inputSTR)
# sys.stdout.write("\n")
# sys.stdout.flush()
# Intd=True
# if Intd:
return inputSTR
def catch_keyboard_int():
import time,sys
print "running catch_keyboard_int"
try:
while True: time.sleep(1)
except KeyboardInterrupt:
sys.stdout.write("\n")
sys.stdout.flush()
if __name__ == '__main__':
prompt_with_timeout()
GetInputWithSignal()
# catch_keyboard_int()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment