How to wait 20 seconds for the user to press any key?

How can I wait for a user to press any key within 20 seconds? That is, I show a message, and it counts 20 seconds, the code continues to execute either after 20 seconds, or if the user pressed any key. How can I do this with python?

+5
source share
3 answers

If you are 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
+7
source

select , , , .
, Linux . , try 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 ''

+2

(Warning: unverified code)

Sort of:

 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 : http://docs.python.org/library/select.html

0
source

All Articles