tmsblgh
tmsblgh

Reputation: 527

Command output parsing in Python2.7

There is a system command which gives output like this:

 OUTPUT    HDMI2  123.123.123
(OUTPUT) * HDMI1  124.124.124

How can I parse it? I need to parse, and I need data from the line with () and *, this is in used. When I got the in-used line I need the HDMI part and the numbers part.

Upvotes: 1

Views: 64

Answers (1)

thebjorn
thebjorn

Reputation: 27321

Check if the line contains the string VGA, then return the numbers:

if 'VGA' in line:
    return line.split('VGA')[1]

if "VGA" should be part of the result:

if 'VGA' in line:
    return "VGA " + line.split('VGA')[1]

and, if you just want the numbers, individually:

if 'VGA' in line:
    return map(int, line.split('VGA')[1].split('.'))

Update: solution for updated requirements.

To find the line marked with () and *, a regular expression might be better, e.g.:

for line in input_lines:
    m = re.match(r'''
        ^\(                  # at the beginning of the line look for a (
        [A-Z]+               # then a group of upper-case letters, i.e. OUTPUT
        \)                   # followed by a )
        \s*                  # some space
        \*                   # a literal *
        \s*                  # more space
        (?P<tag>[A-Z0-9]+)   # create a named group (tag) that matches HDMI1, ie. upper case letters or numbers
        \s*                  # more space
        (?P<nums>[\d\.]+)    # followed by a sequence of numbers and .
        $                    # before reaching the end of the line
        ''', line, re.VERBOSE)
    if m: 
        break
else:  # note: this else goes with the for-loop
    raise ValueError("Couldn't find a match")
# we get here if we hit the break statement
tag = m.groupdict()['tag']    # HDMI1
nums = m.groupdict()['nums']  # 124.124.124

Upvotes: 1

Related Questions