How to run one last function before getting killed in Python?

dan picture dan · May 30, 2009 · Viewed 26k times · Source

Is there any way to run one last command before a running Python script is stopped by being killed by some other script, keyboard interrupt etc.

Answer

Unknown picture Unknown · May 30, 2009
import time

try:
    time.sleep(10)
finally:
    print "clean up"
    
clean up
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyboardInterrupt

If you need to catch other OS level interrupts, look at the signal module:

http://docs.python.org/library/signal.html

Signal Example

from signal import *
import sys, time

def clean(*args):
    print "clean me"
    sys.exit(0)

for sig in (SIGABRT, SIGBREAK, SIGILL, SIGINT, SIGSEGV, SIGTERM):
    signal(sig, clean)

time.sleep(10)