我正在尝试通过threading.Event()交流两个线程。
第一个线程是listener
,它是pynput的键盘记录器。
在其内部,有一个名为write_keys()
的函数,该函数将读取每个键并进行连接,并将连接器传递给foo()
函数,该函数将等待执行。
第二个线程是timer
,它将显示空闲时间,当条件完成时,它将设置事件以触发foo()
函数。
当前,这不起作用,并且正在减慢侦听器的速度,我只能在每个事件上键入一个键
from ctypes import Structure, windll, c_uint, sizeof, byref
from threading import Thread, Event
from pynput import keyboard
from time import sleep
keys = []
message = ' '
# LAST INPUT INFO
class LASTINPUTINFO(Structure):
_fields_ = [
('cbSize', c_uint),
('dwTime', c_uint),
]
def get_idle_duration():
while True:
lastInputInfo = LASTINPUTINFO()
lastInputInfo.cbSize = sizeof(lastInputInfo)
windll.user32.GetLastInputInfo(byref(lastInputInfo))
millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
millis = millis / 1000.0
print(f'\t{millis}')
sleep(1)
if int(millis) == 3: # every 3 sec user is AFK, trigger event.set()
print(f'\t{millis}')
event.set()
def foo(k):
event.wait()
print(f'Event set: {event.is_set()}')
print(f'{k}')
print('PROCESS FINISHED\n')
sleep(3)
event.clear()
def write_keys(keys):
global message
for key in keys:
k = str(key).replace("'", "")
print(k, len(k))
message += k # concatenate keys
if (len(message)) >= 3:
foo(message)
def on_press(key):
global keys
keys.append(key)
write_keys(keys)
keys = []
if __name__ == "__main__":
event = Event()
listener = keyboard.Listener(on_press=on_press)
timer = Thread(target=get_idle_duration)
listener.start()
timer.start()
预期输出:
listener timer
k 0
1
e 0
y 0
1
2
3
output: key
gist.github:link to the code
我对线程库中的事件还很陌生,将考虑任何建议。