ちょっとインデントをしたくなった時に便利
context.redirect_stdoutなどの使い方の例にもなるかもしれない。
import sys import contextlib from io import StringIO @contextlib.contextmanager def indent(n): buf = StringIO() with contextlib.redirect_stdout(buf): yield buf buf.seek(0) prefix = " " * n write = sys.stdout.write for line in buf: write(prefix) write(line) sys.stdout.flush()
こういう関数を定義しておくと。以下の様に書いて。
print("a") with indent(2): print("b") with indent(2): print("c") print("d") print("e")
結果が以下のようになるので便利。
a b c d e