Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python在with关键字范围内延长变量的生存期_Python - Fatal编程技术网

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)