Reputation: 30035
I would like some clean-up activities to occur in case of crash of my program. I understand that some situations cannot be handled (a SIGKILL
for instance) but I would like to cover as much as possible.
The atexit
module was a good candidate but the docs explicitely state that
The functions registered via this module are not called when the program is killed by a signal not handled by Python, when a Python fatal internal error is detected, or when os._exit() is called.
Are there functions or python features which allow to handle sys.exit()
and unhandled exceptions program terminations? (these are the main one I am concerned with)
Upvotes: 2
Views: 2258
Reputation: 44888
SIGKILL
cannot be handled, no matter what, your program is just terminated (killed violently), and you can do nothing about this.
The only thing you can do about SIGKILL
is to look for data that needs to be cleaned up during the next launch of your program.
For other cases use atexit
to handle Python's interpreter normal termination. If you've got some unhandled exceptions, see where they can occur and wrap these pieces of code in try/except
blocks:
try:
pass
except ValueError as e:
pass
except:
# catch other exceptions
pass
To deal with sys.exit
calls, you can wrap the entire program's starting point in a try/except
block and catch the SystemExit
exception:
try:
# your program goes here
# you're calling your functions from here, etc
except SystemExit:
# do cleanup
raise
Upvotes: 1