单键检测以增加长输入的可能性

Single key detection to work with the possibility of adding long inputs

上周我一直在面对这个问题,我认为这会是微不足道的,但在尝试了许多不同的方法之后我不知道还能尝试什么。

我有一个应用程序,我需要进行按键检测(用键盘移动机器人手臂),但是当我按下回车键时,我需要添加一些输入,只要我想要,只要一些正常的input("insert here").

我知道 python 库可以进行键检测,我让 pynput 成功工作但是当我启动和停止线程几次时它使我的 raspberry pi 崩溃,我尝试了键盘库,但整个根要求令人失望,我也得到了 curses 的工作,这似乎很可靠并且(几乎)没有引起任何问题,所以检测 1 个键不是问题。

我当然知道如何命名我的文件并通过执行 input() 获取我需要的所有信息,所以如果我必须使用这些选项之一,工作会相当简单,当我遇到挑战时尝试同时应用这两种方法,基本上检测按键来完成我需要的一切,并使用 python Input 在按下回车键后立即从用户那里获取所有输入,所有检测按键的库似乎都已满控制,他们不想不战而降。他们似乎希望用户总是需要单键检测,但在我的情况下,我需要不断地打开和关闭它,我想不出任何有效(或无效)的方法来让它正常工作。

我的问题是:

在需要时以非阻塞方式使用 curses(或任何替代方法)进行键检测 + 完整用户输入的最佳方法是什么(因为我的代码需要在监听键的同时做一些其他事情),正在创建并摧毁整个事情是唯一的选择?

这是我为简单起见而创建的当前测试代码(它可以工作,但在监听键时会阻止所有内容):

import curses
import time
import os

stdscr = None
addInput = False

def SetupCurses():
    global stdscr
    stdscr = curses.initscr()
    curses.cbreak()
    stdscr.keypad(1)

def StartCurse():
    global addInput

    key = ''
    while key != ord('q'):
        key = stdscr.getch()
        stdscr.addstr(str(key)) 
        if key == ord('a'):
            print("\nyou pressed a\n")
        if key == 10:
            print("\nyou pressed enter!\n")
            addInput = True
            break

def EndCurse():
    curses.endwin()

while(True):
    SetupCurses()
    StartCurse()
    EndCurse()

    if addInput:
        theinput = input("add your input\n")
        print(theinput)
        time.sleep(4)
        addInput = False

    #if there isn't any input to add I want the code to continue because there is non-related keys stuff to do, but of course it stopped at "StartCurse"
    #if there is something to add the code can stop at addInput

循环的原因是因为用户可以保存任意多的位置,所以在添加一些输入后还有添加更多的可能性。

我看到人们通过在几秒钟后关闭 curses 循环(无论如何都会停止一切......)来实现这种非阻塞,有点靠运气获得输入......类似于:

def ExecuteCurses():
    global AddInput
    #open it and close it very quickly to grab a key if it is pressed
    c = stdscr.getch()
    if c == ord('a'):
        print("you pressed a")
        AddInput = True
        time.sleep(1)
    curses.endwin()

如果您想要完整且较长的用户输入,您将需要使用 curses.echo(),然后使用 stdscr.getstr()。这将等待用户按下 enter()。 为了在获取输入时不阻止程序,您需要 threading,您必须在程序顶部导入它

对于线程 here 是 link 因此您可以找到有关线程的更多信息。


我希望它能回答你的问题