标准密钥在curses模块中起作用

时间:2014-05-13 08:25:13

标签: python events curses python-curses

有一个简单的程序:

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

如何启用不会忽略标准Enter键,退格键和箭头键功能的模式?或者只是将所有特殊字符添加到elif:

if event == curses.KEY_DOWN:
    #key down function

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

2 个答案:

答案 0 :(得分:0)

以下示例允许您保留退格(请记住退格的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

我希望这会有所帮助。

答案 1 :(得分:0)

stackoverflow.com/a/58886107/9028532中的代码可让您轻松使用任何键码!
https://stackoverflow.com/a/58886107/9028532

它表明它不会忽略标准ENTER,Backspace和Arrows键。 getch()正常工作。但是也许操作系统在 getch()自己获得机会之前就已经掌握了一些键。通常可以在操作系统中进行某种程度的配置。

相关问题