我有点拼凑了一些脚本,我在网上发现了一些快速的家庭自动化"使用Raspberry Pi进行概念验证的演示。我后来意识到它也可以用作一个没有响应的终端"同样。很抱歉没有给代码的原始所有者,因为我不记得我在哪里找到它,并且开始时没有信用。
反正。我已经对它做了自己的改动,而且效果很好。我把它设置为pi上的一个新贵守护进程,它运行查找并运行它应该2-5天。然后它将挂起,在脚本中的某个地方,并且从不实际执行except:进行错误处理。实际上,我编写并作为守护进程运行的3个脚本中有2个会执行此操作。
这是我的代码。
import imaplib
import email
import GPIO
import subprocess
import prowlpy
import time
import sys
import logging
logger = logging.getLogger('error.log')
# Configure logger to write to a file...
def my_handler(type, value, tb):
logger.exception("Uncaught exception: {0}".format(str(value)))
# Install exception handler
sys.excepthook = my_handler
pnotify = prowlpy.Prowl(###)
if __name__ == '__main__':
while True:
try:
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('###', '###')
mail.select('inbox')
mail.list()
typ, data = mail.search(None, 'ALL')
for num in data[0].split():
typ, data = mail.fetch(num, '(RFC822)')
typ, data = mail.search(None, 'ALL')
ids = data[0]
id_list = ids.split()
if id_list:
latest_email_id = int( id_list[-1] )
for i in range( latest_email_id, latest_email_id-1, -1):
typ, data = mail.fetch( i, '(RFC822)')
for response_part in data:
if isinstance(response_part, tuple):
msg = email.message_from_string(response_part[1])
varSubject = msg['subject']
varFrom = msg['from']
varFrom = varFrom.replace('<','')
varFrom = varFrom.replace('>','')
if varSubject == 'Lights - ON' :
varSubject = 1
GPIO.writePin(3, 0)
pnotify.add('RPi', 'Welcome Home', 'Notification', -2)
elif varSubject == 'Lights - OFF' :
varSubject = 1
GPIO.writePin(3, 1)
pnotify.add('RPi', 'Have a nice day!', 'Notification', -2)
elif 'CMD' in varSubject and '###' in varFrom: #REQUIRES VALIDATION
subprocess.call(varSubject.split("- ")[1], shell=True)
pnotify.add('RPi', 'CMD EXEC - '+varSubject.split("- ")[1], 'Notification', -2)
varSubject = 1
else :
varSubject = 0
else: #No Emails
varSubject = 0
#Remove used emails from mailbox
typ, data = mail.search(None, 'ALL')
for num in data[0].split():
mail.store(num, '+FLAGS', '\\Deleted')
mail.expunge()
mail.close()
mail.logout()
except:
print "Could not establish connection or some other error... waiting 20s"
time.sleep(20)
sys.exit()