program timeout in windows for python
Question: Hi I've seen a bunch of questions here on SE that deal with similar issues but
I find much of the answers to be unclear and confusing. My question is very
simple. How on a Windows platform can I kill a running function after a
certain amount of time using Python v2.6? If I have:

    
    
    def my_function(start):
        x=start
        while True:
            print x
            x=x+1
        return x
    

how can I have this stop after X seconds? Please keep your answers clear about
where to put in my function and how to adjust the time limit. Thanks


Answer: If you just want to run a normal function with a timeout, try:

    
    
    from datetime import timedelta, datetime
    from time import sleep
    
    endtime = datetime.utcnow() + timedelta(seconds = 2)
    
    while True:
        sleep(1) # just an example
        if datetime.utcnow() > endtime: # if more than two seconds has elapsed
            break
    

If you're talking about stopping a thread, there is a blog post about doing
this with threads which covers all the bases.

[How (not) to set a timeout on a computation in
Python](http://eli.thegreenplace.net/2011/08/22/how-not-to-set-a-timeout-on-a-
computation-in-python/). The [author](http://stackoverflow.com/users/8206/eli-
bendersky) also uses this site.

Basically, the answer is that there is no "right way" to do this in Python,
though if you're not on Windows `SIGALARM` works.

