-
-
Save alecvinent/2eb628732a5cfe8aa6a03d2152c6d3a0 to your computer and use it in GitHub Desktop.
Keyboard input with timeout in Python
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 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!" |
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 = 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 |
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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment