Search code examples
pythonsignals

signal to stop script in python


i am trying out signals for the first time with python and i created some basic script that just cant seem to get it right. Can somebody explain where im making the mistake?

import signal
import sys


def signal_abort_script(signal, frame):
    """
    Signal handler function to catch KeyboardInterrupt (Ctrl+C) and exit the script gracefully.
    """
    sys.exit()


def main():
    # Set up the signal handler to catch KeyboardInterrupt (Ctrl+C)
    signal.signal(signal.SIGINT, signal_abort_script)

    # print not stopped forever
    while True:
        print("not stopped forever")


if __name__ == "__main__":
    main()

Solution

  • just included the sleep and a print statement to just see the result

    result was ok

    $ winpty python test.py
    not stopped forever
    not stopped forever
    pressed ctrl C
    
    import signal
    import sys
    import time
    
    
    def signal_abort_script(signal, frame):
        """
        Signal handler function to catch KeyboardInterrupt (Ctrl+C) and exit the script gracefully.
        """
        print("pressed ctrl C")
        sys.exit()
    
    
    def main():
        # Set up the signal handler to catch KeyboardInterrupt (Ctrl+C)
        signal.signal(signal.SIGINT, signal_abort_script)
    
        # print not stopped forever
        while True:
            time.sleep(1)
            print("not stopped forever")
    
    
    if __name__ == "__main__":
        main()