简体   繁体   English

使用 Python 在 Linux 上的框架内获取按键

[英]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.我正在尝试创建一个函数,在调用时创建一个临时侦听器(大约 0.01 秒),记录在当前时间范围内按下的键,并返回这些键的列表。 Something like this would be easy to do with the win32api GetAsyncKeyState , but I'm not quite sure how to do it on Linux.使用win32api GetAsyncKeyState很容易做到这样的GetAsyncKeyState ,但我不太确定如何在 Linux 上做到这一点。

I found the pynput module to be quite useful, but the way it handles listeners has confused me.我发现 pynput 模块非常有用,但它处理侦听器的方式让我感到困惑。

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.在 Posix 终端上,您必须将 stdin 重新配置为非阻塞,然后将其改回。 It can be done in a stand-alone way, but maybe you are better using a 3rdy party library for that.它可以以独立的方式完成,但也许您最好使用 3rdy 方库。

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 Terminedia(开发分支)进行重新配置,并有一个getch函数将返回第一个按键 - 它可以很容易地添加到间隔内的所有 kepresses: https : //github.com/jsbueno/terminedia/blob/d97976fb11ac54b527db4183497730885/ba7151终端/input.py#L116

So, adapting that getch you can use:因此,调整该getch您可以使用:

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.您可以使用pip install git+https://github.com/jsbueno/terminedia.git安装开发版本 - 当项目的 0.3 版本完成时,默认情况下所需的“inkey”和“keyboard”将可用。

disclaimer : I am the author of the terminedia package.免责声明:我是terminedia软件包的作者。 Although there were hints, sorry for not making it clear from the start.虽然有提示,但很抱歉没有从一开始就说清楚。

(Also that code should work on Windows as well) (该代码也应该在 Windows 上运行)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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