Python - 解析命令行输出(Linux)

4
我需要使用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 给定为一个列表的列表。 - Rolf of Saxony
1
@RolfofSaxony 这也将分割描述字段,但可以通过重新连接每行的最后几个部分来轻松重建 ' '.join(line.split()[3:]) - Pietro
1个回答

4
以下代码对我有效。来自 @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])

注意:对我来说没问题。可能存在错误或更妥善的方法。


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