[英]try/except while true in a for loop
以下代碼將從 API 收集數據,try/except 子句將幫助處理幾個錯誤(來自身份驗證、索引等)。 只有一個錯誤(身份驗證錯誤)我正在使用while True
來重復 API 調用以確保我得到數據,並且在一兩次嘗試后它會。 但是,如果無論如何我得到另一個錯誤,它將無限循環並且我不能打破它,所以它會進入下一次迭代。 我試圖創建一個計數器,如果計數器達到一個數字( pass
或continue
或break
)但它不起作用。
## 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)
因此,運行此代碼幾天的 output 表明,當它運行 5 次(這是我設置的最大計數器)時,它確實中斷了,但它中斷了整個循環,我只希望它移動到下一個日期。
任何幫助將不勝感激,
您需要使用 break 語句來退出 while True 循環。 為具有固定迭代次數的循環傳遞並繼續工作。 雖然循環可以 go 永遠(因此不同的名稱)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.