这是一个允许您保留退格的示例(请记住退格的 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
忽略打印 127 (key not in [-1, 127]
ASCII DEL)或 -1(错误)。您可以在其中添加其他项目,以获取其他字符代码。
try/except/finally 用于处理 Ctrl-C。这会重置终端,因此您在运行时不会得到奇怪的提示输出。
这是官方 Python 文档的链接,供将来参考:
https
://docs.python.org/2.7/library/curses.html#module-curses
我希望这会有所帮助。