How to retry something with a timeout in Python?

Gabriel Genellina gagsl-py2 at
Wed Apr 29 04:22:18 CEST 2009

En Tue, 28 Apr 2009 17:56:13 -0300, <tinnews at> escribió:

> I want to retry locking a file for a number of times and then give up,
> in pseudo-code it would be something like:-
>     for N times
>         try to lock file
>             if successful break out of for loop
>     if we don't have a lock then give up and exit
> How does one do this tidily in python?

for i in range(N):
   if try_to_lock_file():
   raise RuntimeError, "Could not lock file"

Note the indentation of the `else` clause, it belongs to the `for` loop  
and is executed only when the iteration is completely exhausted.

Gabriel Genellina

More information about the Python-list mailing list