Search code examples
pythonpynput

set variable amount of hotkey listeners pynput


I would like to create a script that detects a variable amount of different hotkeys.
For example, say that I want three listeners on the hotkeys <ctrl>+1, <ctrl>+2, <ctrl>+3. I tried this:

from pynput import keyboard


def on_macro(key):
   print('You pressed <ctrl> '+key)

if __name__ == "__main__":
   for c in range(3):
      hotkey = keyboard.HotKey(
        keyboard.HotKey.parse('<ctrl>+'+str(c)),
        lambda: on_macro(c)
      )
      listener = keyboard.Listener(on_press=hotkey.press, on_release=hotkey.release)
      listener.start()

My goal would be to have the same callback (on_macro) for every hotkey, and then inside of it determine which hotkey has been pressed and act consequently.


Solution

  • I noticed that whenever I press ctrl together with another key, the output of printing the key argument of on_macro(key) is in hexadecimal, but the problem is that pynput uses no standard hexadecimal values. In this case the "ctrl + a" is translated into "\x01", "ctrl + b" into "\x02" and so on. Here is what you can do

    import pynput
    
    def on_macro(key):
        key = str(key)
        key = key.replace("'", '')
        # print(key) use this to discover which key has which value
    
        if key == '\\x01': # key == ctrl + a
            do_your_stuff()
        elif key == '\\x02': # key == ctrl + b
            do_other_stuff()
    
    with pynput.keyboard.Listener(on_press=on_macro) as l:
        l.join()
    

    to discover which key pressed with ctrl has which value, just print the key argument of your on_macro(key) function. Hope this helped you