我想访问shell命令的结果:
youtube-dl -g "www.youtube.com..."
将其输出direct url
打印到文件;从python程序中:
import youtube-dl
fromurl="www.youtube.com ...."
geturl=youtube-dl.magiclyextracturlfromurl(fromurl)
有可能吗?我试图了解源代码中的机制,但迷路了:youtube_dl/__init__.py
,youtube_dl/youtube_DL.py
,info_extractors
...
这并不困难,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)
这是一种方法。
我们在列表中设置选项的字符串,就像我们设置命令行参数一样。在这种情况下为opts=['-g', 'videoID']
。然后,调用youtube_dl.main(opts)
。通过这种方式,我们编写了自定义.py模块import youtube_dl
,然后调用了main()
函数。
对于简单代码,也许我认为
import os
os.system('youtube-dl [OPTIONS] URL [URL...]')
上面只是在python内部运行命令行。
文档Using youtube-dl on python中提到了其他这是方法
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'])
如果youtube-dl
是终端程序,则可以使用subprocess
模块访问所需的数据。
查看此链接以获取更多详细信息:Calling an external command in Python
我想要这个
from subprocess import call
command = "youtube-dl https://www.youtube.com/watch?v=NG3WygJmiVs -c"
call(command.split(), shell=False)