开发者

Python: wait for a key press or until timeout

开发者 https://www.devze.com 2023-04-09 05:50 出处:网络
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 i开发者_JS百科nterrupt that sleep c

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 i开发者_JS百科nterrupt 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消