【问题标题】:try/except while true in a for loop在 for 循环中尝试/除外 while true
【发布时间】:2021-03-09 20:44:26
【问题描述】:

以下代码将从 API 收集数据,try/except 子句将帮助处理多个错误(来自身份验证、索引等)。 只有一个错误(身份验证错误)我正在使用while True 重复 API 调用以确保我获得数据,并且在尝试一两次后它会。但是,如果无论如何我得到另一个错误,它将无限循环并且我不能打破它,所以它会进入下一次迭代。我尝试创建一个计数器,如果计数器达到一个数字(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)

因此,运行此代码几天的输出表明,当它运行 5 次时(这是我设置的最大计数器)它确实会中断,但它会中断整个循环,我只希望它移动到下一个日期。

任何帮助将不胜感激,

【问题讨论】:

    标签: python loops exception


    【解决方案1】:

    您需要使用 break 语句来退出 while True 循环。为具有固定迭代次数的循环传递并继续工作。 While 循环可以永远持续下去(因此有不同的名称)

    【讨论】:

    • @JuanHurtado python 不应该这样。你确定你做对了吗?
    • @MichaelHofmann 你是对的。我实际上忘记再次将计数器重置为 0。这解决了一切。
    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 2022-07-21
    相关资源
    最近更新 更多