在执行 keylogger.py 时在计数计时器中按下每个键时连续记录动量

Record momentum consecutively when each key is pressed in a count timer while executing keylogger.py

我在下面有以下代码文件 keylogger.py 来检测按下的特定键并保存到 log.txt 文件。 我想向此 python 代码添加一个计时器,该计时器在代码开始到 运行 时启动,我还希望这部分代码能够保存按下 keys 的确切时刻文件的开头并将此信息保存在 log.txt 文件或另一个单独的文件中(我认为需要使用 with openf.write)。我在 How to create a timer on python and https://pythonhow.com/measure-execution-time-python-code/.

中发现的几个计时想法

所以我的 log.txt 会是这样的

log.py

RLLR     #this line would already be produced by keylogger.py

R: 0.2s
L:0.24s
L:1.34s
R:2.5s

keylogger.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