如何停止从try / for循环代码执行pythonic方式?(How to stop code execution of for loop from try/except in a Pythonic

编程入门 行业动态 更新时间:2024-10-27 14:29:20
如何停止从try / for循环代码执行pythonic方式?(How to stop code execution of for loop from try/except in a Pythonic way?)

我有一些Python代码,如下所示:

for emailCredentials in emailCredentialsList: try: if not emailCredentials.valid: emailCredentials.refresh() except EmailCredentialRefreshError as e: emailCredentials.active = False emailCredentials.save() # HERE I WANT TO STOP THIS ITERATION OF THE FOR LOOP # SO THAT THE CODE BELOW THIS DOESN'T RUN ANYMORE. BUT HOW? # a lot more code here that scrapes the email box for interesting information

正如我已经在代码中评论过的那样,如果EmailCredentialRefreshError被抛出,我希望for循环的迭代停止并移动到EmailCredentialRefreshError中的下一个项目。 我不能使用break因为这会停止整个循环,并且不会覆盖循环中的其他项目。 当然,我可以将所有代码包装在try / except中,但我想将它们紧密放在一起,以便代码保持可读性。

什么是解决这个问题的最好的Pythonic方法?

I've got some Python code as follows:

for emailCredentials in emailCredentialsList: try: if not emailCredentials.valid: emailCredentials.refresh() except EmailCredentialRefreshError as e: emailCredentials.active = False emailCredentials.save() # HERE I WANT TO STOP THIS ITERATION OF THE FOR LOOP # SO THAT THE CODE BELOW THIS DOESN'T RUN ANYMORE. BUT HOW? # a lot more code here that scrapes the email box for interesting information

And as I already commented in the code, if the EmailCredentialRefreshError is thrown I want this iteration of the for loop to stop and move to the next item in the emailCredentialsList. I can't use a break because that would stop the whole loop and it wouldn't cover the other items in the loop. I can of course wrap all the code in the try/except, but I would like to keep them close together so that the code remains readable.

What is the most Pythonic way of solving this?

最满意答案

尝试使用continue语句。 这继续到循环的下一次迭代。

for emailCredentials in emailCredentialsList: try: if not emailCredentials.valid: emailCredentials.refresh() except EmailCredentialRefreshError as e: emailCredentials.active = False emailCredentials.save() continue <more code>

Try using the continue statement. This continues to the next iteration of the loop.

for emailCredentials in emailCredentialsList: try: if not emailCredentials.valid: emailCredentials.refresh() except EmailCredentialRefreshError as e: emailCredentials.active = False emailCredentials.save() continue <more code>

更多推荐

本文发布于:2023-07-24 13:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1246290.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   方式   pythonic   stop   Pythonic

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!