我需要解析 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/