如何通过异常终止cmd / batch文件处理python脚本退出

时间:2019-12-20 08:06:55

标签: python batch-file time automation event-handling

我想在Windows启动时执行python脚本。.该脚本可以跟踪我的日常PC使用情况。

脚本执行将我启动PC的时间记为“ starttime”。并且应该记下我关闭PC的时间“结束时间”。

由于脚本将在后台执行,当我关机时,批处理文件将异常终止(我已创建了要在启动时运行的批处理文件)。 因此,我在处理此类脚本退出以获取“结束时间”时遇到麻烦

尽管我尝试了'sys','atexit'甚至尝试catch语句来获取结束时间。我无法通过“ X”按钮关闭cmd(批处理文件cmd)时获取。


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


1 个答案:

答案 0 :(得分:0)

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

这是使用WMI的VBScript。该程序等待您关闭计算机。