Last active
January 14, 2023 18:45
-
-
Save kevinxhan/6c0bbc68f2ea6b2f4a620e5413c98fb8 to your computer and use it in GitHub Desktop.
python catch kill signal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment