• python中如何使用requests模块下载文件并获取进度提示?


    Reference: https://www.zhihu.com/question/41132103

    #!/usr/bin/env python3
    
    import requests
    from contextlib import closing
    
    """
    作者:微微寒
    链接:https://www.zhihu.com/question/41132103/answer/93438156
    来源:知乎
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    """
    
    class ProgressBar(object):
        def __init__(self, title, count=0.0, run_status=None, fin_status=None, total=100.0,    unit='', sep='/', chunk_size=1.0):
            super(ProgressBar, self).__init__()
            self.info = "[%s] %s %.2f %s %s %.2f %s"
            self.title = title
            self.total = total
            self.count = count
            self.chunk_size = chunk_size
            self.status = run_status or ""
            self.fin_status = fin_status or " " * len(self.statue)
            self.unit = unit
            self.seq = sep
    
        def __get_info(self):
            # 【名称】状态 进度 单位 分割线 总数 单位
            _info = self.info % (self.title, self.status, self.count/self.chunk_size, self.unit, self.seq, self.total/self.chunk_size, self.unit)
            return _info
    
        def refresh(self, count=1, status=None):
            self.count += count
            # if status is not None:
            self.status = status or self.status
            end_str = "
    "
            if self.count >= self.total:
                end_str = '
    '
                self.status = status or self.fin_status
            print(self.__get_info(), end=end_str)
    
    def main():
    	with closing(requests.get("http://www.futurecrew.com/skaven/song_files/mp3/razorback.mp3", stream=True)) as response:
    		chunk_size = 1024
    		content_size = int(response.headers['content-length'])
    		progress = ProgressBar("razorback", total=content_size, unit="KB", chunk_size=chunk_size, run_status="正在下载", fin_status="下载完成")
    		# chunk_size = chunk_size < content_size and chunk_size or content_size
    		with open('./file.mp3', "wb") as file:
    			for data in response.iter_content(chunk_size=chunk_size):
    				file.write(data)
    				progress.refresh(count=len(data))
    
    if __name__ == '__main__':
    	main()
  • 相关阅读:
    推荐系统中的特征处理
    推荐系统之协同过滤
    python 对字典排序
    推荐系统资料汇总
    python print和strip
    python ConfigParse模块(转)
    01_HBase概述
    04_Storm编程上手_WordCount集群模式运行
    03_Storm编程上手-wordcount
    02_Storm集群部署
  • 原文地址:https://www.cnblogs.com/skying555/p/6624567.html
Copyright © 2020-2023  润新知