Reputation: 548
Below is a little code that I have written in python that is scheduled on a crontab to run every 15 minutes. It is supposed to check the temperature of the CPU on my raspberry pi, and text me asking what to do if the temperature is above 45 degrees Celsius. I know I am receiving the correct temperature value because it prints to the screen as a number. However, I seem to get a text message every 15 minutes stating its temperature even thought it is below 45 degrees. I know the error must be in my conditional somewhere, but I am new to python syntax and can't figure it out. Ive tried comparing to both 45 and 45.0 using both > and >=.
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()
Upvotes: 0
Views: 634
Reputation: 17946
CPU_temp needs to be explicitly cast as a float because you're returning a string. You can either convert it like CPU_temp = float(CPU_temp)
or just do the cast in the comparison. Here's a trace explanation of what's happening:
>>> 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
Upvotes: 0
Reputation: 12092
Depends on what getCPUtemperature()
returns. If the method returns a string, say "15", the conditional will be true.
>>> "15" > 45.0
>>> True
>>> "64" > 45.0
>>> True
Cast the return value of getCPUtemperature()
to float
before the if condition.
Upvotes: 0
Reputation: 2323
You can't compare a string (returned by getCPUtemperature
) with a float 45.0
, try casting the string to 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 = '[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()
Upvotes: 2