Python progress bar and downloads

前端 未结 10 1156
庸人自扰
庸人自扰 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:54

    You can use the 'clint' package (written by the same author as 'requests') to add a simple progress bar to your downloads like this:

    from clint.textui import progress
    
    r = requests.get(url, stream=True)
    path = '/some/path/for/file.txt'
    with open(path, 'wb') as f:
        total_length = int(r.headers.get('content-length'))
        for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1): 
            if chunk:
                f.write(chunk)
                f.flush()
    

    which will give you a dynamic output which will look like this:

    [################################] 5210/5210 - 00:00:01
    

    It should work on multiple platforms as well! You can also change the bar to dots or a spinner with .dots and .mill instead of .bar.

    Enjoy!

提交回复
热议问题