你可以从上下文管理器中“破解”吗?

时间:2016-08-06 14:17:19

标签: python control-flow contextmanager

是否有任何模式允许您退出Context Manager并将控制流返回到with (...):之后的代码?

例如(实际上不起作用):

with open('/etc/passwd', 'r') as f:
    f.seek(0, 2)
    if f.tell() < 10:
        print "The file is too small!"
        break

    # Process the file.

我可以用break取代同样的东西吗?

1 个答案:

答案 0 :(得分:1)

它看起来不像你可以从with退出,但是你可以将它包装在一个循环中以便你可以退出 - 例如像这样

for _ in [0]:
    with open('/etc/passwd', 'r') as f:
        f.seek(0, 2)
        if f.tell() < 10:
            print "The file is too small!"
            break

但可以使用异常(如评论中提到的)或包含在函数中return(我更希望return ing)更自然。