如何在Python中编写下载进度指示器?

2024-06-01 03:35:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个通过http下载文件的小应用程序(例如,如here所述)。

我还想包括一个小的下载进度指标,显示下载进度的百分比。

以下是我想到的:

    sys.stdout.write(rem_file + "...")    
    urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)

    def dlProgress(count, blockSize, totalSize):
      percent = int(count*blockSize*100/totalSize)
      sys.stdout.write("%2d%%" % percent)
      sys.stdout.write("\b\b\b")
      sys.stdout.flush()

输出:MyFileName。。。9%

还有其他的想法或建议吗?

有一件事有点烦人,那就是在终端的第一个数字的百分比闪烁光标。有没有办法防止这种情况?有办法隐藏光标吗?

编辑:

这里有一个更好的选择,即对dlProgress中的文件名和'\r'代码使用全局变量:

    global rem_file # global variable to be used in dlProgress

    urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)

    def dlProgress(count, blockSize, totalSize):
      percent = int(count*blockSize*100/totalSize)
      sys.stdout.write("\r" + rem_file + "...%d%%" % percent)
      sys.stdout.flush()

输出:MyFileName…9%

光标出现在行的末尾。好多了。


Tags: countstdoutsysurlliblocfilewrite百分比
3条回答

值得一提的是,下面是我用来让它工作的代码:

from urllib import urlretrieve
from progressbar import ProgressBar, Percentage, Bar

url = "http://......."
fileName = "file"
pbar = ProgressBar(widgets=[Percentage(), Bar()])
urlretrieve(url, fileName, reporthook=dlProgress)

def dlProgress(count, blockSize, totalSize):
    pbar.update( int(count * blockSize * 100 / totalSize) )

http://pypi.python.org/pypi/progressbar/2.2有一个python的文本进度条库,您可能会发现它很有用:

This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway.

The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line.

The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when available.

您也可以尝试:

sys.stdout.write("\r%2d%%" % percent)
sys.stdout.flush()

在字符串开头使用一个回车,而不是几个退格。光标仍将闪烁,但它将在百分比符号后而不是在第一个数字下闪烁,使用一个控制字符而不是三个控制字符时,您可能获得较少的闪烁。

相关问题 更多 >