3

我正在尝试在下载如下文件时实现这个包http://code.google.com/p/python-progressbar/ :

    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
4

1 回答 1

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。

于 2012-06-21T18:26:19.033 回答