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.
Exit Programs With the quit() Function in Python This site module contains the quit() function,, which can be used to exit the program within an interpreter. The quit() function raises a SystemExit exception when executed; thus, this process exits our program.
terminate() function will terminate foo function. p. join() is used to continue execution of main thread. If you run the above script, it will run for 10 seconds and terminate after that.
Killed generically means something from the outside terminated the process, but probably not in this case hitting Ctrl-C since that would cause Python to exit on a KeyboardInterrupt exception. Also, in Python you would get MemoryError exception if that was the problem.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With