Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 491
dan Avatar asked May 30 '09 20:05

dan


People also ask

How does Python handle exit?

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.

How do you stop a function after time in python?

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.

What does Killed mean in Python?

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.


1 Answers

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) 
like image 94
Unknown Avatar answered Sep 28 '22 10:09

Unknown