是否有任何模式允许您退出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
取代同样的东西吗?
答案 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)更自然。