Python获取CPU温度
Python 版本:3.7.15
需要安装:sensors
#!/usr/bin/env python3
from ast import Num
import fileinput
import string
import os
import re
from time import sleep
#读取并计算均值,在某个CPU温度大于 75° 时单独报警
while True:
#使用sensors获取10个CPU温度,写入桌面文件中
s = os.popen("sensors")
a = open('/home/sweetorange/桌面/cpu.txt', 'w')
a.write(s.read())
a.close()
sleep(1)
i = 0
sum = 0
temp = 0
for line in fileinput.input("/home/sweetorange/桌面/cpu.txt"):
# print (i)
if line.startswith("Core"):
ret = re.search("\d+.\d",line)
if ret:
num = float(ret.group( ))
if num != 0:
# print("-")
# print(num)
i = i +1
sum += num
temp = sum/i #计算多个CPU均值
# print(round(temp,1))
if num > 75:
print("警告!!! CPU温度 > 75℃")
print("CPU目前的温度是: ",round(temp,1))
sleep(0.19)
# else:
# print("匹配失败")