如何使用请求测量下载速度和进度?

时间:2013-12-27 12:49:59

标签: python python-2.7 progress python-requests download-speed

我正在使用requests来下载文件,但是对于大文件我需要每次检查磁盘上文件的大小,因为我无法以百分比显示进度,我也想知道下载速度。我怎么去做呢?这是我的代码:

import requests
import sys
import time
import os

def downloadFile(url, directory) :
  localFilename = url.split('/')[-1]
  r = requests.get(url, stream=True)

  start = time.clock()
  f = open(directory + '/' + localFilename, 'wb')
  for chunk in r.iter_content(chunk_size = 512 * 1024) :
        if chunk :
              f.write(chunk)
              f.flush()
              os.fsync(f.fileno())
  f.close()
  return (time.clock() - start)

def main() :
  if len(sys.argv) > 1 :
        url = sys.argv[1]
  else :
        url = raw_input("Enter the URL : ")
  directory = raw_input("Where would you want to save the file ?")

  time_elapsed = downloadFile(url, directory)
  print "Download complete..."
  print "Time Elapsed: " + time_elapsed


if __name__ == "__main__" :
  main()

我认为一种方法是每次在for循环中读取文件,并根据标题Content-Length计算进度百分比。但对于大型文件(大约500MB),这将再次成为问题。还有其他办法吗?

2 个答案:

答案 0 :(得分:18)

见这里:Python progress bar and downloads

我认为代码是这样的,它应该显示自开始以来的平均速度为每秒字节数:

import requests
import sys
import time

def downloadFile(url, directory) :
  localFilename = url.split('/')[-1]
  with open(directory + '/' + localFilename, 'wb') as f:
    start = time.clock()
    r = requests.get(url, stream=True)
    total_length = r.headers.get('content-length')
    dl = 0
    if total_length is None: # no content length header
      f.write(r.content)
    else:
      for chunk in r.iter_content(1024):
        dl += len(chunk)
        f.write(chunk)
        done = int(50 * dl / total_length)
        sys.stdout.write("\r[%s%s] %s bps" % ('=' * done, ' ' * (50-done), dl//(time.clock() - start)))
        print ''
  return (time.clock() - start)

def main() :
  if len(sys.argv) > 1 :
        url = sys.argv[1]
  else :
        url = raw_input("Enter the URL : ")
  directory = raw_input("Where would you want to save the file ?")

  time_elapsed = downloadFile(url, directory)
  print "Download complete..."
  print "Time Elapsed: " + time_elapsed


if __name__ == "__main__" :
  main()

答案 1 :(得分:3)

使用io.Bytes(写入内存)的python3可接受答案的改进版本,产生Mbps,支持ipv4 / ipv6,大小和端口参数。

def speed_test(size=5, ipv="ipv4", port=80):
    import sys, time, io, requests
    if size == 1024:
        size = "1GB"
    else:
        size = f"{size}MB"

    url = f"http://{ipv}.download.thinkbroadband.com:{port}/{size}.zip"

    with io.BytesIO() as f:
        start = time.clock()
        r = requests.get(url, stream=True)
        total_length = r.headers.get('content-length')
        dl = 0
        if total_length is None: # no content length header
            f.write(r.content)
        else:
            for chunk in r.iter_content(1024):
                dl += len(chunk)
                f.write(chunk)
                done = int(30 * dl / int(total_length))
                sys.stdout.write("\r[%s%s] %s Mbps" % ('=' * done, ' ' * (30-done), dl//(time.clock() - start) / 100000))

    print( f"\n{size} = {(time.clock() - start):.2f} seconds")

用法示例:

speed_test()
speed_test(10)
speed_test(50, "ipv6")
speed_test(1024, port=8080)

输出样本:

[==============================] 61.34037 Mbps
100MB = 17.10 seconds

可用选项:

大小:5, 10, 20, 50, 100, 200, 512, 1024

ipv:ipv4, ipv6

端口:80, 81, 8080