1

I have a Python script that looks something like this:

for x in range(1000,40000):
    try:
       some_function(x)
       some_other_function(x)
    except Exception, e:
       print e
       pass

I know this is not good practice to handle errors like this but this is a script I'm only going to use once. Anyway, I noticed that the loop sometimes gets stuck on one particular id (x) and freezes for a few hours.

So my question is: How would I implement a timeout function in the loop so that if it takes more than 20 seconds then skip onto the next one?

5
  • 1
    Thread it, I think it's the best way for implementing a timeout. Commented Jul 12, 2012 at 16:21
  • Possible duplicate stackoverflow.com/q/11403275/748858 Commented Jul 12, 2012 at 16:22
  • @mgilson - Windows 7. I looked at that thread but I'm not sure how to implement it. This is my first Python script so I'm an amateur (I'm a C++ programmer) Commented Jul 12, 2012 at 16:25
  • @DopeMonk You're right. This is a different question. The other question wanted to exit the program, you just want to exit the loop. Commented Jul 12, 2012 at 16:31
  • I'd recommend figuring out why the function gets stuck and solving that problem at as low a level as practical, rather than band-aiding it with a timeout. Commented Jul 12, 2012 at 18:00

1 Answer 1

1

You can define it as a TimeoutException

except TimeoutException, e:
print e
pass

If you want it to go for only 20 seconds I'd suggest looking up creating signal handlers in python. Heres an example and a link to the python documentation for it. https://docs.python.org/library/signal.html

https://web.archive.org/web/20130511171949/http://pguides.net/python-tutorial/python-timeout-a-function/

Since you're on Windows, you might want to look at this older thread python: windows equivalent of SIGALRM

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

3 Comments

I don't think signals will work on Windows since there's no SIGALRM
I've already done except Exception, e: should that not handle all of the exceptions? The loop freezes for a few hours and no errors are printed it just starts again
Yes, I see if you had this running on Linux you could use SIGALRM to time you out in 20 seconds. However, you have Windows, so you will have to use threading. See my link to python: windows equivalent... it shows how to write a similar function to run on both OS.

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.