阅读电脑的开机和关机时间?

2024-10-05 12:19:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个小程序来跟踪我的睡眠周期。通常当我醒来的时候,我会在几分钟内打开电脑,所以在系统打开和关闭的时候都能读出来。这个程序在这里执行相同的函数https://www.neuber.com/free/pctime/

我试着在谷歌上搜索一个可以调用这些系统事件的库或函数,但大多数结果都是用命令打开和关闭电脑,所以我的问题是:

获得电脑开机和关机时间的最佳方法是什么?你知道吗

谢谢


Tags: 函数https命令程序comfree系统www
1条回答
网友
1楼 · 发布于 2024-10-05 12:19:52

如果您使用的是Linux(这里我假设为Systemd),那么您可以编写一个在启动/关闭时执行代码的服务。该代码会将当前时间戳写入CSV文件,并带有“startup”或“shutdown”指示符。你知道吗

下面是一个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()

接下来,您需要创建触发此脚本的系统服务。我无耻地抄袭了this answer on UnixSX中提供的解决方案:全部归功于“john9631”!如果您仍然使用基于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。你知道吗

相关问题 更多 >

    热门问题