Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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:

signal.signal():-

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!')

       sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

print('Press Ctrl+C')

signal.pause()

Browse Categories

...