python - 读取 PC 开启和关闭时间?
问题描述
我正在写一个小程序来跟踪我的睡眠周期。通常,当我醒来时,我会在几分钟内打开我的电脑,因此读取系统何时打开以及何时关闭会很棒。这个程序在这里做同样的功能https://www.neuber.com/free/pctime/
我尝试使用谷歌搜索可以调用这些系统事件的库或函数,但大多数结果是使用命令打开和关闭 PC,所以我的问题是:
获得电脑打开和关闭时间的最佳方法是什么?
谢谢
解决方案
如果你在 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
.
推荐阅读
- pandas - 使用 groupby() 从后面进行累积乘法
- python - 为什么以不同的方式生成数组会导致代码不同部分的大量加速?
- javascript - ES8 和 ES9 中的 jshint 指的是什么?
- r - 错误 1:从 JavaScript 动态生成 Web 抓取时下标越界
- openssl - 在 OpenSSL 命令行工具中为自定义扩展创建自己的 ASN.1 模块
- jquery - 将导航栏品牌和链接与 Bootstrap 4 中的页面内容对齐
- node.js - 如何通过 nodejs express 应用程序调用 API 获取 png 图像
- javascript - Android 版 Chrome 中文本输入的奇怪行为
- java - 如果我在嵌入式 tomcat 上运行我的 Rest API 并且 IDE 已关闭,它从哪里运行?
- laravel - Laravel-echo-server 码头化问题