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

输出:我的文件名...9%

还有其他想法或建议来做到这一点吗?

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

编辑:

这里有一个更好的选择,在 dlProgress 和 ' ' 代码中使用全局变量作为文件名:

    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%

并且光标出现在该行的末尾。好多了。

有帮助吗?

解决方案

有一个用于 python 的文本进度条库,位于 http://pypi.python.org/pypi/progressbar/2.2 您可能会发现有用:

该库提供了文本模式进度条。这通常用于显示长时间运行的操作的进度,提供处理正在进行的视觉线索。

ProgressBar 类管理进度,线条的格式由许多小部件给出。小部件是一个可以根据进度状态以不同方式显示的对象。小部件分为三种类型:- 一条始终显示自身的字符串;- 一个 ProgressBarWidget,每次调用 update 方法时可能会返回不同的值;- ProgressBarWidgetHFill,它类似于 ProgressBarWidget,只不过它会扩展以填充行的剩余宽度。

进度条模块非常易于使用,但功能非常强大。并自动支持自动调整大小等功能(如果可用)。

其他提示

您也可以尝试:

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

在字符串的开头使用一个回车而不是几个退格。您的光标仍然会闪烁,但它会在百分号后面闪烁,而不是在第一个数字下面闪烁,并且使用一个控制字符而不是三个控制字符,您可能会减少闪烁。

对于它的价值,这是我用来让它工作的代码:

from urllib import urlretrieve
from progressbar import ProgressBar, Percentage, Bar

url = "http://......."
fileName = "file"
pbar = ProgressBar(widgets=[Percentage(), Bar()])
urlretrieve(url, fileName, reporthook=dlProgress)

def dlProgress(count, blockSize, totalSize):
    pbar.update( int(count * blockSize * 100 / totalSize) )

如果您使用 curses 包,您可以更好地控制控制台。它还会增加代码复杂性,并且可能没有必要,除非您正在开发基于控制台的大型应用程序。

对于一个简单的解决方案,您始终可以将旋转轮放在状态消息的末尾(字符序列 |, \, -, / 在闪烁的光标下实际上看起来不错。

我使用了这段代码:

url = (<file location>)
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)

file_size_dl = 0
block_sz = 8192
while True:
    buffer = u.read(block_sz)
    if not buffer:
        break

    file_size_dl += len(buffer)
    f.write(buffer)
    status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
    status = status + chr(8)*(len(status)+1)
    print status,

f.close()
def download_progress_hook(count, blockSize, totalSize):
  """A hook to report the progress of a download. This is mostly intended for users with slow internet connections. Reports every 5% change in download progress.
  """
  global last_percent_reported
  percent = int(count * blockSize * 100 / totalSize)

  if last_percent_reported != percent:
    if percent % 5 == 0:
      sys.stdout.write("%s%%" % percent)
      sys.stdout.flush()
    else:
      sys.stdout.write(".")
      sys.stdout.flush()

    last_percent_reported = percent

urlretrieve(url, filename, reporthook=download_progress_hook)

对于小文件,您可能需要使用以下行以避免出现疯狂的百分比:

sys.stdout.write(" %2d%%" % 百分比)

sys.stdout.flush()

干杯

我就是这样做的,这可以帮助你:https://github.com/mouuff/MouDownloader/blob/master/api/download.py

像往常一样,聚会迟到了。这是一个支持报告进度的实现,就像核心一样 urlretrieve:

import urllib2

def urlretrieve(urllib2_request, filepath, reporthook=None, chunk_size=4096):
    req = urllib2.urlopen(urllib2_request)

    if reporthook:
        # ensure progress method is callable
        if hasattr(reporthook, '__call__'):
            reporthook = None

        try:
            # get response length
            total_size = req.info().getheaders('Content-Length')[0]
        except KeyError:
            reporthook = None

    data = ''
    num_blocks = 0

    with open(filepath, 'w') as f:
        while True:
            data = req.read(chunk_size)
            num_blocks += 1
            if reporthook:
                # report progress
                reporthook(num_blocks, chunk_size, total_size)
            if not data:
                break
            f.write(data)

    # return downloaded length
    return len(data)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top