2017-09-01 49 views
0

This is the best one so far的Python:添加一个进度条的下载

我看到的计算器的许多问题,但没有答案的给出一个简洁大方的方法。

link = "http://download.thinkbroadband.com/10MB.zip" 
file_name = "test" 
with open(file_name, "wb") as f: 
     print('Downloading: {}'.format(file_name)) 
     response = requests.get(link, stream=True) 
     total_length = response.headers.get('content-length') 

     if total_length is None: 
      f.write(response.content) 
     else: 
      dl = 0 
      total_length = int(total_length) 
      for data in response.iter_content(chunk_size=4096): 
       dl += len(data) 
       f.write(data) 
       done = int(50 * dl/total_length) 
       sys.stdout.write("\r[%s%s]" % ('=' * done, ' ' * (50-done))) 
       sys.stdout.flush() 

当下载文件时,能否获得更多详细信息?所有以前的问题都没有一个好的简单答案。

+0

除非你没有参数为什么你不想使用这个很难建议不同的东西(你可能也不想使用它) – DonGru

+0

好的我的重新解释的问题:我想要更多的细节,当我从链接下载。 – Varun

回答

1

为什么要重新发明轮子?使用tqdm。按照链接并按照说明导入tqdm并为任何迭代添加进度栏。例如:

from tqdm import tqdm 
... 
for data in tqdm(response.iter_content(chunk_size=4096)): 
    # additional logic here 
... 

请阅读提供的pypi链接中的示例,以将其他信息添加到进度栏。