curses模块中的标准键函数

4 投票
2 回答
3875 浏览
提问于 2025-04-18 06:23

有一个简单的程序:

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()和其他模式,但没有效果……如果可以的话,请加个例子。

2 个回答

1

在stackoverflow.com/a/58886107/9028532上的代码可以让你轻松使用任何按键代码!
https://stackoverflow.com/a/58886107/9028532

这个代码演示了它不会忽略标准的回车键、退格键和方向键。getch()的功能正常。不过,有可能操作系统在getch()有机会之前就捕捉到了一些按键。这通常在操作系统中可以进行一定程度的配置。

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的删除符号)和-1(表示错误)。你可以把其他字符的代码也加到这里面。

try/except/finally 是用来处理Ctrl-C的。这可以重置终端,避免在运行后出现奇怪的提示信息。
这里有一个链接,指向官方的Python文档,供你将来参考:
https://docs.python.org/2.7/library/curses.html#module-curses

希望这对你有帮助。

撰写回答