如何将此输出格式化为数组/可用数据

时间:2019-07-18 13:28:37

标签: python

我不是行业编码人员,而是基础结构工程师,正在学习为我的角色编写代码。我有一个输出,正在努力思考如何使它工作。

我已经利用了一些同事,但是数据是以奇怪的格式输出的,我不确定如何获得想要的结果。我已经尝试过分界线,但效果不理想。

当前代码很简单。它只是从开关中拉出输出命令,然后将其分开:

output = net_connect.send_command("show switch")
switchlines = output.splitlines()
print(output)
print(switchlines[5])

在这种情况下,它将输出以下内容:

Switch/Stack Mac Address : 188b.45ea.a000 - Local Mac Address
Mac persistency wait time: Indefinite
                                             H/W   Current
Switch#   Role    Mac Address     Priority Version  State 
------------------------------------------------------------
*1       Active   188b.45ea.a000     15     V01     Ready               
 2       Standby  00ca.e5fc.1780     14     V06     Ready               
 3       Member   00ca.e5fc.5e80     13     V06     Ready               
 4       Member   00ca.e588.f480     12     V06     Ready               
 5       Member   00ca.e588.ee80     11     V06     Ready               


*1       Active   188b.45ea.a000     15     V01     Ready

该表以字符串形式出现,从本质上讲,我需要找到一种将其拆分为可用块(即2D数组)的方法,以便可以单独使用每个字段。

1 个答案:

答案 0 :(得分:1)

您已经将行中的行分隔在一个列表(switchlines)中,因此您要做的就是遍历该列表,并split在空格上逐行。因为有许多空格分开,所以我们也想strip这些元素。因此,您可以执行以下操作:

res = []

for line in switchlines[5:]:
    elements = [x.strip() for x in line.split()]
    res.append(elements)

这给出了您的示例文本:

[['*1', 'Active', '188b.45ea.a000', '15', 'V01', 'Ready'],
 ['2', 'Standby', '00ca.e5fc.1780', '14', 'V06', 'Ready'], 
 ['3', 'Member', '00ca.e5fc.5e80', '13', 'V06', 'Ready'], 
 ['4', 'Member', '00ca.e588.f480', '12', 'V06', 'Ready'], 
 ['5', 'Member', '00ca.e588.ee80', '11', 'V06', 'Ready']]

另一个可以稍后帮助您处理数据的选项是将其收集到字典中而不是列表中:

for line in switchlines[5:]:
    switch, role, mac, prio, ver, state, *extras = [x.strip() for x in line.split()]
    res.append({'switch': switch, 'role': role, 'mac': mac,
                'prio': prio, 'ver': ver, 'state': state, 'extras': extras})

这给出了您的示例文本:

[{'switch': '*1', 'role': 'Active', 'mac': '188b.45ea.a000', 'prio': '15', 'ver': 'V01', 'state': 'Ready', 'extras': []},
 {'switch': '2', 'role': 'Standby', 'mac': '00ca.e5fc.1780', 'prio': '14', 'ver': 'V06', 'state': 'Ready', 'extras': []},
 {'switch': '3', 'role': 'Member', 'mac': '00ca.e5fc.5e80', 'prio': '13', 'ver': 'V06', 'state': 'Ready', 'extras': []},
 {'switch': '4', 'role': 'Member', 'mac': '00ca.e588.f480', 'prio': '12', 'ver': 'V06', 'state': 'Ready', 'extras': []},
 {'switch': '5', 'role': 'Member', 'mac': '00ca.e588.ee80', 'prio': '11', 'ver': 'V06', 'state': 'Ready', 'extras': []}]