Python在with关键字范围内延长变量的生存期
假设我的代码打开一个带有Python在with关键字范围内延长变量的生存期,python,Python,假设我的代码打开一个带有和关键字的文件,并且我希望它在特定条件下关闭后保持打开状态 假设最简单的函数: def do_sth(): with open('/tmp/foobar') as f: # do anything to stop f from closing 有没有办法绕过python解释器来调用f.\uuuu exit\uuu()? 您可以假设,这应该适用于任何实现\uuuuuuuuuuuuuuuuuuuu和\uuuuuuuuuuuuuu的类 到目前为止,我尝试用另一个可
和
关键字的文件,并且我希望它在特定条件下关闭后保持打开状态
假设最简单的函数:
def do_sth():
with open('/tmp/foobar') as f:
# do anything to stop f from closing
有没有办法绕过python解释器来调用f.\uuuu exit\uuu()
?
您可以假设,这应该适用于任何实现\uuuuuuuuuuuuuuuuuuuu
和\uuuuuuuuuuuuuu
的类
到目前为止,我尝试用另一个可关闭对象替换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.
阅读之后,我得出结论,这不应该是语义学的一部分
我找到的唯一选择是编写自己的上下文管理器,它执行有条件的发布
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)