The following code waits for a global F1 key press, then controls the keyboard to type out the string “hello”.
from pynput import keyboard
print("Waiting for key press...")
with keyboard.Events() as events:
for event in events:
if event.key == keyboard.Key.f1:
print("1")
break
print("2")
print("Received key press.")
print("Simulating key press...")
controller = keyboard.Controller()
controller.type("hello")
print("Finished key press.")
But as the result, the word that got typed out is:
helloello
instead of
hello
The console log is normal:
Waiting for key press...
1
2
Received key press.
Simulating key press...
Finished key press.
Without the listening part, it works normally.
I have tried listening to different keys, such as F3
, HOME
, DOWN
and SPACE
and in different applications, such as code editor and Notes.app, but it is still not working, and the string helloello
was typed out. I am running Mac OS Sonoma 14.5 and Python 3.12.3.