HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How do I capture SIGINT in Python?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
capturesiginthowpython

Problem

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?

Solution

Register your handler with signal.signal like this:

#!/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()


Code adapted from here.

More documentation on signal can be found here.

Code Snippets

#!/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()

Context

Stack Overflow Q#1112343, score: 1087

Revisions (0)

No revisions yet.