Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a Ctrl+C signal, and I'd like to do some cleanup.

In Perl I'd do this:

$SIG{'INT'} = 'exit_gracefully';

sub exit_gracefully {

        print "Caught ^C \n";

        exit (0);


How do I do the analogue of this in Python?

1 Answer

0 votes
by (106k points)

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.

#!/usr/bin/env python

import signal

import sys

def signal_handler(sig, frame):

       print('You pressed Ctrl+C!')


signal.signal(signal.SIGINT, signal_handler)

print('Press Ctrl+C')


Browse Categories