0

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

2
  • how do you get video_size? Is it correct value - do you get downloaded file with the same size?
    – furas
    Feb 10, 2021 at 20:08
  • I get video_size correctly and the downloaded file is working when downloading complete, the only probleme is the progressbar finishes before download complete
    – Hadi Ayoub
    Feb 10, 2021 at 23:05

1 Answer 1

1

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))
1
  • Thanks, it works just fine... I was gonna use requests module instead but this is easier
    – Hadi Ayoub
    Feb 10, 2021 at 23:22

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.