Python Curses - 检测退格键

标签 python python-3.x macos-high-sierra python-curses

我在使用 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/

相关文章:

python - 如何从 Python 脚本中列出 Python 可用的所有包/模块?

python - 如何找到内存中最大的对象?

python-3.x - 用 Pandas 中的if条件逐列求和

xcode - Xcode 7.3.1 是否可以在 macOS High Sierra (10.13) 上运行?

configuration - Flutter macOS high Sierra 错误

python : Apply distributive law to elements in list

python - 成对平方差的高效 Numpy 计算

django - 在 Travis 上运行 django unittests 时如何解决 "psycopg2.errors.UndefinedTable: relation "auth_user“不存在”

objective-c - AppleEvents:收到 mach 消息,它不是 getMemoryReference 中预期的复杂类型

python - 将包含 JSON 对象的数据框扩展为更大的数据框