我想要一个按键记录器,该按键记录器可以通过按下一个键(任意键)来激活,然后将在设定的时间(例如10秒)内按下的所有键保存在列表中,然后打印出来。 我尝试过:
from pynput import keyboard
from time import sleep
def on_press(key):
global recording, keys_pressed
if not recording:
recording = True
sleep(10)
print(" ".join(keys_pressed))
recording = False
listener = keyboard.Listener(
on_press=on_press)
listener.start()
def on_release(key):
global recording
if recording:
print("key pressed")
global keys_pressed
Key = str(key)
if Key.startswith("Key."):
keys_pressed.append(Key[4:].strip("'"))
else:
keys_pressed.append(str(key).strip("'"))
listener2 = keyboard.Listener(
on_release=on_release)
listener2.start()
keys_pressed = []
recording = False
while True:
pass
这有点用,但是它多次打印列表,这显然是我所不希望的。该程序的运行速度也非常慢。
如果您知道任何解决方案,请告诉我。
答案 0 :(得分:1)
它会多次打印我显然不希望的列表
您明确要求它在每次按此按钮时打印列表
print(" ".join(keys_pressed))
此外,我不明白您为什么要尝试实现2个侦听器?
我会做更多类似的事情,尽管我敢肯定还有更好的解决方案!
from pynput import keyboard
from time import time
my_log = []
started = False
start_time = time() # just here to initialize, won't be used until started = True
def on_press(key):
global started
global start_time
if started is False:
started = True
start_time = time()
print("starting timer")
try:
character = '{0}'.format(key.char)
except AttributeError:
character = '{0}'.format(key)
my_log.append(character)
def listen():
global started
print('keyboard listener is initialized')
with keyboard.Listener(on_press=on_press):
while True:
if started:
now = time()
if now - start_time > 10:
break
return # end our listener
listen()
print("done listening")
print(my_log)
示例输出如下(有点混乱,因为打印内容与键入的内容结合在一起):
keyboard listener is initialized
astarting timer
bcdefghijklmnopqrstuvwxyzdone listening
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']