11

我正在编写一个记录终端交互的 Python 程序(类似于脚本程序),并且我想在写入磁盘之前过滤掉 VT100 转义序列。我想使用这样的功能:

def strip_escapes(buf):
    escape_regex = re.compile(???) # <--- this is what I'm looking for
    return escape_regex.sub('', buf)

应该进去什么escape_regex

4

3 回答 3

4

转义序列的组合表达式可以是这样的通用表达式:

(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]

应该与re.I

这包括:

  1. 两字节序列,即\x1b后跟一个在@until范围内的字符_
  2. 一字节 CSI,即\x9b相对于\x1b + "[".

但是,这不适用于定义键映射或包含在引号中的字符串的序列。

于 2013-02-26T08:48:50.813 回答
3

VT100 代码已经(大部分)根据此处的类似模式进行了分组:

http://ascii-table.com/ansi-escape-sequences-vt-100.php

我认为最简单的方法是使用 regexbuddy 之类的工具为每个 VT100 代码组定义一个正则表达式。

于 2011-11-20T15:48:08.960 回答
1

我找到了以下解决方案来成功解析 vt100 颜色代码并删除不可打印的转义序列。使用 telnetlib 运行 telnet 会话时,此处找到的代码片段成功地为我删除了所有代码:

    def __processReadLine(self, line_p):
    '''
    remove non-printable characters from line <line_p>
    return a printable string.
    '''

    line, i, imax = '', 0, len(line_p)
    while i < imax:
        ac = ord(line_p[i])
        if (32<=ac<127) or ac in (9,10): # printable, \t, \n
            line += line_p[i]
        elif ac == 27:                   # remove coded sequences
            i += 1
            while i<imax and line_p[i].lower() not in 'abcdhsujkm':
                i += 1
        elif ac == 8 or (ac==13 and line and line[-1] == ' '): # backspace or EOL spacing
            if line:
                line = line[:-1]
        i += 1

    return line
于 2015-03-09T08:55:48.750 回答