我正在编写一个小应用程序来通过 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()
输出:我的文件名... 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()
输出:我的文件名...9%
光标出现在行的末尾。好多了。
最佳答案
在 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.
关于python - 如何在 Python 中编写下载进度指示器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51212/