Kush
Kush

Reputation: 1522

Python loop timeout

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?

Upvotes: 1

Views: 3826

Answers (1)

Alex
Alex

Reputation: 146

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

Upvotes: 1

Related Questions