python - Tweeking retry logic to download files in a list
问题描述
I have a list of URLs (around 20) that I am iterating over a for loop to download the file (using URLLib) each of them is pointing to. I have this for loop inside a try-except block (for obvious reasons), which is inside a for loop that is essentially a logic for retry attempts (3 times). What I'd like to know is if there's a way to avoid downloading the whole list from the beginning, if something fails (and the except block catches it and retries).
So, now, if the loop has executed the download for 13 files, and at the 14th file, it encounters an error, instead of downloading all the files from the beginning, can I just try to re-download the 14th one and carry on?
Here's the code:
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
解决方案
You can swap the for
loops:
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
推荐阅读
- python - 无法打开文件'file.py':[Errno 2] 没有这样的文件或目录
- react-native - react-native Metro 捆绑器错误:捆绑失败:ReferenceError:文件的 SHA-1
- android - 在 android studio 中实现 Firebase admin sdk 时出错
- reactjs - this.state.characters.map 不是函数
- excel - 将每列中的值乘以每列中的第二个单元格
- angular - Angular 8 应用程序:window.open 在新窗口中总是重定向到 index.html
- javascript - ReactJS - 外部 JS 函数“不是函数”
- python - 如何使用 python 监听 firebase 数据库更改?
- python - 在后台 Django 中做某事的最佳方式
- javascript - 警报适用于条件,但在按下“确定”时重定向到另一个页面,并且不允许用户更改输入