如何在python中按下最后一个键?

tim*_*kro 5 python keyevent

首先,我想说,我知道有一个解决方案与诅咒.
我的程序是一个每秒运行的while循环.每一秒我都想得到最后一个被按下的按键.因此,如果你在循环睡眠时按下一个键我想要保存该键,这样我就可以获得最后按下的键,即使它不再被按下了.我不希望保存的密钥在获取后被"删除".因此,当用户按下"a"键时,我希望每秒钟一次,直到他按下另一个键.如果按下特定键我想打印文本.这篇文章我想用stdout的重定向写一个文件:

 ./test.py > file.txt
Run Code Online (Sandbox Code Playgroud)

用curses解决我的python程序看起来像这样:

import curses
from time import sleep

stdscr=curses.initscr()
stdscr.nodelay(1)
curses.noecho()
curses.cbreak()

while True:
    char=stdscr.getch()
    if char == 111:        #111 = "o" key
        print("test")
        break
    elif char == 97        #97 = "a" key

        #code that have to be run every second
        #if the a key is the last pressed key!

    sleep(1)

curses.nocbreak()
curses.echo()
curses.endwin()
Run Code Online (Sandbox Code Playgroud)

这个解决方案的问题是curses给了我疯狂的输出.我只按了一次"o"键,程序停止后,file.txt看起来像这样:

^[[?1049h^[[1;30r^[(B^[[m^[[4l^[[?7h^[[H^[[2Jtest
^[[30;1H^[[?1049l^M^[[?1l^[>
Run Code Online (Sandbox Code Playgroud)

但它应该是这样的:

test
Run Code Online (Sandbox Code Playgroud)

如果有人写回答,我会非常感激.我知道python不是使用keypress事件的程序的最佳选择.但我有理由为什么我使用python这个.

非常感谢您的答案.

shx*_*hx2 3

您可以安装并使用该getch包。

import getch
from time import sleep
while True:
    char = getch.getch()
    if char == 111:
        print("test")
        break
    sleep(1)
Run Code Online (Sandbox Code Playgroud)

(您可能需要使用getch.getche而不是getch.getch。您的问题并不完全清楚)