简体   繁体   English

在 for 循环中尝试/除外 while true

[英]try/except while true in a for loop

The following code will gather data from an API and the try/except clause will help to handle several errors (from authentication, index, anything).以下代码将从 API 收集数据,try/except 子句将帮助处理几个错误(来自身份验证、索引等)。 There's only one error (an authentication error) that I'm using the while True to repeat the API call to make sure I get the data and it will after a try or two.只有一个错误(身份验证错误)我正在使用while True来重复 API 调用以确保我得到数据,并且在一两次尝试后它会。 However if by any means I get another error, it'll be infinitely looping and I can't break it so it goes to the next iteration.但是,如果无论如何我得到另一个错误,它将无限循环并且我不能打破它,所以它会进入下一次迭代。 I tried to create a counter and if the counter reaches to a number then ( pass or continue or break ) but it's not working.我试图创建一个计数器,如果计数器达到一个数字( passcontinuebreak )但它不起作用。

## Create a array to loop to:
data_array_query = pd.date_range(start_date,end_date,freq='6H')

#This is my idea but is not working
#Create a counter
counter = 0

#Loop through the just created array
for idx in range(len(data_array_query)-1):
    ## If counter reaches move on to next for loop element
    while True:
        if counter>=5:
            break
        else:
            try:
                start_date  = data_array_query[idx]
                end_date = data_array_query[idx+1]

                print('from',start_date,'to',end_date)

                df = api.query(domain, site_slug, resolution, data_series_collection, start_date=str(start_date), end_date=str(end_date), env='prod', from_archive=True, phase='production').sort_index()
                print(df.info())
                break
            except Exception as e:
                print(e)
                counter +=1
                print(counter)

在此处输入图像描述

So the output of running this code for a couple of days show that when it runs 5 times (that's the counter max I set up) it does break but it breaks the whole loop and I only want it to move to the next date.因此,运行此代码几天的 output 表明,当它运行 5 次(这是我设置的最大计数器)时,它确实中断了,但它中断了整个循环,我只希望它移动到下一个日期。

Any help will be appreciated,任何帮助将不胜感激,

You need to use a break statement to get out of a while True loop.您需要使用 break 语句来退出 while True 循环。 pass and continue work for for loops that have a fixed number of iterations.为具有固定迭代次数的循环传递并继续工作。 While loops can go on forever (hence the different names)虽然循环可以 go 永远(因此不同的名称)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM