简体   繁体   English

Python:等待按键或直到超时

[英]Python: wait for a key press or until timeout

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. 我在终端会话中有一个长时间运行的Python脚本(主机是一个FreeBSD盒子),它每9分钟执行一次任务。 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). 捕获Ctrl + C不是一个选项,因为我需要它来停止程序(而不是仅仅中断睡眠)。 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. 它等待输入最多timeout秒。

Under Windows, I suppose you could replace raw_input() with getch() from msvcrt . 在Windows下,我想你可以用 msvcrt getch()替换 raw_input()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM