python - 在执行 keylogger.py 时在计数计时器中按下每个键时连续记录动量
问题描述
我在下面有以下代码文件keylogger.py
来检测被按下的特定键并保存到log.txt
文件中。我想在这个 python 代码中添加一个在代码开始运行时启动的计时器,我还希望这部分代码保存keys
从文件开头开始按下的确切时刻,并将此信息保存在log.txt
文件中或另一个单独with open
的文件(我认为需要使用f.write
)。我在How to create a timer on python和https://pythonhow.com/measure-execution-time-python-code/中发现了几个计时想法。
所以我的 log.txt 会是这样的
日志文件
RLLR #this line would already be produced by keylogger.py
R: 0.2s
L:0.24s
L:1.34s
R:2.5s
键盘记录器.py
from pynput.keyboard import Listener, Key
#set log file location
logFile = "/home/diego/log.txt"
def writeLog(key):
translate_keys = {
Key.right: "R",
Key.left: "L",
}
if key in translate_keys:
with open(logFile, "a") as f:
f.write(translate_keys[key])
with Listener(on_press=writeLog) as l:
l.join()
解决方案
我认为使用单独的文件将是最简单的解决方案:
from pynput.keyboard import Listener, Key
import time
#set log file location for keys pressed
keysLogFile = "/home/diego/keys_log.txt"
#set log file location for keys timestamps
timestampsLogFile = "/home/diego/ts_log.txt"
#store start timestamp
startTime = time.time()
def writeLog(key):
translate_keys = {
Key.right: "R",
Key.left: "L",
}
if key in translate_keys:
currentTime = time.time() - startTime
with open(keysLogFile, "a") as f:
f.write(translate_keys[key])
with open(timestampsLogFile, "a") as f:
f.write(translate_keys[key] + ": " + str(currentTime) + "s\n")
with Listener(on_press=writeLog) as l:
l.join()
这将为您提供两个单独的文件:
keys_log.txt
RLLR
ts_log.txt
R: 0.2s
L: 0.24s
L: 1.34s
R: 2.5s
推荐阅读
- testing - Heroku 中的拆分 (A/B) 测试?
- r - 如何从多个向量创建数据框?
- amazon-web-services - 上传文件 AWS 时出现“413 请求实体太大”错误。(文件大小为 3MB)
- ios - 使用索引在 ForEach 循环 SwiftUI 中获取索引
- javascript - 将 `CROSS` 放在模态框之外
- neo4j - 具有不同标签和关系的不同节点的 Neo4j 子图(如果有)
- c++ - std::optional 的详细程度
- pandas - 熊猫打印整列值
- sql - 使用 Int 列将天数增加到 Start Date 列,并用所有日期填充临时表
- json - 使用 serde_json 序列化具有非字符串键的映射