Catch kill signal in Python

We can check for Ctrl-C with KeyboardInterrupt exception as follows:

    while True:
        print "Echo ", raw_input(">")
except KeyboardInterrupt:
    print "Good bye"

When python process was killed, we will not get KeyboardInterrupt. But we can instead catch SIGTERM sent by kill command.

In order to catch SIGTERM, we can do:

import signal
import sys

def signal_term_handler(signal, frame):
    print 'got SIGTERM'

signal.signal(signal.SIGTERM, signal_term_handler)

List of signal is available in POSIX Signals. Note that SIGKILL cannot be caught.

3 ความเห็นบน “Catch kill signal in Python


Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  เปลี่ยนแปลง )

Google photo

You are commenting using your Google account. Log Out /  เปลี่ยนแปลง )

Twitter picture

You are commenting using your Twitter account. Log Out /  เปลี่ยนแปลง )

Facebook photo

You are commenting using your Facebook account. Log Out /  เปลี่ยนแปลง )

Connecting to %s