2017-09-01 47 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鏈接中的示例,以將其他信息添加到進度欄。