How to clean up upon a crash?
<p>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 <code>SIGKILL</code> for instance) but I would like to cover as much as possible.</p>

<p>The <a href="https://docs.python.org/3.5/library/atexit.html#module-atexit" rel="nofollow"><code>atexit</code></a> module was a good candidate but the docs explicitely state that</p>

<blockquote>
  <p>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.</p>
</blockquote>

<p>Are there functions or python features which allow to handle <code>sys.exit()</code> and unhandled exceptions program terminations? (these are the main one I am concerned with)</p>

<p><code>SIGKILL</code> <a href="https://en.m.wikipedia.org/wiki/Unix_signal#SIGKILL" rel="nofollow">cannot be handled</a>, no matter what, your program is just terminated (killed violently), and you can do nothing about this. </p>

<p>The only thing you can do about <code>SIGKILL</code> is to look for data that needs to be cleaned up <em>during the next launch of your program</em>. </p>

<p>For other cases use <code>atexit</code> to handle Python's interpreter <em>normal</em> termination. If you've got some unhandled exceptions, see where they can occur and wrap these pieces of code in <code>try/except</code> blocks:</p>

<pre><code>try:
    pass
except ValueError as e:
    pass
except:
    # catch other exceptions
    pass
</code></pre>

<p>To deal with <code>sys.exit</code> calls, you can wrap <em>the entire program's starting point</em> in a <code>try/except</code> block and catch the <code>SystemExit</code> exception:</p>

<pre><code>try:
    # your program goes here
    # you're calling your functions from here, etc
except SystemExit:
    # do cleanup
    raise
</code></pre>

python python-3.x crash code-cleanup