pythonbackground-processatexit

Run atexit() when python process is killed


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?


Solution

  • 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.