I'm trying to communicate two threads through threading.Event().
The first thread is listener
which is the keyboard logger from pynput.
Inside it, there is a function called write_keys()
that will read each key and concatenate them, passing the concatenator to a foo()
function, this one will wait to execute.
The second thread is timer
, which will show the idle duration, when a condition is complete, will set the event to trigger the foo()
function.
Currently this is not working and is slowing down the listener, where I can only type one key on each event
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()
EXPECTED OUTPUT:
listener timer
k 0
1
e 0
y 0
1
2
3
output: key
gist.github: link to the code
I'm pretty new to events in threading library, any advice will be considered.