如何从 python 程序中使用 youtube-dl
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18054500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use youtube-dl from a python program
提问by JulienFr
I would like to access the result of the shell command:
我想访问 shell 命令的结果:
youtube-dl -g "www.youtube.com..."
to print its output direct url
to file; from within a python program:
将其输出打印direct url
到文件;从 python 程序中:
import youtube-dl
fromurl="www.youtube.com ...."
geturl=youtube-dl.magiclyextracturlfromurl(fromurl)
Is that possible ?
I tried to understand the mechanism in the source but got lost : youtube_dl/__init__.py
, youtube_dl/youtube_DL.py
, info_extractors
...
那可能吗 ?我试图了解源的机制,但迷路了:youtube_dl/__init__.py
,youtube_dl/youtube_DL.py
,info_extractors
...
采纳答案by jaimeMF
It's not difficult and actually documented:
这并不困难,而且实际记录在案:
import youtube_dl
ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s%(ext)s'})
with ydl:
result = ydl.extract_info(
'http://www.youtube.com/watch?v=BaW_jenozKc',
download=False # We just want to extract the info
)
if 'entries' in result:
# Can be a playlist or a list of videos
video = result['entries'][0]
else:
# Just a video
video = result
print(video)
video_url = video['url']
print(video_url)
回答by JulienFr
If youtube-dl
is a terminal program, you can use the subprocess
module to access the data you want.
如果youtube-dl
是终端程序,则可以使用该subprocess
模块访问您想要的数据。
Check out this link for more details: Calling an external command in Python
查看此链接以获取更多详细信息:在 Python 中调用外部命令
回答by cogitoergosum
Here is a way.
这是一种方法。
We set-up options' string, in a list, just as we set-up command line arguments. In this case opts=['-g', 'videoID']
. Then, invoke youtube_dl.main(opts)
. In this way, we write our custom .py module, import youtube_dl
and then invoke the main()
function.
我们在列表中设置选项的字符串,就像我们设置命令行参数一样。在这种情况下opts=['-g', 'videoID']
。然后,调用youtube_dl.main(opts)
. 这样,我们编写自定义的 .py 模块,import youtube_dl
然后调用该main()
函数。
回答by Krishna Deepak
I would like this
我想要这个
from subprocess import call
command = "youtube-dl https://www.youtube.com/watch?v=NG3WygJmiVs -c"
call(command.split(), shell=False)