跟踪自上次击键以来的时间?

Tracking the time since last keystroke?

这是我目前完成的键盘记录器。我之前已经发布过这个问题,但我自己真的很难重复。 On_press和On_release是这里面的两个主要功能。他们都跟踪一次击键。我需要跟踪两次击键之间的时间,但我不确定如何完成这项工作。我想我可以跟踪以查看字符串附加之间的时间。我需要能够看到击键之间的时间,因为如果时间超过一定时间(十秒),我希望清除包含击键(键)的字符串。谢谢大家!

import pynput
import time 
import os, sys
from pynput.keyboard import Key, Listener
import psutil 

count = 0
keys = []

if (time.time() - lastKeystroke > 10):
   keys =[]

def on_press(key):
    global keys, count
    
    keys.append(str(key).replace("'",'').replace("Key.space", ' ').replace("Key.shift", "").lower())

    print(keys)

    count += 1
def on_release(key):
    if key == Key.esc:
        return False

lastKeystroke = time.time()

with Listener(on_press, on_release =on_release) as listener:
    listener.join()

获取任意两个按键之间的时间是最小示例。

开始时它设置 previous_timetime.time() 并且当我按下键时它得到 current_time 并与 previous_time 比较以查看第一次按下之前的时间。然后它在 previous_time 中保留 current_time 以在我按下一个键时再次计算它。

from pynput.keyboard import Key, Listener
import time

# --- functions ---

def on_press(key):
    global previous_time

    # get current time and calculate time between two pressed keys
    current_time = time.time()
    diff_time = current_time - previous_time

    print('seconds:', diff_time)
    
    # save current time for next calculation
    previous_time = current_time
    
    # use this value for something
    if diff_time > 10:
         print("Too late!")

def on_release(key):
    if key == Key.esc:
        return False

# --- main ---

previous_time = time.time() # value as start

with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()