python3 linux - 检测没有root按下的键盘键

标签 python python-3.x

我正在尝试检测键盘按下的键但没有 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,但不检查是否按下了键

最佳答案

在这个模块的已知限制下提到了它

To avoid depending on X, the Linux parts reads raw device files (/dev/input/input*) but this requires 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。

关于python3 linux - 检测没有root按下的键盘键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53773272/

相关文章:

python-3.x - 对于这种特殊情况,如何使用地理编码获得公司的正确位置? (Python、谷歌 API)

python - 装饰一个 python 类,使得大多数方法在有条件时引发异常

python - wxPython 不会关闭父级为窗口句柄的 Frame

python - 删除表语句中的 Hive ParseException

python - 限制在 telegram.org API 中测试 auth.sendCode

python - 使用 memcache.gets() 时出现 AttributeError

excel - Python合并多个Excel表格形成汇总表

Python3 Pillow 获取一条线上的所有像素

python - Matplotlib 刻度标签字体粗细仅限于几个选项

python - 当第一项包含可变对时可变 rlist(家庭作业)