I just found out about the pynput
library which is exactly what I have been looking for. My goal is to capure the keys the user is typing and whenever a specific sequence of keys was captured I want the computer to write a sequence to the current carret's position. After that I want to capture the users´s keys again until another noteworthy sequence occurs. And so on.
The problem is that the simulated key strokes of keyboard.write()
are also considered by the Listener
which leads to an infinite loop which was funny the first time it occurred but I am trying to get rid of it now obv.
My approach is to stop the Listener
and create a new one after the computer is done typing but this process slows down a lot after the first start_listener()
invocation and isn't optimal in the first place I think. And I am out of further ideas so I was hoping someone could help here.
Here is my code so far:
import keyboard
from pynput.keyboard import Key, Listener
def on_press(key):
stop_listener()
keyboard.write("Hello", 0.05)
start_listener()
def on_release(key):
if key == Key.esc:
return False
def start_listener():
global listener
listener = Listener(on_press=on_press, on_release=on_release)
listener.start()
listener.join()
def stop_listener():
global listener
listener.stop()
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()