使用Python获取CPU温度?

30

如何使用Python检索CPU温度?(假设我正在使用Linux)

12个回答

23

19

我最近在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)]}

8
如果您的Linux支持ACPI,那么读取伪文件/proc/acpi/thermal_zone/THM0/temperature(路径可能有所不同,在某些系统中是/proc/acpi/thermal_zone/THRM/temperature)就可以了。但我不认为在全世界的每个Linux系统中都有一种方法可行,因此您需要更具体地说明您使用的是哪个Linux系统!-)

7

我读取 /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

6

1
py-cputemp 基本上只是 /proc/acpi/thermal_zone 上的一个薄层。一开始它对我不起作用,直到我意识到需要在我的 BIOS 中启用 ACPI。我曾经禁用它,因为我认为服务器上不需要电源管理。感谢你的答案;我接受这个答案,因为它最先发布,并让我思考了我的问题来源。 - jamieb
6
这不是一个答案。 - GLHF
2
这个库已经不再维护,甚至没有在PyPI中注册... - Cerin
此外,这里没有说明如何使用它的指示。 - SDsolar
我更喜欢使用 gpiozero 模块。 从 gpiozero 模块中导入 CPUTemperature 和 LoadAverage。cpu = CPUTemperature() print("CPU 温度是 %s" % cpu.temperature) load = LoadAverage() print("负载平均值为 %s" % load.load_average) - Vasif
try "sensors -j" - Vincent Alex

4

pip 中查找并安装 pyspectator

需要 Python3

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

while True:
    print (cpu.temperature)
    sleep(1)

1
我尝试了您提供的代码,但首先似乎应该是从pyspectator.processor导入Cpu,如果是Python3,就像警告所说的那样,print命令应该使用括号。无论如何,这对我来说不起作用,cpu.load被正确显示,但温度始终为None :( - Lukr
16.04 LTS 似乎不喜欢这个导入。 - SDsolar

3

根据您的Linux发行版,您可能会在/proc下找到一个包含此信息的文件。例如,这个页面建议使用/proc/acpi/thermal_zone/THM/temperature


1

Sysmon很好用。它不仅可以测量CPU温度,而且做得非常好。它是一个命令行程序,并将所有测量的数据记录到文件中。此外,它是开源的,使用Python 2.7编写。

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


1

作为替代方案,您可以安装lm-sensors软件包,然后安装PySensors(libsensors的Python绑定)。


很遗憾,PySensors 只能在 Python 2.x 版本下运行。 - Vlad Bezden

0

针对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命令的输出保存到一个文本文件中,然后读取它。由于数据都是字符串类型的,我们需要将其转换为整数。

  • 注意:在WSL中使用此命令时不会显示CPU温度。

这种方法不错,但是你提取电池百分比的方式可能需要改进 - 至少在我的Ubuntu系统上,acpi命令的第一行输出是“Battery 0: Full, 100%”。 - Dr. V
啊,我的错,我把两个问题搞混了。关于CPU温度的问题,我稍后会进行更改,感谢您指出这个问题。 - Luce
此外,请确保获取 CPU 温度。似乎这可能是电池温度,但我不确定。 - Dr. V

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接