问题
I would like to access the result of the shell command:
youtube-dl -g \"www.youtube.com...\"
to print its output direct url
to file; from within a python program:
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
...
回答1:
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)
回答2:
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.
回答3:
I would like this
from subprocess import call
command = "youtube-dl https://www.youtube.com/watch?v=NG3WygJmiVs -c"
call(command.split(), shell=False)
回答4:
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
来源:https://stackoverflow.com/questions/18054500/how-to-use-youtube-dl-from-a-python-program