下载文件时下载速率?

Downloading Rate while downloading a file?


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 # 好

比率:2.3952649685390823e-07 # 错了吗?我知道大约 1.5

问题是如何在文件还在下载的时候得到下载率。

您正在使用当前时间戳来计算 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 的文件,在达到我的网速限制之前它就完成了。我想用另一个文件进行测试,但不知何故它不起作用,尽管我更改了 url 和文件名。