使用带 tqdm 进度条的 pafy 模块下载 YouTube 视频

Downloading YouTube videoes with pafy module with tqdm progressbar

我正在尝试编写代码以使用 pafy 模块从 YouTube 下载视频,并使用 tqdm 模块制作进度条,但是进度条在下载完成之前就完成了。

这是我的代码下载片段:

with tqdm.tqdm(desc=video_name, total=video_size, unit_scale=True, unit='B', initial=0) as pbar:
     bestVideo.download(filepath=full_path, quiet=True, callback=lambda _, received, *args: pbar.update(received))

这是进度条的图片:

https://i.stack.imgur.com/VMBUN.png

问题是因为 pbar.update() 期望值 current_received - previous_received

download 只给出 current_received 所以你必须使用一些变量来记住以前的值并减去它


最小工作代码:

import pafy
import tqdm

# --- functions ---

previous_received = 0

def update(pbar, current_received):
    global previous_received
    
    diff = current_received - previous_received
    pbar.update(diff)
    previous_received = current_received

# --- main ---

v = pafy.new("cyMHZVT91Dw")
s = v.getbest()

video_size = s.get_filesize()
print("Size is", video_size)
    
with tqdm.tqdm(desc="cyMHZVT91Dw", total=video_size, unit_scale=True, unit='B', initial=0) as pbar:
     s.download(quiet=True, callback=lambda _, received, *args:update(pbar, received))