10

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!

DJMcCarthy12
  • 3,819
  • 8
  • 28
  • 34

2 Answers2

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():
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

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
Mia Altieri
  • 19
  • 1
  • 4