下面是我用python编写的一个小代码,它安排在crontab上,每隔15分钟运行一次。它应该检查我的树莓派上CPU的温度,并且告诉我如果温度高于45摄氏度时该怎么办。我知道我正在接收正确的温度值,因为它将数字打印到屏幕上。不过,我似乎每隔15分钟就会收到一条短信,说明它的温度即使低于45度。我知道错误必须在我的条件某处,但我是python语法的新手,无法弄清楚。我试着用>和> =来比较45和45.0。python代码问题
import os
import smtplib
import sys
# Return CPU temperature as a character string
def getCPUtemperature():
res = os.popen('vcgencmd measure_temp').readline()
return(res.replace("temp=","").replace("'C\n",""))
# CPU informatiom
CPU_temp = getCPUtemperature()
if CPU_temp > 45.0:
fromaddr = '[email protected]'
toaddrs = '[email protected]'
msg = 'My current CPU temperature is %s degrees. Should I shutdown?' % (CPU_temp)
# Credentials (if needed)
username = 'xxxxxxxxxx'
password = 'xxxxxxxxxx'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
sys.exit()
else:
sys.exit()
尝试将类似float的CPU_temp强制转换为float(CPU_temp)> 45.0。如果你将它作为字符串返回,它可能需要显式强制转换。 –