调整重试逻辑以下载列表中的文件
Tweeking retry logic to download files in a list
我有一个 URL 列表(大约 20 个),我正在通过 for 循环迭代这些 URL 以下载它们每个指向的文件(使用 URLLib)。我在一个 try-except 块中有这个 for 循环(出于明显的原因),它位于一个 for 循环中,该循环本质上是重试尝试(3 次)的逻辑。我想知道的是,是否有一种方法可以避免从头开始下载整个列表,如果出现问题(并且 except 块捕获它并重试)。
所以,现在,如果循环执行了13个文件的下载,在第14个文件遇到错误,而不是从头下载所有文件,我是否可以尝试重新下载第 14 个继续?
代码如下:
retry = 3
for r in range(retry):
try:
for i in urls:
n = os.path.basename(i)
urllib.request.urlretrieve(i, f'app/test/{n}') # Downloading the file and saving it at app/test with the file name n
except Exception as e:
if r < 2:
print(f'Failed. Attempt # {r + 1}')
continue
else:
print('Error encoutered at third attempt')
print(e)
break
您可以交换 for
循环:
retry = 3
for i in urls:
for r in range(retry):
try:
n = os.path.basename(i)
urllib.request.urlretrieve(i, f'app/test/{n}') # Downloading the file and saving it at app/test with the file name n
except Exception as e:
if r < 2:
print(f'Failed. Attempt # {r + 1}')
else:
print('Error encoutered at third attempt')
print(e)
else:
print(f"Success: {n}")
break
我有一个 URL 列表(大约 20 个),我正在通过 for 循环迭代这些 URL 以下载它们每个指向的文件(使用 URLLib)。我在一个 try-except 块中有这个 for 循环(出于明显的原因),它位于一个 for 循环中,该循环本质上是重试尝试(3 次)的逻辑。我想知道的是,是否有一种方法可以避免从头开始下载整个列表,如果出现问题(并且 except 块捕获它并重试)。
所以,现在,如果循环执行了13个文件的下载,在第14个文件遇到错误,而不是从头下载所有文件,我是否可以尝试重新下载第 14 个继续?
代码如下:
retry = 3
for r in range(retry):
try:
for i in urls:
n = os.path.basename(i)
urllib.request.urlretrieve(i, f'app/test/{n}') # Downloading the file and saving it at app/test with the file name n
except Exception as e:
if r < 2:
print(f'Failed. Attempt # {r + 1}')
continue
else:
print('Error encoutered at third attempt')
print(e)
break
您可以交换 for
循环:
retry = 3
for i in urls:
for r in range(retry):
try:
n = os.path.basename(i)
urllib.request.urlretrieve(i, f'app/test/{n}') # Downloading the file and saving it at app/test with the file name n
except Exception as e:
if r < 2:
print(f'Failed. Attempt # {r + 1}')
else:
print('Error encoutered at third attempt')
print(e)
else:
print(f"Success: {n}")
break