0

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 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.