【问题标题】:Downloading Rate while downloading a file?下载文件时的下载速率?
【发布时间】:2026-02-14 05:15:02
【问题描述】:

import time # to use it later with downloading Rate,

import urllib.request # to download a file
url = "http://xxxx.xxx.com/xxx/Setup.exe"

file_name = url[-9:] # file name will be setup.exe just for Ex .


class Download(): # i'm useing a Class but its ok if you have an answer in another way .

def __init__(self):
    urllib.request.urlretrieve(url, file_name, self.progress)

def progress(self,block,blocksize,total):
    print("Total : \t\t",total)
    downloaded = block * blocksize
    print("Downlaoded : \t\t",downloaded)
    left = total - downloaded
    print("Left : \t\t",left)
    percent =  downloaded * 100 / total
    print("Percent : \t\t",percent)
    print("Rate : \t\t",self.rate_return(downloaded)) # i dont get it . 



def rate_return(self,current_size):
    while True:
        # here is my problem ! i know its size / time to get Rate of downloading file .
        # but its totaly wrong :(
        return (current_size/1024)/time.time()
        # size / 1024 to convert it to KB . / time in seconds .

Download()

..................

输出:

总计:10913768 # 好

已下载:385024 # 好

左:10528744 # 好

百分比:3.527874149423004 # 好

Rate : 2.3952649685390823e-07 # 错了吗?我知道它大约是 1.5

问题是如何在文件仍在下载时获得下载速率。

【问题讨论】:

  • 我使用了内置的 curl 调用,它已经足够详细了。看看这是否适合你。 curl -o {} {}'.format(path, url)

标签: python download rate


【解决方案1】:

您正在使用当前时间戳来计算 kbps。 相反,它应该像这样工作:

import time # to use it later with downloading Rate
import urllib.request # to download a file

# Downloading Sublime as an Example .
url = "https://download.sublimetext.com/Sublime%20Text%20Build%203207%20x64%20Setup.exe"
file_name = url[-9:] # file name will be setup.exe just for Ex .
class Download(): # i'm useing a Class but its ok if you have an answer in another way .
    def __init__(self):
        self.start = time.time()
        urllib.request.urlretrieve(url, file_name, self.progress)

    def progress(self,block,blocksize,total):
        print("Total : \t\t",total)
        downloaded = block * blocksize
        print("Downlaoded : \t\t",downloaded)
        left = total - downloaded
        print("Left : \t\t",left)
        percent =  downloaded * 100 / total
        print("Percent : \t\t",percent)
        print("Rate : \t\t",self.rate_return(downloaded)) # i dont get it . 

    def rate_return(self,current_size):
        #while True:  # worthless
        # here is my problem ! i know its size / time to get Rate of downloading file .
        # but its totaly wrong :(
        return (current_size / 1024) / (time.time() - self.start)
        # size / 1024 to convert it to KB . / time in seconds .

Download()

我无法对其进行深入测试,但这些值似乎还可以。 这是一个 10MB 的文件,在达到我的 Internet 速度限制之前它就完成了。我想用另一个文件进行测试,但不知何故,尽管我更改了 url 和文件名。

【讨论】:

  • 谢谢,你的方法是对的,但为什么它给了我一半的真实速度!所以我不得不这样做:return (current_size*2) / (time.time() - self.start) 但我确定这不是 pythonic 的方式,但它完成了工作。有什么建议吗?