6

I wanted to print the OS system information for a Pi in python. The OS command "cat /etc/os-release" works fine in the Terminal with nice row formatting.

In Python I used :

import subprocess

output = subprocess.check_output("cat /etc/os-release", shell=True)
print("Version info: ",output)

That works, but I do not get any newlines:

Version info:  b'PRETTY_NAME="Raspbian GNU/Linux 9 (stretch)"\nNAME="Raspbian GNU/Linux"\nVERSION_ID="9"\nVERSION="9 (stretch)"\nID=raspbian\nID_LIKE=debian\nHOME_URL="http://www.raspbian.org/"\nSUPPORT_URL="http://www.raspbian.org/RaspbianForums"\nBUG_REPORT_URL="http://www.raspbian.org/RaspbianBugs"\n'

How can I format the output to add newlines?

2
  • 2
    Possible duplicate of Convert bytes to a string? Commented Dec 18, 2018 at 23:49
  • 'str(output)' would work Commented Dec 18, 2018 at 23:54

1 Answer 1

19

The problem is that your string is a bytestring, as denoted in the output with the letter b as a prefix to the string: Version info: b'PRETTY_NAME="Raspbian GNU/Linux...

A simple fix would be to decode the string as follows:

import subprocess

output = subprocess.check_output("cat /etc/os-release", shell=True)
output = output.decode("utf-8")
print("Version info: ",output)

And the result will be printed correctly. You can verify that this is a different object if you print its type before and after decoding:

import subprocess

output = subprocess.check_output("cat /etc/os-release", shell=True)
print(type(output))
output = output.decode("utf-8")
print(type(output))

This will result in the following output:

<class 'bytes'>
<class 'str'>
Sign up to request clarification or add additional context in comments.

1 Comment

That did it !Nice clean solution !

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.