Filtering terminal commands on linux

Lonnie Princehouse finite.automaton at gmail.com
Fri Jul 29 21:38:28 CEST 2005


Firstly, there's probably a better way to do whatever you're trying to
do w.r.t cd/dvd burning.  I'm not familiar with gear, but its webpage
lists "Batch file scripting capability" as a feature, which suggests
that you might be able to do what you want without parsing output
intended for humans.  There are also a multitude of command-line cd and
dvd utilities for Linux which might be better for scripting.

That said, it shouldn't be too hard to craft a regular expression that
matches ANSI control sequences. Using
http://www.dee.ufcg.edu.br/~rrbrandt/tools/ansi.html as a reference,
here's how to do this for the first few control sequences...

esc = '\x1B'
start_control_sequence = esc + '['

Pn = r'\d+'     # Numeric parameter
Ps = '%s(;%s)*' % (Pn,Pn)   # Selective parameter
PL = Pn
Pc = Pn

control_sequences = [
    PL + ';' + Pc + '[Hf]',     # Cursor position
    Pn + '[ABCD]',              # Cursor up|down|forward|backward
    's',                        # Save cursor position
    'u',                        # Restore cursor position
    '2J',                       # Erase display
    'K',                        # Erase line
    Ps + 'm',                   # Set graphics mode
    '=' + Pn + '[hl]',          # Set|Reset mode
    # ... etc
]

match_ansi = re.compile(start_control_sequence +
    '(' + '|'.join(control_sequences) + ')')

def strip_ansi(text):
    return match_ansi.sub('',text)


(note: code is untested.. may contain typos)




More information about the Python-list mailing list