0

I want to execute a python script on my windows startup.. which tracks my daily PC usage.

Script execution notes the time when i start my PC as 'starttime'. and should note the time 'endtime' when i shut down my PC.

Since script will be executed background, when i shutdown, batch file will be terminated abnormally(I've created batch file to run in startup). So I am facing trouble to handle such script exit to fetch the 'endtime'

Though i tried 'sys','atexit' and even try,catch statements to have the end time. I am unable to fetch when the cmd(batch file cmd) is closed via 'X' button.


import time

with open("report_time.txt",'a') as f:
    f.write(str(int(time.time()))+ '\n')      # Start time

def main():
    try:
        while(True):
            pass
    finally:
        with open("report_time.txt",'a') as f:
            f.write(str(int(time.time()))+ '\n')   # End time(This code works fine for keyboard interrupt)
main()


Praneeth A
  • 51
  • 8
  • 1
    Did you take a look at your CPU while executing this script? Polling in a tight loop might not be what you want. And keyboard interrupt is fundamentally different from system exit events. This https://stackoverflow.com/questions/1411186/python-windows-shutdown-events might help – Patrick Artner Dec 20 '19 at 08:16
  • Your Python code is in such a tight loop, the `finally` never executes. You might have better luck if you replaced the `pass` with a call to `time.sleep()`. – martineau Dec 20 '19 at 08:51
  • What batch file are you talking about? – aschipfl Dec 20 '19 at 14:44
  • You will need to put a Ctrl+Exit thread/function into your program, replacing the windows one (which terminates programs). See https://learn.microsoft.com/en-us/windows/console/registering-a-control-handler-function. –  Dec 20 '19 at 19:04
  • You could turn of logon/off auditing. Then Windows will write it to the Security log. –  Dec 20 '19 at 20:16

1 Answers1

1
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2") 
Set objEvents = objWMIService.ExecNotificationQuery("SELECT * FROM Win32_ComputerShutdownEvent")

Do
    Set objReceivedEvent = objEvents.NextEvent
    wscript.echo objReceivedEvent.Type
Loop

This is VBScript using WMI. The program waits for you to shutdown computer.