LA_
LA_

Reputation: 20409

How to wait for 20 secs for user to press any key?

How can I wait for user to press any key for 20 secs? I.e. I show the message and it counts 20 secs, the code continues execution either if 20 secs are passed OR if user pressed any key. How can I do it with python?

Upvotes: 5

Views: 1221

Answers (3)

Brenden Brown
Brenden Brown

Reputation: 3215

If you're on Windows:

def wait_for_user(secs):
    import msvcrt
    import time
    start = time.time()
    while True:
        if msvcrt.kbhit():
            msvcrt.getch()
            break
        if time.time() - start > secs:
            break

Upvotes: 7

Rsh
Rsh

Reputation: 7742

One possible solution is to use select to check the values, but I don't like it, I feel like I'm wasting my time.
On the other hand you can use signaling on Linux systems to handle the problem. after a certain amount of time, a exception will be raised, try fails and code continues in except :

import signal

class AlarmException(Exception):
    pass

def alarmHandler(signum, frame):
    raise AlarmException

def nonBlockingRawInput(prompt='', timeout=20):
    signal.signal(signal.SIGALRM, alarmHandler)
    signal.alarm(timeout)
    try:
        text = raw_input(prompt)
        signal.alarm(0)
        return text
    except AlarmException:
        print '\nPrompt timeout. Continuing...'
    signal.signal(signal.SIGALRM, signal.SIG_IGN)
    return ''

The code has been taken from here

Upvotes: 2

gsk
gsk

Reputation: 578

(Warning: untested code)

Something like:

 import sys
 import select

 rlist, _, _ = select.select([sys.stdin], [], [], timeout=20)
 if len(rlist) == 0:
     print "user didnt input anything within 20 secs"
 else:
     print "user input something within 20 secs. Now you just have to read it"

edit see: http://docs.python.org/library/select.html

Upvotes: 0

Related Questions