记录python脚本停止的时间?

编程入门 行业动态 更新时间:2024-10-28 10:30:43
本文介绍了记录python脚本停止的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想记录 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/2/library/atexit.html

For regular terminations, I would suggest using the atexit module: https://docs.python/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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 12:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1393652.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   时间   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!