How to let a loop run for a while before checking for break condition?
Claudio Grondi
claudio.grondi at freenet.de
Sun Aug 27 10:16:54 EDT 2006
Fredrik Lundh wrote:
> Diez B. Roggisch wrote:
>
>> A while loop has a condition. period. The only thing to change that is
>> to introduce a uncoditioned loop, and use self-modifying code to make
>> it a while-loop after that timer interrupt of yours.
>
>
> or use a timer interrupt to interrupt the loop:
>
> import signal, time
>
> def func1(timeout):
>
> def callback(signum, frame):
> raise EOFError # could use a custom exception instead
> signal.signal(signal.SIGALRM, callback)
> signal.alarm(timeout)
>
> count = 0
> try:
> while 1:
> count += 1
> except EOFError:
> for i in range(10):
> count += 1
> print count
>
> for an utterly trivial task like the one in that example, the alarm
> version runs about five times faster than a polling version, on my test
> machine (ymmv):
>
> def func2(timeout):
>
> gettime = time.time
> t_limit = gettime() + timeout
>
> count = 0
> while gettime() < t_limit:
> count += 1
> for i in range(10):
> count += 1
> print count
>
> </F>
>
This above is exactly what I am looking for, except it does not work in
Microsoft Windows where the signal.alarm() function is not available.
So now the only thing I would like to know is how to achieve the same
functionality when running Python on a Microsoft Windows box.
Claudio Grondi
More information about the Python-list
mailing list