0

在我的公司,我们有一个秤,可以在将箱子装入卡车之前检查它们的重量。如果盒子包含的产品多于或少于可接受的产品,则该盒子将被拒绝并传送到另一条传送带。电子秤记录操作的执行情况。文件存储在秤的磁盘中,并使用 ftp 从附近的台式计算机访问。我的老板希望报告自动通过电子邮件发送到他的帐户,这样他就不需要去那个设施检查前一天的拒绝情况。我开始用 Python 编写一个程序来做到这一点,但被困在从文件夹中检索文件的部分。这是我的代码:

#This program tries to retrieve the latest report and send it by email.
import urllib
import shutil
import ftplib
import os
import sys
import glob
import time
import datetime
import smtplib
import email

#Define the server and folder where the reports are stored.
carpetaftp = "/reports/"

#This function looks for the last file in the folder.
def obtenerultimoarchivo(camino):
    for cur_path, dirnames, filenames in os.walk(camino):
        for filename in filenames:
            datos_archivo = os.stat(filename)
            tiempo_archivo = datos_archivo.st_mtime

#Connects to an ftp folder and downloads the last report.
def descargareporteftp(carpetaftp):
    ftp = ftplib.FTP("server.scale.com")
    ftp.login()
    ftp.cwd(carpetaftp)
    #Uses 'ultimoreporte.pdf' as a copy of the last report.
    archivo = open('C:\\Balanza\\Reportes\\ultimoreporte.pdf',"wb")
    ftp.retrbinary("RETR " + obtenerultimoarchivo(),archivo.write)
    archivo.close()
    return archivo

#The function enviaemail() sends an email with an attachment.
def enviaemail(destinatario, adjunto):
    remitente = "electronic_scale@email.com.uy"
    msg = email.MIMEMultipart()
    msg['From'] = remitente
    msg['To'] = destinatario
    msg['Subject'] = "Ultimo informe de la balanza."
    adjunto = open('C:\\Balanza\\Reportes\\ultimoreporte.pdf', 'rb')
    attach = email.MIMENonMultipart('application', 'pdf')
    payload = base64.b64encode(adjunto.read()).decode('ascii')
    attach.set_payload(payload)
    attach['Content-Transfer-Encoding'] = 'base64'
    adjunto.close()
    attach.add_header('Content-Disposition', 'attachment', filename = 'ultimoreporte.pdf')
    msg.attach(attach)
    server = smtplib.SMTP('smtp.email.com.uy')
    server.login('electronic_scale@email.com.uy', 'thermofischer')
    server.sendmail('electronic_scale@email.com.uy',destinatario, msg.as_string())
    server.quit()


#The main routine, to retrieve the last report and send it by email.
adjunto = descargareporteftp(carpetaftp)
print("Reporte descargado")
enviaemail('myemail@email.com.uy',reporte)
print("Reporte enviado")
4

1 回答 1

0

这是我通过犯错误发现的一种肮脏方式:

如果在 urllib 检索命令中没有指定文件,它将返回目录中的文件列表(如 ls 命令中)。

因此,使用它,代码执行以下操作:

  1. 检索 FTP 文件夹中的文件列表并将文件保存到本地
  2. 读取文件并找到列表中的最后一个条目
  3. 从 FTP 文件夹中检索最后一个文件

    import urllib
    
    def retrieve(address,output):
       # Run the ftp retrieve command here
       urllib.urlretrieve(address, output)
       # Flush the urllib so that we can download a second file
       urllib.urlcleanup()
    
    def main():
       #let's build the ftp address here:
       usr = "usrname"
       psswrd = "password"
       host = "host.com"
       path = "/foo/bar/"
       list_file = "list"
       address = 'ftp://%s:%s@%s%s' % (usr,psswrd,host,path)
       print "Getting file listing from: " + address
    
       # Retrieve the list
       retrieve(address,list_file)
    
       # read a text file as a list of lines
       # find the last line, change to a file you have
       list_file_reader = open ( 'list',"r" )
       lineList = list_file_reader.readlines()
       last_file = lineList[-1].split(' ')[-1:][0].rstrip()
    
       output = "wanted_file.dat"
       address = 'ftp://%s:%s@%s%s%s' % (usr,psswrd,host,path,last_file)
    
       # Retrieve the file you are actually looking for
       retrieve(address, output)
    
       print address
    
    main()
    

这当然不是最有效的方法,但它适用于我的场景。

参考:

Python:通过 FTP 服务器下载文件

https://www.daniweb.com/programming/software-development/threads/24544/how-do-i-read-the-last-line-of-a-text-file

从 ftp 下载第二个文件失败

于 2017-12-14T06:56:27.237 回答