2014-04-05 152 views
0

下面是我用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() 
+1

尝试将类似float的CPU_temp强制转换为float(CPU_temp)> 45.0。如果你将它作为字符串返回,它可能需要显式强制转换。 –

回答

2

你不能用一个浮点数45.0一个字符串(由getCPUtemperature返回)比较,试图铸造字符串浮动:

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() 
0

要看什么getCPUtemperature()回报。如果该方法返回一个字符串,比如说“15”,则条件为真。

>>> "15" > 45.0 
>>> True 

>>> "64" > 45.0 
>>> True 

演员的getCPUtemperature()返回值float如果条件之前。

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