python-3.x - 如何在 pytube 中使用进度条?

标签 python-3.x pytube

我想在我的代码中实现一个进度条,但是旧的和新的实现方式都不起作用。

How to add progress bar? 此修复程序在最新版本中不起作用。
这是最新的文档 https://pypi.org/project/pytube/

from pytube import YouTube
url="https://youtu.be/J5EXnh53A1k"
path=r'D://'
yt = YouTube(url)
yt.register_on_progress_callback(show_progress_bar)#by commenting this line code works fine but no progress bar is displyed
yt.streams.filter(file_extension='mp4').first().download(path)


def show_progress_bar(stream, _chunk, _file_handle, bytes_remaining):
  current = ((stream.filesize - bytes_remaining)/stream.filesize)
  percent = ('{0:.1f}').format(current*100)
  progress = int(50*current)
  status = '█' * progress + '-' * (50 - progress)
  sys.stdout.write(' ↳ |{bar}| {percent}%\r'.format(bar=status, percent=percent))
  sys.stdout.flush()

最佳答案

首先需要定义进度条函数,比如progress_function:

def progress_function(chunk, file_handle, bytes_remaining):
    global filesize
    current = ((filesize - bytes_remaining)/filesize)
    percent = ('{0:.1f}').format(current*100)
    progress = int(50*current)
    status = '█' * progress + '-' * (50 - progress)
    sys.stdout.write(' ↳ |{bar}| {percent}%\r'.format(bar=status, percent=percent))
    sys.stdout.flush()

然后将上面定义的函数progress_function注册到on_progress_callback中,如下:

yt_obj = YouTube(<<youtube_video_url>>, on_progress_callback = progress_function)

其余代码如下:

yt_obj.streams.filter(progressive=True, file_extension='mp4').get_highest_resolution().download(output_path='/home/myusername/Videos', filename='MyVideo')

输出看起来像这样:

↳ |██████████████████████████████████---------- ------| 68.4%

玩得开心!!

关于python-3.x - 如何在 pytube 中使用进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56197879/

相关文章:

python-3.x - python : append to value-list using dictionary-comprehension

python - "AttributeError: no attribute ' 下载“使用PyTube

python - 如何使用 pytube 下载 YouTube 视频剪辑?

python - 使用pytube下载管视频时如何添加tqdm以显示进度栏?

python - 文档字符串是否应该只包含函数显式引发的异常?

python-3.x - bert层中的池化输出和序列输出有什么区别?

python - 在 python 上找不到用于导入 csv 的文件。文件路径正确,一切都已安装

python - 尝试通过Python下载youtube字幕时,为什么会出现Regex错误?

python - 如何使用 pytube 从 Youtube 播放列表下载中间视频

python - 计算 pandas 数据帧的总和