Reputation: 910
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?
Upvotes: 4
Views: 5596
Reputation:
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!"))
Upvotes: 2
Reputation: 127
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()
Upvotes: 1
Reputation: 1121
I don't know is it possible to send combinations of Ctrl and/or alt. I tried couple of times but I think it doesn't work. (If someone has any other information please correct me). What you can do is something like this:
from msvcrt import getch
while True:
key = ord(getch())
if key == 27: #ESC
PrintSomething()
def PrintSomething():
print('Printing something')
this will run a scrpit every time you press ESC although it will only work when you run it in command prompt.
Upvotes: 1