I have a python process which runs in background, and I would like it to generate some output only when the script is terminated.
def handle_exit(): print('\nAll files saved in ' + directory) generate_output() atexit.register(handle_exit)
Calling raising a KeyboardInterupt
exception and sys.exit()
calls handle_exit()
properly, but if I were to do kill {PID}
from the terminal it terminates the script without calling handle_exit().
Is there a way to terminate the process that is running in the background, and still have it run handle_exit()
before terminating?
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.
To enable signals when debugging PyCharm on Windows:
Ctrl + Shift + A
to bring up the "Find Actions..." menukill.windows.processes.softly
and enable it (you can start typing "kill" and it will search for the key)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With