如何为Pytube下载添加开始与完成提示信息?
解决方法
方法1:直接在下载前后添加打印语句
stream.download()是阻塞式调用,会等到下载完成才执行后续代码,直接在调用前后加打印语句就能实现需求:
from pytube import YouTube yt = YouTube(input("请输入视频链接:\n")) stream = yt.streams.get_by_itag(22) print("download has started, and is continuing") stream.download() print("download is finished")
方法2:使用Pytube内置回调函数(精准触发)
如果需要更精准捕捉下载启动和完成的时机(比如处理大文件或多线程场景),可以给YouTube对象注册回调函数:
from pytube import YouTube def download_started(stream, chunk): print("download has started, and is continuing") def download_finished(stream, file_path): print("download is finished") yt = YouTube( input("请输入视频链接:\n"), on_download_start=download_started, on_complete_callback=download_finished ) stream = yt.streams.get_by_itag(22) stream.download()
两种方法对比
- 方法1代码简洁直观,适合简单场景;
- 方法2的回调会在下载真正开始接收数据、完成文件写入时触发,时机更精准,适合需要额外逻辑处理的场景。
内容的提问来源于stack exchange,提问作者Mert_Aslan
相关产品推荐
相关产品推荐

