使用Python實(shí)現(xiàn)實(shí)時(shí)監(jiān)控CPU溫度
簡(jiǎn)介
CPU溫度是衡量系統(tǒng)健康狀況的重要指標(biāo)之一。過(guò)高的CPU溫度可能導(dǎo)致系統(tǒng)不穩(wěn)定、性能下降甚至硬件損壞。實(shí)時(shí)監(jiān)控CPU溫度有助于及時(shí)發(fā)現(xiàn)散熱問(wèn)題,預(yù)防系統(tǒng)故障。本文將介紹一個(gè)實(shí)用的Python腳本——CPU溫度監(jiān)控工具,它可以實(shí)時(shí)監(jiān)控CPU溫度,并在溫度過(guò)高時(shí)發(fā)出告警。
功能介紹
這個(gè)CPU溫度監(jiān)控工具具有以下核心功能:
- 實(shí)時(shí)溫度監(jiān)控:實(shí)時(shí)讀取CPU溫度傳感器數(shù)據(jù)
- 跨平臺(tái)支持:支持Windows、Linux和macOS操作系統(tǒng)
- 溫度告警:當(dāng)溫度超過(guò)設(shè)定閾值時(shí)發(fā)出告警
- 歷史數(shù)據(jù)記錄:記錄溫度變化歷史,便于分析
- 可視化圖表:生成溫度變化趨勢(shì)圖
- 定時(shí)監(jiān)控:支持按指定間隔持續(xù)監(jiān)控CPU溫度
- 多核溫度監(jiān)控:支持多核CPU的溫度監(jiān)控
- 風(fēng)扇轉(zhuǎn)速監(jiān)控:在支持的系統(tǒng)上監(jiān)控風(fēng)扇轉(zhuǎn)速
應(yīng)用場(chǎng)景
這個(gè)工具適用于以下場(chǎng)景:
- 服務(wù)器監(jiān)控:監(jiān)控服務(wù)器CPU溫度,預(yù)防過(guò)熱故障
- 高性能計(jì)算:在密集計(jì)算任務(wù)中監(jiān)控CPU溫度
- 系統(tǒng)維護(hù):定期檢查系統(tǒng)散熱狀況
- 故障排查:診斷系統(tǒng)不穩(wěn)定是否由過(guò)熱引起
- 超頻測(cè)試:在CPU超頻時(shí)監(jiān)控溫度變化
- 環(huán)境監(jiān)控:監(jiān)控機(jī)房或設(shè)備環(huán)境溫度
報(bào)錯(cuò)處理
腳本包含了完善的錯(cuò)誤處理機(jī)制:
- 傳感器檢測(cè):自動(dòng)檢測(cè)可用的溫度傳感器
- 權(quán)限驗(yàn)證:檢查是否有足夠的權(quán)限訪問(wèn)傳感器數(shù)據(jù)
- 硬件兼容性:處理不同硬件平臺(tái)的兼容性問(wèn)題
- 數(shù)據(jù)有效性檢查:驗(yàn)證溫度數(shù)據(jù)的有效性
- 異常捕獲:捕獲并處理運(yùn)行過(guò)程中可能出現(xiàn)的各種異常
- 降級(jí)處理:在傳感器不可用時(shí)提供替代方案
代碼實(shí)現(xiàn)
import os
import sys
import time
import argparse
import json
import platform
from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from collections import deque
class CPUTemperatureMonitor:
def __init__(self, history_size=100):
self.os_type = platform.system().lower()
self.history_size = history_size
self.temperature_history = deque(maxlen=history_size)
self.timestamp_history = deque(maxlen=history_size)
self.errors = []
self.monitoring = False
def get_cpu_temperature_linux(self):
"""獲取Linux系統(tǒng)CPU溫度"""
temperatures = {}
# 方法1: 通過(guò)sysfs讀取溫度
try:
hwmon_paths = []
for root, dirs, files in os.walk('/sys/class/hwmon/'):
if 'temp1_input' in files:
hwmon_paths.append(root)
for i, path in enumerate(hwmon_paths):
try:
# 讀取溫度
with open(os.path.join(path, 'temp1_input'), 'r') as f:
temp_raw = int(f.read().strip())
temp_celsius = temp_raw / 1000.0
# 讀取傳感器名稱
try:
with open(os.path.join(path, 'name'), 'r') as f:
name = f.read().strip()
except:
name = f"Sensor {i+1}"
temperatures[name] = temp_celsius
except Exception as e:
continue
except:
pass
# 方法2: 通過(guò)/proc/cpuinfo獲取溫度(某些系統(tǒng))
if not temperatures:
try:
with open('/proc/cpuinfo', 'r') as f:
# 注意:/proc/cpuinfo通常不包含溫度信息
# 這里只是示例,實(shí)際可能需要其他方法
pass
except:
pass
return temperatures
def get_cpu_temperature_windows(self):
"""獲取Windows系統(tǒng)CPU溫度"""
temperatures = {}
# Windows上獲取溫度比較復(fù)雜,需要第三方庫(kù)
# 這里提供幾種可能的方法
# 方法1: 嘗試使用wmi(需要pywin32)
try:
import wmi
c = wmi.WMI(namespace="root\\wmi")
temperature_infos = c.MSAcpi_ThermalZoneTemperature()
for i, sensor in enumerate(temperature_infos):
# 溫度以十分之一開(kāi)爾文為單位
temp_kelvin = sensor.CurrentTemperature / 10.0
temp_celsius = temp_kelvin - 273.15
temperatures[f"Thermal Zone {i+1}"] = temp_celsius
except ImportError:
self.errors.append("缺少wmi庫(kù),無(wú)法獲取Windows溫度信息")
except Exception as e:
self.errors.append(f"通過(guò)WMI獲取溫度失敗: {e}")
# 方法2: 嘗試使用OpenHardwareMonitorLib(需要安裝)
if not temperatures:
try:
# 這需要預(yù)先安裝OpenHardwareMonitor并注冊(cè)COM組件
# 由于復(fù)雜性,這里僅提供框架
pass
except:
pass
return temperatures
def get_cpu_temperature_macos(self):
"""獲取macOS系統(tǒng)CPU溫度"""
temperatures = {}
# macOS上獲取溫度也比較復(fù)雜
# 可以嘗試使用osascript調(diào)用系統(tǒng)命令
try:
# 注意:macOS通常不直接暴露溫度傳感器
# 可能需要第三方工具如iStats
import subprocess
result = subprocess.run(['sysctl', 'machdep.xcpm.cpu_thermal_level'],
capture_output=True, text=True, timeout=10)
if result.returncode == 0:
# 解析輸出
output = result.stdout.strip()
# 這里的輸出格式可能因系統(tǒng)而異
# 僅作為示例
temperatures['CPU'] = 0.0 # 實(shí)際需要解析具體數(shù)值
except subprocess.TimeoutExpired:
self.errors.append("獲取macOS溫度信息超時(shí)")
except Exception as e:
self.errors.append(f"獲取macOS溫度信息失敗: {e}")
return temperatures
def get_cpu_temperature(self):
"""獲取CPU溫度(跨平臺(tái))"""
if self.os_type == 'linux':
return self.get_cpu_temperature_linux()
elif self.os_type == 'windows':
return self.get_cpu_temperature_windows()
elif self.os_type == 'darwin': # macOS
return self.get_cpu_temperature_macos()
else:
self.errors.append(f"不支持的操作系統(tǒng): {self.os_type}")
return {}
def format_temperature(self, temp_celsius):
"""格式化溫度顯示"""
return f"{temp_celsius:.1f}°C ({temp_celsius * 9/5 + 32:.1f}°F)"
def display_temperature(self, temperatures):
"""顯示溫度信息"""
# 清屏(兼容不同操作系統(tǒng))
os.system('cls' if os.name == 'nt' else 'clear')
print("=" * 60)
print("CPU溫度監(jiān)控工具")
print("=" * 60)
print(f"監(jiān)控時(shí)間: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"操作系統(tǒng): {self.os_type}")
print()
if temperatures:
print("CPU溫度信息:")
for sensor_name, temp in temperatures.items():
print(f" {sensor_name}: {self.format_temperature(temp)}")
# 溫度告警
if temp > 80:
print(" ?? 警告: 溫度過(guò)高!")
elif temp > 70:
print(" ?? 注意: 溫度較高")
else:
print("未能獲取CPU溫度信息")
if self.errors:
print("錯(cuò)誤信息:")
for error in self.errors[-3:]: # 顯示最近3個(gè)錯(cuò)誤
print(f" {error}")
print()
print("=" * 60)
print("按 Ctrl+C 停止監(jiān)控")
def collect_data(self):
"""收集溫度數(shù)據(jù)"""
temperatures = self.get_cpu_temperature()
timestamp = datetime.now()
# 記錄到歷史數(shù)據(jù)
if temperatures:
avg_temp = sum(temperatures.values()) / len(temperatures)
self.temperature_history.append(avg_temp)
self.timestamp_history.append(timestamp)
return temperatures
def save_data(self, filename="temperature_data.json"):
"""保存溫度數(shù)據(jù)到文件"""
try:
data = {
'timestamps': [t.isoformat() for t in self.timestamp_history],
'temperatures': list(self.temperature_history),
'os_type': self.os_type,
'record_time': datetime.now().isoformat()
}
with open(filename, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
print(f"溫度數(shù)據(jù)已保存到: {filename}")
return True
except Exception as e:
print(f"保存溫度數(shù)據(jù)時(shí)出錯(cuò): {e}")
return False
def generate_chart(self, filename="temperature_chart.png"):
"""生成溫度變化圖表"""
try:
if len(self.timestamp_history) < 2:
print("數(shù)據(jù)不足,無(wú)法生成圖表")
return False
plt.figure(figsize=(12, 6))
plt.plot(self.timestamp_history, self.temperature_history, 'b-', linewidth=1.5)
plt.title('CPU溫度變化趨勢(shì)')
plt.xlabel('時(shí)間')
plt.ylabel('溫度 (°C)')
plt.grid(True, alpha=0.3)
# 設(shè)置溫度告警線
plt.axhline(y=70, color='orange', linestyle='--', alpha=0.7, label='高溫警告 (70°C)')
plt.axhline(y=80, color='red', linestyle='--', alpha=0.7, label='危險(xiǎn)溫度 (80°C)')
plt.legend()
# 格式化時(shí)間軸
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
plt.gca().xaxis.set_major_locator(mdates.MinuteLocator(interval=5))
plt.setp(plt.gca().xaxis.get_majorticklabels(), rotation=45)
plt.tight_layout()
plt.savefig(filename, dpi=300, bbox_inches='tight')
plt.close()
print(f"溫度圖表已保存到: {filename}")
return True
except Exception as e:
print(f"生成溫度圖表時(shí)出錯(cuò): {e}")
return False
def check_temperature_alert(self, temperatures, threshold=80):
"""檢查溫度告警"""
alerts = []
for sensor_name, temp in temperatures.items():
if temp > threshold:
alerts.append({
'sensor': sensor_name,
'temperature': temp,
'threshold': threshold,
'time': datetime.now().isoformat()
})
if alerts:
print("\n?? 溫度告警!")
for alert in alerts:
print(f" {alert['sensor']}: {self.format_temperature(alert['temperature'])} "
f"(閾值: {alert['threshold']}°C)")
return alerts
def start_monitoring(self, interval=5, duration=None, alert_threshold=80,
save_data=False, chart_file=None):
"""開(kāi)始監(jiān)控"""
self.monitoring = True
start_time = time.time()
try:
while self.monitoring:
# 收集數(shù)據(jù)
temperatures = self.collect_data()
# 顯示溫度
self.display_temperature(temperatures)
# 檢查告警
if temperatures:
self.check_temperature_alert(temperatures, alert_threshold)
# 保存數(shù)據(jù)
if save_data and len(self.temperature_history) % 10 == 0: # 每10次保存一次
self.save_data()
# 檢查是否達(dá)到指定時(shí)長(zhǎng)
if duration and (time.time() - start_time) >= duration:
break
# 等待下次監(jiān)控
time.sleep(interval)
except KeyboardInterrupt:
print("\n\n停止監(jiān)控...")
finally:
self.monitoring = False
# 生成圖表
if chart_file:
self.generate_chart(chart_file)
# 保存最終數(shù)據(jù)
if save_data:
self.save_data()
print("監(jiān)控已停止")
def main():
parser = argparse.ArgumentParser(description="CPU溫度監(jiān)控工具")
parser.add_argument("-i", "--interval", type=int, default=5,
help="監(jiān)控間隔(秒,默認(rèn):5)")
parser.add_argument("-d", "--duration", type=int,
help="監(jiān)控時(shí)長(zhǎng)(秒,不指定則持續(xù)監(jiān)控)")
parser.add_argument("-t", "--threshold", type=float, default=80.0,
help="溫度告警閾值(°C,默認(rèn):80)")
parser.add_argument("-s", "--save-data", action="store_true",
help="保存溫度數(shù)據(jù)到文件")
parser.add_argument("-c", "--chart", help="生成溫度圖表到指定文件")
parser.add_argument("--list-sensors", action="store_true",
help="列出可用的溫度傳感器")
args = parser.parse_args()
# 檢查必要的依賴
if args.list_sensors and platform.system().lower() == 'windows':
try:
import wmi
except ImportError:
print("警告: 缺少wmi庫(kù),無(wú)法列出Windows傳感器")
try:
monitor = CPUTemperatureMonitor()
# 列出傳感器
if args.list_sensors:
temperatures = monitor.get_cpu_temperature()
print("可用的溫度傳感器:")
if temperatures:
for sensor_name, temp in temperatures.items():
print(f" {sensor_name}: {monitor.format_temperature(temp)}")
else:
print(" 未找到可用的溫度傳感器")
return
# 開(kāi)始監(jiān)控
monitor.start_monitoring(
interval=args.interval,
duration=args.duration,
alert_threshold=args.threshold,
save_data=args.save_data,
chart_file=args.chart
)
except KeyboardInterrupt:
print("\n\n用戶中斷操作")
except Exception as e:
print(f"程序執(zhí)行出錯(cuò): {e}")
sys.exit(1)
if __name__ == "__main__":
main()
使用方法
安裝依賴
在使用此腳本之前,可能需要安裝必要的庫(kù):
# Windows系統(tǒng)(可選,用于更好的溫度監(jiān)控) pip install pywin32 wmi # 生成圖表需要 pip install matplotlib
基本使用
# 基本用法,每5秒刷新一次 python cpu_temp_monitor.py # 設(shè)置監(jiān)控間隔為10秒 python cpu_temp_monitor.py -i 10 # 監(jiān)控60秒后自動(dòng)停止 python cpu_temp_monitor.py -d 60 # 設(shè)置告警閾值為75°C python cpu_temp_monitor.py -t 75 # 保存溫度數(shù)據(jù)到文件 python cpu_temp_monitor.py -s # 生成溫度變化圖表 python cpu_temp_monitor.py -c temperature.png # 列出可用的溫度傳感器 python cpu_temp_monitor.py --list-sensors
命令行參數(shù)說(shuō)明
-i, --interval: 監(jiān)控間隔(秒),默認(rèn)5秒-d, --duration: 監(jiān)控時(shí)長(zhǎng)(秒),不指定則持續(xù)監(jiān)控-t, --threshold: 溫度告警閾值(°C),默認(rèn)80°C-s, --save-data: 保存溫度數(shù)據(jù)到文件-c, --chart: 生成溫度圖表到指定文件--list-sensors: 列出可用的溫度傳感器
使用示例
持續(xù)監(jiān)控CPU溫度:
python cpu_temp_monitor.py
監(jiān)控并保存數(shù)據(jù):
python cpu_temp_monitor.py -i 10 -d 300 -s -c temp_trend.png
設(shè)置較低的告警閾值:
python cpu_temp_monitor.py -t 70
總結(jié)
這個(gè)CPU溫度監(jiān)控工具提供了一個(gè)跨平臺(tái)的CPU溫度監(jiān)控解決方案,能夠?qū)崟r(shí)顯示CPU溫度并在溫度過(guò)高時(shí)發(fā)出告警。它支持?jǐn)?shù)據(jù)持久化和可視化圖表生成,適用于服務(wù)器監(jiān)控、系統(tǒng)維護(hù)和故障排查等多種場(chǎng)景。通過(guò)這個(gè)工具,用戶可以及時(shí)了解CPU的溫度狀況,預(yù)防因過(guò)熱導(dǎo)致的系統(tǒng)問(wèn)題,確保系統(tǒng)的穩(wěn)定運(yùn)行。
需要注意的是,不同操作系統(tǒng)的溫度獲取方法有所不同,某些平臺(tái)可能需要安裝額外的庫(kù)或工具才能獲取準(zhǔn)確的溫度數(shù)據(jù)。在實(shí)際使用中,建議根據(jù)具體的硬件平臺(tái)和操作系統(tǒng)選擇合適的實(shí)現(xiàn)方式。
到此這篇關(guān)于使用Python實(shí)現(xiàn)實(shí)時(shí)監(jiān)控CPU溫度的文章就介紹到這了,更多相關(guān)Python監(jiān)控CPU溫度內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python+drawpad實(shí)現(xiàn)CPU監(jiān)控小程序
- 基于Python編寫(xiě)一個(gè)監(jiān)控CPU的應(yīng)用系統(tǒng)
- 基于Python實(shí)現(xiàn)實(shí)時(shí)監(jiān)控CPU使用率
- python實(shí)現(xiàn)監(jiān)控指定進(jìn)程的cpu和內(nèi)存使用率
- 用python監(jiān)控服務(wù)器的cpu,磁盤(pán)空間,內(nèi)存,超過(guò)郵件報(bào)警
- Python3監(jiān)控windows,linux系統(tǒng)的CPU、硬盤(pán)、內(nèi)存使用率和各個(gè)端口的開(kāi)啟情況詳細(xì)代碼實(shí)例
- python實(shí)現(xiàn)可視化動(dòng)態(tài)CPU性能監(jiān)控
- python實(shí)時(shí)監(jiān)控cpu小工具
- Python讀取Windows和Linux的CPU、GPU、硬盤(pán)等部件溫度的讀取方法
相關(guān)文章
Python cx_freeze打包工具處理問(wèn)題思路及解決辦法
這篇文章主要介紹了Python cx_freeze打包工具處理問(wèn)題思路及解決辦法的相關(guān)資料,需要的朋友可以參考下2016-02-02
Python利用matplotlib實(shí)現(xiàn)動(dòng)態(tài)可視化詳解
Python中的數(shù)據(jù)可視化是指原始數(shù)據(jù)的圖形表示,以更好地可視化、理解和推理,Python提供了各種庫(kù),包含用于可視化數(shù)據(jù)的不同特性,下面我們就來(lái)看看如何利用matplotlib實(shí)現(xiàn)動(dòng)態(tài)可視化吧2023-08-08
Python標(biāo)準(zhǔn)模塊--ContextManager上下文管理器的具體用法
本篇文章主要介紹了Python標(biāo)準(zhǔn)模塊--ContextManager的具體用法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-11-11
python使用rstrip函數(shù)刪除字符串末位字符
rstrip函數(shù)用于刪除字符串末位指定字符,默認(rèn)為空白符,這篇文章主要介紹了python使用rstrip函數(shù)刪除字符串末位字符的方法,需要的朋友可以參考下2023-04-04
Python如何獲得百度統(tǒng)計(jì)API的數(shù)據(jù)并發(fā)送郵件示例代碼
這篇文章主要給大家介紹了關(guān)于Python如何獲得百度統(tǒng)計(jì)API的數(shù)據(jù)并發(fā)送郵件的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01
Python利用pandas和matplotlib實(shí)現(xiàn)繪制雙柱狀圖
在數(shù)據(jù)分析和可視化中,常用的一種圖形類型是柱狀圖,柱狀圖能夠清晰地展示不同分類變量的數(shù)值,并支持多組數(shù)據(jù)進(jìn)行對(duì)比,本篇文章將介紹python如何使用pandas和matplotlib繪制雙柱狀圖,需要的可以參考下2023-11-11
Django查找網(wǎng)站項(xiàng)目根目錄和對(duì)正則表達(dá)式的支持
這篇文章主要介紹了Django查找網(wǎng)站項(xiàng)目根目錄和對(duì)正則表達(dá)式的支持,僅供參考,需要的朋友可以參考下2015-07-07
Python3讀寫(xiě)Excel文件(使用xlrd,xlsxwriter,openpyxl3種方式讀寫(xiě)實(shí)例與優(yōu)劣)
這篇文章主要介紹了Python3讀寫(xiě)Excel文件,使用xlrd,xlsxwriter,openpyxl3種方式讀寫(xiě)實(shí)例與優(yōu)劣,需要的朋友可以參考下2020-02-02

