forked from tam7t/photograbber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
repeater.py
executable file
·107 lines (88 loc) · 2.81 KB
/
repeater.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Ourbunny
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import time
log = logging.getLogger('pg.%s' % __name__)
class DoNotRepeatError(Exception):
"""Raise DoNotRepeatError in a function to force repeat() to exit."""
def __init__(self, error):
Exception.__init__(self, error.message)
self.error = error
class PauseRepeatError(Exception):
"""Raise PauseRepeatError in a function to delay repeating for a set number
of seconds."""
def __init__(self, error, delay):
Exception.__init__(self, error.message)
self.error = error
self.delay = delay
def repeat(func, n=5, standoff=1.5):
"""Execute a function repeatedly until success (no exceptions raised).
Args:
func (function): The function to repeat
Kwargs:
n (int): The number of times to repeate `func` before raising an error
standoff (float): Multiplier increment to wait between retrying `func`
>>>import repeater.repeat
>>>@repeater.repeat
>>>def fail():
>>> print 'A'
>>> raise Exception()
>>> print 'B'
>>>@repeater.repeat
>>>def pass():
>>> print 'B'
>>>@repeater.repeat
>>>def failpass():
>>> print 'C'
>>> raise repeater.DoNotRepeatError(Exception())
>>> print 'D'
>>>fail() # prints 'A' 10 times, failing each time
A
A
A
A
A
A
A
A
A
A
>>>pass() # prints 'B' once, succeeding on first try
B
>>>failpass() # prints 'C' once, then fails
C
"""
def wrapped(*args, **kwargs):
retries = 0
while True:
try:
return func(*args, **kwargs)
except DoNotRepeatError as e:
# raise the exception that caused funciton failure
raise e.error
except PauseRepeatError as e:
log.exception(e)
time.sleep(e.delay)
retries += 1
except Exception as e:
log.exception(e)
if retries < n:
retries += 1
time.sleep(retries * standoff)
else:
raise
return wrapped