首页 > 解决方案 > python3 linux - 用root检测键盘按键

问题描述

我正在尝试检测键盘按下的键但没有 root - 我找到了库键盘,但它没有用(因为它需要 root)

我发现一些网站说它不需要root,但它肯定需要。

我试过这段代码

import keyboard
def key_press(key):
    print(key.name)
keyboard.on_press(key_press)

但就像我说的 - 它需要root

...
line 174, in ensure_root
raise ImportError('You must be root to use this library on linux.')
ImportError: You must be root to use this library on linux.

我需要没有 root,因为当然首先是安全性,并且因为我稍后会添加 pygame - 你不能用 root 运行 gui

我也尝试搜索其他库,但我没有找到任何用于检测按下的键的东西 - 有用于按下键的 pykeyboard,但不检查是否按下了键

标签: pythonpython-3.x

解决方案


在此模块的已知限制下提到它

为了避免依赖 X,Linux 部分读取原始设备文件 ( /dev/input/input*),但这需要 root。

这可以从源代码 ( _nixkeyboard.py ) 中确认。

def ensure_root():
    if os.geteuid() != 0:
        raise ImportError('You must be root to use this library on linux.')

device = None
def build_device():
    global device
    if device: return
    ensure_root()
    device = aggregate_devices('kbd')

def init():
    build_device()
    ...

def listen(callback):
    build_device()
    ...

def write_event(scan_code, is_down):
    build_device()
    ...

请注意,在执行任何操作之前build_device都会调用该调用ensure_root,以检查调用进程的有效用户 ID。


推荐阅读