RPi 2上的Python:使用相同变量的两个脚本

时间:2016-01-26 17:11:27

标签: python

我在RPi 2上有两个python脚本,第一个用于在检测到运动时捕获图像,第二个用于将捕获的图像发送到我的邮件。问题是我不知道如何让这些脚本一起工作。

以下是第一个脚本的代码:

    import RPi.GPIO as GPIO
 import time
import picamera
import datetime
from pushetta import Pushetta

def get_file_name():
     return datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%S.jpg")

sensor = 4

GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN)

previous_state = False
current_state = False

cam = picamera.PiCamera()

API_KEY="key"
CHANNEL_NAME="CzechBery"
p=Pushetta(API_KEY)

while True:
    time.sleep(0.1)
    previous_state = current_state
    current_state = GPIO.input(sensor)
    if current_state != previous_state:
        new_state = "HIGH" if current_state else "LOW"
        print("GPIO pin %s is %s" % (sensor, new_state))
        if current_state:
            fileName = get_file_name()
            cam.start_preview()
            p.pushMessage(CHANNEL_NAME, "Motion Detected")
            time.sleep(2)
            cam.capture(fileName)
 time.sleep(1)
        else:
            cam.stop_preview()

这是第二个:

import smtplib
from datetime import datetime
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage

fromaddr = 'from'
toaddrs  = 'to'  # can be list of strings
subject = 'Testing'

#
# Email object
#
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddrs
msg['Subject'] = subject

#
# Email body
body = 'Alert!! Motion Detected!!\nTime: %s' % str(datetime.now())
msg.attach(MIMEText(body, 'plain'))

#msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>Nifty!', 'html')
#msgAlternative.attach(msgText)

fp = open('image.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

# Define the image's ID as referenced above
#msgImage.add_header('Content-ID', 'image')
msg.attach(msgImage)

#
# Connecting to SMTP server and
# sending the email
#
smtp = smtplib.SMTP()
smtp.connect('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login('from','passwd')
text = msg.as_string()
smtp.sendmail(fromaddr, toaddrs, text)
smtp.quit()

#
# Output
#
print "Message sent." + "\n" + "From: " + fromaddr + "\n" + "To: " + toaddrs

我需要使用第二个脚本发送第一个脚本创建的图像,但仅在检测到运动时。图像以此方法命名:

def get_file_name():
     return datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%S.jpg")

0 个答案:

没有答案