python-3.x - tqdm 以人类可读的单位显示下载

标签 python-3.x python-requests tqdm

我正在使用 tqdm 和请求来管理 Python 中的文件下载。但是我不知道如何让 tqdm 以人类可读的格式显示进度条,即以 MB/s 为单位。

这是我的代码

import requests
import os
from tqdm import tqdm

def download_file(url, local_path="./"):
    local_filename = url.split('/')[-1]
    path = local_path + local_filename

    r = requests.get(url, stream=True)
    total_size = int(r.headers.get('content-length', 0))
    chunk_size = 32*1024
    with open(local_filename, 'wb') as f:
        # 1KB = 1024 bytes
        for chunk in tqdm(r.iter_content(chunk_size), total=total_size, unit_scale=True, 
                          unit_divisor=1024):
            if chunk:
                f.write(chunk)

    return path

weightLink = "https://pjreddie.com/media/files/yolov3.weights"
weigthPath = r"/PyTorch-YOLOv3/weights/"
weightLink = "https://pjreddie.com/media/files/yolov3.weights"
download_file(weightLink, weigthPath)

使用上面的代码,下载大小的进程是错误的,我在 it/s 中看到了下载速度。我想以 MB/s 的形式显示所有内容。

最佳答案

为 tqdm unit='B', unit_scale=True, unit_divisor=1024 传递额外参数。

示例:

from tqdm import tqdm

for i in tqdm(range(9999999), unit='B', unit_scale=True, unit_divisor=1024):
    pass

输出:

100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 9.54M/9.54M [00:03<00:00, 2.66MB/s]

关于python-3.x - tqdm 以人类可读的单位显示下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59124357/

相关文章:

for-loop - 如何在目录的for循环中使用tqdm获取进度条

python 请求给出 'None' 响应,其中需要 json 数据

python - 为什么 Poloniex API 被验证码屏蔽?应为 JSON,但响应为 HTML

python - 如何在scrapy中添加下载视频的进度条?

python-3.x - 如何绘制一条指示 Apriltag 方向的线?

python - bs4 - 根据其他值提取特定的 href

python - 在 Pandas 中使用 TQDM 进度条

python - 在 Python 中,检查是否以 root 身份执行

python - 如何从 Pandas USFederalHolidayCalendar 中删除特定假期?

python-3.x - 如何使用 asyncio 优雅地超时