下面是我在python中编写的一些代码,它安排在crontab上,每15分钟运行一次。它应该检查我的覆盆子pi上CPU的温度,并发短信给我,询问如果温度高于45摄氏度该怎么办。我知道我收到了正确的温度值,因为它以数字的形式打印到屏幕上。但是,我似乎每15分钟收到一条短信,说明它的温度甚至低于45度。我知道错误必须在我的条件某处,但我是python语法的新手,无法弄明白。我曾尝试使用>比较45和45.0。和> =。
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 = 'xxxxxxxxxx@gmail.com'
toaddrs = 'xxxxxxxxxx@vtext.com'
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()
答案 0 :(得分:2)
您无法将字符串(由getCPUtemperature
返回)与float 45.0
进行比较,请尝试将字符串转换为float:
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 float(CPU_temp) > 45.0:
fromaddr = 'xxxxxxxxxx@gmail.com'
toaddrs = 'xxxxxxxxxx@vtext.com'
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()
答案 1 :(得分:0)
取决于getCPUtemperature()
返回的内容。如果该方法返回一个字符串,例如" 15",则条件为真。
>>> "15" > 45.0
>>> True
>>> "64" > 45.0
>>> True
在if条件之前将getCPUtemperature()
的返回值转换为float
。
答案 2 :(得分:0)
CPU_temp需要显式转换为float,因为你要返回一个字符串。你可以像CPU_temp = float(CPU_temp)
一样转换它,或者只是在比较中进行转换。以下是对正在发生的事情的痕迹解释:
>>> CPU_temp = "53.1"
>>> if CPU_temp > 45.0:
print("True")
TypeError: unorderable types: str() > float()
>>> if float(CPU_temp) > 45.0:
print("True")
True