在Python中尝试直到没有错误 [英] In Python try until no error

查看:126
本文介绍了在Python中尝试直到没有错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中有一段代码,似乎会导致错误概率,因为它正在访问服务器,有时该服务器有500内部服务器错误。我想继续尝试,直到我没有得到错误。我的解决方案是:

  while True:
try:
#code with possible error
除了:
继续
其他:
#剩下的代码
break

这似乎是对我的一个黑客。有没有更多的Pythonic方式来做到这一点?

解决方案

它不会变得更清洁。这不是一件很干净的事情。最好的(因为 break 的条件是),那么这个方法更可读,您可以创建一个变量 result = None 并循环,而为无。您还应该调整变量,您可以用语义上可能正确的 pass 替换 continue (你不在乎一个错误发生,你只想忽略它),并删除 break - 这也得到剩下的代码,只执行一次,出来的循环。另外请注意,裸体除了:子句是因为

包含以上所有内容的示例:

  result = None 
while result is None:
try:
#connect
result = get_data(...)
除了:
pass
#其他使用结果的代码,但不涉及获取


I have a piece of code in Python that seems to cause an error probabilistically because it is accessing a server and sometimes that server has a 500 internal server error. I want to keep trying until I do not get the error. My solution was:

while True:
    try:
        #code with possible error
    except:
         continue
    else:
         #the rest of the code
         break

This seems like a hack to me. Is there a more Pythonic way to do this?

It won't get much cleaner. This is not a very clean thing to do. At best (which would be more readable anyway, since the condition for the break is up there with the while), you could create a variable result = None and loop while it is None. You should also adjust the variables and you can replace continue with the semantically perhaps correct pass (you don't care if an error occurs, you just want to ignore it) and drop the break - this also gets the rest of the code, which only executes once, out of the loop. Also note that bare except: clauses are evil for reasons given in the documentation.

Example incorporating all of the above:

result = None
while result is None:
    try:
        # connect
        result = get_data(...)
    except:
         pass
# other code that uses result but is not involved in getting it

这篇关于在Python中尝试直到没有错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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