有没有一种pythonic的方法可以尝试最大次数的尝试?
我有一个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子句中进行另一次尝试来做到这一点,但这非常丑陋,而且我觉得必须有一种不错的方法来实现这一目标。
-
怎么样:
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])