python 下载ftp_用python通过FTP下载大文件

本文介绍了如何使用Python的ftplib模块下载FTP上的大文件,包括处理连接超时和断点续传的方法。作者通过设置低超时时间,实现重新连接以完成文件下载。在下载过程中,如果发生错误,程序会尝试重新连接并继续下载,直到文件完整下载为止。
摘要由CSDN通过智能技术生成

抱歉,如果我回答自己的问题,但我找到了解决办法。

我尝试了很多方法,但没有成功,所以我尝试了很多方法,最后,这个方法奏效了:def ftp_connect(path):

link = FTP(host = 'example.com', timeout = 5) #Keep low timeout

link.login(passwd = 'ftppass', user = 'ftpuser')

debug("%s - Connected to FTP" % strftime("%d-%m-%Y %H.%M"))

link.cwd(path)

return link

downloaded = open('/local/path/to/file.tgz', 'wb')

def debug(txt):

print txt

link = ftp_connect(path)

file_size = link.size(filename)

max_attempts = 5 #I dont want death loops.

while file_size != downloaded.tell():

try:

debug("%s while > try, run retrbinary\n" % strftime("%d-%m-%Y %H.%M"))

if downloaded.tell() != 0:

link.retrbinary('RETR ' + filename, downloaded.write, downloaded.tell())

else:

link.retrbinary('RETR ' + filename, downloaded.write)

except Exception as myerror:

if max_attempts != 0:

debug("%s while > except, something going wrong: %s\n \tfile lenght is: %i > %i\n" %

(strftime("%d-%m-%Y %H.%M"), myerror, file_size, downloaded.tell())

)

link = ftp_connect(path)

max_attempts -= 1

else:

break

debug("Done with file, attempt to download m5dsum")

[...]

在我的日志文件中,我发现:01-12-2011 23.30 - Connected to FTP

01-12-2011 23.30 while > try, run retrbinary

02-12-2011 00.31 while > except, something going wrong: timed out

file lenght is: 1754695793 > 1754695793

02-12-2011 00.31 - Connected to FTP

Done with file, attempt to download m5dsum

遗憾的是,即使文件已经完全下载,我也必须重新连接到FTP,这在我的cas中不是问题,因为我还必须下载md5sum。

如您所见,我无法检测到超时并重试连接,但当我获得超时时,我只是重新连接;如果有人知道如何在不创建新ftplib.FTP实例的情况下重新连接,请告诉我;)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值