如何使用Python检索CPU温度?(假设我正在使用Linux)
有一个新的“sysfs thermal zone”API(另请参见LWN文章和Linux内核文档),可以显示例如下面的温度。
/sys/class/thermal/thermal_zone0/temp
我最近在Linux上实现了这个功能,在psutil中。
>>> 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)]}
/proc/acpi/thermal_zone/THM0/temperature
(路径可能有所不同,在某些系统中是/proc/acpi/thermal_zone/THRM/temperature
)就可以了。但我不认为在全世界的每个Linux系统中都有一种方法可行,因此您需要更具体地说明您使用的是哪个Linux系统!-)我读取 /sys/class/hwmon/hwmon*/temp1_* 中的文件可行,但是据我所知并没有标准可以使其更加清晰简单。总之,你可以尝试这个方法,并确保它提供了与"sensors"命令行工具显示相同数量的CPU,这样你就可以认为它是可靠的。
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
Py-cputemp似乎能胜任这项工作。
在 pip
中查找并安装 pyspectator
需要 Python3
from pyspectator import Cpu
from time import sleep
cpu = Cpu(monitoring_latency=1)
while True:
print (cpu.temperature)
sleep(1)
根据您的Linux发行版,您可能会在/proc
下找到一个包含此信息的文件。例如,这个页面建议使用/proc/acpi/thermal_zone/THM/temperature
。
Sysmon很好用。它不仅可以测量CPU温度,而且做得非常好。它是一个命令行程序,并将所有测量的数据记录到文件中。此外,它是开源的,使用Python 2.7编写。
作为替代方案,您可以安装lm-sensors软件包,然后安装PySensors(libsensors的Python绑定)。
针对Linux系统(在Ubuntu 18.04上测试过)
通过sudo apt install acpi
安装acpi模块。
运行acpi -V
应该会给出有关您的系统的大量信息。现在我们只需要通过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)
percentage
变量将给出温度。因此,首先我们将acpi -V
命令的输出保存到一个文本文件中,然后读取它。由于数据都是字符串类型的,我们需要将其转换为整数。
acpi
命令的第一行输出是“Battery 0: Full, 100%”。 - Dr. V