如何在进度条和Python中显示mb/s而不是b/s?

How to display mb/s instead of b/s in progressbar and Python?

我正在尝试更改进度条(版本 2)在 Python 中显示 transferred/total 文件大小的方式 3。这是代码:

import progressbar
import requests

url = 'http://download.openbricks.org/sample/H264/big_buck_bunny_1080p_H264_AAC_25fps_7200K_short.MP4'

request = requests.get(url, stream=True)

file         = open('test.mp4', 'wb')
file_size    = int(request.headers['Content-Length'])
file_size_mb = round(file_size / 1024 / 1024,2)

chunk_sz = 512

widgets = [progressbar.Bar(marker="#",left="[",right="]"),
           progressbar.Percentage()," | ",
           progressbar.FileTransferSpeed()," | ",
           progressbar.SimpleProgress()," | ",
           progressbar.ETA()]

bar = progressbar.ProgressBar(widgets=widgets, maxval=file_size).start()

i = 0

for chunk in request.iter_content(chunk_size=chunk_sz):
    file.write(chunk)
    i += len(chunk)
    bar.update(i)

bar.finish()
print('File size: {0} MB'.format(file_size_mb))

file.close()

输出:

[#########################] 91% | 741.3 KiB/s | 3397632 of 3714474 | Time: 00:00:08

File size: 3.54 MB

我希望能够使 3714474 的“3397632”以 MB 格式显示(如 file_size_mb 变量),而不是字节,因为它默认由进度条显示。

我已阅读 Progress Bar’s documentation 中的文档,但我无法在此处给出的任何示例中找到问题的答案。

来自 progressbar 文档:

class progressbar.widgets.SimpleProgress(format=’%(value)d of %(max_value)d’,
max_width=None, **kwargs)

Bases: progressbar.widgets.FormatWidgetMixin, progressbar.widgets.WidgetBase

Returns progress as a count of the total (e.g.: “5 of 47”)

所以我假设您可以使用 format 参数来执行您需要的操作。

widgets = [progressbar.Bar(marker="#",left="[",right="]"),
           progressbar.Percentage()," | ",
           progressbar.FileTransferSpeed()," | ",
           progressbar.SimpleProgress(format='%(value/1024/1024)d of %(max_value/1024/1024)d')," | ",
           progressbar.ETA()]

另一种方法是从 simpleProgress 获取输出,解析它以获取值,然后手动进行数学计算。

您可以使用 DataSize 小部件相对轻松地获得这种显示:

[######                                 ] 17% | 256.0 KiB/s | 631.0 KiB /   3.5 MiB | ETA: 0:00:11

您可以通过将 SimpleProgress 小部件替换为两个 DataSize 小部件来实现此目的,如下所示:

widgets = [progressbar.Bar(marker="#",left="[",right="]"),
           progressbar.Percentage(), " | ",
           progressbar.FileTransferSpeed(), " | ",
           progressbar.DataSize(), " / ",
           progressbar.DataSize(variable="max_value"), " | ",
           progressbar.ETA()]

默认情况下,DataSize 小部件显示当前值,但您可以通过将 "max_value" 作为 变量 参数.

问题是它没有记录,您必须检查代码才能找到此信息。所以这可能有一天会改变,并且不再使用更高版本的模块。

考虑到 the DataSize doc,您似乎可以通过将自定义值传递给 format 参数来更改默认格式。默认格式为

format='%(scaled)5.1f %(prefix)s%(unit)s'

我想你可以通过指定这种格式得到两位小数:

format='%(scaled)5.2f %(prefix)s%(unit)s'

关于显示单位,文档提到了默认为

的前缀参数
prefixes=('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi')

您或许可以传递另一个带有所需前缀的元组。但是在这样做之前考虑这个article discussing about binary prefixes。如果您使用 1024 的幂来转换您的单位,并且如果您想要精确,那么您可能希望使用带有 "i" 字符的 IEC 二进制前缀。


实现您想要的东西的另一种但更长的方法是派生 SimpleProgress class 来制作适合您需要的东西。