简体   繁体   English

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

[英]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.我想在我的 Windows 启动时执行一个 python 脚本......它跟踪我的日常 PC 使用情况。

Script execution notes the time when i start my PC as 'starttime'.脚本执行将我启动 PC 的时间记为“开始时间”。 and should note the time 'endtime' when i shut down my PC.并且应该注意我关闭 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.虽然我尝试了 'sys'、'atexit' 甚至 try,catch 语句来结束时间。 I am unable to fetch when the cmd(batch file cmd) is closed via 'X' button.当 cmd(批处理文件 cmd)通过“X”按钮关闭时,我无法获取。


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


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.这是使用 WMI 的 VBScript。 The program waits for you to shutdown computer.该程序等待您关闭计算机。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM