Python progress bar and downloads

前端 未结 10 1175
庸人自扰
庸人自扰 2020-11-28 02:28

I have a python script that launches a URL that is a downloadable file. Is there some way to have python use commandline to display the download progress as oppose to launch

10条回答
  •  醉酒成梦
    2020-11-28 02:44

    Sorry for being late with an answer; just updated the tqdm docs:

    https://github.com/tqdm/tqdm/#hooks-and-callbacks

    Using urllib.urlretrieve and OOP:

    import urllib
    from tqdm.auto import tqdm
    
    class TqdmUpTo(tqdm):
        """Provides `update_to(n)` which uses `tqdm.update(delta_n)`."""
        def update_to(self, b=1, bsize=1, tsize=None):
            """
            b  : Blocks transferred so far
            bsize  : Size of each block
            tsize  : Total size
            """
            if tsize is not None:
                self.total = tsize
            self.update(b * bsize - self.n)  # will also set self.n = b * bsize
    
    eg_link = "https://github.com/tqdm/tqdm/releases/download/v4.46.0/tqdm-4.46.0-py2.py3-none-any.whl"
    eg_file = eg_link.split('/')[-1]
    with TqdmUpTo(unit='B', unit_scale=True, unit_divisor=1024, miniters=1,
                  desc=eg_file) as t:  # all optional kwargs
        urllib.urlretrieve(
            eg_link, filename=eg_file, reporthook=t.update_to, data=None)
        t.total = t.n
    

    or using requests.get and file wrappers:

    import requests
    from tqdm.auto import tqdm
    
    eg_link = "https://github.com/tqdm/tqdm/releases/download/v4.46.0/tqdm-4.46.0-py2.py3-none-any.whl"
    eg_file = eg_link.split('/')[-1]
    response = requests.get(eg_link, stream=True)
    with tqdm.wrapattr(open(eg_file, "wb"), "write", miniters=1,
                       total=int(response.headers.get('content-length', 0)),
                       desc=eg_file) as fout:
        for chunk in response.iter_content(chunk_size=4096):
            fout.write(chunk)
    

    You could of course mix & match techniques.

提交回复
热议问题