使用Python获取CPU温度?

jam*_*ieb 26 python cpu temperature

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

Cra*_*een 15

有一个较新的"sysfs热区"API(另见LWN文章Linux内核文档),显示例如温度

/sys/class/thermal/thermal_zone0/temp
Run Code Online (Sandbox Code Playgroud)

读数是千分之一摄氏度(虽然在较旧的内核中,它可能只是C级).


Ale*_*lli 8

如果您的Linux支持ACPI,那么读取伪文件/proc/acpi/thermal_zone/THM0/temperature(路径可能不同,我知道它/proc/acpi/thermal_zone/THRM/temperature在某些系统中)应该这样做.但是我认为世界上每个 Linux系统都没有这种方法,所以你必须更具体地了解你拥有的Linux! - )


Gia*_*olà 6

读取/ sys/class/hwmon/hwmon*/temp1_*中的文件对我有用,但是AFAIK没有完全干净的标准.无论如何,您可以尝试这一点,并确保它提供" sensors "cmdline实用程序显示的相同数量的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
Run Code Online (Sandbox Code Playgroud)


Gia*_*olà 6

我最近仅在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)]}
Run Code Online (Sandbox Code Playgroud)


DrD*_*Dee 5

Py-cputemp似乎做了这个工作.

  • 这不是答案. (5认同)
  • 这个库没有维护,甚至没有在 PyPI 中注册...... (2认同)