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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With