0

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?

Kush
  • 1,332
  • 2
  • 15
  • 32
  • 1
    Thread it, I think it's the best way for implementing a timeout. – Maresh Jul 12 '12 at 16:21
  • Possible duplicate http://stackoverflow.com/q/11403275/748858 – mgilson Jul 12 '12 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) – Kush Jul 12 '12 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. – mgilson Jul 12 '12 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. – Russell Borogove Jul 12 '12 at 18:00

1 Answers1

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

Community
  • 1
  • 1
Alex
  • 146
  • 6
  • I don't think signals will work on Windows since there's no `SIGALRM` – mgilson Jul 12 '12 at 16:28
  • 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 – Kush Jul 12 '12 at 16:38
  • 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. – Alex Jul 12 '12 at 16:41