0

我将 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

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

关于如何显示正确进度的任何想法?

谢谢!

4

1 回答 1

0

以 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()
于 2021-11-07T10:26:30.717 回答