【问题标题】:How to get the last key pressed in python?如何在python中按下最后一个键?
【发布时间】:2014-05-06 18:12:46
【问题描述】:

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

 ./test.py > file.txt

我用 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()

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

^[[?1049h^[[1;30r^[(B^[[m^[[4l^[[?7h^[[H^[[2Jtest
^[[30;1H^[[?1049l^M^[[?1l^[>

但它应该是这样的:

test

如果有人写答案,我将非常感激。我知道 python 不是使用按键事件的程序的最佳选择。但我有理由为此使用 python。

非常感谢您的回答。

【问题讨论】:

  • 如果您直接写入文件而不是重定向标准输出 - 那么您的文件中就不会出现来自 curses 的“疯狂输出”...
  • 我有一些其他程序写在 .fifo 中,我总是使用重定向。我想保持这种我可以轻松处理的“格式”。

标签: python keyevent


【解决方案1】:

您可以安装和使用getch 包。

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

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

【讨论】:

  • 如果你使用 getch 你必须这样做:if char == "o"
  • 我希望循环中的代码每秒运行一次并使用按键输入。
猜你喜欢
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-21
  • 2018-09-08
  • 2010-11-27
相关资源
最近更新 更多