How do I retrieve the temperature of my CPU using Python? (Assuming I\'m on Linux)
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
You could try the PyI2C module, it can read directly from the kernel.
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)
Py-cputemp seems to do the job.
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).
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)]}