15

Goal is to switch an exhaust fan at an outside data-logging station at a solar power station. The data-collection program is written in Python under Raspbian.

For reading CPU temp at a command line, there is the vcgencmd command.

Example in bash:

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

The CPU is at temp=39.2'C degrees.

as the command returns the string "temp=39.2'C"

I've never personally seen this fail, although I know there is a question about that point.

vcgencmd measure_temp doesn't always work

Meanwhile, I would like to obtain the CPU temp in Python.

Back to the Goal: the fans are controlled by PiGPIO calls, and during data-logging I keep my external system calls to the minimum (ie., there aren't any other than Python file I/O). Also, it would be much preferable to get the answer as a simple floating-point value than to extract it from a return strung.


The question is: How to directly get CPU temp in Python?

8 Answers 8

16

For those coming here from Google. You can get Raspberry CPU temp in Python using gpiozero package.

 pip install gpiozero

Create your temp.py

from gpiozero import CPUTemperature

cpu = CPUTemperature()
print(cpu.temperature)

Output :

$ python temp.py
56.92
11

It has already been answered and accepted but I see that no one has brought up this alternative that doesn't depend on running a command but rather on reading from a file: /sys/class/thermal/thermal_zone0/temp.

This file holds the temperature in milli-degrees Celsius.

$ vcgencmd measure_temp && cat /sys/class/thermal/thermal_zone0/temp
temp=47.8'C
47774

So, open the file and read the content. No need to do string processing.

2
  • 1
    From where do you get such valuable information?
    – Old Geezer
    Sep 29, 2020 at 2:39
  • 2
    This is, IMHO, the best approach. No libraries, no binary executions. Linux at its best. Thanks for this info! Dec 22, 2020 at 20:32
3

First, set up Python:

pip install setuptools
sudo pip install git+https://github.com/nicmd/vcgencmd.git

Handy bash script cputemp

(shebang)/usr/bin/python
import vcgencmd
CPUc=vcgencmd.measure_temp()
print str(CPUc)

chmod +x cputemp
sudo cp cputemp /usr/bin

Example use in bash:

echo "The CPU is at $(cputemp) degrees C."

The CPU is at 39.6 degrees C.

Short and to the point, and in the floating data format for comparisons within the Python program..

1
  • Good answer. Is this any faster or slower than os.popen('vcgencme measure_temp')?
    – Elliott B
    Jul 23, 2018 at 2:51
2

"On Stretch there is no vcgencmd command at all."

So what is

 vcgencmd commands
commands="vcos, ap_output_control, ap_output_post_processing, vchi_test_init, vchi_test_exit, vctest_memmap, vctest_start, vctest_stop, vctest_set, vctest_get, pm_set_policy, pm_get_status, pm_show_stats, pm_start_logging, pm_stop_logging, version, commands, set_vll_dir, set_backlight, set_logging, get_lcd_info, arbiter, cache_flush, otp_dump, test_result, codec_enabled, get_camera, get_mem, measure_clock, measure_volts, scaling_kernel, scaling_sharpness, get_hvs_asserts, get_throttled, measure_temp, get_config, hdmi_ntsc_freqs, hdmi_adjust_clock, hdmi_status_show, hvs_update_fields, pwm_speedup, force_audio, hdmi_stream_channels, hdmi_channel_map, display_power, read_ring_osc, memtest, dispmanx_list, get_rsts, schmoo, render_bar, disk_notify, inuse_notify, sus_suspend, sus_status, sus_is_enabled, sus_stop_test_thread, egl_platform_switch, mem_validate, mem_oom, mem_reloc_stats, hdmi_cvt, hdmi_timings, file"

 vcgencmd measure_temp
temp=42.9'C
2
  • You are correct. Changing Q&A to focus on Python.
    – SDsolar
    Jun 28, 2018 at 6:44
  • translation... yes, the vcgencmd is indeed available on Stretch, and here are all its available arguments. Nov 30, 2019 at 23:52
1

Related to the other answers:

Using the nice answer to Less ugly yet reliable way to find this floating-point value embedded within a string without padding?:

import re, commands

def check_CPU_temp():
    temp = None
    err, msg = commands.getstatusoutput('vcgencmd measure_temp')
    if not err:
        m = re.search(r'-?\d\.?\d*', msg)   # https://stackoverflow.com/a/49563120/3904031
        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 both a floating point value and the original message in which it is contained.

temperature (°C):  49.0
full message:     temp=49.9'C
3
  • 1
    note commands is python2, it has been replaced with subprocess, though there are other py2-specific things in here too.
    – tedder42
    Sep 7, 2018 at 21:28
  • @tedder42 thanks for that! I'll try tend to this soon, but you are welcome to edit it yourself or post a new answer if you feel so inclined. I'm aware that the time is coming and 2.7 will no longer be supported and us 2.7ers need to port ourselves over, I've just been procrastinating... which reminds me that I hadn't accepted your Space answer yet... done!
    – uhoh
    Sep 8, 2018 at 0:05
  • I was/am still reticent to change it this dramatically. I think it's okay to just leave it, especially because there's no canonical way to do it anyhow.
    – tedder42
    Sep 9, 2018 at 1:16
1

well we gotta use python 3 here - since python 2 is not used any more duhhh

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}")
1

I didn't see anyone else respond this way so I figured I would post it:

import psutil

def get_cpu_temp():
    temp = psutil.sensors_temperatures()['cpu_thermal'][0].current
    return temp

print(get_cpu_temp())
0

On the RPi Foundation site, there is a guide on how to make a temperature log. In it are instructions on the GPIO Python library built into Raspbian. https://projects.raspberrypi.org/en/projects/temperature-log

1
  • 1
    It goes back to same as answer given by @hg8 i.e. pip install gpiozero and from gpiozero import CPUTemperature to get the temp.
    – Adarsha
    Sep 5, 2019 at 2:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.