ls0f / my-issues

0 stars 0 forks source link

Python中的上下文管理器 #12

Open ls0f opened 8 years ago

ls0f commented 8 years ago

当打开文件的时候,我习惯这样写:

with open(file) as f:
    ....

这样就不用显示调用close方法去关闭fd。

with ... as就使用了Python的上下文管理器,当所属的程序块执行结束的时候上下文管理器自动关闭了文件。那它是怎么做到的呢?看下面这段代码:

class MyOpen(object):
    def __init__(self, filename):
        self.f = open(filename, 'rb')

    def __enter__(self):
        return self.f

    def __exit__(self,exc_type,exc_value,traceback):
        self.f.close()

with MyOpen('/tmp/test') as f:
    print f.read()

print f

下面是输出:

Hello,World

<closed file '/tmp/test', mode 'rb' at 0x10167a270>

其实就是类似于下面的代码:

try:
    f = MyOpen('/tmp/test').__enter__()
    print f.read()
finally:
    f.close()
print f

使用with ... as明显能简化代码。