我正在编写一个通过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%
光标出现在行的末尾。好多了。
值得一提的是,下面是我用来让它工作的代码:
在http://pypi.python.org/pypi/progressbar/2.2有一个python的文本进度条库,您可能会发现它很有用:
您也可以尝试:
在字符串开头使用一个回车,而不是几个退格。光标仍将闪烁,但它将在百分比符号后而不是在第一个数字下闪烁,使用一个控制字符而不是三个控制字符时,您可能获得较少的闪烁。
相关问题 更多 >
编程相关推荐