2012-06-21 77 views
3

我想下載象下面這樣一個文件時,實施一攬子http://code.google.com/p/python-progressbar/如何使用Python進度條進行下載?

def dlProgress(count, blockSize, totalSize): 
     widgets = ['Test: ', Percentage(), ' ', Bar(marker=RotatingMarker()), ' ', ETA(), ' ', FileTransferSpeed()] 
     pbar = ProgressBar(widgets=widgets, maxval=totalSize).start() 
     for count in range(totalSize): 
      #print count 
      pbar.update(int(count*blockSize*100/totalSize)) 
     pbar.finish()    
    urllib.urlretrieve(url, fileName, reporthook=dlProgress) 

的問題是,進度條達到100%真實的下載進度完成之前,並繼續開始新的吧,像這樣:

Test: 100% |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| Time: 0:00:31 402.06 kB/s 
Test: 100% |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| Time: 0:00:31 408.39 kB/s 
Test: 100% |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| Time: 0:00:32 389.47 kB/s 

回答

5

您應該在進度回調之外初始化進度欄。然後在第一次的召回,檢查並設置MAXVAL並啓動它:

widgets = ['Test: ', Percentage(), ' ', Bar(marker=RotatingMarker()), ' ', ETA(), ' ', FileTransferSpeed()] 
pbar = ProgressBar(widgets=widgets) 

def dlProgress(count, blockSize, totalSize): 
    if pbar.maxval is None: 
     pbar.maxval = totalSize 
     pbar.start() 

    pbar.update(min(count*blockSize, totalSize)) 

urllib.urlretrieve(url, fileName, reporthook=dlProgress) 
pbar.finish() 

作爲一個側面說明,這最後一塊不會是一個完整的塊,所以你要確保你的不會超過totalSize。