2

我正在使用该线程中的代码来限制我的下载速率。

如何将部分下载恢复与速率限制代码合并?我发现的示例使用urlopen而不是urlretrieve,并且RateLimit该类取决于urlretrieve.

我想要一个控制部分下载的外部函数,而不必更改RateLimit类:

from throttle import TokenBucket, RateLimit

def retrieve_limit_rate(url, filename, rate_limit):
    """Fetch the contents of urls"""
    bucket = TokenBucket(10*rate_limit, rate_limit)

    print "rate limit = %.1f kB/s" % (rate_limit,)

    print 'Downloading %s...' % filename
    rate_limiter = RateLimit(bucket, filename)
    #
    # What do I put here to allow resuming files?
    #
    return urllib.urlretrieve(url, filename, rate_limiter)
4

1 回答 1

4

或许可以改用 PyCurl:

def curl_progress(total, existing, upload_t, upload_d):
    try:
        frac = float(existing)/float(total)
    except:
        frac = 0
    print "Downloaded %d/%d (%0.2f%%)" % (existing, total, frac)

def curl_limit_rate(url, filename, rate_limit):
    """Rate limit in bytes"""
    import pycurl
    c = pycurl.Curl()
    c.setopt(c.URL, url)
    c.setopt(c.MAX_RECV_SPEED_LARGE, rate_limit)
    if os.path.exists(filename):
        file_id = open(filename, "ab")
        c.setopt(c.RESUME_FROM, os.path.getsize(filename))
    else:
        file_id = open(filename, "wb")

    c.setopt(c.WRITEDATA, file_id)
    c.setopt(c.NOPROGRESS, 0)
    c.setopt(c.PROGRESSFUNCTION, curl_progress)
    c.perform()
于 2010-12-26T10:12:34.003 回答