[Python] CPUの温度を取得して監視する方法
PythonでCPUの温度を取得して監視するには、OSに依存した方法を使用します。
Linuxではpsutil
やos
モジュールを使って温度情報を取得できます。
例えば、psutil.sensors_temperatures()
を使用すると、センサー情報が取得可能です。
Windowsでは直接的な方法はなく、専用のライブラリ(例: OpenHardwareMonitor
)や外部ツールを利用する必要があります。
定期的に温度を監視するには、time.sleep()
を使って一定間隔で温度を取得することが可能です。
PythonでCPU温度を取得する方法
Linux環境での取得方法
psutilライブラリのインストール
Linux環境でCPU温度を取得するためには、まずpsutil
ライブラリをインストールする必要があります。
以下のコマンドをターミナルで実行してください。
pip install psutil
psutil.sensors_temperatures()の使い方
psutil
ライブラリを使ってCPU温度を取得するには、sensors_temperatures()関数
を使用します。
以下はそのサンプルコードです。
import psutil
# CPU温度を取得
try:
temperatures = psutil.sensors_temperatures()
# CPU温度の表示
if not temperatures:
print("温度センサーが見つかりませんでした。")
else:
for name, entries in temperatures.items():
for entry in entries:
print(f"{name} - {entry.label}: {entry.current}°C")
except AttributeError:
print("この環境ではpsutil.sensors_temperatures()がサポートされていません。")
coretemp - Package id 0: 45.0°C
coretemp - Core 0: 43.0°C
coretemp - Core 1: 42.0°C
coretemp - Core 2: 44.0°C
coretemp - Core 3: 43.0°C
取得できるデータの解釈
psutil.sensors_temperatures()
は、システム内の温度センサーの情報を辞書形式で返します。
各センサーの名前、ラベル、現在の温度、最大温度、最小温度などの情報が含まれています。
これにより、CPUの温度をリアルタイムで監視することが可能です。
Windows環境での取得方法
OpenHardwareMonitorのインストールと設定
Windows環境では、OpenHardwareMonitor
というツールを使用してCPU温度を取得します。
以下の手順でインストールします。
- OpenHardwareMonitorの公式サイトから最新のリリースをダウンロードします。
- ダウンロードしたZIPファイルを解凍し、
OpenHardwareMonitor.exe
を実行します。
PythonからOpenHardwareMonitorを操作する方法
OpenHardwareMonitor
をPythonから操作するためには、pywin32
ライブラリを使用します。
以下のサンプルコードを参考にしてください。
import clr # .NETライブラリを使用するためのモジュール
import time
# OpenHardwareMonitorのDLLを読み込む
clr.AddReference('OpenHardwareMonitorLib')
from OpenHardwareMonitor import Hardware
# OpenHardwareMonitorのインスタンスを作成
computer = Hardware.Computer()
computer.CPUEnabled = True
computer.Open()
# CPU温度の取得
while True:
computer.Update()
for hardware in computer.Hardware:
if hardware.HardwareType == Hardware.HardwareType.CPU:
for sensor in hardware.Sensors:
if sensor.SensorType == Hardware.SensorType.Temperature:
print(f"{sensor.Name}: {sensor.Value}°C")
time.sleep(1)
CPU Package: 50°C
Core #1: 48°C
Core #2: 52°C
取得できるデータの解釈
OpenHardwareMonitor
を使用すると、CPUの各コアやパッケージの温度を取得できます。
センサーの名前とその値を表示することで、CPUの温度状況を把握できます。
macOS環境での取得方法
osx-cpu-tempのインストール
macOS環境では、osx-cpu-temp
というコマンドラインツールを使用してCPU温度を取得します。
以下のコマンドでインストールします。
brew install osx-cpu-temp
Pythonからosx-cpu-tempを操作する方法
osx-cpu-temp
をPythonから呼び出すことで、CPU温度を取得できます。
以下はそのサンプルコードです。
import subprocess
# osx-cpu-tempを実行して温度を取得
result = subprocess.run(['osx-cpu-temp'], capture_output=True, text=True)
print(result.stdout.strip())
CPU Temperature: 45.0°C
取得できるデータの解釈
osx-cpu-temp
は、CPUの現在の温度を簡単に取得できるツールです。
コマンドを実行することで、温度情報が文字列として返されます。
この情報を利用して、CPUの温度を監視することができます。
CPU温度を監視する方法
定期的に温度を取得する方法
time.sleep()を使った監視
CPU温度を定期的に取得するためには、time.sleep()
を使用して一定の間隔で温度を取得する方法があります。
以下はそのサンプルコードです。
import psutil
import time
# 温度を定期的に取得する関数
def monitor_cpu_temperature(interval):
while True:
temperatures = psutil.sensors_temperatures()
for name, entries in temperatures.items():
for entry in entries:
print(f"{name} - {entry.label}: {entry.current}°C")
time.sleep(interval) # 指定した間隔で待機
# 5秒ごとに温度を取得
monitor_cpu_temperature(5)
coretemp - Package id 0: 45.0°C
coretemp - Core 0: 44.0°C
coretemp - Core 1: 46.0°C
ループ処理の実装例
上記のコードでは、無限ループを使用して温度を定期的に取得しています。
ループ内で温度を取得し、time.sleep()
で指定した秒数だけ待機することで、CPU温度を監視することができます。
この方法を使うことで、リアルタイムで温度の変化を追跡できます。
温度が閾値を超えた場合のアクション
警告メッセージの表示
CPU温度が設定した閾値を超えた場合に警告メッセージを表示することができます。
以下はその実装例です。
import psutil
import time
# 温度の閾値
THRESHOLD = 75.0 # 75°Cを閾値とする
def monitor_cpu_temperature(interval):
while True:
temperatures = psutil.sensors_temperatures()
for name, entries in temperatures.items():
for entry in entries:
if entry.current > THRESHOLD:
print(f"警告: {name} - {entry.label}が{entry.current}°Cを超えました!")
time.sleep(interval)
# 5秒ごとに温度を取得
monitor_cpu_temperature(5)
警告: coretemp - Package id 0が76.0°Cを超えました!
ログファイルへの記録
温度が閾値を超えた場合に、その情報をログファイルに記録することも可能です。
以下はその実装例です。
import psutil
import time
# 温度の閾値
THRESHOLD = 75.0 # 75°Cを閾値とする
def log_temperature(message):
with open("temperature_log.txt", "a") as log_file:
log_file.write(message + "\n")
def monitor_cpu_temperature(interval):
while True:
temperatures = psutil.sensors_temperatures()
for name, entries in temperatures.items():
for entry in entries:
if entry.current > THRESHOLD:
log_message = f"警告: {name} - {entry.label}が{entry.current}°Cを超えました!"
print(log_message)
log_temperature(log_message)
time.sleep(interval)
# 5秒ごとに温度を取得
monitor_cpu_temperature(5)
警告: coretemp - Package id 0が76.0°Cを超えました!
(temperature_log.txt
に記録されます)
メール通知の実装
温度が閾値を超えた場合にメール通知を送信することもできます。
以下はその実装例です。
import psutil
import time
import smtplib
from email.mime.text import MIMEText
# 温度の閾値
THRESHOLD = 75.0 # 75°Cを閾値とする
# メール送信関数
def send_email(subject, body):
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = 'your_email@example.com'
msg['To'] = 'recipient@example.com'
with smtplib.SMTP('smtp.example.com', 587) as server:
server.starttls()
server.login('your_email@example.com', 'your_password')
server.send_message(msg)
def monitor_cpu_temperature(interval):
while True:
temperatures = psutil.sensors_temperatures()
for name, entries in temperatures.items():
for entry in entries:
if entry.current > THRESHOLD:
message = f"警告: {name} - {entry.label}が{entry.current}°Cを超えました!"
print(message)
send_email("CPU温度警告", message)
time.sleep(interval)
# 5秒ごとに温度を取得
monitor_cpu_temperature(5)
警告: coretemp - Package id 0が76.0°Cを超えました!
このコードを実行すると、温度が閾値を超えた際に指定したメールアドレスに通知が送信されます。
メールサーバーの設定や認証情報は適宜変更してください。
応用例
複数のセンサー情報を取得する
CPU温度だけでなく、GPUやその他のセンサー情報も取得することができます。
以下は、psutil
を使用して複数のセンサー情報を取得するサンプルコードです。
import psutil
# センサー情報を取得
def get_all_sensor_data():
temperatures = psutil.sensors_temperatures()
for name, entries in temperatures.items():
for entry in entries:
print(f"{name} - {entry.label}: {entry.current}°C")
# センサー情報を表示
get_all_sensor_data()
coretemp - Package id 0: 45.0°C
coretemp - Core 0: 44.0°C
coretemp - Core 1: 46.0°C
nvme - NVMe Device: 30.0°C
このコードを実行することで、CPUやGPUなど、システム内のすべての温度センサーの情報を取得できます。
グラフで温度変化を可視化する
温度データをグラフで可視化するためには、matplotlib
ライブラリを使用します。
以下は、温度データをリアルタイムでグラフ表示するサンプルコードです。
import psutil
import matplotlib.pyplot as plt
import time
# 温度データを格納するリスト
temperature_data = []
# グラフの初期設定
plt.ion()
fig, ax = plt.subplots()
line, = ax.plot(temperature_data)
# 温度をリアルタイムで取得してグラフに表示
def plot_temperature(interval):
while True:
temperatures = psutil.sensors_temperatures()
current_temp = temperatures['coretemp'][0].current
temperature_data.append(current_temp)
# グラフの更新
line.set_ydata(temperature_data)
line.set_xdata(range(len(temperature_data)))
ax.relim()
ax.autoscale_view()
plt.draw()
plt.pause(interval)
# 1秒ごとに温度を取得
plot_temperature(1)
このコードを実行すると、CPU温度の変化がリアルタイムでグラフに表示されます。
温度データをクラウドに送信して監視する
温度データをクラウドに送信することで、リモートで監視することができます。
以下は、requests
ライブラリを使用して温度データをHTTP POSTリクエストで送信するサンプルコードです。
import psutil
import requests
import time
# 温度データを送信する関数
def send_temperature_to_cloud():
temperatures = psutil.sensors_temperatures()
current_temp = temperatures['coretemp'][0].current
data = {'temperature': current_temp}
response = requests.post('https://your-cloud-endpoint.com/api/temperature', json=data)
print(f"データ送信: {data}, ステータスコード: {response.status_code}")
# 定期的に温度データを送信
while True:
send_temperature_to_cloud()
time.sleep(60) # 1分ごとに送信
このコードを実行すると、1分ごとにCPU温度が指定したクラウドのエンドポイントに送信されます。
温度データをデータベースに保存する
温度データをデータベースに保存することで、後で分析や監視が可能になります。
以下は、SQLiteデータベースに温度データを保存するサンプルコードです。
import psutil
import sqlite3
import time
# SQLiteデータベースの接続
conn = sqlite3.connect('temperature_data.db')
c = conn.cursor()
# テーブルの作成
c.execute('''CREATE TABLE IF NOT EXISTS temperatures (timestamp DATETIME, temperature REAL)''')
# 温度データをデータベースに保存する関数
def save_temperature_to_db():
temperatures = psutil.sensors_temperatures()
current_temp = temperatures['coretemp'][0].current
c.execute("INSERT INTO temperatures (timestamp, temperature) VALUES (DATETIME('now'), ?)", (current_temp,))
conn.commit()
# 定期的に温度データを保存
while True:
save_temperature_to_db()
time.sleep(60) # 1分ごとに保存
このコードを実行すると、1分ごとにCPU温度がSQLiteデータベースに保存されます。
温度に応じてファンの速度を制御する
温度が一定の閾値を超えた場合に、ファンの速度を制御することができます。
以下は、温度に応じてファンの速度を調整するサンプルコードです。
import psutil
import time
# 温度の閾値
THRESHOLD = 75.0 # 75°Cを閾値とする
# ファンの速度を制御する関数(仮想的な関数)
def set_fan_speed(speed):
print(f"ファンの速度を{speed}%に設定しました。")
# 温度に応じてファンの速度を調整
def control_fan_speed():
while True:
temperatures = psutil.sensors_temperatures()
current_temp = temperatures['coretemp'][0].current
if current_temp > THRESHOLD:
set_fan_speed(100) # 高温時はファンを最大に
else:
set_fan_speed(50) # 通常時はファンを50%に
time.sleep(5) # 5秒ごとにチェック
# ファンの制御を開始
control_fan_speed()
このコードを実行すると、CPU温度に応じてファンの速度が調整されます。
ファンの制御は仮想的な関数で示していますが、実際のハードウェア制御には適切なライブラリやAPIを使用する必要があります。
まとめ
この記事では、Pythonを使用してCPUの温度を取得し、監視する方法について詳しく解説しました。
具体的には、Linux、Windows、macOSそれぞれの環境での温度取得方法や、温度を定期的に監視するための実装例、さらには温度データを活用した応用例についても触れました。
これらの知識を活用することで、システムの温度管理をより効果的に行うことができるでしょう。
ぜひ、実際にコードを試してみて、あなたの環境に合った温度監視システムを構築してみてください。