Python讀取Windows和Linux的CPU、GPU、硬盤等部件溫度的讀取方法
這篇博客介紹了如何使用Python讀取計算機(jī)的CPU、GPU、硬盤等部件的溫度,讀取后的信息可以根據(jù)需要進(jìn)行日志記錄、溫度監(jiān)控等。
根據(jù)不同的平臺,本文分別介紹Windows下和Linux下的部件溫度讀取方法。
Windows下讀取方法
這種方法僅適用于Windows10,Windows11運(yùn)行會報錯(我原本是在Windows10下寫的代碼,能正常讀取溫度,但是電腦更新到Windows11后運(yùn)行直接就報錯了),至于其他更低版本的Windows系統(tǒng)則沒有測試過。
Windows下讀取計算機(jī)部件的溫度需要用到一款叫做 Open Hardware Monitor 的軟件(下載地址),下載后得到的是一個壓縮包,解壓后的結(jié)果如下:

- 這里我們主要用到兩個文件(紅色框標(biāo)記),也是利用這個軟件的兩種方法。
- 使用 OpenHardwareMonitor.exe
- 這種方法要求始終在后臺保持 OpenHardwareMonitor.exe 處于運(yùn)行狀態(tài)。
- 程序運(yùn)行需要管理員權(quán)限??梢栽趩覫DE時便選擇
以管理員權(quán)限運(yùn)行。
以下為代碼:
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}的當(dāng)前溫度為:{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中。
- 同樣的,運(yùn)行代碼需要管理員權(quán)限,否則啥都讀不出來。可以在啟動IDE時便選擇
以管理員權(quán)限運(yùn)行。
以下為代碼:
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()
輸出示例:

以上就是Python讀取Windows和Linux的CPU、GPU、硬盤等部件溫度的讀取方法的詳細(xì)內(nèi)容,更多關(guān)于Python讀取Windows和Linux部件溫度的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python繪制規(guī)則網(wǎng)絡(luò)圖形實例
今天小編大家分享一篇python繪制規(guī)則網(wǎng)絡(luò)圖形實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
python中通過pip安裝庫文件時出現(xiàn)“EnvironmentError: [WinError 5] 拒絕訪問”的問題
這篇文章主要介紹了python中通過pip安裝庫文件時出現(xiàn)“EnvironmentError: [WinError 5] 拒絕訪問”的問題,本文給大家分享解決方案,感興趣的朋友跟隨小編一起看看吧2020-08-08
python統(tǒng)計文本字符串里單詞出現(xiàn)頻率的方法
這篇文章主要介紹了python統(tǒng)計文本字符串里單詞出現(xiàn)頻率的方法,涉及Python字符串操作的相關(guān)技巧,需要的朋友可以參考下2015-05-05
python自動化測試selenium執(zhí)行js腳本實現(xiàn)示例
這篇文章主要為大家介紹了python自動化測試selenium執(zhí)行js腳本的實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11
Linux下Python自動化腳本編寫到運(yùn)維工具開發(fā)詳解
Python 憑借其簡潔的語法、豐富的內(nèi)置庫與第三方生態(tài),成為 Linux 自動化運(yùn)維的首選語言,下面我們就來看看Linux下Python自動化腳本編寫到運(yùn)維工具開發(fā)的相關(guān)知識吧2025-12-12

