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

标签 python python-3.x parsing

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

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).

最佳答案

以下代码对我有用。萨克森州@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])
备注 : 对我来说没问题。可能有错误或更合适的方法。

关于Python - 解析命令行输出 (Linux),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66659750/

相关文章:

python - Vim python 语法高亮显示在很长的行中挂起

python - 为什么@staticmethod 没有跨类保留,而@classmethod 是?

python - 如何将 pandas DataFrame 拆分为多个 DataFrame?

python - 为什么我不能在 map() 中使用字符串函数?

c# - 将字符串解析为 Unity3D 中的代码 (C#)

python - 有没有办法获得多条曲线与另一条曲线的所有交点?

python - 如何检查用户是否已经通过某种方法

python - Python3 函数中没有标识符的单个 * 是什么意思?

Python 的 re.split() 没有删除所有匹配的字符

c# - C#解析XML数据并显示到ListBox