Pablo Pablo - 4 months ago 34
Python Question

Keyboard input with timeout in Python

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 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.


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():
            print 'You have 5 seconds to type in your stuff...'
            foo = raw_input()
            return foo
            # timeout

# set alarm
s = input()
# disable the alarm after success
print 'You typed', s