I'd like to get input on the terminal and give only a few seconds to respond. When the timeout is reached I'd like to read whatever has been typed in an accept that as the given input. Optionally I'd like the user to be able to press "enter" to submit their answer early.
I have the code below which works ok, but requires the user to press "enter" to submit. It has a bug: Entering text and then waiting for the timeout keeps the text in the "buffer". Then when you get prompted again you enter different text, press enter and then both strings are printed (see output). When the timeout is reached I'd like to accept whatever has been typed as "the answer." I'd like the user to still be able to submit an answer faster by pressing "enter".
Is there a way to achieve the desired behavior?
Note: I'm using Mac OS X
import sys
from select import select
def getResponse(timeout):
print "Enter something:"
rlist, wlist, xlist = select([sys.stdin], [], [], timeout)
if rlist:
result = sys.stdin.readline()
return result
else:
return ''
while True:
response = getResponse(3)
print "Your input is:", response
Output:
Enter something:
pythonYour input is:
Enter something:
dangit
Your input is: pythondangit