Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyboard input with timeout?

How would you prompt the user for some input but timing out after N seconds?

Google is pointing to a mail thread about it at http://mail.python.org/pipermail/python-list/2006-January/533215.html but it seems not to work. The statement in which the timeout happens, no matter whether it is a sys.input.readline or timer.sleep(), I always get:

<type 'exceptions.TypeError'>: [raw_]input expected at most 1 arguments, got 2 

which somehow the except fails to catch.

like image 877
pupeno Avatar asked Aug 26 '09 15:08

pupeno


People also ask

How do you enter a keyboard in python?

Python user input from the keyboard can be read using the input() built-in function. The input from the user is read as a string and can be assigned to a variable. After entering the value from the keyboard, we have to press the “Enter” button. Then the input() function reads the value entered by the user.


2 Answers

Using a select call is shorter, and should be much more portable

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!" 
like image 82
Pontus Avatar answered Sep 20 '22 05:09

Pontus


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 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 
like image 44
user137673 Avatar answered Sep 18 '22 05:09

user137673