Python を使用して CPU の温度を取得するにはどうすればよいですか? (私がLinuxを使用していると仮定して)
12 に答える
たとえば、以下の温度を示す新しい「sysfsサーマルゾーン」API(LWNの記事とLinuxカーネルのドキュメントも参照)があります
/sys/class/thermal/thermal_zone0/temp
読み取り値は摂氏の 1,000 分の 1 です (ただし、古いカーネルでは摂氏であった可能性があります)。
LinuxがACPIをサポートしている場合は、疑似ファイルを読み取る/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がその仕事をしているようです。
Linuxディストリビューションによっては、/proc
この情報を含むファイルが下にある場合があります。たとえば、このページはを提案し/proc/acpi/thermal_zone/THM/temperature
ます。
PyI2Cモジュールを試すことができます。カーネルから直接読み取ることができます。