Like described in the titel, the function on_press
of the pynput listener gets triggerd by it's own keypress.
I tried doing several things, like adding a boolean that makes it so that when the code itselfs run the keypress or keyrelease, it doesn't print or press the key, and even added a massive delay, but none of this works.
The code:
from pynput import keyboard
from pynput.keyboard import Key, Controller
import time
k = Controller()
randomVar = True
def on_press(key):
global randomVar
if randomVar:
print(key)
randomVar = False
k.press(key)
time.sleep(0.45)
randomVar = True
def on_release(key):
global randomVar
if randomVar:
print(key)
randomVar = False
k.release(key)
time.sleep(0.45)
randomVar = True
# Collect events until released
with keyboard.Listener(suppress=True, on_press=on_press, on_release=on_release) as listener:
try:
listener.join()
except Exception as e:
print('{0} was pressed'.format(e.args[0]))
Expected output when I push d
'd'
'd'
Actual output:
'd'
'd'
'd'
'd'
'd'
'd'
...
EDIT: I also tried just putting everything in on_press, but this gives the same result:
def on_press(key):
global randomVar
if randomVar:
print(key)
randomVar = False
k.press(key)
k.release(key)
time.sleep(0.45)
randomVar = True
def on_release(key):
pass