1

I have a python program which needs to clean up something when the shell exits unexpectly, what kind of signal have to be caught?

2
  • yes....the problem is sometimes, the shell connection will be unstable, which will shutdown the program, but I have to do something cleanup...
    – Zhenyu Li
    Commented Aug 6, 2012 at 8:11
  • Rob's comment under his answer is right then, catching SIGHUP should work in your situation. Commented Aug 6, 2012 at 17:01

1 Answer 1

2

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
2
  • 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.
    – Zhenyu Li
    Commented Aug 6, 2012 at 8:09
  • 1
    @ZhenyuLi Listen to SIGHUP. For an overview of signals, see man 7 signal.
    – Rob W
    Commented Aug 6, 2012 at 12:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.