我正在编写一个Python程序,它记录终端交互(类似于脚本程序),我想在写入磁盘之前过滤掉VT100转义序列。我想用这样的函数:
def strip_escapes(buf):
escape_regex = re.compile(???) # <--- this is what I'm looking for
return escape_regex.sub('', buf)在escape_regex中应该做什么
发布于 2013-02-26 08:48:50
转义序列的组合表达式可以是泛型的,如下所示:
(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]应该与re.I一起使用
这包括:
\x1b后面跟着@范围内的一个字符,直到_为止.\x9b而不是\x1b + "["。但是,对于定义键映射或以其他方式包含在引号中的字符串的序列来说,这是行不通的。
发布于 2011-11-20 15:48:08
在这里,VT100代码已经按照类似的模式分组(主要是):
http://ascii-table.com/ansi-escape-sequences-vt-100.php
我认为最简单的方法是使用regexbuddy这样的工具为每个VT100代码组定义一个regex。
发布于 2015-03-09 08:55:48
我找到了以下解决方案来成功地解析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 linehttps://stackoverflow.com/questions/7857352
复制相似问题