I am running a python script in the background using the command python script.py &. The script might look like this.
import time
def loop():
    while True:
        time.sleep(1)
if __name__=='__main__':
    try:
        loop()
    except KeyboardInterrupt:
        print("Terminated properly")
When it comes to terminating the script, I would like to do some cleanup before it is stopped (such as printing "Terminated properly"). If I run as a current process, this would be handled by the except statement after a keyboard interrupt. 
Using the kill PID command means the cleanup is never executed. How can I stop a background process and execute some lines of code before it is terminated?
 
     
    