Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Python subprocess.check_output()

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!

like image 472
DJMcCarthy12 Avatar asked Mar 03 '15 21:03

DJMcCarthy12


People also ask

What is subprocess Check_output in Python?

The subprocess. check_output() is used to get the output of the calling program in python. It has 5 arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the commands that are to be passed as a string.

What is the return type of subprocess Check_output?

CalledProcessError Exception raised when a process run by check_call() or check_output() returns a non-zero exit status. returncode Exit status of the child process.

How do I get output to run from subprocess?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.


1 Answers

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():
like image 60
Martijn Pieters Avatar answered Sep 19 '22 15:09

Martijn Pieters