使用模块键盘重复输出

Duplicates in output with module keyboard

我正在开发一个键盘记录器,它使用 python 模块“键盘”捕获键。但是我的输出有问题。当我输入“Hello World”时,输出是 flase。像这样:“shift-H-shift-e-e-l-l-o-space-W-o-r-l-d-d-enter
代码:

print("starting")
import keyboard                 # imports the keyboard-module
file = open("log.txt", "w")     # creates a file
nZ = 0
keyboard.unhook_all()           # clears all keys that were typed in

def on_key(key):
    file.write(str(key.name) + "\n")    # writes the output to a file
    file.flush()                        # saves the written stuff

while True:
    keyboard.hook(on_key)       # waits for a key typed in
    keyboard.unhook_all()       # again clears all keys that were typed in
    nZ += 1

file.close()

所以它们有时是重复的,有时不是。这是为什么?是我的电脑变慢了,是在模块本身上还是我使用了错误的功能或类似的东西?

编辑 - 正确的代码(工作得更好但不太好用,因为其中仍然有一些重复):

print("starting")
import keyboard                 # imports the keyboard-module
file = open("log.txt", "w")     # creates a file
keyboard.unhook_all()           # clears all keys that were typed in

def on_key(key):
    file.write(str(key.name) + "\n")    # writes the output to a file
    file.flush()                        # saves the written stuff

while True:
    keyboard.on_release(on_key)       # waits for a key typed in
    keyboard.unhook_all()              # again clears all keys that were typed in

file.close() 

** 编辑 2 - 使用模块 keyboard 最有效的方法是以下代码:

import keyboard
rk = keyboard.record(until="Esc")
keyboard.play(rk)
 

问题是挂钩发射、松开、反弹并在键仍被按下时立即再次发射。

您可以使用 keyboard.on_release(on_key) 而不是 keyboard.hook(on_key) 来防止这种情况发生。这会导致钩子仅在释放键时触发。这样回弹时就不再按下键了