简体   繁体   中英

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!

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():

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM