Search code examples
pythonkeycodepynput

Comparing a KeyCode object to string in python


I'm trying to trigger functions on key presses in python. I'm using the pynput library's listen function, which returns a Keycode object. I've tried casting the object to string but the following code still returns the following output (when pressing the 'a' key):

def on_press(key):
    mod = str(key)
    print(mod)
    print(type(mod))
    print(mod=='a')

I get:

'a'
< class 'str'>
False

Solution

  • Use next:

    def on_press(key):
        print(key.char=='a')
    

    Above will print True.

    Your code cannot work just because:

    mod = str(key)
    print(mod)
    

    Will get 'a', but for a normal string, print('a') will just print a, they are not the same string. You can confirm it with print(len(mod)) & print(len('a'))

    BTW, next is a full code for your test:

    from pynput.keyboard import Key, Listener
    import sys
    
    def on_press(key):
        mod = str(key)
        print(mod)
        print(type(mod))
        print(mod=='a')
        print(key.char=='a')
        print(len(mod))
        print(len('a'))
        sys.exit(0)
    
    def on_release(key):
        pass
    
    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()