我正在尝试检测键盘按下的键但没有 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/