我们设置了树莓派以测量服务器房间的温度,并使用python脚本以"Temp: 24.0 C Humidity: 67.0 %"
格式(每2秒更新一次)将输出保存在文本文件中。
现在我正在寻找python代码以从文本文件中读取温度值(例如24.0),并在条件为true时向我发送电子邮件,例如(Temp> 35.0),否则什么也不做,然后退出。
我是python的新手,请帮助我,我们已经编写了电子邮件代码及其工作方式,只需在以下代码中启用上述要求的条件即可。
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
fromaddr = "sender@gmail.com"
toaddr = "recipient@gmail.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Alert: Server Room "
body = "Server room current temprature is : "
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
此脚本将使用cron
选项卡运行。
答案 0 :(得分:1)
我想像这样的事情会做:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
def send_email(temperature):
fromaddr = "sender@gmail.com"
toaddr = "recipient@gmail.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Alert: Server Room "
body = "Server room current temprature is : " + temperature
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
f = open("temp_log.txt", "r")
content = f.read()
temp = content.split(' ')[1]
if float(temp) > 35:
send_email(temp)
答案 1 :(得分:1)
with open ('temp.txt', 'r', encoding='utf-8') as temp:
for line in temp:
try:
temperature = float(line.split()[1])
if temperature > 35.0:
#SENDEMAIL
else:
pass
except:
pass
temp.txt
是您的树莓派文件。
您需要担心的是: