Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering out ANSI escape sequences [duplicate]

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 escapes I don't care about. These escapes are JSON encoded, so they look like "\033[A" and "\033]0;". I don't actually need to interpret the codes, but I do need to know how many characters are included in each (you'll notice the first sequence is 6 characters while the second is 7). Is there a straightforward way to filter out these codes from the strings I have?

like image 790
rivenmyst137 Avatar asked Nov 22 '12 04:11

rivenmyst137


3 Answers

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

like image 113
Jeff Avatar answered Oct 30 '22 17:10

Jeff


Another variant:

def strip_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)
like image 22
boxed Avatar answered Oct 30 '22 16:10

boxed


#!/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)
    for match in ansi_eng.finditer(string):
        start = match.start()
        end = match.end()
        matches.append(match)
    matches.reverse()
    for match in matches:
        start = match.start()
        end = match.end()
        string = string[0:start] + string[end:]
    return string

if __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
like image 24
Brian Bruggeman Avatar answered Oct 30 '22 18:10

Brian Bruggeman