How to retry something with a timeout in Python?
tinnews at isbd.co.uk
tinnews at isbd.co.uk
Wed Apr 29 04:41:27 EDT 2009
Scott David Daniels <Scott.Daniels at acm.org> wrote:
> tinnews at isbd.co.uk wrote:
> > This feels like it should be simple but I can't see a clean way of
> > doing it at the moment.
> >
> > 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
>
> for attempt in range(N):
> try:
> lock_file_with_timeout(per_try) # change to what you mean
> except LockAttemptFailure: # or however the failure is shown
> pass # here the attempt+1th try failed.
> else:
> break # success -- have the lock
> else:
> raise ImTiredError # however you handle N attempts w/o success
> <rest_of_code>
>
Ah, yes, it's the 'else:' with the 'for' that makes it easier, I've
come from languages which don't have that, thank you! :-)
> Often it is easiest to stick it in a function:
>
> def retry_lock(tries=3, wait_per_attempt=.5):
> for attempt in range(tries):
> try:
> # change following to whatever you do to attempt a lock.
> lock_file_with_timeout(wait_per_attempt)
> except LockAttemptFailure: # or however the failure is shown
> pass # here the attempt+1th try failed.
> else:
> return # success -- have the lock
> raise ImTiredError
>
> --Scott David Daniels
> Scott.Daniels at Acm.Org
--
Chris Green
More information about the Python-list
mailing list