Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@Weiqing121 Weiqing121 commented Feb 17, 2017

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

@kumarmuthu

This comment has been minimized.

Copy link

@kumarmuthu kumarmuthu commented Sep 17, 2019

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

@naimurhasan

This comment has been minimized.

Copy link

@naimurhasan 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/

@NisheetNakrani

This comment has been minimized.

Copy link

@NisheetNakrani NisheetNakrani commented May 29, 2021

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

AttributeError: module 'signal' has no attribute 'alarm'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment