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
My solution is a terrible way of doing this, but currently after struggling for hours, the only thing I could come up with. It stops the listener and then pressed the key, and then starts the listener again, making it a loop of stopping and starting the listener, which is very suboptimal
I would love to hear from people how this could've been differently, but for now, this is my only solution:
from pynput import keyboard
from pynput.keyboard import Controller
k = Controller()
def on_press(key):
global listener
print(str(key))
listener.stop()
def on_release(key):
pass
while True:
listener = keyboard.Listener(suppress=True, on_press=on_press, on_release=on_release)
listener.start()
listener.join()
k.press("l")
k.release("l")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.