title: Terminate background python script nicely
body: <p>I am running a python script in the background using the command <code>python script.py &amp;</code>. The script might look like this.</p>
  
  <pre><code>import time
  
  def loop():
      while True:
          time.sleep(1)
  
  if __name__=='__main__':
      try:
          loop()
      except KeyboardInterrupt:
          print("Terminated properly")
  </code></pre>
  
  <p>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 <code>except</code> statement after a keyboard interrupt. </p>
  
  <p>Using the <code>kill PID</code> command means the cleanup is never executed. How can I stop a background process and execute some lines of code before it is terminated?</p>