There are many ways to solve this problem but I am mentioning the most preferable and important way:-
The first thing you have to register your handler with signal.signal like this:
This function allows defining custom handlers to be executed when a signal is received. A small number of default handlers are installed: SIGPIPE is ignored (so write errors on pipes and sockets can be reported as ordinary Python exceptions) and SIGINT is translated into a KeyboardInterrupt exception if the parent process has not changed it.
def signal_handler(sig, frame):
print('You pressed Ctrl+C!')