如何在Python中解析CLI命令输出(表格)?

3

我对解析技术还是新手。

switch-630624 [standalone: master] (config) # show interface ib status

Interface      Description                                Speed                   Current line rate   Logical port state   Physical port state
---------      -----------                                ---------               -----------------   ------------------   -------------------
Ib 1/1                                                    14.0 Gbps rate          56.0 Gbps           Initialize           LinkUp
Ib 1/2                                                    14.0 Gbps rate          56.0 Gbps           Initialize           LinkUp
Ib 1/3                                                    2.5 Gbps rate only      10.0 Gbps           Down                 Polling

假设我有一个引擎,它在交换机上注入命令,并将上述输出作为一个名为“output”的变量中的一个巨大字符串。
我想返回一个仅包含端口号的字典,如下所示:
{'Ib1/11': '1/11', 'Ib1/10': '1/10', ... , }

我想我应该使用Python的Subprocess模块和正则表达式。
端口数量可能会有所不同(可以是3个,10个,20个,30个,60个...)。
我将感激任何方向。
谢谢,
Qwerty

为什么要用字典?如果你只有端口,为什么不使用集合或(更简单的)列表呢? - cdarke
我不太关心返回的数据结构。我不知道如何使用正则表达式和字符串函数来忽略/删除所有无关的文本(无关的标题名称,无关的---,无关的列值等)。 - Qwerty
1个回答

1
# Did this in Python 2.7
import re

# Assume your input is in this file
INPUT_FILE = 'text.txt'

# Regex to only pay attention to lines starting with Ib
# and capture the port info
regex = re.compile(r'^(Ib\s*\S+)')
result = [] # Store results in a list
with open(INPUT_FILE, 'r') as theFile:
  for line in theFile:
    match = regex.search(line)
    if not match: continue
    result.append(match.group())
print result

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接