Search code examples
pythonexception

is there a pythonic way to try something up to a maximum number of times?


I have a python script which is querying a MySQL server on a shared linux host. For some reason, queries to MySQL often return a "server has gone away" error:

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

If you try the query again immediately afterwards, it usually succeeds. So, I'd like to know if there's a sensible way in python to try to execute a query, and if it fails, to try again, up to a fixed number of tries. Probably I'd want it to try 5 times before giving up altogether.

Here's the kind of code I have:

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])

Clearly I could do it by having another attempt in the except clause, but that's incredibly ugly, and I have a feeling there must be a decent way to achieve this.


Solution

  • How about:

    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])