python – Keyboard input with timeout?

python – Keyboard input with timeout?

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 = [sys.stdin], [], [], 10 )

if (i):
  print You said, sys.stdin.readline().strip()
  print You said nothing!

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

python – Keyboard input with timeout?

Not a Python solution, but…

I ran in to this problem with a script running under CentOS (Linux), and what worked for my situation was just running the Bash read -t command in a subprocess. Brutal disgusting hack, I know, but I feel guilty enough about how well it worked that I wanted to share it with everyone here.

import subprocess -t 30, shell=True)

All I needed was something that waited for 30 seconds unless the ENTER key was pressed. This worked great.

Leave a Reply

Your email address will not be published. Required fields are marked *