-
-
Save treo/728327 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from functools import wraps | |
import time | |
def retry(tries, exceptions=None, delay=0): | |
""" | |
Decorator for retrying a function if exception occurs | |
tries -- num tries | |
exceptions -- exceptions to catch | |
delay -- wait between retries | |
""" | |
exceptions_ = exceptions or (Exception, ) | |
def _retry(fn): | |
@wraps(fn) | |
def __retry(*args, **kwargs): | |
for _ in xrange(tries+1): | |
try: | |
return fn(*args, **kwargs) | |
except exceptions_, e: | |
print "Retry, exception:" + str(e) | |
time.sleep(delay) | |
#if no success after tries raise last exception | |
raise | |
return __retry | |
return _retry | |
if __name__ == '__main__': | |
@retry(1) | |
def fail(): | |
raise Exception("Oh woe is me") | |
@retry(42) | |
def no_fail(): | |
print "I work" | |
print "This will not fail" | |
no_fail() | |
print "--" | |
print "The next test is going to fail" | |
fail() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The script will produce this output when run: