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!

2 Answers 2

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():
Sign up to request clarification or add additional context in comments.

1 Comment

You're the man! Thanks. Knew there had to be a simple function like splitlines() for this :D
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.