Run atexit() when python process is killed

To enable signals when debugging PyCharm on Windows:

  1. Within PyCharm hit Ctrl + Shift + A to bring up the "Find Actions..." menu
  2. Search for "Registry" and hit enter
  3. Find the key kill.windows.processes.softly and enable it (you can start typing "kill" and it will search for the key)
  4. Restart PyCharm

Try signal.signal. It allows to catch any system signal:

import signal

def handle_exit():
    print('\nAll files saved in ' + directory)
    generate_output()

atexit.register(handle_exit)
signal.signal(signal.SIGTERM, handle_exit)
signal.signal(signal.SIGINT, handle_exit)

Now you can kill {pid} and handle_exit will be executed.