How to retry something with a timeout in Python?

T

tinnews

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


How does one do this tidily in python?
 
G

Gabriel Genellina

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():
break
else:
raise RuntimeError, "Could not lock file"
do_real_work()

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

tinnews

Scott David Daniels said:
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! :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,140
Latest member
SweetcalmCBDreview
Top