1

In python3 I am using subprocess.check_output to get the output from a command, but when I print it it looks something like

b'first line\nsecond line\nthird line'

How can I easily 'convert' that to something like the following:

first line
second line
third line

I tried the following code:

for line in output.split(b'\n'):
    print(line)

but got the following output:

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

How to do it correct (and probably in one short line)?

1 Answer 1

2

According to the official documentation here, the output from check_output is:

By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level.

So, to convert from bytes to str you need to use the decode function like so:

print(x.decode("utf-8") )
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.