将控制字符应用于字符串 - Python

Per*_*l W 5 python string repr control-characters backspace

我正在尝试将控制字符(例如应该删除先前字符的'\ x08\x08)应用于字符串(向后移动,写入空格,向后移动)
例如当我键入python控制台时:

s = "test\x08 \x08"
print s
print repr(s)
Run Code Online (Sandbox Code Playgroud)

我进入我的终端:

tes
'test\x08 \x08'
Run Code Online (Sandbox Code Playgroud)

我正在寻找一个函数,让我们说"函数",它将"应用"控制字符到我的字符串:

v = function("test\x08 \x08")
sys.stdout.write(v)
sys.stdout.write(repr(v))
Run Code Online (Sandbox Code Playgroud)

所以我得到一个"干净",无控制字符的字符串:

tes
tes
Run Code Online (Sandbox Code Playgroud)

我理解在终端中,这部分是由客户端处理的,所以可能有一种方法来获取显示的字符串,使用核心unix函数

echo -e 'test\x08 \x08'
cat file.out # control char are here handled by the client
>> tes
cat -v file.out # which prints the "actual" content of the file
>> test^H ^H
Run Code Online (Sandbox Code Playgroud)

Per*_*l W 5

实际上,答案比简单的格式化要复杂一些。

进程发送到终端的每个字符都可以视为有限状态机 (FSM) 中的转换。该 FSM 的状态大致对应于显示的句子和​​光标位置,但还有许多其他变量,例如终端的尺寸、当前输入的控制序列*、终端模式(例如:VI 模式/经典 BASH 控制台), ETC。

在pexpect 源代码中可以看到此 FSM 的良好实现。

为了回答我的问题,没有核心unix“函数”可以将字符串格式化为终端中显示的内容,因为这样的函数特定于呈现进程输出的终端,并且您必须将完整的终端重写为处理每个可能的字符和控制序列。

不过我们可以自己实现一个简单的。我们需要定义一个具有初始状态的 FSM:

  • 显示的字符串:“”(空字符串)
  • 光标位置:0

和转换(输入字符):

  • 任何字母数字/空格字符:单独替换光标位置处的字符(如果没有则添加)并增加光标位置
  • \x08十六进制代码:减少光标位置

并给它喂绳子。

Python解决方案

def decode(input_string):

    # Initial state
    # String is stored as a list because
    # python forbids the modification of
    # a string
    displayed_string = [] 
    cursor_position = 0

    # Loop on our input (transitions sequence)
    for character in input_string:

        # Alphanumeric transition
        if str.isalnum(character) or str.isspace(character):
            # Add the character to the string
            displayed_string[cursor_position:cursor_position+1] = character 
            # Move the cursor forward
            cursor_position += 1

        # Backward transition
        elif character == "\x08":
            # Move the cursor backward
            cursor_position -= 1
        else:
            print("{} is not handled by this function".format(repr(character)))

    # We transform our "list" string back to a real string
    return "".join(displayed_string)
Run Code Online (Sandbox Code Playgroud)

举个例子

>>> decode("test\x08 \x08")
tes 
Run Code Online (Sandbox Code Playgroud)

关于控制序列的注意事项

ANSI 控制序列是一组字符,充当终端(显示/光标/终端模式/...)状态的转换。它可以被视为对我们的 FSM 状态和转换的改进,具有更多的子状态和子转换。

例如:当您在经典的 Unix 终端(例如 VT100)中按下 UP 键时,您实际上输入了控制序列:ESC 0 Awhere ESCis hex code \x1bESC转换到 ESCAPE 模式,并在 A 之后返回到正常模式。

一些进程将此序列解释为垂直光标位置 (VI) 的移动,其他进程解释为历史记录中的向后移动 (BASH):这完全取决于处理输入的程序。

但是,可以在输出过程中使用相同的序列,但它很可能会在屏幕中向上移动光标:这取决于终端实现。

此处提供了 ANSI 控制序列的详细列表。