Python 3将代码连接在一起 - Raspberry Pi

时间:2016-05-01 08:27:41

标签: python linux python-3.x raspberry-pi raspbian

我将这三组代码加在一起有问题。该项目是一个烟雾系统警报。当烟雾传感器检测到烟雾时,将拍摄照片并发送电子邮件并附上照片附件。我感到困惑的是如何将3个代码加在一起。

感谢您的帮助!

摄像头代码:

#!/usr/bin/python
import os
import pygame, sys

from pygame.locals import *
import pygame.camera

width = 480
height = 360

#initialise pygame   
pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0",(width,height))
cam.start()

#setup window
windowSurfaceObj = pygame.display.set_mode((width,height),1,16)
pygame.display.set_caption('Camera')

#take a picture
image = cam.get_image()
cam.stop()

#display the picture
catSurfaceObj = image
windowSurfaceObj.blit(catSurfaceObj,(0,0))
pygame.display.update()

#save picture
pygame.image.save(windowSurfaceObj,'picture.jpg')

电子邮件代码:

#!/usr/bin/env python
# encoding: utf-8
import os
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '

def main():
    sender = ''
    gmail_password = ''
    recipients = ['']

    # Create the enclosing (outer) message
    outer = MIMEMultipart()
    outer['Subject'] = 'SMOKE HAS BEEN DETECTED!'
    outer['To'] = COMMASPACE.join(recipients)
    outer['From'] = sender
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    # List of attachments
    attachments = ['']

    # Add the attachments to the message
    for file in attachments:
        try:
            with open(file, 'rb') as fp:
                msg = MIMEBase('application', "octet-stream")
                msg.set_payload(fp.read())
            encoders.encode_base64(msg)
            msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
            outer.attach(msg)
        except:
            print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])
            raise

    composed = outer.as_string()

    # Send the email
    try:
        with smtplib.SMTP('smtp.gmail.com', 587) as s:
            s.ehlo()
            s.starttls()
            s.ehlo()
            s.login(sender, gmail_password)
            s.sendmail(sender, recipients, composed)
            s.close()
        print("Email sent!")
    except:
        print("Unable to send the email. Error: ", sys.exc_info()[0])
        raise

if __name__ == '__main__':
    main()

MQ2烟雾传感器代码:

import time
import botbook_mcp3002 as mcp #

smokeLevel= 0

def readSmokeLevel():
global smokeLevel
smokeLevel= mcp.readAnalog()

def main():
while True: #
readSmokeLevel() #
print ("Current smoke level is %i " % smokeLevel) #
if smokeLevel > 120:
print("Smoke detected")
time.sleep(0.5) # s

if_name_=="_main_":
main()

2 个答案:

答案 0 :(得分:1)

看起来你可能会受益于一两个Python教程:)

执行所需操作的最简单方法(但不一定是最好的方法)是创建单个文件,将所有import语句放在顶部然后执行此操作:

添加相机代码,但将其转换为功能:

def take_picture():
    width = 480
    height = 360

    # initialise pygame   
    pygame.init()
    [etc.]

注意,前导空格很重要。

也可以编写该函数以在调用时指定文件名(如Roland的示例所示)。如果您想保存多个图像,这将是一种更好的方法。

然后添加电子邮件代码,但在这里您应该将main函数的名称更改为email_picture之类的其他内容。此外,您还需要填写详细信息,例如更改attachments变量以匹配take_picture函数正在保存的文件的名称。 (同样,最好允许调用者像Roland的例子那样指定发件人/收件人地址和文件名等内容。此处不包括if __name__ == "__main__"部分。

e.g:

COMMASPACE = ', '

def email_picture():
    sender = 'Your@Email.address'
    gmail_password = 'YourGmailPassword'
    recipients = ['Your@Email.address']

    # Create the enclosing (outer) message
    outer = MIMEMultipart()
    outer['Subject'] = 'SMOKE HAS BEEN DETECTED!'
    outer['To'] = COMMASPACE.join(recipients)
    outer['From'] = sender
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    # List of attachments
    # This must match what the take_picture funtion is saving the file as
    attachments = ['picture.jpg']
    [etc.]

然后添加烟雾检测代码。你帖子中的代码有点严重。缺少前导空格,一些双下划线已更改为单个下划线。

将相机代码和电子邮件代码的调用添加到烟雾检测代码中。此外,您可能希望在检测到烟雾时发送电子邮件后添加睡眠状态,以便您的脚本在检测到烟雾时不会向您发送数百/数千封电子邮件。

看起来应该更像(尽管全局变量似乎没必要):

smokeLevel = 0

def readSmokeLevel():
    global smokeLevel
    smokeLevel = mcp.readAnalog()

def main():
    while True: # Loop forever
        readSmokeLevel() #
        print("Current smoke level is %i " % smokeLevel) #
        if smokeLevel > 120:
            print("Smoke detected")
            take_picture()
            email_picture()
            time.sleep(600) # Cut down on emails when smoke detected
        time.sleep(0.5) # seconds

if __name__ == "__main__":
    main()

答案 1 :(得分:-1)

可能最简单的方法是在Python 3.5(或早期版本的<nav class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- Logo --> <a class="navbar-brand" href="./index.html"><img src="images/logo.png" class="img-responsive" alt=""/></a> </div> <!-- Navmenu --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li> <a href="#home">Home.</a> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Menus.</a> <ul class="dropdown-menu" role="menu"> <li><a href="./breakfast.html">All Day Breakfast</a></li> <li><a href="./lunch.html">Lunch</a></li> <li><a href="./childrenmenu.html">Children's Menu</a></li> <li><a href="./coffeeandcake.html">Coffee and Cakes</a></li> </ul> </li> <li> <a href="#about">Location.</a> </li> <li> <a href="#cater">Catering.</a> </li> <li> <a href="#about">About.</a> </li> <li><a href="#contact">Contact.</a></li> </ul> </div> </div> </nav> )上使用subprocess.run来首先启动照片程序,然后启动烟雾检测程序中的电子邮件程序。

另一种方法是将相机程序和电子邮件程序转换为 modules

相机模块看起来像这样;

subprocess.call

以同样的方式,您可以使用函数"""Camera module""" import pygame def picture(filename): """Take a picture. Arguments: filename: Path where to store the picture """ pygame.init() pygame.camera.init() cam = pygame.camera.Camera("/dev/video0", (480, 360)) cam.start() image = cam.get_image() cam.stop() pygame.image.save(image, filename) 创建email模块。

在烟雾探测程序中,您可以这样做;

send_mail(sender, password, recipient, attachments)
相关问题