首页 > 解决方案 > 读取 PC 开启和关闭时间?

问题描述

我正在写一个小程序来跟踪我的睡眠周期。通常,当我醒来时,我会在几分钟内打开我的电脑,因此读取系统何时打开以及何时关闭会很棒。这个程序在这里做同样的功能https://www.neuber.com/free/pctime/

我尝试使用谷歌搜索可以调用这些系统事件的库或函数,但大多数结果是使用命令打开和关闭 PC,所以我的问题是:

获得电脑打开和关闭时间的最佳方法是什么?

谢谢

标签: pythonwindows

解决方案


如果你在 Linux 上(我在这里假设 Systemd),你可以编写一个在启动/关闭时执行代码的服务。该代码会将当前时间戳连同指示符“启动”或“关闭”写入 CSV 文件。

这是一个 Python3 脚本,它将时间戳类型作为第一个参数,以记录到“updownlog.txt”:

import os
import sys                         
import time                


def main():              
    logfile = "updownlog.csv"
    write_header = False

    if len(sys.argv) != 2:
        sys.exit("Error: script takes exactly one argument")                    

    if sys.argv[1] != "shutdown" and sys.argv[1] != "startup":
        sys.exit("Error: First argument should be 'startup' or 'shutdown'")

    typ = sys.argv[1]

    if not os.path.exists(logfile):
        write_header = True

    with open("updownlog.csv", "a") as f:
        now = time.time()

        if write_header:
            f.write("type,timestamp\n")

        f.write("{},{}\n".format(typ, now))


if __name__ == "__main__":
    main()

接下来,您需要创建触发此脚本的系统服务。我无耻地复制了UnixSX 上这个答案中提供的解决方案:所有功劳归功于“John 9631”!如果您仍然使用基于 init.d 的系统,那么该线程中也有很好的答案。

因此,为您的日志记录创建服务文件:

vim /etc/systemd/system/log_start_stop.service

并复制文件内容:

[Unit]
Description=Log startup and shutdown times

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart="/home/Sungod3k/log.py startup"
ExecStop="/home/Sungod3k/log.py shutdown"

[Install]
WantedBy=multi-user.target

然后使用以下命令启用服务:

systemctl enable log_start_stop

当然,这还不能告诉你你是否有睡眠不足,所以你需要做一些后期处理,例如使用 Python 或 R,甚至awk.


推荐阅读