Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python subprocess output format?

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?

like image 544
user3005949 Avatar asked Jan 02 '23 12:01

user3005949


1 Answers

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'>
like image 95
Sébastien Lavoie Avatar answered Jan 05 '23 05:01

Sébastien Lavoie