Python解析命令行输出(Linux)

2024-03-29 05:43:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用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(" ")将不起作用

我该怎么做

OS:Debian-like Linux x64 (Kernel 4.19).


Tags: no文本终端checktypeservicealllist
1条回答
网友
1楼 · 发布于 2024-03-29 05:43:22

下面的代码适合我。萨克森州的@Rolf和@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])

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

相关问题 更多 >