简体   繁体   中英

Get key presses within a frame on Linux in Python

I'm trying to make a function that, while called, creates a temporary listener (about 0.01s), records keys pressed in that current timeframe, and returns a list of those keys. Something like this would be easy to do with the win32api GetAsyncKeyState , but I'm not quite sure how to do it on Linux.

I found the pynput module to be quite useful, but the way it handles listeners has confused me.

I currently have something like this:

from pynput import keyboard
import time

t0 = time.time()
def on_press_loop(key):
    pressed_keys = []
    if time.time() - t0 < 0.01:
        pressed_keys.append(key.char)
    return pressed_keys

with keyboard.Listener(on_press=on_press_loop) as listener:
    listener.join()

On Posix terminals you have to reconfigure stdin to be non-blocking, and change it back. It can be done in a stand-alone way, but maybe you are better using a 3rdy party library for that.

Terminedia (the development branch) makes the reconfiguration, and hav a getch function that will return the first keypress - it can be easily addaptted for all kepresses on the interval: https://github.com/jsbueno/terminedia/blob/d97976fb11ac54b527db4183497730883ba71515/terminedia/input.py#L116

So, adapting that getch you can use:

from terminedia import keyboard, inkey
import time


def collect_keys(timeout=0.1) -> str:
    """Returns all keys pressed in given time interval
    """
    step = 1 / 30
    ellapsed = step
    with keyboard():
        time.sleep(step)
        key = inkey()
        while True:
            key = inkey()
            time.sleep(step)
            ellapsed += step
            if ellapsed >= timeout:
                break
    return key

You can install the development version with pip install git+https://github.com/jsbueno/terminedia.git - the needed "inkey" and "keyboard" will be available by default when release 0.3 of the project is done.

disclaimer : I am the author of the terminedia package. Although there were hints, sorry for not making it clear from the start.

(Also that code should work on Windows as well)

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