最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Python實(shí)現(xiàn)實(shí)時(shí)監(jiān)控CPU溫度

 更新時(shí)間:2025年12月04日 09:17:25   作者:零日失眠者  
CPU溫度是衡量系統(tǒng)健康狀況的重要指標(biāo)之一,過(guò)高的CPU溫度可能導(dǎo)致系統(tǒng)不穩(wěn)定,下面我們就來(lái)看看如何使用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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

万载县| 峡江县| 芦山县| 宁阳县| 新宁县| 古丈县| 郁南县| 和平县| 青田县| 阜城县| 昌乐县| 遂平县| 道孚县| 封开县| 广德县| 广德县| 彭阳县| 平舆县| 雅江县| 鄄城县| 南阳市| 邳州市| 清河县| 南涧| 花莲县| 宣城市| 丰都县| 清流县| 西畴县| 图木舒克市| 横峰县| 扬州市| 余姚市| 宾阳县| 唐山市| 灵台县| 清远市| 湟中县| 清徐县| 辽中县| 嘉祥县|