我正在编写一个小应用程序来通过 http 下载文件(例如, 在此处 描述)。
我还想包括一个小的下载进度指示器,显示下载进度的百分比。
这是我想出的:
sys.stdout.write(rem_file + "...")
urllib.urlretrieve (rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
百分比 = int(计数*blockSize*100/totalSize)
sys.stdout.write("%2d%%" % 百分比)
sys.stdout.write("\b\b\b")
系统.stdout.flush()
输出:我的文件名… 9%
还有其他想法或建议吗?
有点烦人的是终端中百分比第一位数字上闪烁的光标。有没有办法防止这种情况?有没有办法隐藏光标?
编辑:
这里有一个更好的选择,使用全局变量作为 dlProgress 中的文件名和 ‘\r’ 代码:
global rem_file # 在 dlProgress 中使用的全局变量
urllib.urlretrieve (rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
百分比 = int(计数*blockSize*100/totalSize)
sys.stdout.write("\r" + rem_file + "...%d%%" % 百分比)
系统.stdout.flush()
输出:我的文件名…9%
光标出现在行尾。好多了。
原文由 cschol 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 http://pypi.python.org/pypi/progressbar/2.2 有一个用于 python 的文本进度条库,您可能会发现它很有用: