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

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)