【问题标题】:Python - Parsing Command Line Output (Linux)Python - 解析命令行输出 (Linux)
【发布时间】:2021-03-16 16:52:13
【问题描述】:

我需要使用 Python 3 解析systemctl list-units --type=service --all --no-pager 终端输出。我需要获取输出文本的每个单元格值。

为每一行分割整个输出:

text1 = subprocess.check_output("systemctl list-units --type=service --all --no-pager", shell=True).strip().decode()
text_split = text1.split("\n")

但是每一行都有空格,有些行数据也有空格。使用.split(" ") 将不起作用。

我该怎么做?

操作系统:Debian-like Linux x64 (Kernel 4.19).

【问题讨论】:

  • 试试for i in text_split: i.split(),它将提供每行中数据项的列表。或 x = [i.split() for i in text_split] 将 x 作为列表列表。
  • @RolfofSaxony 也将拆分描述字段,但可以通过重新加入每行的所有最后部分轻松重建它' '.join(line.split()[3:])

标签: python python-3.x parsing


【解决方案1】:

以下代码对我有用。 @Rolf of Saxony 和 @Pietro 的评论对我很有帮助。我已经使用它们并进行了一些添加/更改。

    text1 = subprocess.check_output("systemctl list-units --type=service --all --no-pager", shell=True).strip().decode()
    text_split = text1.split("\n")
    for i, line in reversed(list(enumerate(text_split))):
        if ".service" not in line:
            del text_split[i]
    
    cell_data = []
    for i in text_split:
        if i == "":
            continue
        others = i.split()
        description = ' '.join(i.split()[4:])
        if others[0] == "●":
            description = ' '.join(i.split()[5:])
        if others[0] == "●":
            cell_data.append([others[1], others[2], others[3], others[4], description])
            continue
        cell_data.append([others[0], others[1], others[2], others[3], description])

注意:对我来说没问题。可能有错误或更正确的方法。

【讨论】:

    猜你喜欢
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多