title: Trapping a shutdown event in Python
body: <p>I posted a question about how to catch a "sudo shutdown -r 2" event in Python.  I was sent to this thread: <a href="https://stackoverflow.com/questions/21613710/run-code-in-python-script-on-shutdown-signal">Run code in python script on shutdown signal</a> . </p>
  
  <p>I'm running a Raspberry Pi v2 with Jessy.</p>
  
  <p>I have read about </p>
  
  <blockquote>
    <p>signal</p>
  </blockquote>
  
  <p>and have tried to follow the ideas in the above thread, but so far I have not been successful.  Here is my code:</p>
  
  <pre><code>import time
  import signal
  import sys
  def CloseAll(Code, Frame):
      f = open('/mnt/usbdrive/output/TestSignal.txt','a')
      f.write('Signal Code:' + Code)
      f.write('Signal Frame:' + Frame)
      f.write('\r\n')
      f.close()
      sys.exit(0)
  
  signal.signal(signal.SIGTERM,CloseAll)
  print('Program is running')
  try:
    while True:
  #get readings from sensors every 15 seconds 
      time.sleep(15)
  
      f = open('/mnt/usbdrive/output/TestSignal.txt','a')
      f.write('Hello ')
      f.write('\r\n')
      f.close()
  
  except KeyboardInterrupt:
       f = open('/mnt/usbdrive/output/TestSignal.txt','a')
       f.write('Done')
       f.write('\r\n')
       f.close()
  </code></pre>
  
  <p>The program runs in a "screen" session/window and reacts as expected to a CNTL-C.  However, when I exit the screen session, leaving the program running, and enter "sudo shutdown -r 2", the Pi reboots as expected after 2 minutes, but the TestSignal.txt file does not show that the signal.SIGTERM event was processed.</p>
  
  <p>What am I doing wrong?  Or better yet, how can I trap the shutdown event, usually initiated by a cron job, and close my Python program running in a screen session gracefully?</p>