Skip to content
Advertisement

How to add “pytube” downloading info to tqdm Progress Bar?

I am trying make a YouTube video downloader. I want make a progress bar while downloading the YouTube video but I cant get any info (how many MB have been downloaded or how many video MB). I don’t know if this is possible with python or not. Here is my code so far:

import time , os
from pytube import YouTube
from tqdm import tqdm


al = str(input("C4ommand:"))


if al == "4":
    af = input("Link:")
    you = YouTube(af)

    try:
        os.mkdir("Download")
    except:
        pass

    time.sleep(2)
    time.sleep(1)
    res = you.streams.get_highest_resolution()
    a = res.download()
    with tqdm(total=100) as pbar:
        for i in range(10):
            time.sleep(0.5)
            pbar.update(10)
    print(af + "Link downloading....")
    b = open("Download", "w")
    b.write(a)
    b.close()
    print("Downloaded")

Advertisement

Answer

To access the progress of the download, you can use the on_progress_callback argument when creating a YouTube instance.

The pytube quickstart says the following:

The on_progress_callback function will run whenever a chunk is downloaded from a video, and is called with three arguments: the stream, the data chunk, and the bytes remaining in the video. This could be used, for example, to display a progress bar.

from pytube import Stream
from pytube import YouTube
from tqdm import tqdm


def progress_callback(stream: Stream, data_chunk: bytes, bytes_remaining: int) -> None:
    pbar.update(len(data_chunk))


url = "http://youtube.com/watch?v=2lAe1cqCOXo"
yt = YouTube(url, on_progress_callback=progress_callback)
stream = yt.streams.get_highest_resolution()
print(f"Downloading video to '{stream.default_filename}'")
pbar = tqdm(total=stream.filesize, unit="bytes")
path = stream.download()
pbar.close()
print(f"Saved video to {path}")

Sample output:

Downloading video to 'YouTube Rewind 2019 For the Record  YouTubeRewind.mp4'
100%|██████████████████████████████| 87993287/87993287 [00:17<00:00, 4976219.51bytes/s]
Saved video to /tmp/testing/YouTube Rewind 2019 For the Record  YouTubeRewind.mp4

Pytube has a built-in progress bar, but it does not use tqdm. Please see https://stackoverflow.com/a/60678355/5666087 for more information.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement