I'm running a Raspberry Pi v2 with Jessy.
Is there a way from a Python program to detect that a "shutdown" or "restart" event has been initiated? I have a Python program which runs 24x7 in a Screen session window on one of my Raspberry Pi's. I also have a cron job which reboots the Raspberry Pi (shutdown -r 2) every couple days. When it does that I lose any information in the file buffers.
I have read about signal and have tried to follow the information on the web. No success so far. Here is my code:
Code: Select all
import time
import signal
import sys
#import syslog
Log_File = '/usr/pgms/TestSignal.txt'
#Define function which will process Signal event
def CloseAll(Code, Frame):
print(time.strftime("%Y-%m-%d %H:%M")+'\r\nshutdown detected')
# syslog.syslog(syslog.LOG_CRIT, 'Signal Number:%d {%s}' % (Code, Frame))
f = open(Log_File,'a')
f.write(time.strftime("%Y-%m-%d %H:%M")+'\r\nSignal Code:' + str(Code) + ' ')
f.write('Signal Frame:' + str(Frame))
f.write('\r\n')
f.close()
sys.exit(0)
#Register CloseAll function with Signal
signal.signal(signal.SIGTERM,CloseAll)
f = open(Log_File,'a')
f.write('\r\n')
f.write('Program Started')
f.write('\r\n')
f.close()
print(time.strftime("%Y-%m-%d %H:%M")+'\r\nProgram is running')
try:
while True:
#write something every 15 seconds
time.sleep(15)
f = open(Log_File,'a')
f.write(time.strftime("%Y-%m-%d %H:%M")+'\r\nHello ')
f.write('\r\n')
f.close()
# trap cntl-c keyboard entry
except KeyboardInterrupt:
f = open(Log_File,'a')
f.write(time.strftime("%Y-%m-%d %H:%M")+'\r\nCntl-C detected')
f.write('\r\n')
f.close()
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? Thanks....RDK