Skip to content

Instantly share code, notes, and snippets.

@martijnvermaat
Created November 23, 2011 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martijnvermaat/1388680 to your computer and use it in GitHub Desktop.
Save martijnvermaat/1388680 to your computer and use it in GitHub Desktop.
Try something a predefined number of times
#!/usr/bin/env python
"""
Example Python pattern: try something a number of times, and only really fail
after that.
"""
import sys
import time
NUM_FAILS = int(sys.argv[1])
NUM_TRIES = int(sys.argv[2])
RETRY_SLEEP = 1
def some_computation(i):
if i < NUM_FAILS:
raise Exception('Computation failed')
return i
result = None
for i in range(NUM_TRIES - 1):
try:
result = some_computation(i)
break
except Exception:
time.sleep(RETRY_SLEEP)
else:
try:
result = some_computation(NUM_TRIES)
except Exception as e:
print e
sys.exit(1)
print 'The result is %d' % result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment