本文介绍了突破或退出“with"陈述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在某些条件下退出 with 语句:

I'd just like to exit out of a with statement under certain conditions:

with open(path) as f:
    print 'before condition'
    if <condition>: break #syntax error!
    print 'after condition'

当然,以上是行不通的.有没有办法做到这一点?(我知道我可以反转条件:if not <condition>: print 'after condition' - 有没有像上面那样的方式?)

Of course, the above doesn't work. Is there a way to do this? (I know that I can invert the condition: if not <condition>: print 'after condition' -- any way that is like above?)

推荐答案

最好的方法是将其封装在一个函数中并使用return:

The best way would be to encapsulate it in a function and use return:

def do_it():
    with open(path) as f:
        print 'before condition'
        if <condition>:
            return
        print 'after condition'

这篇关于突破或退出“with"陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 04:54