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

时间:2020-03-05 18:49:50  来源:igfitidea点击:

我正在编写一个小应用程序,以通过http下载文件(例如,此处描述)。

我还希望包含一个小的下载进度指示器,以显示下载进度的百分比。

这是我想出的:

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%

光标显示在该行的末尾。好多了。

解决方案

回答

如果我们使用curses软件包,则可以更好地控制控制台。它还会增加代码复杂性的成本,并且除非我们正在开发基于控制台的大型应用程序,否则可能是不必要的。

对于一个简单的解决方案,我们始终可以将纺车置于状态消息的末尾(字符" |,\,-,/"的顺序实际上在闪烁的光标下看起来不错)。

回答

我们也可以尝试:

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

在字符串的开头使用单个回车符,而不要使用多个退格键。光标仍然会闪烁,但是它将在百分号之后而不是在第一位数字下方闪烁,并且使用一个控制字符而不是三个控制字符,闪烁可能会更少。

回答

在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 %%"%%)

sys.stdout.flush()

干杯