如何在Python中编写下载进度指示器? [英] How to write a download progress indicator in Python?

查看:393
本文介绍了如何在Python中编写下载进度指示器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a little application to download files over http (as, for example, described here).

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

I also want to include a little download progress indicator showing the percentage of the download progress.

以下是我的想法:


    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%

Output: MyFileName... 9%

要做到这一点的任何其他想法或建议?

Any other ideas or recommendations to do this?

有些烦人的事情是在百分比第一位数字的终端上闪烁光标。有办法防止这种情况吗?有没有办法隐藏光标?

One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?

编辑:

这里有一个dlProgress中使用全局变量作为文件名的更好替代方法和'\ r'代码:

Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:


    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%

Output: MyFileName...9%

光标显示在END这条线。好多了。

And the cursor shows up at the END of the line. Much better.

推荐答案

http://pypi.python.org/pypi/progressbar/2.2


此库提供文本模式进度条。这通常用于显示长时间运行的进度,提供正在进行处理的直观线索。

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.

ProgressBar类管理进度和格式line由许多小部件给出。窗口小部件是可以根据进度状态不同地显示的对象。小部件有三种类型: - 一个字符串,总是显示自己; - ProgressBarWidget,每次调用update方法时都可能返回不同的值;和 - 一个ProgressBarWidgetHFill,就像ProgressBarWidget一样,除了它扩展以填充该行的剩余宽度。

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中编写下载进度指示器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆