如何使用 Paffy 获取下载百分比和下载速度?

How to get the download percentage and speed of a download using Paffy?

我写了一个 python 小程序来从 youtube 下载视频。该函数将 URL 作为输入,然后下载它。

代码:

def download(i):
    global path
    global c
    global threads
    try:
        fh1 = open(path + "done.txt","a") 
        fh = open(path +"err.txt", "a")
        video = pafy.new(i)
        name = str(c) + '. ' + video.title
        c += 1
        try:
            for p in ('|', '?', '\', '/', ':', '*', '<', '>', '\"'):
                 name = name.replace(p, '_')

            best = video.getbest(preftype="mp4")
            print("Downloading "+name+"...")
            best.download(quiet=False, filepath= path + name + '.' + best.extension)
            print("Done Downloading "+name)
            fh1.write("Done : " +name+ '\n')
            fh1.close()

best.download(quiet=False, filepath= path + name + '.' + best.extension) 行显示了剩余的下载速度百分比时间和其他一些内容,但我找不到正确的方法来获取那里显示的数据。我想将数据存储在某个变量中,以便我可以在其他地方显示数据或将其写入某个文件。

pafy documentation 指定 download() 函数可以采用回调参数,为您提供有关下载状态的定期更新。这听起来正是您要搜索的内容。

If a callback function is provided, it will be called repeatedly for each chunk downloaded. It must be a function that takes the following five arguments:

  • total bytes in stream, int
  • total bytes downloaded, int
  • ratio downloaded (0-1), float
  • download rate (kbps), float
  • ETA in seconds, float

文档甚至包含回调示例:

import pafy

# callback function, this callback simply prints the bytes received,
# ratio downloaded and eta.
def mycb(total, recvd, ratio, rate, eta):
    print(recvd, ratio, eta)

p = pafy.new("cyMHZVT91Dw")
ba = p.getbestaudio()
filename = ba.download(quiet=True, callback=mycb)

如果您想将额外的信息传递给您的回调,您可以使用可调用的 class 对象:

import pafy

# Callback class
class MyCallback:
    def __init__(self, callbackId):
        self.callbackId = callbackId

    def __call__(self, total, recvd, ratio, rate, eta):
        print("Downloader #{:d}: {:>7.3f} MB {:>6.1f} % {:>10.1f} kBps    ETA: {:>5.1f} s".format(self.callbackId, recvd/(1024*1024), ratio*100, rate, eta))

p = pafy.new("cyMHZVT91Dw")
ba = p.getbestaudio()
filename = ba.download(quiet=True, callback=MyCallback(42))