Get the speed of downloading a file using python
<p>I'm using requests lib to download a file, i got many info. about the response like: size,type and date. but i need to get the download speed and set a maximum and minimum for it. How could i get downloading speed ?</p>

<p>Here's the code:</p>

<pre><code>import requests
import sys


link = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"
file_name = "downloaded.png"
response = requests.get(link, stream=True)
with open(file_name, "wb") as f:
        print "Downloading %s" % file_name
        response = requests.get(link, stream=True)
        total_length = int(response.headers.get('content-length'))
        print response.headers["content-type"]
        print total_length / 1024, "Kb"
        print int(response.headers["Age"]) * (10 ** -6), "Sec"
        print response.headers["date"]

        if total_length is None: # no content length header
            f.write(response.content)
        else:
            dl = 0
            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()
</code></pre>

<p>and here's the output:</p>

<pre><code>Downloading downloaded.png
image/png
213 Kb
0.054918 Sec
Wed, 19 Oct 2016 08:43:47 GMT
[==================================================]
</code></pre>

<p>I just added <code>import time</code>, the <code>start</code> variable and replaced the <code>sys.stdout.write</code> line with the one from: <a href="http://stackoverflow.com/questions/20801034/how-to-measure-download-speed-and-progress-using-requests">How to measure download speed and progress using requests?</a></p>

<pre><code>import requests
import sys
import time


link = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"
file_name = "downloaded.png"
start = time.clock()
response = requests.get(link, stream=True)
with open(file_name, "wb") as f:
    print "Downloading %s" % file_name
    response = requests.get(link, stream=True)
    total_length = int(response.headers.get('content-length'))
    print response.headers["content-type"]
    print total_length / 1024, "Kb"
    print int(response.headers["Age"]) * (10 ** -6), "Sec"
    print response.headers["date"]

    if total_length is None: # no content length header
        f.write(response.content)
    else:
        dl = 0
        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] %s bps" % ('=' * done, ' ' * (50-done), dl//(time.clock() - start)))
            sys.stdout.flush()
</code></pre>

python network-programming urllib