<p>基于Dana的回答,您可能希望作为一名装饰师:</p>
<pre><code>def retry(howmany):
def tryIt(func):
def f():
attempts = 0
while attempts < howmany:
try:
return func()
except:
attempts += 1
return f
return tryIt
</code></pre>
<p>然后。。。</p>
<pre><code>@retry(5)
def the_db_func():
# [...]
</code></pre>
<h3>使用<code>decorator</code>模块</h3>的增强版本
<pre><code>import decorator, time
def retry(howmany, *exception_types, **kwargs):
timeout = kwargs.get('timeout', 0.0) # seconds
@decorator.decorator
def tryIt(func, *fargs, **fkwargs):
for _ in xrange(howmany):
try: return func(*fargs, **fkwargs)
except exception_types or Exception:
if timeout is not None: time.sleep(timeout)
return tryIt
</code></pre>
<p>然后。。。</p>
<pre><code>@retry(5, MySQLdb.Error, timeout=0.5)
def the_db_func():
# [...]
</code></pre>
<p>要安装<a href="http://pypi.python.org/pypi/decorator" rel="noreferrer">the ^{<cd1>} module</a>:</p>
<pre><code>$ easy_install decorator
</code></pre>