Create Keyboard Shortcut?

Viewed 3197

I am searching for a way to create a cross-platform keyboard shortcut in Python. Such that when I press something like Ctrl+C or Ctrl+Alt+F, the program will run a certain function.

Does there exist such method or library?

3 Answers

You can create a listener for keypress event by pynput library. this is a simple code that run a function when press CTRL+ALT+H keys:

from pynput import keyboard

def on_activate():
    print('Global hotkey activated!')

def for_canonical(f):
    return lambda k: f(l.canonical(k))

hotkey = keyboard.HotKey(
    keyboard.HotKey.parse('<ctrl>+<alt>+h'),
    on_activate)
with keyboard.Listener(
        on_press=for_canonical(hotkey.press),
        on_release=for_canonical(hotkey.release)) as l:
    l.join()

Try keyboard. It can be installed with pip install keyboard, and the Ctrl + C example can be accomplished with the syntax:

import keyboard
keyboard.add_hotkey("ctrl + c", print, args=("Hello", "world!"))
Related