记录python脚本停止的时间? [英] Log the time a python script stopped?

查看:30
本文介绍了记录python脚本停止的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想记录 Python 脚本停止的时间(到 txt 文件中).这个问题与逻辑有关:

I want to log (into a txt file) the time a Python script stopped. The issue with this is regarding to logic:

如果它停止了,它必须知道它何时停止了——但如果它关闭了,它怎么知道?它必须在关闭之前知道大约 1 秒前的关闭.这让我进入了下一个阶段:

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:

进程 "python.exe" 的看门狗,但由于我想使用它的上下文,这不起作用:我想知道我的计算机何时通过 Python 关闭脚本.

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

推荐答案

对于常规终止,我建议使用 atexit 模块:https://docs.python.org/2/library/atexit.html

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

这篇关于记录python脚本停止的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆