theMusicMan
Posts: 111
Joined: Tue May 23, 2017 8:41 pm

Syntax for running shell command in Python

Thu Feb 07, 2019 12:33 pm

Hi All

I would like to run the shell command;

Code: Select all

vcgencmd measure_temp 
... which runs perfectly in the terminal, within a Python script, assigning that to a variable for subsequent

Code: Select all

cpu_temp = subprocess.check_output("vcgencmd measure_temp", shell=True)
I tried the above (obtained from elsewhere) but the result returned is not what I expected, which is;.

b"temp=52.6'C/n"

Could someone offer some advice please, many thanks.

pcmanbob
Posts: 6248
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Syntax for running shell command in Python

Thu Feb 07, 2019 1:48 pm

If you just want the temperature value you can do it like this

Code: Select all

with open("/sys/class/thermal/thermal_zone0/temp", "r") as file:
    temp = float(file.read())
tempC = temp/1000
print (tempC)
but if you want the output as a string including the text then this code

Code: Select all

with open("/sys/class/thermal/thermal_zone0/temp", "r") as file:
    temp = float(file.read())
tempC = temp/1000

tempC = str(tempC)
output = "temp=" + tempC + "'C"
print (output)
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

User avatar
MrYsLab
Posts: 334
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: Syntax for running shell command in Python

Thu Feb 07, 2019 4:10 pm

If you wish to us Popen, this will work:

Code: Select all

import subprocess

# execute the command using Popen
sb = subprocess.Popen(['vcgencmd', 'measure_temp'], stdout=subprocess.PIPE)

# get the command output
cmd_out = sb.communicate()

# convert from byte string to string
temp = cmd_out[0].decode()
print(temp)

And here is the output when I run this:

Code: Select all

[email protected]:~ $ python3 pop.py
temp=44.0'C

Return to “Python”