#! /usr/bin/env python

import sys, pycurl

num_progress_callbacks = 0
dl_last = 0

def curl_progress (dl_total, dl_now, ul_total, ul_now):
  global num_progress_callbacks, dl_last

  if dl_now > 0.0 and dl_now > dl_last:
     # print ('curl_progress. dl_now %15.0f bytes' % dl_now)
     dl_last = dl_now
  num_progress_callbacks += 1
  return 0

def dev_null (buf):
  pass

def test (url, rate_limit = 0):
  if rate_limit > 0:
    print ('rate_limit %d bytes/sec' % rate_limit)
  else:
    print ('No speed limit')

  curl = pycurl.Curl()
  curl.setopt (curl.URL, url)
  curl.setopt (curl.MAX_RECV_SPEED_LARGE, rate_limit)

  curl.setopt (curl.WRITEFUNCTION, dev_null)
  curl.setopt (curl.NOPROGRESS, 0)
  curl.setopt (curl.PROGRESSFUNCTION, curl_progress)
  curl.setopt (curl.FOLLOWLOCATION, 1)

  curl.perform()
  curl.close()

rate_limit = 0
if len(sys.argv) > 1:
  rate_limit = int(sys.argv[1])

test ('http://www.vg.no', rate_limit)
print ('num_progress_callbacks %d' % num_progress_callbacks)

