pynput
pynput copied to clipboard
press(key) does not always work
I am trying to write a script that intercepts some keys and replaces their input. Because I cannot suppress individual keys, I wrote a "pass-through" for all keys that are not my hotkeys:
from pynput import keyboard
from pynput.keyboard import Key
kc = keyboard.Controller()
ignore_press = False
ignore_release = False
def on_press(key):
# Make sure we don't intercept the key we just sent.
global ignore_press
if ignore_press:
ignore_press = False
return
ignore_press = True
try:
kc.press(key.char)
except AttributeError:
kc.press(key)
def on_release(key):
# Make sure we don't intercept the key we just sent.
global ignore_release
if ignore_release:
ignore_release = False
return
ignore_release = True
try:
kc.release(key.char)
except AttributeError:
kc.release(key)
with keyboard.Listener(on_press=on_press, on_release=on_release, suppress=True) as listener:
listener.join()
Now if I try to type, this works for all the keys that do not cause an AttributeError when trying to access key.char
. But any key that does not have a .char (i.e. space, backspace, enter) will simply have no effect.
However if I just directly try to press() the key, it does work:
from pynput import keyboard
from pynput.keyboard import Key
from time import sleep
kc = keyboard.Controller()
sleep(3)
kc.press(Key.backspace)
kc.release(Key.backspace)
Sleep is here just to have time to switch to an editor to test the input.
I'm doing this on linux with xorg. Haven't tested it anywhere else.