Python Forum

Full Version: monitoring the temperature of the CPU with Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
dear fellows,  Wink

 

what is aimed: on Raspberry Pi i want monitor the CPU temp at a command line, there is the vcgencmd command.


Well  We can do this in bash:

To read CPU temp at a command line, we can use the vcgencmd command.

how to do this in bash:

 
echo "The CPU is at $(vcgencmd measure_temp) degrees."

The CPU is at temp=45.5'C degrees.
i think that we can do this with Python as well: 

 
import re, subprocess


def check_CPU_temp():
    temp = None
    err, msg = subprocess.getstatusoutput('vcgencmd measure_temp')
    if not err:
        m = re.search(r'-?\d\.?\d*', msg)   # a solution with a  regex 
        try:
            temp = float(m.group())
        except:
            pass
    return temp, msg

temp, msg = check_CPU_temp()

print "temperature (" + u'\xb0' + "C): ", temp
print "full message:    ", msg
 #which returns uns a floating point value  and furtermore additionally the original message in which it is contained.
 
this will return the following output

temperature (°C):  67.0
full message:     temp=67.6'C
 

I hopefully have ceated the the code right - with usage of supprocess 

 
cf: Python 3 Subprocess Examples
https://queirozf.com/entries/python-3-su...s-examples

 Your Apollo Smile


on a sidenote: with psutil i can do much much more. i know. But this is my first step in gathering some data out of the system. with psutil i am able to monitor much much better the status of my raspberry pi. We re able to monitor the parameters of the CPU, the memory size and also the disk.

in the next step i will use psutil
You stop using Python 2(dead💀),that you use Raspberry Pi is no excuse as most of there stuff is updated.
So in Python 3.9,see that Unicode can now be used in string one biggest update moving from 2 to 3.
>>> temp = 24.5
>>> print(f"temperature {temp}°C)")
temperature 24.5°C)
import re, subprocess

def check_CPU_temp():
    temp = None
    err, msg = subprocess.getstatusoutput('vcgencmd measure_temp')
    if not err:
        m = re.search(r'-?\d\.?\d*', msg)   # a solution with a  regex
        try:
            temp = float(m.group())
        except ValueError: # catch only error needed
            pass
    return temp, msg

temp, msg = check_CPU_temp()
print(f"temperature {temp}°C")
print(f"full message {msg}")
dear Snippsat Smile

many thanks for the headsup

glad that you have had a look at this.


i will check all my scripts and will do all of them in Python 3.9


Many thanks for your help.

Have a great day Smile