在Python中尝试直到没有错误 [英] In Python try until no error
问题描述
while True:
try:
#code with possible error
除了:
继续
其他:
#剩下的代码
break
这似乎是对我的一个黑客。有没有更多的Pythonic方式来做到这一点?
它不会变得更清洁。这不是一件很干净的事情。最好的(因为 包含以上所有内容的示例: 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: 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 Example incorporating all of the above:
这篇关于在Python中尝试直到没有错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! break
的条件是而
),那么这个方法更可读,您可以创建一个变量 result = None
并循环,而为无
。您还应该调整变量,您可以用语义上可能正确的 pass
替换 continue
(你不在乎一个错误发生,你只想忽略它),并删除 break
- 这也得到剩下的代码,只执行一次,出来的循环。另外请注意,裸体除了:
子句是因为
result = None
while result is None:
try:
#connect
result = get_data(...)
除了:
pass
#其他使用结果的代码,但不涉及获取
while True:
try:
#code with possible error
except:
continue
else:
#the rest of the code
break
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.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