[英]Python - Parsing Command Line Output (Linux)
I need to parse systemctl list-units --type=service --all --no-pager
terminal output by using Python 3. I need to get every cell value of the output text.我需要使用 Python 来解析systemctl list-units --type=service --all --no-pager
terminal output 3. 我需要获取 Z78E6221F6393D1356681DBCE66 的每个单元格值
Splitting whole output for every line:为每一行拆分整个 output :
text1 = subprocess.check_output("systemctl list-units --type=service --all --no-pager", shell=True).strip().decode()
text_split = text1.split("\n")
But every line have spaces and some line data also have spaces.但是每一行都有空格,一些行数据也有空格。 Using .split(" ")
will not work.使用.split(" ")
将不起作用。
How can I do that?我怎样才能做到这一点?
OS: Debian-like Linux x64 (Kernel 4.19).
操作系统: Debian-like Linux x64 (Kernel 4.19).
Following code works for me.以下代码对我有用。 Comments from @Rolf of Saxony and @Pietro were helpful for me. @Rolf of Saxony 和 @Pietro 的评论对我很有帮助。 I have used them and made some additions/changes.我已经使用它们并进行了一些添加/更改。
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])
Note : It is OK for me.注意:对我来说没问题。 There maybe mistakes or a more proper way to to it.可能有错误或更正确的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.