使用 yt-dlp 获取下载视频的文件名

LT_*_*nge 9 python ffmpeg yt-dlp

我打算使用 yt-dlp 下载视频,然后使用 ffmpeg 剪切视频。但为了能够使用 ffmpeg,我必须知道 yt-dlp 生成的文件的名称。我已阅读他们的文档,但我似乎找不到将文件名返回到我的程序中的方法。

小智 7

这是文档示例

我相信您提到的数字(例如.f399)只是临时的,并且最终在合并最终文件时被删除。

如果你想获取文件名:

import subprocess
someFilename = subprocess.getoutput('yt-dlp --print filename https://www.youtube.com/something')
# then pass someFilename to FFmpeg
Run Code Online (Sandbox Code Playgroud)

使用您自己的文件名:

subprocess.run('yt-dlp -o thisIsMyName https://www.youtube.com/something')
# this will likely download a file named thisIsMyName.webm
Run Code Online (Sandbox Code Playgroud)

但如果您事先不确定文件类型/扩展名并且只想获取:

someFileType = subprocess.getoutput('yt-dlp --print filename -o "%(ext)s" https://www.youtube.com/something')
print(someFileType)
Run Code Online (Sandbox Code Playgroud)

它不是很有效,但可以帮助解释它:

import subprocess

someFileType = subprocess.getoutput('yt-dlp --print filename -o "%(ext)s" https://www.youtube.com/something')
subprocess.run('yt-dlp -o "myFileName.%(ext)s" https://www.youtube.com/something')
subprocess.run(f'ffmpeg -i "myFileName.{someFileType}" outputFile.mp4')
Run Code Online (Sandbox Code Playgroud)


小智 6

根据文档,您应该能够传递进度挂钩并在那里检索文件名。它应该可以通过filenameattribute访问,但我见过它附加.f399和/或随时间变化的实例。我认为这与部分下载视频有关,实际上是临时文件名。

我发现通过捕获整个info_dict字典,有一个_filename键似乎具有最终的文件名。

这基本上就是我所做的:

import yt_dlp

final_filename = None

def yt_dlp_monitor(self, d):
    final_filename  = d.get('info_dict').get('_filename')
    # You could also just assign `d` here to access it and see all the data or even `print(d)` as it updates frequently

ydl_opts = {
    "outtmpl": '/whatever/directory/%(uploader)s_%(title)s.%(ext)s',  # this is where you can edit how you'd like the filenames to be formatted
    "progress_hooks": [yt_dlp_monitor]  # here's the function we just defined
    }
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
    info = ydl.extract_info("http://youtu.be/whatever_video)
Run Code Online (Sandbox Code Playgroud)

现在,final_filename每次调用该挂钩时,都会继续更新文件名。d['status'] == 'finished'如果您愿意,您可以只更新它。