'pynput events executing twice

def pressLetter(charIn):
    val = getKeyValue(charIn)   
    PressKey(val)
    return

def KeyboardEvents():
from pynput import keyboard
    with keyboard.Events() as events:
    for event in events:
        if event.key == keyboard.Key.space:
            pressLetter('w')

Pressing space types ww. How would I rewrite this so that it only presses w once?



Solution 1:[1]

Well, I figured it out. It appears that keyboard.Events() registers button press events on both key pressed and key released. Meaning that...

if event.key == keyboard.Key.space:
            pressLetter('w')

Presses w twice because it executes both on key pressed, and then key released. The solution I found was to use keyboard.Listener() instead

def pressLetter(charIn):
    val = getKeyValue(charIn)   
    PressKey(val)
    return

def on_press(key):
    if key == keyboard.Key.space:
        pressLetter('w')

def on_release(key):
    if key == keyboard.Key.esc:
        return False

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

listener = keyboard.Listener(on_press=on_press, on_release=on_release)
    listener.start()

Solution 2:[2]

This worked for me:

def KeyboardEvents():
    from pynput import keyboard
        with keyboard.Events() as events:
            for event in events:
                if isinstance(event, keyboard.Events.Press):
                    if event.key == keyboard.Key.space:
                        pressLetter('w')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bran Washington
Solution 2 K. Jensen