4

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

2
  • Try for i in text_split: i.split() which will provide a list of the data items within each line. Or x = [i.split() for i in text_split] giving x as a list of lists. Commented Mar 16, 2021 at 17:19
  • 1
    @RolfofSaxony that will also split the description field, but it could be easily rebuilt by rejoining all the last pieces of each line ' '.join(line.split()[3:]) Commented Mar 16, 2021 at 17:23

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Cool, You can add it to the linux-parsers package so everyone can use it :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.