How to use youtube-dl from a python program?
Asked Answered
A

7

116

I would like to access the result of the following shell command,

youtube-dl -g "www.youtube.com/..."

to print its output direct url to a file, from within a python program. This is what I have tried:

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 ...

Arleyne answered 5/8, 2013 at 9:16 Comment(2)
#89728Sociability
@lollercoaster, that URL is dead... Fixed link here.Khamsin
B
203

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)
Barraza answered 22/9, 2013 at 19:28 Comment(11)
I'm getting this error: import youtube_dl ImportError: No module named youtube_dlCognomen
You have to install the youtube_dl : if you have the pip utility (to install it, sudo apt-get install python-pip ) you can to sudo pip install youtube-dlArleyne
If you have "No module named youtube_dl" on gentoo you can try to add "#!/usr/bin/env python2.7" to the start of python file.Confucianism
is there a way to pass a variable to the options object? Something like: 'outtmpl' : '%(my_variable)s%(id)s.%(ext)s'Gammon
The variables supported for outtmpl are listed in the READMEBarraza
I know this is old and there are other answers but just to clarify. On new versions of youtube_dl there were some changes and instead of video['url'] it changed to video['webpage_url']Snowmobile
How can we add "-c" or continue flag in the options?Tulipwood
The script you gave if wrong if the video url contains "entries". it should be something like try :video = result['entries'][0] except: video=resultArleyne
video['url]` or video[webpage_url] just repeats the same url. I haven't found a way to get the actual stream urls (for both audio or video)Zither
What is the purpose of with ydl:?Timoteo
ydl is an object of the type youtube_dl.YoutubeDL(ydl_opts)Tertullian
Q
12

For simple code, may be i think

import os
os.system('youtube-dl [OPTIONS] URL [URL...]')

Above is just running command line inside python.

Other is mentioned in the documentation Using youtube-dl on python Here is the way

from __future__ import unicode_literals
import youtube_dl

ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])
Quintan answered 15/6, 2020 at 1:39 Comment(0)
S
4

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.

Subheading answered 18/12, 2013 at 21:55 Comment(1)
this kind of works, nothing is returned from the main function, so you can't really get the value of it yet.Zither
P
1
from __future__ import unicode_literals 
import youtube_dl

ydl_opts = {} 
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['Your youtube url'])

You can use 'format', 'continue', 'outtmpl' in ydl_opts As example;

ydl_opts= {
           'format': '22',
           'continue': True,
           'outtmpl': '%(uploader)s - %(title)s.%(ext)s',
           'progress_hooks': [my_hook],
          }

def my_hook(d):
    if d['status'] == 'downloading':
        print('Downloading video!')
    if d['status'] == 'finished':
        print('Downloaded!')

When you need to stop playlist downloading, Just add this code into ydl_opts.

'noplaylist': True;
Prudential answered 6/2, 2022 at 14:44 Comment(0)
S
-3

Usage: python3 AudioFromYtVideo.py link outputName

import os
from sys import argv

try:
    if argv[1] and argv[2]:
        pass
except:
    print("Input: python3 [programName] [url] [outputName]")    

os.system('youtube-dl -x --audio-format mp3 -o '+argv[2]+' '+argv[1])
Swineherd answered 22/8, 2021 at 2:31 Comment(0)
B
-8

If youtube-dl is a terminal program, you can use the subprocess module to access the data you want.

Check out this link for more details: Calling an external command in Python

Bledsoe answered 5/8, 2013 at 9:27 Comment(4)
That's a bit sad to call a python program from a python program, isn't it ?Arleyne
I consider youtube-dl to be a command-line program written in Python and see nothing wrong with calling it from the command-line. If you want to muck around with the source code, please feel free to do so.Bledsoe
@Xaranke You have a lot more control if you import youtube-dl as a module from python. Parsing printed data from command line is nowhere as reliable.Thusly
Also, I dare you to actually try using subprocess/os.system on this youtube-dl command. It doesn't actually work very well, nor as intended, when trying to pass arguments.Witling
R
-11

I would like this

from subprocess import call

command = "youtube-dl https://www.youtube.com/watch?v=NG3WygJmiVs -c"
call(command.split(), shell=False)
Roberts answered 2/5, 2014 at 13:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.