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

标签 python http

我正在编写一个小应用程序来通过 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/

相关文章:

node.js - 如何获取我在node.js http请求中实际发送的http请求 header

http - 使用 JAX-RS 的 "fake"DELETE 和 PUT 方法的最佳方法是什么?

javascript - 在 iFrame 中维护重定向

python - 将 block 旋转到某个位置

python - SciPy 和 NumPy 之间的关系

python - Django 表单和在 View /页面之间传递数据

javascript - Node.js 如何响应升级请求?

java - 我如何使用 apache commons HttpPost 发送文件并对请求的参数进行编码?

python - 如何解释使用 "from X import Y"导入函数 Y,该函数使用 X 文件中的变量?

python - 从 apache_beam.io 导入 fileio 给出错误 : cannot import name fileio