Skip to content

contextlibの使い方

ipynbFile contextlib__contextlibの使い方.ipynb

1
contextmanagerはデコレーターを with を使用して書けるようにできるしろもの

In [1]:

1
from contextlib import contextmanager

In [7]:

1
2
3
4
5
@contextmanager
def sample(*args,**kwargs):
    print('start')
    yield
    print('end')

In [8]:

1
2
with sample() as f:
    print("hoge")

Success

1
2
3
start
hoge
end

In [10]:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@contextmanager
def _Stream(path, *args, **kwargs):
    if path == '-':
        yield sys.stdout
    else:
        with open(path, *args, **kwargs) as fp:
            yield fp

def _Print(stream, msg):
    print(msg, file=stream)

In [12]:

1
2
3
# 指定パス以下にテキストを書き出す
with _Stream("D:/sample.txt",'w') as f:
    _Print(f,'sample')

Success

1
hoge

In [14]:

1
2
3
with _Stream("-") as f:
    _Print(f,"hoge")
    _Print(f,"Hello World!!")

Success

1
2
hoge
Hello World!!