Invoke function before closing script (Ctrl + C)

You can intercept Ctrl-C by overriding the currently assigned signal handler.
Pyton uses SIGINT as the handler for Ctrl-C, which raises a KeyboardInterrupt exception.

This intercepts Ctrl-C and prints Hello World to the console before raising KeyboardInterrupt.

import signal

default_handler = None

def handler(num, frame):    
    # Do something that cannot throw here (important)
    print("Hello World")

    return default_handler(num, frame) 

if __name__ == "__main__":
    default_handler = signal.getsignal(signal.SIGINT)

    # Assign the new handler
    signal.signal(signal.SIGINT, handler)

Note:
99.9% of the time signal.getsignal(signal.SIGINT) will simply return the default handler, but if any script or addon modifiy the handler, it’s important that we get that instead (signal.getsignal(N) does that).

It’s generally expected that all custom handlers subsequently call the default handler as anything else would alter the behavior of Ctrl-C.