Spi*_*dey 5 youtube-dl python-3.6
I'm using python embedded youtube_dl and I'd like to download video content directly into a temporary file. I attempted to create a NamedTemporaryFile and have youtube_dl write into it, but I always get a prompt that the file was already downloaded (the temporary file has that name and it thinks the download already happened).
I also attempted to have youtube_dl stream downloaded data to stdout and redirect stdout to the temporary file but I can't get the python embedded version to do that. It doesn't output to stdout it simply creates a file named -.mp4.
import youtube_dl
ydl_opts = {
"format": "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best",
"merge-output-format": "mp4",
"recode-video": "mp4",
"outtmpl": "-",
"verbose": True,
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(["https://www.youtube.com/watch?v=h3h035Eyz5A&ab_channel=Loku"])
Run Code Online (Sandbox Code Playgroud)
To summarize, the code above won't override -.mp4 files if they already exist and it won't stream the download into stdout so I can redirect it into a temp file.
The temp file is needed because it's an intermediary step for further processing. At this point it feels like I'll need to copy the file to temp file and delete the original or I'll need to use youtube_dl with a subprocess which feels silly.
我以前遇到过类似的问题。我发现一个很好的解决方法是使用 tempfile.TemporaryDirectory() 临时存储文件,然后使用 open() 检索文件。
查看 youtube_dl 代码库,看起来您想使用extract_info而不是download直接使用该方法。
import tempfile
from youtube_dl import YoutubeDL
from youtube_dl.utils import DownloadError
with tempfile.TemporaryDirectory() as tempdirname:
ydl_opts = {
"format": "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best",
"merge_output_format": "mp4",
"outtmpl": f"{tempdirname}/%(id)s.%(ext)s",
"noplaylist": True,
"verbose": True,
}
ydl = YoutubeDL(ydl_opts)
try:
meta = ydl.extract_info(
"https://www.youtube.com/watch?v=h3h035Eyz5A&ab_channel=Loku",
download=True,
)
except DownloadError as e:
raise e
else:
video_id = meta["id"]
video_ext = meta["ext"]
file = open(f"{tempdirname}/{video_id}.{video_ext}", "rb")
# whatever else you gotta do bruh...
# when the with statement finishes execution, the temp directory
# will be cleaned up.
Run Code Online (Sandbox Code Playgroud)
ydl_opts请注意,由于您没有使用 cli,因此您应该使用 Snake_case 作为参数( 中的键)。我也认为recode-video这不是一个受支持的选项,但请检查此处以确定。
另请注意,我假设您想下载一个视频。上面的代码不考虑从临时目录检索播放列表,我故意将选项添加noplaylist到ydl_opts.
| 归档时间: |
|
| 查看次数: |
3861 次 |
| 最近记录: |