python - 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,但不检查是否按下了键
解决方案
在此模块的已知限制下提到它
为了避免依赖 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。
推荐阅读
- python - How to stop iterating over a list once a certain value is reached
- php - 如何在laravel中将数组中属性的JSON字符串值作为JSON数组返回
- python - Reading Dataset from files where some might be missing
- android - 从 Postman 工作的 NODE JS Api 导致 App 超时
- reactjs - 未捕获的 TypeError:this.state.imgData.map 不是函数
- php - 如何使用 openSUSE vim 编辑器在 php 中创建多维 ForEach 循环
- jenkins - 单个 Jenkins 作业上的多个构建
- sql - sql join:检测更改
- mysql - 如果我只编辑一个输入字段,为什么我的可编辑输入字段会提交空字符串?
- html - Angular 7 - 导航
- 带制表键