简体   繁体   中英

python3 linux - detect keyboard key pressed withput root

I am trying to detect keyboard pressed key but without root - I found the library keyboard but it is not useful (because it requires root)

I found some websites that says that it does not require root, but it definitely requires.

I tried this code

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

but like I said - it requires 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.

I need without root because first security of course, and because I will add pygame later - and you can not run gui with root

I tried to search for other libraries too but I did not find anything for detecting pressed key - there is pykeyboard for pressing a key, but not checking if a key is pressed

It's mentioned under known limitations of this module

To avoid depending on X, the Linux parts reads raw device files ( /dev/input/input* ) but this requires root.

Which can be confirmed from the source code ( _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()
    ...

Note that before doing any action build_device is called, which calls ensure_root to check the effective user ID of the calling process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM