假设我有使用with关键字打开文件的代码,并且我希望它在某些情况下关闭后保持打开状态。

所以假设最简单的功能:

def do_sth():
  with open('/tmp/foobar') as f:
    # do anything to stop f from closing


有没有一种方法可以绕过python解释器调用f.__exit__()
您可以假定,这应该适用于实现__enter____exit__的任何类。

到目前为止,我试图用另一个可关闭的对象替换f,如下所示:

d = open('/tmp/bsdf')
with open('/tmp/asdf') as f:
    d,f = f,d
print "f {}, d {}".format(f.closed, d.closed)


一个潜在的用例是创建一个包装器,以便您可以执行以下操作:

with filehandle('foobar') as f:
  # do something

# don't close if filehandle returns sys.stdout.

最佳答案

阅读pep-0343之后,我得出结论,这不应该是语义的一部分。

我发现的唯一选择是编写自己的执行条件释放的上下文管理器。

from contextlib import contextmanager
import sys

@contextmanager
def custom_open(filename, mode='r'):
    if filename is 'stdout':
        yield sys.stdout
    else:
        try:
            f = open(filename, mode)
        except IOError, err:
            yield None
        else:
            try:
                yield f
            finally:
                f.close()


with custom_open('stdout') as f:
    f.write('hello world\n')
print "f {}".format(f.closed)

with custom_open('/tmp/foobar', 'w+') as f:
    f.write('hello world\n')
print "f {}".format(f.closed)

09-16 08:54