title: is there a pythonic way to try something up to a maximum number of times?
body: <p>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:</p>
  
  <pre><code>_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away')
  </code></pre>
  
  <p>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.</p>
  
  <p>Here's the kind of code I have:</p>
  
  <pre><code>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])
  </code></pre>
  
  <p>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.</p>