使用Python获取CPU温度?

发布于 2024-08-24 16:03:40 字数 43 浏览 4 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

带刺的爱情 2024-08-31 16:03:40

有一个较新的“sysfs Thermal zone”API(另请参阅LWN 文章Linux 内核文档)显示了例如下的温度

/sys/class/thermal/thermal_zone0/temp

读数为千分之一摄氏度(尽管在较旧的内核中,它可能只是摄氏度)。

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).

蘑菇王子 2024-08-31 16:03:40

我最近在 psutil 中实现了此功能,仅适用于 Linux。

>>> 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)]}

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)]}
把人绕傻吧 2024-08-31 16:03:40

如果你的Linux支持ACPI,读取伪文件/proc/acpi/Thermal_zone/THM0/Temperature(路径可能不同,我知道它是/proc/acpi/Thermal_zone/THRM/Temperature< /code> 在某些系统中)应该这样做。但我认为没有一种方法适用于世界上每个 Linux 系统,因此您必须更具体地了解您所拥有的 Linux!-)

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!-)

娇柔作态 2024-08-31 16:03:40

读取 /sys/class/hwmon/hwmon*/temp1_* 中的文件对我有用,但据我所知,没有干净地执行此操作的标准。
无论如何,您可以尝试此操作并确保它提供与“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

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
极度宠爱 2024-08-31 16:03:40

Py-cputemp 似乎可以完成这项工作。

Py-cputemp seems to do the job.

若无相欠,怎会相见 2024-08-31 16:03:40

照顾 pip 中的 pyspectator

需要 python3

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

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

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)
鯉魚旗 2024-08-31 16:03:40

根据您的 Linux 发行版,您可能会在 /proc 下找到包含此信息的文件。例如,此页面建议/proc/acpi/Thermal_zone/ THM/温度

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.

葬花如无物 2024-08-31 16:03:40

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

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

零崎曲识 2024-08-31 16:03:40

Sysmon 工作得很好。制作精良,它的功能远不止测量 CPU 温度。它是一个命令行程序,并将其测量的所有数据记录到文件中。此外,它是开源的,用 python 2.7 编写。

Sysmon:https://github.com/calthecoder/sysmon-1.0.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

岁月静好 2024-08-31 16:03:40

您可以尝试 PyI2C 模块,它可以直接从内核读取。

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

じ违心 2024-08-31 16:03:40

我反思了SDsolar上面的解决方案,稍微修改了代码,现在它不仅显示一个值。直到 while 循环,您才能连续获得 CPU 温度的实际值

在 Linux 系统上:

安装 pyspectator 模块:

pip install pyspectator

将此代码放入文件“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)

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)
走过海棠暮 2024-08-31 16:03:40

Linux系统(在Ubuntu 18.04上尝试)

安装acpi模块经过
sudo apt install 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 命令的输出放入文本文件中,然后读取它。由于数据都是String类型,我们需要将其转换为整数。

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文