一个简单的全局键盘快捷键处理程序

一个简单的全局键盘快捷键处理程序

是的,我知道有行动知识库它允许分配全局键盘快捷键,这些快捷键可以在任何地方使用,包括文本控制台和图形会话,但我不想为单个键盘快捷键运行额外的守护进程(也长期无人维护)。我想要更简单的东西,没有配置选项,并且具有绝对最少的代码量。

任务是在按下此组合键时运行命令:

Win+ End->systemctl suspend

这可能值得在 stackoverflow.com 上发布,但我不完全确定。

答案1

因此,Linux 对于此类事情有一个非常好的框架:uinput; evdev 是一个很好的界面,不会隐藏任何内容。它很苗条。

基本上所有 Linux 发行版都有一个python3-evdev软件包(至少在 debian、ubuntu 和 fedora 上是这个软件包名称)。

然后,只需几行代码即可编写您的守护程序;这只是稍微修改了一下例子代码,我在其中添加了一些解释,以便您知道自己在做什么

#!/usr/bin/python3
# Copyright 2022 Marcus Müller
# SPDX-License-Identifier: BSD-3-Clause
# Find the license text under https://spdx.org/licenses/BSD-3-Clause.html

from evdev import InputDevice, ecodes
from subprocess import run

# /dev/input/event8 is my keyboard. you can easily figure that one
# out using `ls -lh /dev/input/by-id`
dev = InputDevice("/dev/input/event8") 

# we know that right now, "Windows Key is not pressed" 
winkey_pressed = False
# suspending once per keypress is enough
suspend_ongoing = False

# read_loop is cool: it tells Linux to put this process to rest
# and only resume it, when there's something to read, i.e. a key
# has been pressed, released
for event in dev.read_loop():

  # only care about keyboard keys
  if event.type == ecodes.EV_KEY:

    # check whether this is the windows key; 125 is the 
    # keyboard for the windows key
    if event.code == 125:
      # now check whether we're releasing the windows key (val=00) 
      # or pressing (1) or holding it for a while (2)
      if event.value == 0:
        winkey_pressed = False
        # clear the suspend_ongoing (if set)
        suspend_ongoing = False
      if event.value in (1, 2):
        winkey_pressed = True
    # We only check whether the end key is *held* for a while
    # (to avoid accidental suspend)
    # key code for END is 107
    elif winkey_pressed and event.code == 107 and event.value == 2:
      run(["systemctl", "suspend"])
      # disable until win key is released
      suspend_ongoing = True

就是这样。你的守护进程只有 16 行代码。

您可以直接使用 运行它sudo python,但您可能希望自动启动它:

将其另存为文件/usr/local/bin/keydaemonsudo chmod 755 /usr/local/bin/keydaemon使其可执行。添加/usr/lib/systemd/system/keydaemon.unit包含内容的文件

[Unit]
Description=Artem's magic suspend daemon

[Service]
ExecStart=/usr/local/bin/keydaemon

[Install]
WantedBy=multi-user.target

然后sudo systemctl enable --now keydaemon您可以确保守护进程已启动(立即启动,并在以后的每次启动时启动)。

相关内容