gpt4 book ai didi

python - curses 模块中的标准键功能

转载 作者:行者123 更新时间:2023-11-28 19:21:39 27 4
gpt4 key购买 nike

有一个简单的程序:

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、Backspace 和箭头键功能的模式?或者唯一的方法是将所有特殊字符添加到 elif:

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

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

最佳答案

这是一个允许您保留退格键的示例(请记住退格键的 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

不在 [-1, 127] 中的 key 忽略打印 127(ASCII DEL)或 -1(错误)。对于其他字符代码,您可以将其他项目添加到其中。

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

我希望这会有所帮助。

关于python - curses 模块中的标准键功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23626158/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com