【问题标题】:Check that FTP connection opened successfully and files have been uploaded to FTP in Python检查 FTP 连接是否成功打开,文件是否已在 Python 中上传到 FTP
【发布时间】:2018-04-02 23:29:31
【问题描述】:

我正在构建一个远程延时相机,它每半小时拍照一次,并通过 FTP 将它们发送到我的服务器。 Raspberry Pi 将通过 Python 脚本控制摄像头、收集文件并将其发送过来,如下所示:

while true
    captureImages()
    renameFiles(picID) 
    upload() #uploads any files and folders in the selected path
    delete () #deletes the uploaded files from the pi

我的问题与这个 upload 函数(工作正常)和随后的 delete 函数有关

def upload():#sends the file to server
    print ("connecting")
    #ftp connection (server, user,pass)
    ftp = ftplib.FTP('server','user','pass')

    #folder from which to upload
    template_dir = '/home/pi/captures/'

    print ("uploading")
    #iterate through dirs and files 
    for root, dirs, files in os.walk(template_dir, topdown=True):
        relative = root[len(template_dir):].lstrip(os.sep)
       #enters dirs 
        for d in dirs:
            ftp.mkd(os.path.join(relative, d))
        #uploads files
        for f in files:
            ftp.cwd(relative)
            ftp.storbinary('STOR ' + f, open(os.path.join(template_dir, relative, f), 'rb'))
            ftp.cwd('/')

我需要的是两件事:

  1. 一种确认文件是否已成功上传的方法,例如 bool 'uploaded(true/false)' 来触发或不触发 'remove' 功能。

  2. 如果由于某种原因无法建立连接,则可以跳过上传过程而不删除文件。就像超时一样,它会在 10 秒的窗口中尝试建立连接,如果无法建立连接,它会跳过“上传”和“删除”,因此将文件存储在本地并在下一次 while 循环迭代时重试。

提前感谢您的帮助!

【问题讨论】:

  • 代码会报错。因此,如果 upload 失败,则不会调用 delete
  • 问题在于相机会停止拍照,因为在这种情况下循环会中断,对吧?
  • 所以在循环中捕获异常。
  • 对不起,我不知道该怎么做。这就是我在问题中提出的问题。你有什么建议吗?

标签: python python-3.x error-handling ftp ftplib


【解决方案1】:

代码会出错。因此,如果连接失败,上传将不会发生。同样,如果upload 失败,delete 也不会被调用。

您所要做的就是在无限循环中捕获任何异常,使其不会中断:

while true
    try:
        captureImages()
        renameFiles(picID) 
        upload() #uploads any files and folders in the selected path
        delete () #deletes the uploaded files from the pi
    except:
        print("Error:", sys.exc_info()[0])

了解Handling exceptions in Python

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多