Why not write status information to a file, and check it on startup?
It could be as simple as create a file ('running') at startup, and delete it at normal shutdown.
At startup, test if it's there; if it is, you had an abnormal shutdown (so assume power failure).
At abnormal shutdown, send a notification to you.
That's not very flexible, and rather ugly, though.
You could write it as a INI file using configparser (Python 3.x) or ConfigParser (Python 2.x).
That way it's a simple text file, easily updated, and you can change values yourself to test different conditions.
You can add other settings to it as you want them (e.g., start time, notification methods, phone number, email address, etc)
(I prefer ConfigObj because it preserves comments and is more powerful, but it's more difficult to use; the documentation could be better. Google usually finds answers though.)
Code: Select all
running = True
started = '2018-0907-1628'
qtyNotifications = 2
active = True
method = text
address = +1-123-555-1234
active = False
method = email
address = [email protected]
Like before, when you start, if 'running' is True, you had an abnormal shutdown (assume it's a power failure; send notifications)
If it's False, you start up normally, writing the started (date and time) and running (True) values.
If running is missing, it's the first time you've started, so same as running = False; normal startup.
When you shut down, set running to False.
You might wrap your code in a try/except so you can write running = False in the event of a code bug. Bugs are abnormal shutdowns, but they're not power failures. You could even send notifications of the exception.
Wrap all that in a while loop to restart it again. (use a flag; set to True at startup, set to False for normal shutdown:
Code: Select all
restart = True
# do my stuff
except Exception as e:
# handle the exception - at least print() it, or log it somewhere
# leave restart True, so we *will* restart
# treat other exceptions (KeyboardInterrupt, SystemExit, etc) as normal shutdown
restart = False
# write False to INI file (so we won't send an 'abnormal shutdown'
# notification if we restart)
# do other cleanup