Reputation: 5974
I have some data that looks likethis, number of lines can vary:
? (192.168.30.4) at 00:10:60:0a:70:26 [ether] on vlan20
? (192.168.30.1) at 70:ca:9b:99:6a:82 [ether] on vlan20
#etc similar format
I want to parse this such that I can print something like this in a table:
#Protocol Address Age (min) Hardware Addr Type Interface
#Internet 192.168.30.4 - 0010.600a.7026 ARPA Vlan20
#Internet 192.168.30.1 - 70ca.9b99.6a82 ARPA Vlan20
I split the data by line into two lists
parse = proc_stdout.split('\n')
This gave a list with two elements:
['? (192.168.30.4) at 00:10:60:0a:70:26 [ether] on vlan20', '? (192.168.30.1) a
t 70:ca:9b:99:6a:82 [ether] on vlan20', '']
Now I wish to split the data further so that at each space in a list a new list is created. This would yield a list of lists for each line of the output above. I could then search each list of lists to extract the data I need and print it. However you can't split a list? What's the best way to do this?
Upvotes: 1
Views: 89
Reputation: 250891
You can use strs.splitlines
and a list comprehension here:
>>> data="""? (192.168.30.4) at 00:10:60:0a:70:26 [ether] on vlan20
... ? (192.168.30.1) at 70:ca:9b:99:6a:82 [ether] on vlan20"""
>>> [line.split() for line in data.splitlines()]
[['?', '(192.168.30.4)', 'at', '00:10:60:0a:70:26', '[ether]', 'on', 'vlan20'],
['?', '(192.168.30.1)', 'at', '70:ca:9b:99:6a:82', '[ether]', 'on', 'vlan20']
]
For the desired output you have to use string formatting here:
data="""? (192.168.30.4) at 00:10:60:0a:70:26 [ether] on vlan20
? (192.168.30.1) at 70:ca:9b:99:6a:82 [ether] on vlan20"""
print "#Protocol Address Age (min) Hardware Addr Type Interface"
for line in data.splitlines():
_,ip,_,har_ad,_,_,interface = line.split()
ip = ip.strip('()')
it = iter(har_ad.split(':'))
har_ad = ".".join([x+y for x,y in zip(it,it)])
print "#Internet {} {:>11s} {:>18s} {:>5s} {:>8s}".format(ip,'-', har_ad,'ARPA' ,interface)
output:
#Protocol Address Age (min) Hardware Addr Type Interface
#Internet 192.168.30.4 - 0010.600a.7026 ARPA vlan20
#Internet 192.168.30.1 - 70ca.9b99.6a82 ARPA vlan20
Upvotes: 1
Reputation: 4182
You can use list comprehension or generator statement for this purposes:
parse = proc_stdout.strip('\n').split('\n')
parsed_list = [line.split() for line in parse]
or generator if You will process result into other structure
parse = proc_stdout.strip('\n').split('\n')
parsed_list = (line.split() for line in parse)
Upvotes: 2