首页 > 解决方案 > 在执行 keylogger.py 时在计数计时器中按下每个键时连续记录动量

问题描述

我在下面有以下代码文件keylogger.py来检测被按下的特定键并保存到log.txt文件中。我想在这个 python 代码中添加一个在代码开始运行时启动的计时器,我还希望这部分代码保存keys从文件开头开始按下的确切时刻,并将此信息保存在log.txt文件中或另一个单独with open的文件(我认为需要使用f.write)。我在How to create a timer on pythonhttps://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()

标签: pythontimerkeyloggerpynput

解决方案


我认为使用单独的文件将是最简单的解决方案:

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

推荐阅读