Getch 在调用之前获取输入

Getch gets input before it is called

我正在 python 中编写 curses 应用程序。

def main(stdscr):
    stuff(stdscr)

def printStuff(stdscr, string):
    stdscr.clear()
    stdscr.addstr(0, 0, string)
    stdscr.refresh()

def stuff(stdscr):
    printStuff(stdscr, 'foo')
    time.sleep(3)
    printStuff(stdscr, 'bar')
    stdscr.getch()

wrapper(main)

当我 运行 代码时,大部分情况下一切都很好。 如果我在睡眠时的三秒间隙按下一个按钮,getch 将很乐意将其作为其输入,即使在调用 getch 之前按下了按钮。为什么会这样,我该如何解决这个问题?

输入被缓冲,getch() 处理输入缓冲区中的任何内容。您可以使用 curses.flushinp

清除缓冲区
def stuff(stdscr):
    printStuff(stdscr, 'foo')
    time.sleep(3)
    printStuff(stdscr, 'bar')
    stdscr.flushinp()
    stdscr.getch()