Keyboard input with timeout?
Using a select call is shorter, and should be much more portable
import sys, selectprint "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!"
The example you have linked to is wrong and the exception is actually occuring when calling alarm handler instead of when read blocks. Better try this:
import signalTIMEOUT = 5 # number of seconds your want for timeoutdef 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 alarmsignal.alarm(TIMEOUT)s = input()# disable the alarm after successsignal.alarm(0)print 'You typed', s
Not a Python solution, but...
I ran in to this problem with a script running under CentOS (Linux), and what worked for my situation was just running the Bash "read -t" command in a subprocess. Brutal disgusting hack, I know, but I feel guilty enough about how well it worked that I wanted to share it with everyone here.
import subprocesssubprocess.call('read -t 30', shell=True)
All I needed was something that waited for 30 seconds unless the ENTER key was pressed. This worked great.