Python在with关键字的作用域中延长变量的生存期



假设我有用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 worldn')
print "f {}".format(f.closed)
with custom_open('/tmp/foobar', 'w+') as f:
    f.write('hello worldn')
print "f {}".format(f.closed)

最新更新