api—如何运行python脚本,直到收集到的所有数据或满足特定条件

gijlo24d  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(390)

我有一个运行我的\u func(list)的脚本,这个脚本运行我的\u request(),它点击公共api服务器获取数据,但是这个查询随机失败,我得到一个responseerror。我必须重新运行脚本,直到所有的分区都被收集(tmp\ulst的长度等于df\ulst的长度)。
我很好奇是否有一种方法可以让我运行这个脚本一次,然后让脚本重试n次,直到收集了所有分区,而不必每次遇到responseerror时都重新运行它。
我试图插入while循环,但这并没有解决问题,我仍然必须手动重新运行它。

  1. import pandas as pd
  2. # from pytrends.exceptions import ResponseError
  3. def my_func(list):
  4. df = my_request(list) #requests api call to grab data for each element in a list
  5. return df # returns pandas dataframe object
  6. df_list = [pd.DataFrame([[1,2],[3,4]]), pd.DataFrame([[5,6],[7,8]])] # there are more in my actual list
  7. try:
  8. if tmp_lst is not None:
  9. try:
  10. while len(tmp_lst) < len(df_list):
  11. for remaining_partition in range(len(tmp_lst),len(df_list)):
  12. tmp_lst.append(my_func(df_list[remaining_partition])) #my_func returns df
  13. print(f"partition {remaining_partition+1} appended")
  14. except ResponseError:
  15. print("Rate limit Exceeded. Progress: ",str(len(tmp_lst)),"/",str(len(df_list)))
  16. except NameError:
  17. tmp_lst = []
  18. try:
  19. while len(tmp_lst) < len(df_list):
  20. for partition in range(len(df_list)):
  21. tmp_lst.append(my_func(df_list[partition]))
  22. print(f"partition {partition} appended")
  23. except ResponseError:
  24. print("Rate limit Exceeded. Progress: ",str(len(tmp_lst)),"/",str(len(df_list)))
bf1o4zei

bf1o4zei1#

你试过把try/except块放在while循环中吗?

相关问题