views:

2996

answers:

7

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?

+19  A: 

Register your handler with signal.signal like this:

#! /usr/bin/python
import signal
import sys
def signal_handler(signal, frame):
        print 'You pressed Ctrl+C!'
        sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print 'Press Ctrl+C'
while 1:
        continue

Code adapted from here.

More documentation on signal can be found here.

Matt J
+8  A: 

You can handle Ctrl-C by catching the KeyboardInterrupt exception. You can implement any clean-up code in the exception handler.

Jay Conrod
+3  A: 

You can treat it like an exception (KeyboardInterrupt), like any other. Make a new file and run it from your shell with the following contents to see what I mean:

import time, sys

x = 1
while True:
    try:
        print x
        time.sleep(.3)
        x += 1
    except KeyboardInterrupt:
        print "Bye"
        sys.exit()
rledley
+1  A: 

You can use the functions in Python's built-in signal module to set up signal handlers in python. Specifically the signal.signal(signalnum, handler) function is used to register the handler function for signal signalnum.

Brandon E Taylor
+1  A: 

from the document

import signal
import time

def handler(signum, frame):
    print 'Here you go'

signal.signal(signal.SIGINT, handler)

time.sleep(10)#press Ctrl+c here
sunqiang
+1  A: 

Btw, you answerers, instead of busy while-loops, you should just use signal.pause() to wait for Ctrl-C.

Chad