Run atexit() when python process is killed
Try signal.signal. It allows to catch any system signal:
import signaldef 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.
To enable signals when debugging PyCharm on Windows:
- Within PyCharm hit
Ctrl + Shift + A
to bring up the "Find Actions..." menu - Search for "Registry" and hit enter
- Find the key
kill.windows.processes.softly
and enable it (you can start typing "kill" and it will search for the key) - Restart PyCharm
To check your system and see which signal is being called:
import signalimport timedef handle_signal(sig_id, frame): sig = {x.value: x for x in signal.valid_signals()}.get(sig_id) print(f'{sig.name}, {sig_id=}, {frame=}') exit(-1)for sig in signal.valid_signals(): print(f'{sig.value}: signal.{sig.name},') signal.signal(sig, handle_signal)time.sleep(30)