Python正则表达式匹配VT100转义序列

11

我正在编写一个Python程序,用于记录终端交互(类似于script程序),我想在将其写入磁盘之前过滤掉VT100转义序列。我想使用以下函数:

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

escape_regex中应该放什么?


有点复杂:http://en.wikipedia.org/wiki/ANSI_escape_sequences - sarnold
2
请查看http://www.webdeveloper.com/forum/showthread.php?t=186004获取PHP版本。将其转换为Python应该很简单。 - Mansour
1
在这些其他评论的精神中,这里也有一个完全相同的 TCL 进程... http://wiki.tcl.tk/9673 - Niall Byrne
1
这是我用过的一个命令:sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" (来源) - Adam Monsen
3个回答

5
组合转义序列的表达式可以像这样通用:
(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]

应与re.I一起使用

这里包括:

  1. 双字节序列,即以@_范围内的字符跟在\x1b后面。
  2. 单字节CSI,即\x9b而不是\x1b + "["

但对于定义键映射或包含在引号中的其他字符串的序列将无效。


3

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

这对于一些常见的初始化序列是行不通的,例如 escape = escape > escape 7 escape 8 以及任何重置模式控制(以“l”结尾)。 这些在xterm的文档中列出:http://invisible-island.net/xterm/ctlseqs/ctlseqs.html - Thomas Dickey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接