Skip to content
Advertisement

Downloading YouTube videoes with pafy module with tqdm progressbar

I am trying to make a code to download videos from YouTube using pafy module and a progressbar using tqdm module, however the progressbar is finished before the download complete.

here is my code download piece:

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))

here is a pic a the progressbar:

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

Advertisement

Answer

Problem is because pbar.update() expects value current_received - previous_received

download gives only current_received so you have to use some variable to rember previous value and substract it


Minimal working code:

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))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement