这篇博客介绍了如何使用Python读取计算机的CPU、GPU、硬盘等部件的温度,读取后的信息可以根据需要进行日志记录、温度监控等。
根据不同的平台,本文分别介绍Windows下和Linux下的部件温度读取方法。
Windows下读取方法
这种方法仅适用于Windows10,Windows11运行会报错(我原本是在Windows10下写的代码,能正常读取温度,但是电脑更新到Windows11后运行直接就报错了),至于其他更低版本的Windows系统则没有测试过。
- Windows下读取计算机部件的温度需要用到一款叫做
Open Hardware Monitor
的软件(下载地址),下载后得到的是一个压缩包,解压后的结果如下:
这里我们主要用到两个文件(红色框标记),也是利用这个软件的两种方法。
- 使用 OpenHardwareMonitor.exe
- 这种方法要求始终在后台保持 OpenHardwareMonitor.exe 处于运行状态。
- 程序运行需要管理员权限。可以在启动IDE时便选择
以管理员权限运行
。
以下为代码:
import ctypes
import datetime
import sys
import time
import wmi
import psutil
import subprocess
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except Exception:
return False
def check_process(path, proc_name):
for proc in psutil.process_iter():
if proc.name() == proc_name:
break
else:
subprocess.Popen(path + proc_name)
time.sleep(5)
if is_admin():
path = 'openhardwaremonitor-v0.9.6/OpenHardwareMonitor/'
proc_name = "OpenHardwareMonitor.exe"
check_process(path, proc_name)
w = wmi.WMI(namespace='root/OpenHardwareMonitor')
while True:
print('{:=^50}'.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
temperature_info = w.Sensor()
temperature_info = sorted(temperature_info, key=lambda x: str(x.Identifier))
for sensor in temperature_info:
if sensor.SensorType == 'Temperature':
identifier = str(sensor.Identifier).split('/')
print(
'{0:^20}的当前温度为:{1:>5}℃'.format('-'.join([identifier[1], identifier[2], identifier[-1]]),
sensor.Value))
time.sleep(1)
else:
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
输出示例:
- 使用 OpenHardwareMonitorLib.dll
- 这种方法类似于将 OpenHardwareMonitorLib.dll 作为第三方库引入到python中。
- 同样的,运行代码需要管理员权限,否则啥都读不出来。可以在启动IDE时便选择
以管理员权限运行
。
以下为代码:
import clr
import time
import datetime
clr.AddReference('D:/OpenHardwareMonitor/OpenHardwareMonitorLib.dll') # 填写绝对路径
import OpenHardwareMonitor as ohm
from OpenHardwareMonitor.Hardware import Computer, HardwareType, SensorType
computer = Computer()
computer.CPUEnabled = True
computer.GPUEnabled = True
computer.HDDEnabled = True
computer.RAMEnabled = True
computer.MainboardEnabled = True
computer.FanControllerEnabled = True
hardwareType = ohm.Hardware.HardwareType
sensorType = ohm.Hardware.SensorType
computer.Open()
while True:
print('{:=^50}'.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
for hardware in computer.Hardware:
hardware.Update()
for sensor in hardware.Sensors:
if sensor.SensorType == sensorType.Temperature:
si_ls = str(sensor.Identifier).split('/')
ssname = f'{si_ls[1]}#{si_ls[-1]}'
print(ssname, sensor.Value)
time.sleep(1)
输出示例:
Linux下读取方法
- Linux下读取部件温度的方法比较简单,直接使用 psutil 包即可。代码如下:
import psutil
def main():
if not hasattr(psutil, "sensors_temperatures"):
sys.exit("platform not supported")
temps = psutil.sensors_temperatures()
if not temps:
sys.exit("can't read any temperature")
for name, entries in temps.items():
print(name)
for entry in entries:
print(" %-20s %s °C (high = %s °C, critical = %s °C)" % (
entry.label or name, entry.current, entry.high,
entry.critical))
print()
main()
输出示例:
原创不易,麻烦大家点个关注收藏评论支持一下~~