How to catch the famous Ctrl+C in Python ?

07-04-2015 08:26 by depado

We all had this one time where we had to do something before exiting a program, no matter what. On Linux we tend to kill every program using the Ctrl+C, or the SIGINT, telling the program to stop right now. Your program bugs, enter an inifinite loop, BAM SIGINT. But what if you had some things setup that you need to clean before exiting the program ? That's why Python has the builtin signal module !

Example. I want to clean the GPIO used in the program before exiting. Let's say, to turn off a LED that is still on when the program is stopped. Here is how you do so :

import signal

def sigint_handler(sig, frame):
    print("\nGraceful exit, cleaning GPIO.")
signal.signal(signal.SIGINT, sigint_handler)