【发布时间】:2021-04-27 20:46:15
【问题描述】:
我有一个运行 my_func(list) 的脚本,该脚本运行 my_request() 访问公共 API 服务器以获取数据,但此查询随机失败,我得到一个ResponseError。而且我必须重新运行脚本,直到收集到所有分区(tmp_lst的长度等于df_list的长度)。
我很好奇是否有办法让我运行这个脚本一次,然后让脚本重试 N 次,直到收集完所有分区,而不必每次遇到 ResponseError 时都重新运行它强>。
我尝试插入一个while循环,但这并没有解决问题,我仍然需要手动重新运行它。
import pandas as pd
# from pytrends.exceptions import ResponseError
def my_func(list):
df = my_request(list) #requests api call to grab data for each element in a list
return df # returns pandas dataframe object
df_list = [pd.DataFrame([[1,2],[3,4]]), pd.DataFrame([[5,6],[7,8]])] # there are more in my actual list
try:
if tmp_lst is not None:
try:
while len(tmp_lst) < len(df_list):
for remaining_partition in range(len(tmp_lst),len(df_list)):
tmp_lst.append(my_func(df_list[remaining_partition])) #my_func returns df
print(f"partition {remaining_partition+1} appended")
except ResponseError:
print("Rate limit Exceeded. Progress: ",str(len(tmp_lst)),"/",str(len(df_list)))
except NameError:
tmp_lst = []
try:
while len(tmp_lst) < len(df_list):
for partition in range(len(df_list)):
tmp_lst.append(my_func(df_list[partition]))
print(f"partition {partition} appended")
except ResponseError:
print("Rate limit Exceeded. Progress: ",str(len(tmp_lst)),"/",str(len(df_list)))
【问题讨论】:
-
在函数 my_request 中,您可以放置一个计数器并将您的 API 调用包装在 try 和 except 块中。例如,对于列表中的每个项目,计数器从零开始,如果失败,则向计数器添加 +1,如果计数器 > N,则退出。