【问题标题】:Python async iterator (httpx) and tqdm.asyncio (download progress bar)Python 异步迭代器(httpx)和 tqdm.asyncio(下载进度条)
【发布时间】:2021-12-20 14:00:39
【问题描述】:

我将 httpx 用作 AsyncClient()(称为 http)并希望显示下载进度。

async with self.http.stream(method='GET', url=download_url) as res:

                file_out = open(file_path, 'wb')

                async for chunk in tqdm.asyncio.tqdm(iterable=res.aiter_bytes(), 
                                   desc=name, unit='iB',unit_scale=True, unit_divisor=1024, total=size):
                    file_out.write(chunk)
                
                file_out.close()

下载工作正常,进度条确实显示了一些进度,但与提供的比例无关。

结果:

test.mov:   0%|                                     | 169/2.52M [00:07<32:42:46, 21.4iB/s]

显示正确的总大小,但显然单位不同。

如果使用特定的块大小,进度也不会正确显示:

async with self.http.stream(method='GET', url=download_url) as res:

                file_out = open(file_path, 'wb')

                async for chunk in tqdm.asyncio.tqdm(iterable=res.aiter_bytes(chunksize), 
                                   desc=name, unit='iB',unit_scale=True, unit_divisor=1024, total=size):
                    file_out.write(chunk)
                
                file_out.close()

然后进度条将遍历块(块计数),但字节的比例设置不起作用,例如对于 10 MB 文件:

test.mov:   0%|                                 | 2.00/10.0M [00:35<51795:37:19, 17.8s/iB

最接近字节流的结果是省略块大小,但单位关闭。

知道如何显示正确的进度吗?

谢谢!

【问题讨论】:

    标签: python asynchronous tqdm httpx


    【解决方案1】:

    以 1 为单位(字节)解决:

    async with self.http.stream(method='GET', url=download_url) as res:
        file_out = open(file_path, 'wb')
        async for chunk in tqdm.asyncio.tqdm(iterable=res.aiter_bytes(1), 
                desc=name, unit='iB',unit_scale=True, unit_divisor=1024, total=size):
            file_out.write(chunk)
        file_out.close()
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多