contextlibの使い方
ipynbFile contextlib__contextlibの使い方.ipynb
| contextmanagerはデコレーターを with を使用して書けるようにできるしろもの。
|
In [1]:
| from contextlib import contextmanager
|
In [7]:
| @contextmanager
def sample(*args,**kwargs):
print('start')
yield
print('end')
|
In [8]:
| with sample() as f:
print("hoge")
|
In [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]:
| # 指定パス以下にテキストを書き出す
with _Stream("D:/sample.txt",'w') as f:
_Print(f,'sample')
|
In [14]:
| with _Stream("-") as f:
_Print(f,"hoge")
_Print(f,"Hello World!!")
|