微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 asyncio 和 tq​​dm 下载多个文件

如何解决使用 asyncio 和 tq​​dm 下载多个文件

我遇到了问题。我正在尝试为我的大学做一项作业,但我坚持使用 asyncio。 我遇到了一个问题,因为主进度条(这个显示已经下载了多少文件的进度条)仅在下载所有文件时更新。我试图修复它几个小时,但我对 asyncio 没有太多经验。有人可以帮我吗?

import requests
import random
import time
from tqdm.auto import tqdm
import asyncio

async def download(link):
    block_size = 1024
    
    response = requests.get(link[0],stream=True)
    total_size_in_bytes= int(response.headers['content-length'])
    extension = str('.'+response.headers['content-type'].split("/")[1])
    
    progress_bar = tqdm(total=total_size_in_bytes,unit='b',unit_scale=True,desc=f'FILE \"{link[1]}{extension}\"')
    
    with open(link[1]+extension,'wb') as file:
        for data in response.iter_content(block_size):
            file.write(data)
            progress_bar.update(len(data))
    progress_bar.close()
    
    if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes:
        print('Error!')
    else:
        print(f'File \"{link[1]}{extension}\" downloaded successfully!')
        
        
async def download_multiple(links):
    tasks = []
    
    for l in links:
        task = asyncio.create_task(download(l))
        tasks.append(task)

    progress_bar = tqdm(asyncio.as_completed(tasks),total=len(tasks),desc="DOWNLOADED: ")
    [await f for f in progress_bar]
    #progress_bar.close()


async def main():
    links = [["https://static.toiimg.com/photo/msid-67586673/67586673.jpg?3918697","jeden"],["https://static.toiimg.com/photo/msid-67586673/67586673.jpg?3918697","dwa"],["https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4","trzy"]]
    await (download_multiple(links))    
    
await main();

这是它的样子:

enter image description here

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。