Reputation: 315
I want to log (into a txt
file) the time a Python script stopped. The issue with this is regarding to logic:
If it stopped, it must know when it did - but if it's closed, how can it know? It'd have to be aware of the closing about 1 second ago before it happens. Which led me to the next phase:
A watchdog for the process "python.exe"
, but that won't work because of the context I want to use it in: I want to know when my computer shuts down via a Python script.
The purpose of this is to log the shutdowns (sleeps) and restarts / wake ups of the computer (Event Viewer doesn't seem to log all of them so I said, hey, why not do it this way?)
Upvotes: 2
Views: 637
Reputation: 395603
Anything in a finally block is guaranteed to run, so you can do this, so long as you don't catch SystemExit
or BaseException
and this gets a shutdown signal or keyboard interrupt:
import logging
import time
logger = logging.getlogger(__name__)
def process():
'''this can be anything, sleep is probably least resource consumptive'''
while 1:
time.sleep(5)
def main():
try:
process()
finally: # guaranteed to run, so long as Python gets an error,
# shutdown signal or keyboard interrupt.
logger.info('shutdown at {0}'.format(datetime.datetime.now()))
if __name__ == '__main__':
main()
Upvotes: 1
Reputation: 8624
For regular terminations, I would suggest using the atexit
module:
https://docs.python.org/2/library/atexit.html
You can write the time of termination of your script like this:
import datetime
import atexit
def leaving():
open("my.log", "w").write("I was closed at %s" % datetime.datetime.now())
atexit.register(leaving)
Another way would be to use decorators, like this:
import atexit
@atexit.register
def leaving():
import datetime
open("my.log", "w").write("I was closed at %s" % datetime.datetime.now())
Upvotes: 3