python 2.7 @contextmanager的使用

@contextmanager利用生成器来实现一个上下文, 例子如下:

# -*- coding: utf-8 -*-

from contextlib import contextmanager

@contextmanager
def get_file(path):
    f = open(path, 'w')
    try:
        yield f
    finally:
        f.close()

with get_file('1.txt') as f:
    f.write('Hello')