python下载大文件-使用python通过FTP下载大文件

对不起,如果我回答我自己的问题,但我找到了解决方案.

我尝试了ftputil没有成功,所以我尝试了很多方式,最后,这工作:

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 " % 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 file lenght is: %i > %i " %

(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、付费专栏及课程。

余额充值