Page 1 of 1

Syntax for running shell command in Python

Posted: Thu Feb 07, 2019 12:33 pm
by theMusicMan
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.

Re: Syntax for running shell command in Python

Posted: Thu Feb 07, 2019 1:48 pm
by pcmanbob
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)

Re: Syntax for running shell command in Python

Posted: Thu Feb 07, 2019 4:10 pm
by MrYsLab
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

pi@RPi3BP:~ $ python3 pop.py
temp=44.0'C