Praneeth A
Praneeth A

Reputation: 51

How to handle python script exit via terminating cmd/batch file abnormally

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()


Upvotes: 0

Views: 334

Answers (1)

user12431753
user12431753

Reputation:

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.

Upvotes: 1

Related Questions