我正在编写一个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
中应该放什么?
(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]
应与re.I
一起使用
这里包括:
@
到_
范围内的字符跟在\x1b
后面。\x9b
而不是\x1b + "["
。但对于定义键映射或包含在引号中的其他字符串的序列将无效。
VT100代码已经分组(大部分)根据类似的模式在这里:
http://ascii-table.com/ansi-escape-sequences-vt-100.php
我认为最简单的方法是使用像regexbuddy这样的工具为每个VT100代码组定义一个正则表达式。
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
sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"
(来源) - Adam Monsen