1 回答
TA贡献1828条经验 获得超3个赞
它多次打印我显然不想要的列表
每次按下按钮时,您都明确要求它打印列表
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']
添加回答
举报