Want some programming help? [close]

Python Catch SIGINT (CTRL-C)

Introduction

If you have a long-running Python application that you want to kill using SIGINT or CTRL-C, there is a way to catch the signal and take action to shut down the application gracefully. This tutorial will show you how to catch a SIGINT or other signal and take action.

Catch signals

To catch a signal in Python, you need to register the signal you want to listen for and specify what function should be called when that signal is received. This example shows how to catch a SIGINT and exit gracefully.

from signal import signal, SIGINT
from sys import exit

def handler(signal_received, frame):
    # Handle any cleanup here
    print('SIGINT or CTRL-C detected. Exiting gracefully')
    exit(0)

if __name__ == '__main__':
    # Tell Python to run the handler() function when SIGINT is recieved
    signal(SIGINT, handler)

    print('Running. Press CTRL-C to exit.')
    while True:
        # Do nothing and hog CPU forever until SIGINT received.
        pass

Documentation

The complete and official documentation can be found at https://docs.python.org/3/library/signal.html

Conclusion

After reading this tutorial, you should understand how to catch SIGINT and other signals and handle them properly.

References

Advertisement