在这里插入图片描述

实现步骤:

1、安装依赖库:使用psutil获取系统资源数据,plyer发送系统通知

打开电脑的powershell软件界面,输入如下命令,然后回车:

pip install psutil plyer

2、 安装 WMI 库

打开电脑的powershell软件界面,输入如下命令,然后回车:

pip install wmi

核心代码:

import psutil
import time
from plyer import notification
from datetime import datetime
import platform
import os

# 尝试导入Windows温度监控库
try:
    if platform.system() == "Windows":
        import wmi
        w = wmi.WMI(namespace="root\\OpenHardwareMonitor")
except ImportError:
    print("警告:无法导入WMI库,Windows温度监控可能不可用",flush=True)

def get_cpu_temperature():
    """跨平台获取CPU温度"""
    if platform.system() == "Windows":
        try:
            # Windows系统通过OpenHardwareMonitor获取温度
            temperatures = w.Sensor()
            for sensor in temperatures:
                if sensor.SensorType == "Temperature" and "CPU" in sensor.Name:
                    return float(sensor.Value)
            return None  # 未找到CPU温度传感器
        except Exception as e:
            print(f"获取温度失败: {e}",flush=True)
            return None
    elif platform.system() == "Linux":
        # Linux系统通过lm-sensors或psutil获取温度
        try:
            temps = psutil.sensors_temperatures()
            if "coretemp" in temps:  # Intel CPU
                return temps["coretemp"][0].current
            elif "cpu_thermal" in temps:  # Raspberry Pi
                return temps["cpu_thermal"][0].current
            return None
        except (AttributeError, KeyError):
            # 尝试通过/proc获取(部分Linux系统)
            try:
                with open("/sys/class/thermal/thermal_zone0/temp", "r") as f:
                    return float(f.read()) / 1000.0
            except:
                return None
    elif platform.system() == "Darwin":  # macOS
        # macOS系统无法直接获取温度,返回None或估算值
        return None
    return None

def monitor_system(threshold=60, temp_threshold=70.0):
    while True:
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        cpu_usage = psutil.cpu_percent(interval=1)
        mem = psutil.virtual_memory()
        mem_usage = mem.percent
        cpu_temp = get_cpu_temperature()

        # 构建温度显示文本
        temp_text = ""
        alert_triggered = False
        
        if cpu_temp is not None:
            temp_text = f" | 温度: {cpu_temp:.1f}°C"
            # 检查温度是否超过阈值
            if cpu_temp > temp_threshold:
                alert_triggered = True
                title = f"【{current_time}】CPU温度过高"
                message = f"温度: {cpu_temp:.1f}°C | 请检查散热!"
        else:
            temp_text = " | 温度: 无法获取"

        # 检查CPU或内存是否超过阈值
        if cpu_usage > threshold or mem_usage > threshold:
            alert_triggered = True
            title = f"【{current_time}】资源使用率过高"
            message = f"CPU: {cpu_usage:.1f}% | 内存: {mem_usage:.1f}%{temp_text}"

        # 触发通知
        if alert_triggered:
            notification.notify(
                title=title,
                message=message,
                timeout=10
            )
            print(f"[警告]: {title}: {message}",flush=True)

        time.sleep(5)

if __name__ == "__main__":
    print("开始监控系统资源... (按Ctrl+C停止)",flush=True)
    
    # 检查Windows系统是否需要安装OpenHardwareMonitor
    if platform.system() == "Windows":
        try:
            w.Sensor()
        except Exception:
            print("\n警告:检测到Windows系统,需要安装OpenHardwareMonitor以获取CPU温度",flush=True)
            print("1. 下载地址: https://openhardwaremonitor.org/",flush=True)
            print("2. 安装后重新运行此脚本\n",flush=True)
    
    try:
        monitor_system(threshold=60, temp_threshold=70.0)  # 温度阈值设为70°C
    except KeyboardInterrupt:
        print("监控已停止",flush=True)

功能说明:

实时监控:		每 5 秒更新一次 CPU 和内存使用率
阈值可调:		默认 60%,可通过monitor_system(threshold=70)修改
多平台支持:		Windows/macOS/Linux 系统通知
异常处理:		按 Ctrl+C 可安全退出监控(在powershell界面中)

使用说明:

1、Windows 用户注意:
需要先安装 OpenHardwareMonitor
运行脚本前需先启动 OpenHardwareMonitor 程序

安装 OpenHardwareMonitor,方法如下:
①打开这个网址:https://openhardwaremonitor.org/downloads/
②:点击如下位置:

在这里插入图片描述
下载完成后是个压缩文件,解压后运行OpenHardwareMonitor.exe 程序
(powshell中执行python命令之前,这个程序必须提前开好,否则powershell中会提示:温度:无法获取)

③ 开启程序后,再在powshell中执行python命令:python E:\python_ing\system_monitor2_BanBen.py
2、Linux 用户:
大多数系统可直接获取温度
若无法获取,可能需要安装 lm-sensors:sudo apt-get install lm-sensors
3、macOS 用户:
由于系统限制,暂不支持获取 CPU 温度
通知中会显示 “温度:无法获取”

使用方法1:实时显示

1、将代码保存为system_monitor.py
2、powershell中,命令行 运行: python E:\python_ing\system_monitor2_BanBen.py

CPU占有率: 超过 60%
内存占有率: 超过 60%
CPU温度: 超过70°C
任意一个条件满足时
会收到系统弹窗通知,显示在电脑右下角位置:
在这里插入图片描述
3、如需调整阈值,修改最后一行的参数:

monitor_system(threshold=70, temp_threshold=75.0)  # CPU/内存阈值70%,温度阈值75°C

运行命令后,并在powershell界面中显示提醒:
在这里插入图片描述

使用方法2:把告警信息输出到记事本中(用于:方便查询历史记录)

powershell中 运行: python E:\python_ing\system_monitor2_BanBen.py > D:\testPythonResult.txt
然后按一下回车,
运行后的样子:如下有个光标一直这样,并无后续报错信息,则代表运行成功
在这里插入图片描述

之后就会在电脑的D磁盘下,自动生成一个txt文件:testPythonResult.txt。
我们可以打开这个文档,就可以查看报警的历史记录了

在这里插入图片描述

停止监控方法:

方法1 或 方法2 在powershell中运行后,按键盘上的CTRL + C 键,可以停止监控。

如果按了之后,有如下提示,不用管,并不影响正常显示 和 正常输出记录到txt文件中
在这里插入图片描述

更多推荐