基于Python的电脑硬件监控工具开发指南

一、核心功能设计

1.1 监控指标体系

graph TD
    A[硬件监控] --> B[CPU]
    A --> C[GPU]
    A --> D[内存]
    A --> E[磁盘]
    A --> F[网络]
    B --> B1[使用率]
    B --> B2[温度]
    B --> B3[频率]
    C --> C1[显存占用]
    C --> C2[温度]
    D --> D1[使用量]
    D --> D2[交换分区]
    E --> E1[读写速度]
    E --> E2[健康状态]
    F --> F1[上传下载]
    F --> F2[连接数]
图片[1]_基于Python的电脑硬件监控工具开发指南_知途无界

1.2 技术架构

# 架构伪代码示例
class HardwareMonitor:
    def __init__(self):
        self.sensors = {
            'cpu': CPUSensor(),
            'gpu': GPUSensor(),
            'memory': MemorySensor(),
            'disk': DiskSensor(),
            'network': NetworkSensor()
        }
        
    def collect_data(self):
        return {name: sensor.read() for name, sensor in self.sensors.items()}

二、关键实现步骤

2.1 依赖库选择

监控目标推荐库安装命令
通用硬件psutilpip install psutil
CPU温度py3sensorspip install py3sensors
NVIDIA GPUpyNVMLpip install nvidia-ml-py3
AMD GPUpyamdgpupip install pyamdgpu
数据可视化matplotlibpip install matplotlib

2.2 CPU监控实现

import psutil
import platform

def get_cpu_info():
    return {
        'usage': psutil.cpu_percent(interval=1),
        'freq': psutil.cpu_freq().current,
        'cores': psutil.cpu_count(logical=False),
        'temp': get_cpu_temp() if platform.system() == 'Linux' else None
    }

def get_cpu_temp():
    # Linux系统获取温度实现
    temps = psutil.sensors_temperatures()
    return temps['coretemp'][0].current if 'coretemp' in temps else None

2.3 GPU监控实现

try:
    from pynvml import *
    nvmlInit()
    
    def get_gpu_info():
        handle = nvmlDeviceGetHandleByIndex(0)
        return {
            'usage': nvmlDeviceGetUtilizationRates(handle).gpu,
            'mem_used': nvmlDeviceGetMemoryInfo(handle).used,
            'mem_total': nvmlDeviceGetMemoryInfo(handle).total,
            'temp': nvmlDeviceGetTemperature(handle, NVML_TEMPERATURE_GPU)
        }
except ImportError:
    def get_gpu_info():
        return {'error': 'NVIDIA library not available'}

2.4 数据存储方案

import sqlite3
from datetime import datetime

def init_db():
    conn = sqlite3.connect('hardware.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS hardware_logs
                 (timestamp TEXT, cpu_usage REAL, gpu_usage REAL, 
                  mem_used INTEGER, temp REAL)''')
    conn.commit()
    conn.close()

def save_data(data):
    conn = sqlite3.connect('hardware.db')
    c = conn.cursor()
    c.execute("INSERT INTO hardware_logs VALUES (?,?,?,?,?)",
              (datetime.now(), data['cpu']['usage'], 
               data['gpu']['usage'], 
               data['memory']['used'],
               data['cpu']['temp']))
    conn.commit()
    conn.close()

三、可视化界面开发

3.1 控制台仪表盘

from rich.console import Console
from rich.table import Table
from rich.live import Live

def display_dashboard(data):
    console = Console()
    table = Table(title="硬件监控仪表盘")
    
    table.add_column("指标", justify="right")
    table.add_column("当前值", justify="left")
    
    table.add_row("CPU使用率", f"{data['cpu']['usage']}%")
    table.add_row("CPU温度", f"{data['cpu']['temp'] or 'N/A'}°C")
    table.add_row("GPU使用率", f"{data['gpu']['usage']}%")
    table.add_row("内存使用", f"{data['memory']['used']/1024/1024:.1f} MB")
    
    console.print(table)

# 实时刷新
with Live(display_dashboard(get_cpu_info()), refresh_per_second=4) as live:
    while True:
        live.update(display_dashboard(get_cpu_info()))
        time.sleep(0.25)

3.2 Matplotlib动态图表

import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, axs = plt.subplots(2, 2)
fig.suptitle('硬件监控实时数据')

def animate(i):
    data = get_cpu_info()
    
    # CPU使用率图表
    axs[0, 0].clear()
    axs[0, 0].plot(cpu_history, 'r-')
    axs[0, 0].set_title('CPU使用率 %')
    
    # 温度图表
    axs[0, 1].clear()
    axs[0, 1].plot(temp_history, 'b-')
    axs[0, 1].set_title('CPU温度 °C')
    
    # 更新数据
    cpu_history.append(data['cpu']['usage'])
    temp_history.append(data['cpu']['temp'] or 0)
    
    # 保持固定长度
    if len(cpu_history) > 50:
        cpu_history.pop(0)
        temp_history.pop(0)

ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()

四、高级功能扩展

4.1 告警系统实现

import smtplib
from email.mime.text import MIMEText

class AlertSystem:
    def __init__(self, thresholds):
        self.thresholds = thresholds
        
    def check_thresholds(self, data):
        alerts = []
        if data['cpu']['usage'] > self.thresholds['cpu_usage']:
            alerts.append(f"CPU使用率超过{self.thresholds['cpu_usage']}%")
        if data['cpu']['temp'] and data['cpu']['temp'] > self.thresholds['cpu_temp']:
            alerts.append(f"CPU温度超过{self.thresholds['cpu_temp']}°C")
        return alerts
    
    def send_email(self, alerts):
        msg = MIMEText("\n".join(alerts))
        msg['Subject'] = '硬件监控告警'
        msg['From'] = 'monitor@example.com'
        msg['To'] = 'admin@example.com'
        
        with smtplib.SMTP('smtp.example.com') as server:
            server.send_message(msg)

4.2 Web API服务

from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/api/hardware')
def hardware_api():
    return jsonify(get_cpu_info())

@app.route('/dashboard')
def dashboard():
    data = get_cpu_info()
    return f"""
    <html>
    <body>
        <h1>硬件监控</h1>
        <p>CPU使用率: {data['cpu']['usage']}%</p>
        <p>CPU温度: {data['cpu']['temp'] or 'N/A'}°C</p>
    </body>
    </html>
    """

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

五、部署与优化建议

5.1 性能优化技巧

  1. 采样频率控制​: # 使用多线程避免阻塞 from threading import Thread class MonitorThread(Thread): def run(self): while True: data = get_cpu_info() save_data(data) time.sleep(5) # 5秒采样间隔
  2. 数据聚合​: # 每分钟计算平均值 def aggregate_data(): conn = sqlite3.connect('hardware.db') c = conn.cursor() c.execute('''INSERT INTO hourly_stats SELECT datetime('now'), AVG(cpu_usage), MAX(temp) FROM hardware_logs WHERE timestamp > datetime('now', '-1 hour')''') conn.commit() conn.close()

5.2 跨平台兼容方案

def get_platform_specific_info():
    system = platform.system()
    if system == 'Windows':
        return get_windows_specific_info()
    elif system == 'Linux':
        return get_linux_specific_info()
    elif system == 'Darwin':
        return get_mac_specific_info()
    else:
        return {}

def get_windows_specific_info():
    try:
        import wmi
        w = wmi.WMI()
        return {
            'gpu_temp': w.Win32_TemperatureProbe()[0].CurrentReading
        }
    except:
        return {}

六、完整实现示例

6.1 主程序结构

import time
import logging
from alert_system import AlertSystem
from db_handler import init_db, save_data

def main():
    # 初始化组件
    init_db()
    alert = AlertSystem({
        'cpu_usage': 90,
        'cpu_temp': 85
    })
    
    # 主监控循环
    while True:
        try:
            data = get_cpu_info()
            save_data(data)
            
            # 检查告警
            alerts = alert.check_thresholds(data)
            if alerts:
                alert.send_email(alerts)
                
            time.sleep(5)
            
        except Exception as e:
            logging.error(f"监控出错: {str(e)}")
            time.sleep(10)

if __name__ == '__main__':
    main()

6.2 打包为可执行文件

使用PyInstaller创建独立应用:

pyinstaller --onefile --windowed hardware_monitor.py

建议将工具开发为系统服务(Linux)或后台进程(Windows),实现开机自启动和持续监控。对于企业级部署,可考虑添加远程监控、多节点管理和历史数据分析等高级功能。

© 版权声明
THE END
喜欢就点个赞,支持一下吧!
点赞14 分享
评论 抢沙发
头像
欢迎您留下评论!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容