monitoring the temperature of the CPU with Python - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: monitoring the temperature of the CPU with Python (/thread-33291.html) |
monitoring the temperature of the CPU with Python - apollo - Apr-13-2021 dear fellows, 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-subprocess-examples Your Apollo 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 RE: monitoring the temperature of the CPU with Python - snippsat - Apr-13-2021 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}") RE: monitoring the temperature of the CPU with Python - apollo - Apr-13-2021 dear Snippsat 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 |