我在使用 Curses 模块检测退格键时遇到了困难。每当我按下 Backspace 键时,返回的字符/字符串都是“^?”,但是我无法通过以下方式检测到它:
如果 str(key) == '^?':
下面的代码已经设置好可以运行了
import curses
def main(win):
win.nodelay(True)
key = ''
record = ''
win.clear()
win.addstr("Key:")
win.addstr('\n\nRecord:')
win.addstr(record)
while True:
try:
key = win.getkey()
if str(key) == '^?':
# Attempt at detecting the Backspace key
record = record[:-1]
elif str(key) == '\n':
# Attempt at detecting the Enter Key
record = ''
else:
record += str(key)
win.clear()
win.addstr("Key:")
win.addstr(str(key))
win.addstr('\n\nRecord:')
win.addstr(record)
if key == os.linesep:
break
except Exception as e:
# No input
pass
curses.wrapper(main)
# CTRL+C to close the program
最佳答案
根据您的澄清评论,您终端中的退格键既不是 'KEY_BACKSPACE'
也不是 '\b'
('\x08'
) .
由于您正在使用调用 curses.initscr()
的 curses.wrapper()
,这表明您的 terminfo< 有问题
数据库(不太可能)或您的终端配置(更有可能)。
getkey() == 'KEY_BACKSPACE'
或 getch() == curses.KEY_BACKSPACE
应该可以在任何正确配置的系统上运行,因此您很可能在其他应用程序中也有问题。
TERM
环境变量是终端类型如何与需要基本电传打字机以外的功能的工具通信的方式,因此,要解决这个问题,首先要检查 TERM
是什么环境变量包含在您运行 Python 的环境中。
print(os.environ['TERM'])
作为快速破解,您可以检查它被观察到的所有值。
if key in ('KEY_BACKSPACE', '\b', '\x7f'):
关于Python Curses - 检测退格键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47481955/