【发布时间】:2020-05-27 16:45:28
【问题描述】:
我正在运行一个脚本以在 python 中使用 youtube-dl 下载视频
def dl_videos():
while True:
try:
while True:
ydl_opts = {
'ignoreerrors': 'True',
'download_archive': 'archive',
'format': 'bestaudio/best',
'outtmpl': 'mp3downloads/%(playlist_title)s/%(title)s.%(ext)s',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '193',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
with open ('PlaylistOnly', 'r') as r:
d = r.readlines()
for line in d:
ydl.download([line])
time.sleep(24.0 * 60.0 * 60.0)
except(FileNotFoundError):
time.sleep(5)
continue
dl_videos()
但是,我希望这个脚本能够处理连接中断。因此,当我在程序中间切断连接时,它会因为这个错误而被彻底拖垮:
[0;31mERROR:[0m Unable to download webpage: <urlopen error [Errno -3] Temporary failure in name resolution> (caused by URLError(gaierror(-3, 'Temporary failure in name resolution')))
注意:如果在线连接丢失,只会在 youtube-dl 进程的某个时间点出现错误
我希望程序稍等片刻,然后重试该模块,但我完全不确定如何处理此错误。如果这是一个特定的错误类型,我可以处理异常。任何帮助表示赞赏
-编辑- (解决方案)
def dl_videos():
while True:
try:
while True:
ydl_opts = {
'ignoreerrors': 'True',
'download_archive': 'archive',
'format': 'bestaudio/best',
'outtmpl': 'mp3downloads/%(playlist_title)s/%(title)s.%(ext)s',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '193',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
with open ('PlaylistOnly', 'r') as r:
d = r.readlines()
for line in d:
ydl.download([line])
#Checks if there's a connection to youtube.com, if there's none it loops back before the "freeze" which my dumb a didnt realize was just the next time.sleep function
if assets.connect() == False:
time.sleep(10)
continue
time.sleep(24.0 * 60.0 * 60.0)
except(FileNotFoundError):
time.sleep(5)
continue
dl_videos()
【问题讨论】:
-
建议:不用
d = r.readlines() for line in d: ydl.download([line]),可以ydl.download(r.readlines())
标签: python python-3.x error-handling youtube-dl