0

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.

2
  • 1
    You are looking for asynchronous programming here. In ideal world your buy_item method should take a timeout argument and/or raise appropriate errors (ItemNotFound, ConnectionError) which you can catch. Maybe you want to show us your buy_item code? Commented Mar 27, 2014 at 4:01
  • In particular, have a look at the Python Decorator Library, which amongst other things, contains decorators for function retry, timeout, etc. This might be a good starting point. Commented Mar 27, 2014 at 8:14

2 Answers 2

1
import threading

thread = threading.Thread(target=buy_item, args=(item,))
thread.start()

This will do async call to buy_item, you can do sys.exit() inside thread or can wait for thread to finish by using thread.join()

Better look for threading module or multiprocess module in python for async calls.

Sign up to request clarification or add additional context in comments.

Comments

0

You don't need to code this yourself. It should be built into whatever software you use to handle HTTP requests.

For example, the requests library lets you configure this as an additional parameter to the get() method. The old urllib2 library also has a timeout parameter. Any good HTTP client library or software will have this feature; if yours doesn't, look harder or find another piece of software.

You are likely to need a try/except to handle timeouts thrown from your HTTP software.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.