Skip to content

Instantly share code, notes, and snippets.

@Kavan72
Forked from khardix/download.py
Created October 1, 2019 10:59
Show Gist options
  • Select an option

  • Save Kavan72/e90de4d54647796b3aea830c07ea69a6 to your computer and use it in GitHub Desktop.

Select an option

Save Kavan72/e90de4d54647796b3aea830c07ea69a6 to your computer and use it in GitHub Desktop.

Revisions

  1. @khardix khardix revised this gist Oct 6, 2017. No changes.
  2. @khardix khardix created this gist Oct 6, 2017.
    45 changes: 45 additions & 0 deletions download.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    #!/usr/bin/env python3.6

    import asyncio
    from contextlib import closing

    import aiohttp
    import tqdm


    async def download(session, url, progress_queue):
    async with session.get(url) as response:
    target = url.rpartition('/')[-1]
    size = int(response.headers.get('content-length', 0)) or None
    position = await progress_queue.get()

    progressbar = tqdm.tqdm(
    desc=target, total=size, position=position, leave=False,
    )

    with open(target, mode='wb') as f, progressbar:
    async for chunk in response.content.iter_chunked(512):
    f.write(chunk)
    progressbar.update(len(chunk))

    await progress_queue.put(position)

    return target


    async def main(loop):
    with open('urls.txt') as f:
    urls = [url.strip() for url in f]

    progress_queue = asyncio.Queue(loop=loop)
    for pos in range(5):
    progress_queue.put_nowait(pos)

    async with aiohttp.ClientSession(loop=loop) as session:

    tasks = [download(session, url, progress_queue) for url in urls]
    return await asyncio.gather(*tasks)

    with closing(asyncio.get_event_loop()) as loop:
    for tgt in loop.run_until_complete(main(loop)):
    print(tgt)