Skip to content

Instantly share code, notes, and snippets.

@atupal
Created June 26, 2013 06:36
Show Gist options
  • Save atupal/5865237 to your computer and use it in GitHub Desktop.
Save atupal/5865237 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
@Weiqing121
Copy link

In the signal_input.py, need to raise the exception in the interrupted() function.

@kumarmuthu
Copy link

Thank you so much this logic is works fine on python 3 with syntax modification.

@naimurhasan
Copy link

naimurhasan commented Sep 14, 2020

A NEW LIBRARRY HAS POPPED UP! Although to avoid dependency issue I will stick with the first example.

https://pypi.org/project/inputimeout/

@Nisheet-Patel
Copy link

I don't know why but I get this error for signal_input.py

AttributeError: module 'signal' has no attribute 'alarm'

@yash9904
Copy link

In signal_input.py, It shows the following error: [WinError 10038] An operation was attempted on something that is not a socket.

@Dannydorestant
Copy link

I don't know why but I get this error for signal_input.py

AttributeError: module 'signal' has no attribute 'alarm'

I got this error too, figure it out?

@kumarmuthu
Copy link

Please check the signal package, whether it is supported for windows or not. Linux support this package.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment