Is there a better way to implement this:

Michael Yanowitz m.yanowitz at kearfott.com
Mon Jan 22 11:53:48 EST 2007


Thanks.

   I suppose I could have used time.sleep(seconds) here.
I did it in 0.01 because in an earlier verion, I did something
else between the sleeps.
   I guess I am looking for something portable (both
Windows and Linux) where I can abort a function after
a certain time limit expires.

-----Original Message-----
From: python-list-bounces+m.yanowitz=kearfott.com at python.org
[mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf
Of Benjamin Niemann
Sent: Monday, January 22, 2007 11:19 AM
To: python-list at python.org
Subject: Re: Is there a better way to implement this:


Michael Yanowitz wrote:

> Hello:
>
>    I wrote the code below (much irrelevant code removed).
> This doesn't quite work. What I wanted it to do was
>  a) Execute function ftimed, which takes a function and a timeout
>     in seconds.
>  b) This will also execute function abort() as a thread.
>     This function just runs for the specified
>     number of seconds and returns.
>     However, before it returns, throws an exception.
> c)  If test() is still running when abort() is
>     finished, ftimed() should catch the exception and
>     return.
>
> It is catching the exception, however it continues running the function.
> Why does it continue and not return?

The exception is raised in the thread that executes the abort() function.
The exception does not get caught and terminates this thread. The other
(main) thread is unaffected - exceptions are local to a thread and there is
currently no (portable) way to raise an exception in another thread.

> What am I missing, or is there a better way to
> implement this (having ftimed() return when the
> abort-timer time is exceeded?

You may use the signal.alarm() function, if you are on a UNIXoid system and
you have only a signle time-out at a time (e.g. not nested).

> import time, thread, sys
>
> thread_finished = "MAX RUN TIME EXCEEDED!"
>
> def abort (seconds):
>      start_time = time.time()
>      while ((time.time() - start_time) < seconds):
>         time.sleep(0.01)

any reason for not using time.sleep(seconds) here?

I suppose I could have, but in earlier versions

>      print "script run time exceeded max_run_time of", seconds, "seconds."
>      raise thread_finished
>      return
>
>
> def test():
>     i = 0
>     while (True):
>        time.sleep(1)
>        print "HELLO", i
>        i+=1
>
>
> def ftimed (func, seconds):
>     thread.start_new_thread (abort, (seconds,))
>
>     try:
>         func()
>     except thread_finished:
>         print  "Timeout"
>         return
>
> ftimed (test, 30)
> print "Script finished"

--
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://pink.odahoda.de/
--
http://mail.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list