是否有一种pythonic方式尝试最多次?

时间:2009-02-19 22:52:02

标签: python exception-handling

我有一个python脚本,它在共享的linux主机上查询MySQL服务器。出于某种原因,对MySQL的查询通常会返回“服务器已经消失”错误:

_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away')

如果您之后立即再次尝试查询,则通常会成功。所以,我想知道在python中是否有一种合理的方法来尝试执行查询,如果它失败了,再试一次,最多可以尝试一定数量的查询。可能我希望它在放弃之前尝试5次。

以下是我的代码类型:

conn = MySQLdb.connect(host, user, password, database)
cursor = conn.cursor()

try:
    cursor.execute(query)
    rows = cursor.fetchall()
    for row in rows:
        # do something with the data
except MySQLdb.Error, e:
    print "MySQL Error %d: %s" % (e.args[0], e.args[1])

显然,我可以通过在except子句中再次尝试来做到这一点,但这非常难看,我觉得必须有一个体面的方法来实现这一点。

10 个答案:

答案 0 :(得分:80)

怎么样:

conn = MySQLdb.connect(host, user, password, database)
cursor = conn.cursor()
attempts = 0

while attempts < 3:
    try:
        cursor.execute(query)
        rows = cursor.fetchall()
        for row in rows:
            # do something with the data
        break
    except MySQLdb.Error, e:
        attempts += 1
        print "MySQL Error %d: %s" % (e.args[0], e.args[1])

答案 1 :(得分:74)

根据Dana的回答,您可能希望以装饰者的身份来做这件事:

def retry(howmany):
    def tryIt(func):
        def f():
            attempts = 0
            while attempts < howmany:
                try:
                    return func()
                except:
                    attempts += 1
        return f
    return tryIt

则...

@retry(5)
def the_db_func():
    # [...]

使用decorator模块

的增强版
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

则...

@retry(5, MySQLdb.Error, timeout=0.5)
def the_db_func():
    # [...]

安装the decorator module

$ easy_install decorator

答案 2 :(得分:11)

更新:有一个名为tenacity的重试库的更好维护分支,它支持更多功能,并且通常更灵活。

是的,有retrying library,它有一个装饰器,可以实现几种可以组合的重试逻辑:

一些例子:

@retry(stop_max_attempt_number=7)
def stop_after_7_attempts():
    print "Stopping after 7 attempts"

@retry(wait_fixed=2000)
def wait_2_s():
    print "Wait 2 second between retries"

@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000)
def wait_exponential_1000():
    print "Wait 2^x * 1000 milliseconds between each retry,"
    print "up to 10 seconds, then 10 seconds afterwards"

答案 3 :(得分:7)

conn = MySQLdb.connect(host, user, password, database)
cursor = conn.cursor()

for i in range(3):
    try:
        cursor.execute(query)
        rows = cursor.fetchall()
        for row in rows:
            # do something with the data
        break
    except MySQLdb.Error, e:
        print "MySQL Error %d: %s" % (e.args[0], e.args[1])

答案 4 :(得分:6)

我会像这样重构它:

def callee(cursor):
    cursor.execute(query)
    rows = cursor.fetchall()
    for row in rows:
        # do something with the data

def caller(attempt_count=3, wait_interval=20):
    """:param wait_interval: In seconds."""
    conn = MySQLdb.connect(host, user, password, database)
    cursor = conn.cursor()
    for attempt_number in range(attempt_count):
        try:
            callee(cursor)
        except MySQLdb.Error, e:
            logging.warn("MySQL Error %d: %s", e.args[0], e.args[1])
            time.sleep(wait_interval)
        else:
            break

分解callee函数似乎打破了功能,因此很容易看到业务逻辑而不会陷入重试代码中。

答案 5 :(得分:6)

像S.Lott一样,我喜欢用旗帜来检查我们是否已经完成:

conn = MySQLdb.connect(host, user, password, database)
cursor = conn.cursor()

success = False
attempts = 0

while attempts < 3 and not success:
    try:
        cursor.execute(query)
        rows = cursor.fetchall()
        for row in rows:
            # do something with the data
        success = True 
    except MySQLdb.Error, e:
        print "MySQL Error %d: %s" % (e.args[0], e.args[1])
        attempts += 1

答案 6 :(得分:1)

def successful_transaction(transaction):
    try:
        transaction()
        return True
    except SQL...:
        return False

succeeded = any(successful_transaction(transaction)
                for transaction in repeat(transaction, 3))

答案 7 :(得分:1)

1.定义:

def try_three_times(express):
    att = 0
    while att < 3:
        try: return express()
        except: att += 1
    else: return u"FAILED"

2.词汇使用:

try_three_times(lambda: do_some_function_or_express())

我将它用于解析html上下文。

答案 8 :(得分:0)

这是我的通用解决方案:

class TryTimes(object):
    ''' A context-managed coroutine that returns True until a number of tries have been reached. '''

    def __init__(self, times):
        ''' times: Number of retries before failing. '''
        self.times = times
        self.count = 0

    def __next__(self):
        ''' A generator expression that counts up to times. '''
        while self.count < self.times:
            self.count += 1
        yield False

    def __call__(self, *args, **kwargs):
        ''' This allows "o() calls for "o = TryTimes(3)". '''
        return self.__next__().next()

    def __enter__(self):
        ''' Context manager entry, bound to t in "with TryTimes(3) as t" '''
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        ''' Context manager exit. '''
        return False # don't suppress exception

这允许以下代码:

with TryTimes(3) as t:
    while t():
        print "Your code to try several times"

也可能:

t = TryTimes(3)
while t():
    print "Your code to try several times"

我希望通过以更直观的方式处理异常来改善这一点。接受建议。

答案 9 :(得分:0)

您可以将for循环与else子句一起使用以达到最大效果:

conn = MySQLdb.connect(host, user, password, database)
cursor = conn.cursor()

for n in range(3):
    try:
        cursor.execute(query)
    except MySQLdb.Error, e:
        print "MySQL Error %d: %s" % (e.args[0], e.args[1])
    else:
        rows = cursor.fetchall()
        for row in rows:
            # do something with the data
        break
else:
    # All attempts failed, raise a real error or whatever

关键是查询成功后立即跳出循环。只有在没有else的循环完成时,break子句才会被触发。