如何处理 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)
建议进行更细粒度的异常处理。
同样对于下载:
超时后恢复 FTP 下载
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)