Skip to content Skip to sidebar Skip to footer

Filtering Out Ansi Escape Sequences

I have a python script that's trying to interpret a trace of data written to and read from stdout and stdin, respectively. The problem is that this data is riddled with ANSI escap

Solution 1:

The complete regexp for Control Sequences (aka ANSI Escape Sequences) is

/(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]/

Refer to ECMA-48 Section 5.4 and ANSI escape code

Solution 2:

Another variant:

defstrip_ansi_codes(s):
    """
    >>> import blessings
    >>> term = blessings.Terminal()
    >>> foo = 'hidden'+term.clear_bol+'foo'+term.color(5)+'bar'+term.color(255)+'baz'
    >>> repr(strip_ansi_codes(foo))
    u'hiddenfoobarbaz'
    """return re.sub(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9]{1,2})?(;[0-9]{3})?)?[m|K]?', '', s)

Solution 3:

#!/usr/bin/env python
import re

ansi_pattern = '\033\[((?:\d|;)*)([a-zA-Z])'
ansi_eng = re.compile(ansi_pattern)

def strip_escape(string=''):
    lastend = 0
    matches = []
    newstring = str(string)
    formatchin ansi_eng.finditer(string):
        start = match.start()
        end = match.end()
        matches.append(match)
    matches.reverse()
    formatchin matches:
        start = match.start()
        end = match.end()
        string = string[0:start] + string[end:]
    returnstringif __name__ == '__main__':
    import sys
    import os

    lname = sys.argv[-1]
    fname = os.path.basename(__file__)
    if lname != fname:
        with open(lname, 'r') as fd:
            for line in fd.readlines():
                print strip_escape(line).rstrip()
    else:
        USAGE = '%s <filename>' % fname
        print USAGE

Solution 4:

This worked for me:

re.sub(r'\x1b\[[\d;]+m', '', s)

Solution 5:

It's far from perfect, but this regex may get you somwhere:

import re
text = r'begin \033[A middle \033]0; end'print re.sub(r'\\[0-9]+(\[|\])[0-9]*;?[A-Z]?', '', text)

It already removes your two examples correctly.

Post a Comment for "Filtering Out Ansi Escape Sequences"