Search code examples
pythoninputkeyboard

How to listen for regular keys and key combinations in Python


I want to make a program that will print out key combinations and regular keys. For example, if the user types a, I want the console to print 'a' and if the user clicks on shift + a the console will print 'shift + a'.

What library/code should I use? Any help is appreciated.


Solution

  • sort of rewrite the pynput sample code so that the program can monitor combination of shift key.

    I made a global variable SHIFT_STATE to record if the shift key is pressed, and I believe you can expand this to monitor ctrl, alt, cmd keys and make the code looks prettier.

    By the way, the library has the power to monitor global-hotkeys however I did not look into it too much. You can check it out here: https://pynput.readthedocs.io/en/latest/keyboard.html#global-hotkeys

    from pynput import keyboard
    
    SHIFT_STATE = False
    def on_press(key):
        global SHIFT_STATE
        if key == keyboard.Key.shift:
            SHIFT_STATE = True
        else:
            try:
                if SHIFT_STATE:
                    print(f'shift + {key}')
                else:
                    print(key)
            except Exception as e:
                print(e)
    
    def on_release(key):
        global SHIFT_STATE
        if key == keyboard.Key.esc:
            # Stop listener
            return False
        elif key == keyboard.Key.shift:
            SHIFT_STATE = False
    
    # Collect events until released
    with keyboard.Listener(
            on_press=on_press,
            on_release=on_release) as listener:
        listener.join()
    
    

    and here's the screenshot I ran the code FYI pynput rewrite