微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Python ftplib FTP 传输文件上传中处理断开连接

如何解决在 Python ftplib FTP 传输文件上传中处理断开连接

如何处理 ftplib 中的断开连接?

我编写了一个 Python 脚本,我将使用它来使用 ftplib 将非常大的文件上传到 FTP 服务器。

我的问题是: 由于文件的大小,上传可能需要很多时间,如果互联网在中间断开然后在 1 分钟后重新连接怎么办?如何在脚本中处理此类问题?有什么想法吗?

我想到的是一个 try except 块,它不断检查互联网连接是否可用。有什么想法吗?

谢谢

解决方法

使用 Python ftplib 上传时处理断开连接的简单实现:

finished = False

local_path = "/local/source/path/file.zip"
remote_path = "/remote/desti/path/file.zip"

with open(local_path,'rb') as f:
    while (not finished):
        try:
            if ftp is None:
                print("Connecting...")
                ftp = FTP(host,user,passwd)

            if f.tell() > 0:
                rest = ftp.size(remote_path)
                print(f"Resuming transfer from {rest}...")
                f.seek(rest)
            else:
                print("Starting from the beginning...")
                rest = None
            ftp.storbinary(f"STOR {remote_path}",f,rest=rest)
            print("Done")
            finished = True
        except Exception as e:
            ftp = None
            sec = 5
            print(f"Transfer failed: {e},will retry in {sec} seconds...")
            time.sleep(sec)

更细粒度的异常处理是可取的。

同样适用于下载:
Resume FTP download after timeout

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。