Python: Catch Ctrl-C command. Prompt "really want to quit (y/n)", resume execution if no

81,315

Solution 1

The python signal handlers do not seem to be real signal handlers; that is they happen after the fact, in the normal flow and after the C handler has already returned. Thus you'd try to put your quit logic within the signal handler. As the signal handler runs in the main thread, it will block execution there too.

Something like this seems to work nicely.

import signal
import time
import sys
def run_program():
    while True:
        time.sleep(1)
        print("a")
def exit_gracefully(signum, frame):
    # restore the original signal handler as otherwise evil things will happen
    # in raw_input when CTRL+C is pressed, and our signal handler is not re-entrant
    signal.signal(signal.SIGINT, original_sigint)
    try:
        if raw_input("\nReally quit? (y/n)> ").lower().startswith('y'):
            sys.exit(1)
    except KeyboardInterrupt:
        print("Ok ok, quitting")
        sys.exit(1)
    # restore the exit gracefully handler here    
    signal.signal(signal.SIGINT, exit_gracefully)
if __name__ == '__main__':
    # store the original SIGINT handler
    original_sigint = signal.getsignal(signal.SIGINT)
    signal.signal(signal.SIGINT, exit_gracefully)
    run_program()

The code restores the original signal handler for the duration of raw_input; raw_input itself is not re-entrable, and re-entering it will lead to RuntimeError: can't re-enter readline being raised from time.sleep which is something we don't want as it is harder to catch than KeyboardInterrupt. Rather, we let 2 consecutive Ctrl-C's to raise KeyboardInterrupt.

Solution 2

from https://gist.github.com/rtfpessoa/e3b1fe0bbfcd8ac853bf

#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame):
  # your code here
  sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)

Bye!

Share:
81,315
Colin M
Author by

Colin M

Updated on September 23, 2020

Comments

  • Colin M
    Colin M about 2 years

    I have a program that may have a lengthy execution. In the main module I have the following:

    import signal
    def run_program()
       ...time consuming execution...
    def Exit_gracefully(signal, frame):
        ... log exiting information ...
        ... close any open files ...
        sys.exit(0)
    if __name__ == '__main__':
        signal.signal(signal.SIGINT, Exit_gracefully)
        run_program()
    

    This works fine, but I'd like the possibility to pause execution upon catching SIGINT, prompting the user if they would really like to quit, and resuming where I left off in run_program() if they decide they don't want to quit.

    The only way I can think of doing this is running the program in a separate thread, keeping the main thread waiting on it and ready to catch SIGINT. If the user wants to quit the main thread can do cleanup and kill the child thread.

    Is there a simpler way?

  • mr2ert
    mr2ert over 9 years
    Wow! This is really cool. However, I think that the ability to crtl-c out of the prompt should be in a decorator, as it makes the code much less mystifying. Would it be appropriate to provide that way as an answer (as I can't edit you answer to add this alternative way)?
  • Antti Haapala -- Слава Україні
    Antti Haapala -- Слава Україні over 9 years
    No, decorator would make it more mystifying, and the signal handler setting is actually part of the logic in the function. Maybe I just add some comments :D
  • mr2ert
    mr2ert over 9 years
    Decorators are a little magical... I'll keep my decorator version in the module I'm writing for this (because it is so sweet :) ). I'd make a note though that you could do this without changing the signal handler, and only exit if the user enters y into the prompt.
  • Colin M
    Colin M over 9 years
    Cool, this works. I do have an issue running your code Antti where exiting the signal handler causes IOERROR: Interruped function call. Only when I set the sleep to be 0.001 seconds does it work, it breaks at 0.01 or higher. This is also only an issue on windows as far as I can tell, the code runs fine as is within Cygwin.
  • Colin M
    Colin M over 9 years
    By exiting I don't mean the call to sys.exit(). Just realized the potential ambiguity. It apparently doesn't like trying to resume the call to sleep() after returning from the signal handler.
  • Antti Haapala -- Слава Україні
    Antti Haapala -- Слава Україні over 9 years
    Ah, Windows. Windows does not even have signals, so how could one suppose the emulation works perfectly. It seems that if CTRL-C is caught by signal handler, then the time.sleep throws IOError? Notice. too, that it is documented that time.sleep might return earlier if a signal is delivered (possibly raising an exception)
  • Ciasto piekarz
    Ciasto piekarz over 8 years
    The strategy doesn't work if we have multithreaded application.
  • Ciasto piekarz
    Ciasto piekarz over 8 years
    why do you need store the original SIGINT handler ? plus I don't think its graceful exit I'd rather call it an ungraceful exit !!
  • Antti Haapala -- Слава Україні
    Antti Haapala -- Слава Україні over 8 years
    @san bc signal handlers are not reentrable, and I want to run the original handler if the ctrl-c is pressed again.
  • Antti Haapala -- Слава Україні
    Antti Haapala -- Слава Україні over 8 years
    @san also, the signal should sort of mostly work in multithreaded application that has 1 main thread handling all the input, but the signal handler must be set in that main thread...
  • Matteo
    Matteo over 6 years
    @AnttiHaapala - what would happen exactly if signal handler was not re-entrant? I.e. if line signal.signal(signal.SIGINT, original_sigint) of the function exit_gracefully was commented out?
  • Matteo
    Matteo over 6 years
    @AnttiHaapala - Also, would it be possible to modify this program to completely ignore signal handlers? In a way that only killing the process would stop the program?
  • Antti Haapala -- Слава Україні
    Antti Haapala -- Слава Україні over 6 years
    @Matteo the posix signal-handlers if registered by signal.signal are one-shot, so if it wasn't reregistered, the next ctrl-c would throw Keyboardinterrupt
  • Antti Haapala -- Слава Україні
    Antti Haapala -- Слава Україні over 6 years
    There are a couple ways to ignore ctrl-c in POSIX - You can make the terminal ignore ctrl-c, you can make the program to not have a controlling terminal, or you can ignore the signal; so you should be simply able to use signal.signal(signal.SIGINT, signal.SIG_IGN) to block the ctrl-c completely.
  • so.very.tired
    so.very.tired over 6 years
    What are the evil things that could happen in raw_input, and why isn't catching KeyboardInterrupt enough? Why is it important to restore the original sigint handler when handling sigint in exit_gracefully?
  • Antti Haapala -- Слава Україні
    Antti Haapala -- Слава Україні over 6 years
    @so.very.tired answered^
  • Marc
    Marc about 3 years
    ok, sorry... now i no have time, as soon as i can, i will follow your advice, thanks
  • Ben Slade
    Ben Slade about 2 years
    Doesn't interrupt a time.sleep() call for me in Python 3.7.3.
  • HumbleBee
    HumbleBee 11 months
    Where exactly is original_sigint being passed to the function?