在纯Python中读取退格,DEL和来自stdin的朋友吗?

时间:2016-01-31 22:45:01

标签: python user-input stdin

如果一个google 退格python stdin 左右,有很多SO结果,没有一个可以解决我的问题。它们都是关于退格键 而不是如何获取的内容。功能

这是一个从stdin读取单个按键的功能,礼貌https://stackoverflow.com/a/6599441/4532996

def read_single_keypress():
    import termios, fcntl, sys, os
    fd = sys.stdin.fileno()
    # save old state
    flags_save = fcntl.fcntl(fd, fcntl.F_GETFL)
    attrs_save = termios.tcgetattr(fd)
    # make raw - the way to do this comes from the termios(3) man page.
    attrs = list(attrs_save) # copy the stored version to update
    # iflag
    attrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK
                  | termios.ISTRIP | termios.INLCR | termios. IGNCR
                  | termios.ICRNL | termios.IXON )
    # oflag
    attrs[1] &= ~termios.OPOST
    # cflag
    attrs[2] &= ~(termios.CSIZE | termios. PARENB)
    attrs[2] |= termios.CS8
    # lflag
    attrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON
                  | termios.ISIG | termios.IEXTEN)
    termios.tcsetattr(fd, termios.TCSANOW, attrs)
    # turn off non-blocking
    fcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK)
    # read a single keystroke
    try:
        ret = sys.stdin.read(1) # returns a single character
    except KeyboardInterrupt:
        ret = 0
    finally:
        # restore old state
        termios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save)
        fcntl.fcntl(fd, fcntl.F_SETFL, flags_save)
    return ret

Hacky就是这样,它似乎是跨平台的。

my module实现这是一个实用功能:

def until(char) -> str:
    """get chars of stdin until char is read"""
    import sys
    y = ""
    sys.stdout.flush()
    while True:
        i = read_single_keypress()
        _ = sys.stdout.write(i)
        sys.stdout.flush()
        if i == char or i == 0:
            break
        y += i
    return y

哪种方法效果很好,除了按退格键无效,你无法移动光标(import readline; input()允许你(至少在用GNU Readline构建的Python上)。)

我理解实现这两者的最佳方式可能是curses。我也理解curses会破坏此模块的标准库和跨平台性。

我正在寻找的是一种以捕捉退格的方式阅读stdin的方法,以及特殊奖励DEL,最好是箭头键。

该模块以Pythons为目标2和3,但我可以使用仅针对Python 3的解决方案,因为人们真的需要停止使用2。

如果你认为我因为想要在没有curses的情况下这样做而感到愤怒,那么这就是重点。

2 个答案:

答案 0 :(得分:1)

考虑使用ActiveState中的this recipe this SO answer

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()
class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch


class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()


getch = _Getch()
# then call getch() to get the input...

答案 1 :(得分:-1)

原始模式下的终端驱动程序允许读取BS ^ H和DEL字符。箭头键往往是ESC序列,而不是一个单字节,除非你有像80年代真正的Wyse终端。 GNU readline功能(例如箭头键)在原始模式下工作是不可取的,它表示不进行任何字符处理。

为了编写的应用程序支持ANSI / DEC VT100样式的终端,开发一个功能键映射器是必要的,这使得假设1键= 1个输入字节,有效地使用Wyse终端控制字符作为内部命令。

类似于通过写入输出,除非读取的输入字节被转换,可能通过管道转换为od(1),你将如何看到非打印字符?

curses库更多的是关于屏幕绘制和高效更新,它使用原始模式和getch()例程来允许菜单选项等,而不会返回。如果您只是阅读键盘输入,则没有必要。

相关问题