Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen letter keys with combination of modifier keys using pynput?

Tags:

python

pynput

I am tying to automate some stuff using python.I use pynput to listen key combinations. I am trying to listen ctrl+shift+alt s combination. I have no problem with modifier keys but only with letter keys. I have looked the python documentation page and tried followings:

from pynput import keyboard
from subprocess import Popen, PIPE
from evdev import uinput, ecodes as e
import os

# The key combination to check
COMBINATION = {keyboard.Key.shift, keyboard.Key.ctrl, keyboard.Key.alt, keyboard.KeyCode.from_char('k')}

# The currently active modifiers
current = set()

def on_press(key):
    if key in COMBINATION:
        current.add(key)
        if all(k in current for k in COMBINATION):
            print("x")
    if key == keyboard.Key.esc:
        listener.stop()

def on_release(key):
    try:
        current.remove(key)
    except KeyError:
        pass

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

After running the python file from terminal, script cannot detect my key combination.

like image 961
Emre CEKEN Avatar asked Nov 20 '25 10:11

Emre CEKEN


1 Answers

From the docs, you can use this method. https://pynput.readthedocs.io/en/latest/keyboard.html

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()
like image 168
Sri Avatar answered Nov 21 '25 23:11

Sri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!