Python测量两次按键之间的时间以及一次按键与释放之间的时间

时间:2020-07-29 19:43:39

标签: python pynput

我正在尝试测量按键之间的时间以及按键和释放之间的时间。这是我到目前为止的代码:

import pynput
from pynput.keyboard import Key, Listener
import time
import threading
key_pressed_twice = True
key_is_pressed = False
startPressed = time.time()

key_pressed_list = []
key_released_list = []

def on_press(key):
    global key_is_pressed
    global startRelease
    global key_pressed_twice
    global startPressed

    key_pressed_twice = not key_pressed_twice
    if(key_pressed_twice):
        endPressed = time.time()
        miliSeconds = '%.1f' % ((endPressed-startPressed)*1000) 
        #writeToFile(miliSeconds,"pressed.txt")
        key_pressed_list.append(miliSeconds + ", ")
        startPressed = time.time()
    if key_is_pressed == False:
        startRelease = time.time()
        key_is_pressed = True

def on_release(key):
    global key_is_pressed
    global endRelease
    global startRelease
    key_is_pressed = False
    endRelease = time.time()
    miliSeconds = '%.1f' % ((endRelease-startRelease)*1000) 
    print(miliSeconds)
    key_released_list.append(miliSeconds + ", ")
    if key == Key.esc:
        writeToFile(key_released_list,"release.txt")
        writeToFile(key_pressed_list,"pressed.txt")
        return False

def writeToFile(tempList,filename):
    with open(filename, "a") as file:
        file.write("".join(tempList))


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

我遇到的问题是按键之间的时间间隔似乎很远。如果我敲键,则会有大约300毫秒的延迟。自从我向密钥发送垃圾邮件以来,这似乎很长一段时间。所以有人知道什么地方可能出问题了吗?

编辑:减少文件输入,计时似乎仍然无效。

0 个答案:

没有答案