17

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?

SDsolar
  • 2,378
  • 8
  • 26
  • 43

8 Answers8

18

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
hg8
  • 305
  • 2
  • 10
17

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.

Matthias Braun
  • 233
  • 2
  • 7
eftshift0
  • 800
  • 1
  • 7
  • 13
4

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..

SDsolar
  • 2,378
  • 8
  • 26
  • 43
2

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())

Greenonline
  • 2,969
  • 5
  • 27
  • 38
Binky
  • 21
  • 1
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
Milliways
  • 62,573
  • 32
  • 113
  • 225
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}")

zero
  • 111
  • 3
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
uhoh
  • 562
  • 6
  • 21
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