I have a subprocess running from a python script and I would like to kill this process if the user terminates python (ctrl+D or ctrl+Z or quit()). Is there a function I can define in my python script that will run automatically right before the python script is exited?
1 Answer
You can use the atexit module to register functions to be run.
import atexit
def bar():
print "World"
atexit.register(bar)
#atexit.register also can be used as a decorator since it returns
# the function:
@atexit.register
def foo():
print "Goodbye"
These functions will be run unless the script exits with os._exit (which it shouldn't) or unless the script causes python to encounter a serious error (e.g a Segmentation Fault) which doesn't usually happen, but can if you're using C extensions that are buggy.