我一直在修补youtube_dl,并且一直在将问题实现到我的Python 3.4脚本中。
我只是想创建一个存储输出的变量(通过几个选项进行调整。)
但是,我似乎无法弄清楚如何将选项添加到函数中,并且无论我做什么,输出似乎只会被打印(而不是存储在我的变量中。)
这是我目前的代码:
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'])
目前只下载测试视频。以下是解释嵌入youtube_dl的GitHub链接:
这是我想要做的伪代码:
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))
有没有人有任何建议或想法?我一直坚持这个问题的时间超过了我想承认的时间。
答案 0 :(得分:1)
从简短的潜水到youtube_dl
的来源,看起来如果不修改youtube_dl
就无法做到。来自the source:
def download(self, url_list):
"""Download a given list of URLs."""
outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
if (len(url_list) > 1 and
'%' not in outtmpl and
self.params.get('max_downloads') != 1):
raise SameFileError(outtmpl)
for url in url_list:
try:
# It also downloads the videos
res = self.extract_info(
url, force_generic_extractor=self.params.get('force_generic_extractor', False))
except UnavailableVideoError:
self.report_error('unable to download video')
except MaxDownloadsReached:
self.to_screen('[info] Maximum number of downloaded files reached.')
raise
else:
if self.params.get('dump_single_json', False):
self.to_stdout(json.dumps(res))
return self._download_retcode
正如您所看到的,它会调用self.to_screen
和self.to_stdout
,而不是返回代码。您可以修补其中一个函数来重定向输出,但我不认为这是可能的。
如果你想修补self.to_screen
,你应该可以做这样的事情
警告:这可能会有所作为
def patched_to_screen(self, message, skip_eol=False):
return message
def patch_to_stdout(self, message, skip_eol=False, check_quiet=False):
return message
ydl = YoutubeDL()
ydl.to_screen = patched_to_screen
tdl.to_stdout = patched_to_stdout
答案 1 :(得分:1)
使用extract_info
方法,它会返回字典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']))