如何从try/except以Pythonic方式停止for循环的代码执行?

2024-05-13 09:10:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些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循环的这个迭代停止并移动到emailCredentialsList中的下一个项目。我不能使用break,因为这样会停止整个循环,并且不会覆盖循环中的其他项。当然,我可以在try/except中包装所有代码,但我希望将它们紧密地放在一起,以便代码保持可读性。在

什么是最Python式的解决方法?在


Tags: the代码inforifasnotthis
1条回答
网友
1楼 · 发布于 2024-05-13 09:10:10

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

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

相关问题 更多 >