Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I capture SIGINT in Python?

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?

like image 343
James Thompson Avatar asked Jul 10 '09 22:07

James Thompson


People also ask

How do you capture a SIGINT in Python?

Catch signals To catch a signal in Python, you need to register the signal you want to listen for and specify what function should be called when that signal is received. This example shows how to catch a SIGINT and exit gracefully.

How do you get signals in Python?

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 .

How do you SIGINT?

SIGINT is the signal sent when we press Ctrl+C. The default action is to terminate the process.


2 Answers

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.  

like image 164
Matt J Avatar answered Sep 28 '22 03:09

Matt J


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() 
like image 24
rledley Avatar answered Sep 28 '22 02:09

rledley