Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Splitting whole output for every line:

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.

How can I do that?

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

like image 450
pythonlearner9001 Avatar asked Sep 07 '25 10:09

pythonlearner9001


1 Answers

Following code works for me. Comments from @Rolf of Saxony and @Pietro were helpful for me. 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.

like image 193
pythonlearner9001 Avatar answered Sep 10 '25 22:09

pythonlearner9001