如何保存yt-dlp下载的输出?
我写了一个程序来下载YouTube视频:
import yt_dlp
URL = "https://www.youtube.com/watch?v=YV2tUZIZ3Bs"
ydl_opts = {
"format": f"bestvideo[height<=144]",
"merge_output_format": "mp4",
"outtmpl": "/home/lankergd/PycharmProjects/LankerTools/films_test/yez.mp4",
"quiet": False
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download(URL)
在下载和保存的过程中,这些输出会打印到控制台的多行。我想把这些行捕获下来并存储到一个变量中。我该怎么做?
输出如下:
/home/lankergd/PycharmProjects/LankerTools/.venv/bin/python /home/lankergd/PycharmProjects/LankerTools/tests.py
[youtube] Extracting URL: https://www.youtube.com/watch?v=YV2tUZIZ3Bs
[youtube] YV2tUZIZ3Bs: Downloading webpage
WARNING: [youtube] No supported JavaScript runtime could be found. Only deno is enabled by default; to use another runtime add --js-runtimes RUNTIME[:PATH] to your command/config. YouTube extraction without a JS runtime has been deprecated, and some formats may be missing. See https://github.com/yt-dlp/yt-dlp/wiki/EJS for details on installing one
[youtube] YV2tUZIZ3Bs: Downloading android vr player API JSON
[youtube] YV2tUZIZ3Bs: Downloading ios downgraded player API JSON
WARNING: [youtube] YouTube said: ERROR - Precondition check failed.
WARNING: [youtube] HTTP Error 400: Bad Request. Retrying (1/3)...
[youtube] YV2tUZIZ3Bs: Downloading ios downgraded player API JSON
WARNING: [youtube] YouTube said: ERROR - Precondition check failed.
WARNING: [youtube] HTTP Error 400: Bad Request. Retrying (2/3)...
[youtube] YV2tUZIZ3Bs: Downloading ios downgraded player API JSON
WARNING: [youtube] YouTube said: ERROR - Precondition check failed.
WARNING: [youtube] HTTP Error 400: Bad Request. Retrying (3/3)...
[youtube] YV2tUZIZ3Bs: Downloading ios downgraded player API JSON
WARNING: [youtube] YouTube said: ERROR - Precondition check failed.
WARNING: [youtube] Unable to download API page: HTTP Error 400: Bad Request (caused by <HTTPError 400: Bad Request>)
[info] YV2tUZIZ3Bs: Downloading 1 format(s): 160
[download] Destination: /home/lankergd/PycharmProjects/LankerTools/films_test/yez.mp4
[download] 100% of 365.55KiB in 00:00:00 at 958.59KiB/s
Process finished with exit code 0
解决方案
YoutubeDL 支持传递自定义日志记录器。若这样做,下载的输出将写入日志对象,而不是打印到控制台。例如,这个程序将输出写入一个 StringIO 对象以便后续使用:
import io
import logging
import yt_dlp
URL = "https://www.youtube.com/watch?v=YV2tUZIZ3Bs"
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
yt_dlp_output = io.StringIO()
handler = logging.StreamHandler(yt_dlp_output)
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)
ydl_opts = {
"format": "bestvideo[height<=144]",
"merge_output_format": "mp4",
"outtmpl": "yez.mp4",
"quiet": False,
"logger": logger
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download(URL)
yt_dlp_output.seek(0)
for line in yt_dlp_output:
print(line)
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。