[英]python code to get (latest) file with timestamp as name to attach to a e-mail
I have a BASH script that takes a photo with a webcam. 我有一个BASH脚本,用网络摄像头拍照。
#!/bin/bash # datum (in swedish) = date datum=$(date +'%Y-%m-%d-%H:%M') fswebcam -r --no-banner /home/pi/webcam/$datum.jpg
I have a python code to take run the BASH script when recieve a signal from a motion detector and also call a module wich send the e-mail 我有一个python代码来接收来自运动检测器的信号时运行BASH脚本,并调用发送电子邮件的模块
import RPi.GPIO as GPIO import time import gray_camera import python_security_mail GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) while True: if(GPIO.input (23)== 1): print('discovered!!!') gray_camera.camera() time.sleep(1) python_security_mail.mail() time.sleep(1.5) GPIO.cleanup()
And the mail code: 和邮件代码:
import os
import smtplib
import userpass
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
def SendMail(ImgFileName):
img_data = open('/home/pi/solstol.png', 'rb').read()
msg = MIMEMultipart()
msg['Subject'] = 'subject'
msg['From'] = userpass.fromaddr
msg['To'] = userpass.toaddr
fromaddr = userpass.fromaddr
toaddr = userpass.toaddr
text = MIMEText("test")
msg.attach(text)
image = MIMEImage(img_data, name=os.path.basename('/home/pi/solstol.png'))
msg.attach(image)
s = smtplib.SMTP('smtp.gmail.com', 587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(fromaddr, userpass.password)
s.sendmail(fromaddr, toaddr, msg.as_string())
s.quit()
I have just learned how to attach a file to a e-mail. 我刚学会了如何将文件附加到电子邮件中。 The code works so far. 该代码到目前为止工作。 But I would like to get the latest photo taken and attach to the email. 但我想获取最新照片并附在电子邮件中。
I am still just a beginner in Python. 我还只是Python的初学者。 The code in here I have mostly copied from various tutorials and changed a little bit to work for me. 这里的代码我大部分从各种教程中复制并改变了一点为我工作。 I have no deep understanding in all of this. 我对这一切都没有深刻的理解。 In some few parts I may perhaps have intemediate knowledge. 在一些部分,我可能有中级知识。 I have no idea how to write the code to get python to find the file (photo with jpg format) I want and attach it to the mail. 我不知道如何编写代码让python找到我想要的文件(jpg格式的照片)并将其附加到邮件中。
So I am very glad if there is someone who can guide me how to fill in the missing part. 如果有人可以指导我如何填补缺失的部分,我很高兴。
I put in wrong code for the mail function. 我为邮件功能输入了错误的代码。 I got a little bit better result with this one: 我用这个得到了更好的结果:
#!/usr/bin/python
import userpass
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
def send_a_picture():
gmail_user = userpass.fromaddr
gmail_pwd = userpass.password
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = userpass.toaddr
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
mailServer.close()
mail(userpass.toaddr,
"One step further",
"Hello. Thanks for the link. I am a bit closer now.",
"solstol.png")
send_a_picture()
Edit. 编辑。
Hello. 你好。 I have now added seconds to the filename. 我现在已经添加了文件名的秒数。 If there is no picture in the folder when running glob.glob("/home/pi/ .jgp") I got: Traceback (most recent call last): File "", line 1, in last_photo_taken = glob.glob("/home/pi/ .jpg")[-1] IndexError: list index out of range. 如果在运行glob.glob(“/ home / pi / .jgp”)时文件夹中没有图片, 我得到:Traceback(最近一次调用最后一次):文件“”,第1行,在last_photo_taken = glob.glob(“ / home / pi / .jpg“)[ - 1] IndexError:列表索引超出范围。
When I take a picture I got a return ('/home/pi/2017-01-16-23:39:46.jpg'). 当我拍照时,我得到了回报('/ home /pi/2017-01-16-23:39:46.jpg')。 If I then takes another picture the return still is '/home/pi/2017-01-16-23:39:46.jpg'. 如果我再拿另一张照片,那么回报仍然是'/home/pi/2017-01-16-23:39:46.jpg'。 If I restart the shell I got the next picture as return. 如果我重新启动shell,我会得到下一张图片作为返回。 Thank you for your help today. 谢谢你今天的帮助。 I will write more tomorow. 我会写更多的tomorow。
the format you chose '%Y-%m-%d-%H:%M'
has the nice property to have the same sort order alphabetically or date-wise. 您选择的格式'%Y-%m-%d-%H:%M'
具有良好的属性,可以按字母顺序或按日期顺序排列相同的排序顺序。
So since your files are located in /home/pi/webcam
and have the jpg extension, you could compute the last photo like this: 因此,由于您的文件位于/home/pi/webcam
并具有jpg扩展名,因此您可以像这样计算最后一张照片:
import glob
last_photo_taken = glob.glob("/home/pi/webcam/*.jpg")[-1]
Attach the last_photo_taken
file to your e-mail. 将last_photo_taken
文件附加到您的电子邮箱中。
Note: photos taken at the same minute will overlap: last photo overwrites the previous one. 注意:在同一分钟拍摄的照片将重叠:最后一张照片会覆盖前一张照片。 You should consider adding seconds to the file name. 您应该考虑在文件名中添加秒数。
Note: even if your files weren't conveniently named with the date, you could sort the images by modification date and take the last one: 注意:即使您的文件没有使用日期方便地命名,您也可以按修改日期对图像进行排序并选择最后一个:
last_photo_taken = sorted(glob.glob("/home/pi/webcam/*.jpg"),key=os.path.getmtime)[-1]
Here's an example of some code to list all files and folders in a specific folder: 以下是列出特定文件夹中所有文件和文件夹的一些代码示例:
import os
files = os.listdir("myfolder")
And here's one way to take that list and filter for names that match a specific regular expression (I've used filenames of the format YYYYMMDD-HHMM.jpg, but you can change that): 这里有一种方法可以获取该列表并过滤与特定正则表达式匹配的名称(我使用了格式为YYYYMMDD-HHMM.jpg的文件名,但您可以更改它):
import re
jpgre = re.compile(r"\d{8}-\d{4}\.jpg")
jpgs = [s for s in files if jpgre.match(s)]
Now we need to sort by date/time because the list is in arbitrary order. 现在我们需要按日期/时间排序,因为列表是按任意顺序排列的。 Note that all my filenames are of the form YYYYMMDD-HHMM.jpg, so we can easily sort it by date/time, as follows: 请注意,我的所有文件名都是YYYYMMDD-HHMM.jpg形式,因此我们可以按日期/时间轻松对其进行排序,如下所示:
jpgs.sort()
And finally, the newest JPG filename is the last in the list: 最后,最新的JPG文件名是列表中的最后一个:
file = jpgs[-1]
Hope this gets you started. 希望这能让你开始。 Note that I've assumed that you may have other JPGs in the same folder so a listing of *.jpg might yield undesirable files, and that's why I gave a general solution using regular expression matching. 请注意,我假设您可能在同一文件夹中有其他JPG,因此* .jpg列表可能会产生不需要的文件,这就是为什么我使用正则表达式匹配给出了一般解决方案。 If you don't have other JPGs then you could use glob ("folder/*.jpg"). 如果你没有其他JPG,那么你可以使用glob (“folder / * .jpg”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.