curses模块中的标准键功能

4

有一个简单的程序:

import curses
import time

window = curses.initscr()

curses.cbreak()
window.nodelay(True)

while True:
    key = window.getch()
    if key != -1:
        print key
    time.sleep(0.01)


curses.endwin()

我该如何开启不忽略标准回车、退格和箭头键功能的模式?或者唯一的方法是将所有特殊字符添加到elif:中吗?
if event == curses.KEY_DOWN:
    #key down function

我正在尝试使用curses.raw()和其他模式,但是没有效果...如果可能的话,请添加示例。


1
我不确定你的意思。你能在你的代码示例中表达你想要达到什么吗? - chtenb
2个回答

1
以下是一个示例,可以让您保留退格键(请记住退格键的ASCII代码为127):
import curses
import time

window = curses.initscr()

curses.cbreak()
window.nodelay(True)
# Uncomment if you don't want to see the character you enter
# curses.noecho()
while True:
    key = window.getch()
    try:
        if key not in [-1, 127]:
           print key
    except KeyboardInterrupt:
        curses.echo()
        curses.nocbreak() # Reset the program, so the prompt isn't messed up afterwards
        curses.endwin()
        raise SystemExit
    finally:
        try:
            time.sleep(0.01)
        except KeyboardInterrupt:
            curses.echo()
            curses.nocbreak() # Reset the program, so the prompt isn't messed up afterwards
            curses.endwin()
            raise SystemExit
        finally:
            pass
key not in [-1, 127]表示忽略打印127(ASCII DEL)或-1(错误)。您可以添加其他项以处理其他字符编码。

try/except/finally用于处理Ctrl-C。这将重置终端,以便在运行后不会出现奇怪的提示输出。
以下是官方Python文档的链接,供以后参考:
https://docs.python.org/2.7/library/curses.html#module-curses

希望这可以帮到您。

希望如果您解释为什么需要那个双重try-except级联,但没有“finally:curses.endwin()”,它会有所帮助......另外:“finally:pass”有什么意义吗? - dotbit

1

stackoverflow.com/a/58886107/9028532中的代码使您能够轻松使用任何键码!
https://dev59.com/rYvda4cB1Zd3GeqPgPTv#58886107

它演示了它不会忽略标准的ENTER、回退和箭头键,getch()正常工作。但是可能操作系统在getch()有机会之前就捕获了某些键。这通常在操作系统中可以在一定程度上进行配置。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接