Python progress bar and downloads

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

    Updated for your sample url:

    I've just written a super simple (slightly hacky) approach to this for scraping pdfs off a certain site. Note, it only works correctly on unix based systems (linux, mac os) as powershell does not handle "\r"

    import requests
    
    link = "http://indy/abcde1245"
    file_name = "download.data"
    with open(file_name, "wb") as f:
        print "Downloading %s" % file_name
        response = requests.get(link, stream=True)
        total_length = response.headers.get('content-length')
    
        if total_length is None: # no content length header
            f.write(response.content)
        else:
            dl = 0
            total_length = int(total_length)
            for data in response.iter_content(chunk_size=4096):
                dl += len(data)
                f.write(data)
                done = int(50 * dl / total_length)
                sys.stdout.write("\r[%s%s]" % ('=' * done, ' ' * (50-done)) )    
                sys.stdout.flush()
    

    It uses the requests library so you'll need to install that. This outputs something like the following into your console:

    >Downloading download.data

    >[=============                            ]

    The progress bar is 52 characters wide in the script (2 characters are simply the [] so 50 characters of progress). Each = represents 2% of the download.

提交回复
热议问题