We can check for Ctrl-C with KeyboardInterrupt exception as follows:
try: 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' sys.exit(0) signal.signal(signal.SIGTERM, signal_term_handler)
List of signal is available in POSIX Signals. Note that SIGKILL cannot be caught.
When python process was killed, we will not get KeyboardInterrupt. But we can instead catch SIGTERM sent by kill command.
When I use
signal.SIGTERM
I got KeyboardInterrupt, but when I changed it tosignal.SIGINT
it works like expected.Could you explain this to me please?
It depends on how you kill the process.
If you use Ctrl-C, and catch SIGINT, then that might be the case that you got what you expected.
But if you use
kill $PID
, this might give you SIGTERM instead.