I have a python program which needs to clean up something when the shell exits unexpectly, what kind of signal have to be caught?
1 Answer
Use the signal module to add a handler for a specific signal. For example SIGINT and SIGTERM:
import signal
def handler(signum, frame):
print('Caught signal %d' % signum)
# Now do something (clean-up?) ...
signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGTERM, handler)
input() # Example to keep the program running
-
it seems that these two signals couldn't be caught when I shutdown the terminal, you could try by write to a file in the handler and you will see that terminating the terminal won't write anything to the file. Commented Aug 6, 2012 at 8:09
-
1@ZhenyuLi Listen to SIGHUP. For an overview of signals, see
man 7 signal
.– Rob WCommented Aug 6, 2012 at 12:20
SIGHUP
should work in your situation.