python - 如何在 python 中解析 CLI 命令输出(表)?

标签 python parsing

我是解析新手。

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

假设我有一个在交换机上注入(inject)命令的引擎,并将上述输出作为 1 个大字符串放入名为“output”的变量中。

我想返回一个仅包含端口号的字典,如下所示:

{'Ib1/11': '1/11', 'Ib1/10': '1/10', ... , }

我想我应该使用 Python 的 Subprocess 模块和正则表达式。

端口数量可能有所不同(可以是 3、10、20、30、60...)。

我会感激任何形式的指导。

谢谢

Qwerty

最佳答案

# 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

关于python - 如何在 python 中解析 CLI 命令输出(表)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27129850/

相关文章:

python - 使用表单发布请求,然后能够保存它在单独请求中返回的数据

Python - 线程 pyinotify 输出。最好写入文件或字符串

python - Tensorflow Beta 2.0 中的 tf.keras 是否支持自动混合精度?

linux - Linux 中的_splitpath

php - 可以通过索引访问 PHP parse_str 数组值吗?

php - 是否有 PHP 的 PDF 解析器?

javascript - 拆分 json 并使用 ng-repeat Angular Directive(指令)显示它

python - 来自听众的循环中断

c++ - 在 C++ 中解析字符串以分配参数

python - 改进的欧拉方法