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?
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'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With