I have a loop that runs the following code every 5 minutes, the code actually downloads a timeseries of stockprices. Sometimes, maybe once a week I get the following error:
Traceback (most recent call last):
File "./regression_12_5min.py", line 284, in <module>
last_price_long = listone[(len(listone)-1)][4]
IndexError: list index out of range
I guess, but not sure about that... that this happens because in that occasion I don't receive any don't receive any data from the broker.
This is the code:
try:
r = requests.get(myurl, params=price_long)
except:
pprint("Si e' verificato un errore")
else:
print "cwlong5"
pprint(r.status_code)
print(r.headers['content-type'])
pprint(r.url)
listone = crea_lista(r)
last_price_long = listone[(len(listone)-1)][4]
print " ultimo prezzo long" + " " + str(last_price_long)
Is my idea about the cause of the error correct? Is there a way to bypass this error? The problem is that the raised error blocks the loop, but I would be just ok if instead of bloking itself the loop start again after other 5 minutes
Thanks
答案 0 :(得分:4)
First of all, you need to check that your response.status_code
is equal to 20X to ensure that you have a successful request. Secondly you should always check if the list is not empty before fetching value from it to avoid index error. With that said you could always catch index error like this
try:
last_price_long = listone[-1][4]
except IndexError:
last_price_long = None