GlobalHotKeys pynput not working not reacting to function keys

Viewed 13

community. I'm trying to put together a quick hotkey script in python here. For some reason it doesn't react to function keys, meaning the expression '<ctrl>+<F2>': function_1 doesn't work.

I was not able to find any clues in the official documentation or other examples online. Any thoughts?

Here is the script for testing.

from pynput import keyboard

def function_1():
    print('Function 1 activated')

def function_2():
    print('Function 2 activated')

with keyboard.GlobalHotKeys({
        '<ctrl>+<F2>': function_1,
        '<ctrl>+t': function_2}) as h:
    h.join()
1 Answers

You could try setting up a generic handler to see what events are generated:

from pynput import keyboard
from pynput.keyboard import Controller

keyboard_controller = Controller()

# The event listener will be running in this block
with keyboard.Events() as events:
    for event in events:
        if event.key == keyboard.Key.esc:
            break
        else:
            print(f"Received event {event}")

Running this script will then print the key press events, pressing Esc will exit the script:

Received event Press(key='a')
Received event Release(key='a')
Received event Press(key=Key.media_volume_up)
Received event Release(key=Key.media_volume_up)
Received event Press(key=Key.f3)
Received event Release(key=Key.f3)
Received event Press(key=Key.ctrl)
Received event Press(key=Key.media_volume_up)
Received event Release(key=Key.media_volume_up)
Received event Release(key=Key.ctrl)

Note that this won't handle hot keys and I don't see some key presses, e.g. to get Key.media_volume_up events I press Fn + F3.

You could potentially use keyboard.Events() handling to trigger your own hotkey equivalent.

Related