【问题标题】:Getting CPU temperature using Python?使用 Python 获取 CPU 温度?
【发布时间】:2010-03-13 23:35:19
【问题描述】:

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

【问题讨论】:

    标签: python cpu temperature


    【解决方案1】:

    有一个newer "sysfs thermal zone" API(另见LWN articleLinux kernel doc)显示温度低于例如

    /sys/class/thermal/thermal_zone0/temp
    

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          读取 /sys/class/hwmon/hwmon*/temp1_* 中的文件对我有用,但 AFAIK 没有标准可以干净地做到这一点。 不管怎样,你可以试试这个,并确保它提供的 CPU 数量与“sensors”命令行实用程序显示的相同,在这种情况下你可以假设它是可靠的。

          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
          

          【讨论】:

            【解决方案5】:

            Py-cputemp 似乎可以胜任。

            【讨论】:

            • py-cputemp 基本上是 /proc/acpi/thermal_zone 之上的薄薄的一层。这最初对我不起作用,直到我意识到我需要在我的 BIOS 中启用 ACPI。我禁用了它,因为我认为我不想在服务器上进行电源管理。感谢你的回答;我接受这个是因为它是最先发布的,并引导我思考问题的根源。
            • 这不是答案。
            • 这个库没有维护,甚至没有在 PyPI 中注册...
            • 另外,这里没有关于如何使用它的说明。
            • 我更喜欢 gpiozero from gpiozero import CPUTemperature, LoadAverage cpu = CPUTemperature() print ("CPU temperature is %s" % cpu.temperature) load = LoadAverage() print ("CPU temperature is %s" % load.load_average)
            【解决方案6】:

            pip 中照顾pyspectator

            需要python3

            from pyspectator import Cpu
            from time import sleep
            cpu = Cpu(monitoring_latency=1)
            
            while True:
                print (cpu.temperature)
                sleep(1)
            

            【讨论】:

            • 我尝试了您提供的代码,但首先导入似乎来自 pyspectator.processor import Cpu,如果它是 python3,因为警告说打印命令应该使用括号..无论如何这不起作用我 cpu.load 显示正确,但温度始终为 None :(
            • 16.04 LTS 似乎不喜欢这个导入。
            【解决方案7】:

            根据您的 Linux 发行版,您可能会在 /proc 下找到包含此信息的文件。例如,this page 建议 /proc/acpi/thermal_zone/THM/temperature

            【讨论】:

              【解决方案8】:

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

              【讨论】:

              • 不幸的是 PySensors 只能在 Python 2.x 版本下运行
              【解决方案9】:

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

              【讨论】:

                【解决方案10】:

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

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

                【讨论】:

                  【解决方案11】:

                  我会反思上面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)
                  

                  【讨论】:

                    【解决方案12】:

                    适用于 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 温度

                    【讨论】:

                    • 这个方法很好,但是你提取了电池百分比——至少在我的 Ubuntu 系统上,acpi 的第一行输出是Battery 0: Full, 100%
                    • 我的错,我混淆了两个问题。关于CPU温度我稍后会更改,谢谢指出
                    • 另外,请务必获取CPU温度。似乎这可能是电池温度,但我不确定。
                    猜你喜欢
                    • 2020-10-18
                    • 2014-06-12
                    • 2015-02-02
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2022-08-05
                    • 1970-01-01
                    相关资源
                    最近更新 更多