ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python3 retrieve()

2020-03-31 13:56:13  阅读:368  来源: 互联网

标签:localfile retrieve url self per urllib import python3


retreive()被认为是个老旧函数,可能会在将来抛弃。
urllib.request.urlretrieve(url, filename=None, reporthook=None, data=None)
Exceptions和函数urlopen()相同。
具体文档,参见https://docs.python.org/3/library/urllib.request.html#module-urllib.request

代码片段

from urllib.request import urlretrieve
import socket
import os
import sys

def  reporthook(blocknum, bs, size):
    #  blocknum:已经下载的数据块       bs:数据块的大小      size:远程文件的大小
    per = 100.0 * blocknum * bs / size
    if per > 100 :
        per = 100
    sys.stdout.write('Download progress: %.2f%%  \r'%per)
    sys.stdout.flush()
class ClassName():
    def __init__(self):
        socket.setdefaulttimeout(30)

        def run(self):
               ...
           while True:
                .....
                try:
                    urlretrieve(url,localfile, reporthook= reporthook) 
                except socket.timeout:
                    self.redownload(url,localfile) 
                except Exception as e:
                    StatusCode=e.getcode()
                    if StatusCode == 404:
                        print(e)
                        break
                    self.redownload(url,localfile)

    def redownload(self,url,localfile):
        count = 1
        while count <= 5:
            try:
                urlretrieve(url,localfile, reporthook= reporthook)                                                
                break
            except socket.timeout:
                err_info = 'Reloading for %d time.....'%count if count == 1 else 'Reloading for %d times.....'%count
                print(err_info)
                count += 1
        if count > 5:
            print("download job failed!") 

标签:localfile,retrieve,url,self,per,urllib,import,python3
来源: https://blog.51cto.com/whbill/2483367

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有