有没有一种pythonic的方式来尝试最多次数? [英] is there a pythonic way to try something up to a maximum number of times?

查看:128
本文介绍了有没有一种pythonic的方式来尝试最多次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python脚本,它在一个共享的linux主机上查询MySQL服务器。由于某些原因,对MySQL的查询往往返回一个服务器已经消失的错误:

  _mysql_exceptions.OperationalError:(2006, MySQL服务器已经消失了)

如果你以后再次尝试查询,它通常会成功。所以,我想知道python中是否有一个合理的方法来尝试执行一个查询,如果它失败了,再试一次,最多可以尝试一次。可能我想要尝试5次,然后放弃。



这是我有的代码:



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $



$ b尝试:
cursor.execute(query)
rows = cursor.fetchall()
行中的行:
#执行某些数据
除了MySQLdb.Error,e:
打印MySQL错误%d:%s%(e.args [0],e.args [1])$ ​​b $ b

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

解决方案

如何:

  conn = MySQLdb.connect ,用户,密码,数据库)
cursor = conn.cursor()
attempts = 0

while attempts< 3:
try:
cursor.execute(query)
rows = cursor.fetchall()
行中的行:
#用数据$ b执行某些操作$ b break
除了MySQLdb.Error,e:
尝试+ = 1
打印MySQL错误%d:%s%(e.args [0],e.args [1 ])


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.

解决方案

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

这篇关于有没有一种pythonic的方式来尝试最多次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆