Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: wait for a key press or until timeout

Tags:

python

I have a long-running Python script inside a terminal session (the host machine is a FreeBSD box) that performs a task every 9 minutes. Now, I'd like to be able to interrupt that sleep call at any moment so that it performs the task right away.

How can I do that? Catching Ctrl+C is not an option as I need it to stop the program (rather than merely interrupting the sleep). Anything else that I can do with a terminal window and a keyboard is fine.

like image 264
zneak Avatar asked Oct 24 '22 23:10

zneak


1 Answers

With Thomas's suggestion, I came up with this function:

import signal

def input_or_timeout(timeout):
    def nothing(sig, frame): pass
    signal.signal(signal.SIGALRM, nothing)
    signal.alarm(timeout)
    try:
        raw_input()
        signal.alarm(0)
    except (IOError, EOFError): pass

It waits for input for at most timeout seconds.

Under Windows, I suppose you could replace raw_input() with getch() from msvcrt.

like image 200
zneak Avatar answered Oct 27 '22 11:10

zneak