Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 397
LA_ Avatar asked Aug 02 '12 18:08

LA_


2 Answers

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
like image 159
Brenden Brown Avatar answered Nov 17 '22 05:11

Brenden Brown


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

like image 42
Rsh Avatar answered Nov 17 '22 05:11

Rsh