Python: wait for a key or timeout

I have a long Python script inside a terminal session (the host machine is a FreeBSD field) that executes a task every 9 minutes. Now I would like to be able to interrupt this sleep call at any moment so that it immediately fulfills the task.

How can i do this? Capturing Ctrl+ is Cnot an option, as I need to stop the program (and not just interrupt sleep). All I can do with the terminal window and keyboard is fine.

+5
source share
1 answer

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 expects input no more than timeoutseconds.

Windows, , raw_input() getch() msvcrt.

+3

All Articles