0

我正在尝试编写代码以使用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

4

1 回答 1

1

问题是因为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))
于 2021-02-10T20:57:47.333 回答