如何添加 "pytube" 下载信息到 tqdm 进度条?

How to add "pytube" downloading info to tqdm Progress Bar?

我正在尝试制作 YouTube 视频下载器。 我想在下载 YouTube 视频时制作一个进度条,但我无法获得任何信息(已下载多少 MB 或多少视频 MB)。 我不知道 python 是否可行。到目前为止,这是我的代码:

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

要访问下载进度,您可以在创建 YouTube 实例时使用 on_progress_callback 参数。

pytube quickstart 表示如下:

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

示例输出:

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 内置了进度条,但是没有使用tqdm。请参阅 了解更多信息。