我想在我的代码中实现一个进度条,但是旧的和新的实现方式都不起作用。
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/