Parsing Python subprocess.check_output()
Asked Answered
S

2

11

I am trying to use and manipulate output from subprocess.check_output() in python but since it is returned byte-by-byte

for line in output:
    # Do stuff

Does not work. Is there a way that I can reconstruct the output to the line formatting that it has when it is printed to stdout? Or what is the best way to search through and use this output?

Thanks in advance!

Sauter answered 3/3, 2015 at 21:56 Comment(0)
I
13

subprocess.check_output() returns a single string. Use the str.splitlines() method to iterate over individual lines in that string:

for line in output.splitlines():
Indican answered 3/3, 2015 at 21:58 Comment(1)
You're the man! Thanks. Knew there had to be a simple function like splitlines() for this :DSauter
S
1

For anyone following along:

output = subprocess.check_output(cmd, shell=True)

for line in output.splitlines():
   print(line)

will output:

b'first line'
b'second line'
b'third line'

doing:

output = subprocess.check_output(cmd, shell=True)

output = output.decode("utf-8")
for line in output.splitlines():
   print(line)

will output:

first line
second line
third line
Surplus answered 27/1, 2023 at 10:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.