Getting CPU temperature using Python?
Asked Answered
K

12

30

How do I retrieve the temperature of my CPU using Python? (Assuming I'm on Linux)

Kathlenekathlin answered 13/3, 2010 at 23:35 Comment(0)
M
6

Py-cputemp seems to do the job.

Mobley answered 13/3, 2010 at 23:40 Comment(6)
py-cputemp is basically a thin veneer over /proc/acpi/thermal_zone. This originally didn't work for me until I realized that I needed to enable ACPI in my BIOS. I had disabled it because I figured I didn't want power management on a server. Thanks for the answer; I'm accepting this one because it was posted first and lead me to think about the source of my problem.Kathlenekathlin
This is not an answer.Hakan
This library is unmaintained and isn't even registered in PyPI...Reputed
Plus there are no instructions here as to how it is used.Kratzer
I prefer gpiozero from gpiozero import CPUTemperature, LoadAverage cpu = CPUTemperature() print ("CPU temperature is %s" % cpu.temperature) load = LoadAverage() print ("CPU temperature is %s" % load.load_average)Howie
try "sensors -j"Sible
D
23

There is a newer "sysfs thermal zone" API (see also LWN article and Linux kernel doc) showing temperatures under e.g.

/sys/class/thermal/thermal_zone0/temp

Readings are in thousandths of degrees Celcius (although in older kernels, it may have just been degrees C).

Disservice answered 4/3, 2013 at 23:40 Comment(0)
R
20

I recently implemented this in psutil for Linux only.

>>> import psutil
>>> psutil.sensors_temperatures()
{'acpitz': [shwtemp(label='', current=47.0, high=103.0, critical=103.0)],
 'asus': [shwtemp(label='', current=47.0, high=None, critical=None)],
 'coretemp': [shwtemp(label='Physical id 0', current=52.0, high=100.0, critical=100.0),
              shwtemp(label='Core 0', current=45.0, high=100.0, critical=100.0),
              shwtemp(label='Core 1', current=52.0, high=100.0, critical=100.0),
              shwtemp(label='Core 2', current=45.0, high=100.0, critical=100.0),
              shwtemp(label='Core 3', current=47.0, high=100.0, critical=100.0)]}
Rior answered 6/2, 2017 at 13:19 Comment(0)
A
8

If your Linux supports ACPI, reading pseudo-file /proc/acpi/thermal_zone/THM0/temperature (the path may differ, I know it's /proc/acpi/thermal_zone/THRM/temperature in some systems) should do it. But I don't think there's a way that works in every Linux system in the world, so you'll have to be more specific about exactly what Linux you have!-)

Affirmative answered 13/3, 2010 at 23:42 Comment(0)
R
7

Reading files in /sys/class/hwmon/hwmon*/temp1_* worked for me but AFAIK there are no standards for doing this cleanly. Anyway, you can try this and make sure it provides the same number of CPUs shown by "sensors" cmdline utility, in which case you can assume it's reliable.

from __future__ import division
import os
from collections import namedtuple


_nt_cpu_temp = namedtuple('cputemp', 'name temp max critical')

def get_cpu_temp(fahrenheit=False):
    """Return temperatures expressed in Celsius for each physical CPU
    installed on the system as a list of namedtuples as in:

    >>> get_cpu_temp()
    [cputemp(name='atk0110', temp=32.0, max=60.0, critical=95.0)]
    """
    # http://www.mjmwired.net/kernel/Documentation/hwmon/sysfs-interface
    cat = lambda file: open(file, 'r').read().strip()
    base = '/sys/class/hwmon/'
    ls = sorted(os.listdir(base))
    assert ls, "%r is empty" % base
    ret = []
    for hwmon in ls:
        hwmon = os.path.join(base, hwmon)
        label = cat(os.path.join(hwmon, 'temp1_label'))
        assert 'cpu temp' in label.lower(), label
        name = cat(os.path.join(hwmon, 'name'))
        temp = int(cat(os.path.join(hwmon, 'temp1_input'))) / 1000
        max_ = int(cat(os.path.join(hwmon, 'temp1_max'))) / 1000
        crit = int(cat(os.path.join(hwmon, 'temp1_crit'))) / 1000
        digits = (temp, max_, crit)
        if fahrenheit:
            digits = [(x * 1.8) + 32 for x in digits]
        ret.append(_nt_cpu_temp(name, *digits))
    return ret
Rior answered 27/4, 2013 at 19:38 Comment(0)
M
6

Py-cputemp seems to do the job.

Mobley answered 13/3, 2010 at 23:40 Comment(6)
py-cputemp is basically a thin veneer over /proc/acpi/thermal_zone. This originally didn't work for me until I realized that I needed to enable ACPI in my BIOS. I had disabled it because I figured I didn't want power management on a server. Thanks for the answer; I'm accepting this one because it was posted first and lead me to think about the source of my problem.Kathlenekathlin
This is not an answer.Hakan
This library is unmaintained and isn't even registered in PyPI...Reputed
Plus there are no instructions here as to how it is used.Kratzer
I prefer gpiozero from gpiozero import CPUTemperature, LoadAverage cpu = CPUTemperature() print ("CPU temperature is %s" % cpu.temperature) load = LoadAverage() print ("CPU temperature is %s" % load.load_average)Howie
try "sensors -j"Sible
A
4

Look after pyspectator in pip

Requires python3

from pyspectator import Cpu
from time import sleep
cpu = Cpu(monitoring_latency=1)

while True:
    print (cpu.temperature)
    sleep(1)
Antecedents answered 28/2, 2017 at 23:27 Comment(2)
I tried the code you provided but first of all the import seems to be from pyspectator.processor import Cpu and if it's python3 as the warning says the print command should use brackets.. anyway this dont work for me the cpu.load is displayed correctly but the temperature is always None :(Pentalpha
16.04 LTS seems not to like this import.Kratzer
O
3

Depending on your Linux distro, you may find a file under /proc that contains this information. For example, this page suggests /proc/acpi/thermal_zone/THM/temperature.

Oler answered 13/3, 2010 at 23:41 Comment(0)
M
1

As an alternative you can install the lm-sensors package, then install PySensors (a python binding for libsensors).

Myungmyxedema answered 8/9, 2012 at 17:4 Comment(1)
Unfortunately PySensors only runs under Python 2.x versionKlehm
P
1

Sysmon works nice. Nicely made, it does much more than measure CPU temperature. It is a command line program, and logs all the data it measured to a file. Also, it is open-source and written in python 2.7.

Sysmon: https://github.com/calthecoder/sysmon-1.0.1

Phrase answered 26/5, 2015 at 17:28 Comment(0)
D
0

You could try the PyI2C module, it can read directly from the kernel.

Dumm answered 13/3, 2010 at 23:41 Comment(0)
E
0

I would reflect on SDsolar's solving above, modified the code a bit., and now it shows not only one value. Until the while loop you gets continuously the actual value of the CPUs temperature

On linux systems:

Install the pyspectator module:

pip install pyspectator

Put this code into a file 'cpu-temp.py'

#!/usr/bin/env python3
from pyspectator.processor import Cpu
from time import sleep

while True:
    cpu = Cpu(monitoring_latency=1) #changed here
    print (cpu.temperature)
    sleep(1)
Eckblad answered 2/2, 2021 at 7:56 Comment(0)
C
0

For Linux systems(Tried on Ubuntu 18.04)

Install the acpi module by sudo apt install acpi

Running acpi -V should give you a ton of info about your system. Now we just need to get the temperature value via python.

import os
os.system("acpi -V > output.txt")
battery = open("output.txt", "r")
info = battery.readline()
val = info.split()
percent4real = val[3]
percentage = int(percent4real[:-1])
print(percentage)

The percentage variable will give you the temperature. So, first we take the output of the acpi -V command in a text file and then read it. We need to convert it into an integer since the data is all in String type.

  • Note: This command does not display CPU temperature when used in WSL
Commutable answered 12/6, 2021 at 18:3 Comment(3)
The approach is good, but you extract the battery percentage - at least on my Ubuntu-system, where the first line of output from acpiis Battery 0: Full, 100%.Less
Ah my bad, I confused two questions. I'll change it later with regards to the CPU temperature, thanks for pointing it outCommutable
Additionally, please make sure to obtain the CPU temperature. It seems that maybe this is the battery temperature, but I'm not sure.Less

© 2022 - 2024 — McMap. All rights reserved.