Run atexit() when python process is killed : <p>I have a python process which runs in background, and I would like it to generate some output only when the script is terminated.</p>

<pre><code>def handle_exit():
    print('\nAll files saved in ' + directory)
    generate_output()

atexit.register(handle_exit)
</code></pre>

<p>Calling raising a <code>KeyboardInterupt</code> exception and <code>sys.exit()</code> calls <code>handle_exit()</code> properly, but if I were to do <code>kill {PID}</code> from the terminal it terminates the script without calling handle_exit().</p>

<p>Is there a way to terminate the process that is running in the background, and still have it run <code>handle_exit()</code> before terminating?</p>
