繁体   English   中英

记录python脚本停止的时间?

[英]Log the time a python script stopped?

我想在Python脚本停止时登录(进入txt文件)。 这个问题与逻辑有关:

如果它停止了,它必须知道它什么时候做的-但是如果它关闭了,怎么知道呢? 它必须在大约1秒钟前知道关闭时间。 这导致我进入下一阶段:

进程"python.exe"看门狗,但由于要在以下环境中使用而无法使用:我想知道我的计算机何时通过Python脚本关闭。

这样做的目的是记录计算机的关闭(睡眠)和重新启动/唤醒(事件查看器似乎并没有记录所有日志,所以我说,嘿,为什么不这样做呢?)

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

您可以这样写脚本终止的时间:

import datetime
import atexit

def leaving():
   open("my.log", "w").write("I was closed at %s" % datetime.datetime.now())

atexit.register(leaving)

另一种方法是使用装饰器,如下所示:

import atexit

@atexit.register
def leaving():
    import datetime
    open("my.log", "w").write("I was closed at %s" % datetime.datetime.now())

保证finally块中的任何内容都可以运行,因此只要您不捕获SystemExitBaseException并且获得关闭信号或键盘中断,就可以执行此操作:

import logging
import time

logger = logging.getlogger(__name__)

def process():
    '''this can be anything, sleep is probably least resource consumptive'''
    while 1:
        time.sleep(5)

def main():
    try:
        process()
    finally: # guaranteed to run, so long as Python gets an error, 
             # shutdown signal or keyboard interrupt.
        logger.info('shutdown at {0}'.format(datetime.datetime.now()))

if __name__ == '__main__':
    main()

暂无
暂无

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

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