Search code examples
pythonpython-3.xyoutubeyoutube-dl

Issues with basic embedding of youtube_dl into a Python 3.4 script


I have been tinkering with youtube_dl and have been having issues implementing it into my Python 3.4 script.

I am simply trying to create a variable that stores the output (adjusted with a few options.)

However, I can't seem to figure out how to add the options to the function and the output seems to only be printed no matter what I do (as opposed to be stored in my variable.)

Here is my current code:

class MyLogger(object):
    def debug(self, msg):
        pass

    def warning(self, msg):
        pass

    def error(self, msg):
        print(msg)

ydl_opts = {
'logger': MyLogger(),
}

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['http://www.youtube.com/watch?v=BaW_jenozKc'])

Which just downloads a test video currently. Here is the GitHub links that explain embedding youtube_dl:

And here is the pseudo-code of what I am trying to do:

class MyLogger(object):
    def debug(self, msg):
        pass

    def warning(self, msg):
        pass

    def error(self, msg):
        print(msg)

ydl_opts = {
'logger': MyLogger(),
'InfoExtractors':[{'simulate','forceduration'}]
}

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    duration = ydl.download(['http://www.youtube.com/watch?v=BaW_jenozKc'])
print('The duration is {0}'.format(duration))

Does anyone have any advice or ideas? I have been stuck on this issue for longer than I would care to admit.


Solution

  • Use the extract_info method, it returns a dictionary with the video info:

    import youtube_dl
    
    class MyLogger(object):
        def debug(self, msg):
            pass
    
        def warning(self, msg):
            pass
    
        def error(self, msg):
            print(msg)
    
    ydl_opts = {
        'logger': MyLogger(),
    }
    
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info('http://www.youtube.com/watch?v=BaW_jenozKc', download=True)
    print('The duration is {0}'.format(info['duration']))