Linux-Kernel

一個簡單的全域鍵盤快捷鍵處理程序

  • March 24, 2022

是的,我知道actkbd允許分配全域鍵盤快捷鍵,這些快捷鍵在任何地方都可以使用,包括文本控制台和圖形會話,但我不想為單個鍵盤快捷鍵執行額外的守護程序(也長期無人維護)。我想要一些更簡單的東西,沒有配置選項,並且具有絕對最少的程式碼量。

任務是在按下此組合鍵時執行命令:

Win+ End->systemctl suspend

這可能值得在 stackoverflow.com 上發布,但我不完全確定。

所以,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您可以確保守護程序已啟動(立即啟動,並且在以後每次啟動時)。

引用自:https://unix.stackexchange.com/questions/696526