I want to prevent a stall in my for loop.
import datetime as dt
shopping_list = ['eggs','milk','bread']
def buy_item(item):
connect_to_website()
send_order_instruction(item)
disconnect()
for i in range(0,len(shopping_list)):
item = shopping_list[i]
time_elapsed = 0
start_time = dt.datetime.now()
while time_elapsed < 60:
buy_item(item)
check_time = dt.datetime.now()
time_elapsed = check_time - start_time
buy_item() logs onto a website and goes through a buying procedure. But sometime it would get stuck on an item because of internet connection, item not found, website down temporarily for split second, or some other reasons. And the function simply stalls. I tried using a while loop, but that didn't work. How do I make the loop skip over an item if it stalls for more than 1 minute? Is it even possible to make the loop skip over a buy_item for a particular item? Would a try and except be appropriate in this situation? Just thinking out loud. Thank you for your help. I really appreciate it.
buy_itemmethod should take a timeout argument and/or raise appropriate errors (ItemNotFound, ConnectionError) which you can catch. Maybe you want to show us yourbuy_itemcode?