如何使用Python中的进度条进行下载?

时间:2012-06-21 17:43:36

标签: python progress-bar

我正在尝试在下载如下文件时实现此程序包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

1 个答案:

答案 0 :(得分: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。