I'm writing a Python program that logs terminal interaction (similar to the script program), and I'd like to filter out the VT100 escape sequences before writing to disk. I'd like to use a function like this:
def strip_escapes(buf):
escape_regex = re.compile(???) #
return escape_regex.sub('', buf)
What should go in escape_regex?
解决方案
The combined expression for escape sequences can be something generic like this:
(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]
Should be used with re.I
This incorporates:
Two-byte sequences, i.e. \x1b followed by a character in the range of @ until _.
One-byte CSI, i.e. \x9b as opposed to \x1b + "[".
However, this will not work for sequences that define key mappings or otherwise included strings wrapped in quotes.