如何 运行 Python 编写脚本,直到收集到所有数据或满足特定条件

How to run Python script until all data collected or certain condition met

我有一个脚本 运行s my_func(list),运行s my_request() 访问 public API 服务器以获取数据,但此查询随机失败,我收到 ResponseError。而且我必须重新运行脚本,直到收集所有分区(tmp_lst的长度等于[的长度=34=]).

我很好奇是否有办法让我 运行 这个脚本一次,然后让脚本重试 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)))

您是否尝试过将 try/except 块放入 while 循环中?