返回

Python 工程师教你无需 X 大师也能轻松掌握老电脑 CPU 温度

后端

作为一名 Python 工程师,我深知电脑维护的重要性,尤其是老电脑的维护。最近,我买了一台 09 年的老电脑,为了确保它的稳定运行,我需要掌握它的 CPU 温度。然而,我不想安装 X 大师这样的软件,因为我更喜欢使用 Python 来解决问题。

1. 准备工作

在开始之前,我们需要确保我们的电脑已经安装了 Python。如果没有,请访问 Python 官方网站下载并安装。此外,我们还需要安装一些 Python 库,以便我们能够与电脑的硬件进行交互。这些库包括 psutil、gputil 和 py-cpuinfo。您可以使用 pip 命令来安装这些库:

pip install psutil
pip install gputil
pip install py-cpuinfo

2. 获取 CPU 温度

现在,我们可以使用 Python 代码来获取 CPU 温度了。以下是一个简单的示例:

import psutil

def get_cpu_temperature():
    """获取 CPU 温度"""
    temperature = psutil.sensors_temperatures()['coretemp'][0].current
    return temperature

if __name__ == "__main__":
    cpu_temperature = get_cpu_temperature()
    print(f"CPU 温度: {cpu_temperature} 摄氏度")

运行这段代码,您将看到当前的 CPU 温度。

3. 监控 CPU 温度

如果我们想监控 CPU 温度,我们可以使用以下代码:

import psutil
import time

def monitor_cpu_temperature():
    """监控 CPU 温度"""
    while True:
        temperature = psutil.sensors_temperatures()['coretemp'][0].current
        print(f"CPU 温度: {temperature} 摄氏度")
        time.sleep(1)

if __name__ == "__main__":
    monitor_cpu_temperature()

运行这段代码,您将看到每秒钟更新一次的 CPU 温度。

4. 告警

如果我们想在 CPU 温度过高时发出告警,我们可以使用以下代码:

import psutil
import time
import smtplib

def monitor_cpu_temperature():
    """监控 CPU 温度"""
    while True:
        temperature = psutil.sensors_temperatures()['coretemp'][0].current
        if temperature > 80:
            send_email_alert()
        print(f"CPU 温度: {temperature} 摄氏度")
        time.sleep(1)

def send_email_alert():
    """发送电子邮件告警"""
    smtp_server = "smtp.gmail.com"
    smtp_port = 587
    sender_email = "your_email@gmail.com"
    sender_password = "your_password"
    receiver_email = "receiver_email@gmail.com"
    subject = "CPU 温度过高告警"
    body = "您的电脑 CPU 温度过高,请尽快采取措施。"

    message = f"Subject: {subject}\n\n{body}"

    try:
        smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
        smtp_obj.starttls()
        smtp_obj.login(sender_email, sender_password)
        smtp_obj.sendmail(sender_email, receiver_email, message)
        smtp_obj.quit()
    except smtplib.SMTPException:
        print("发送电子邮件告警失败")

if __name__ == "__main__":
    monitor_cpu_temperature()

运行这段代码,当 CPU 温度超过 80 摄氏度时,您将收到一封电子邮件告警。

我希望这篇博文对您有所帮助。如果您有任何问题,请随时留言。