Skip to content

Instantly share code, notes, and snippets.

@xhjkl
Created July 19, 2015 03:46
Show Gist options
  • Save xhjkl/f195a195da1c09d85d40 to your computer and use it in GitHub Desktop.
Save xhjkl/f195a195da1c09d85d40 to your computer and use it in GitHub Desktop.
Indentation context manager
import sys
import functools
import contextlib
@contextlib.contextmanager
def indented_output(indent=4, space=chr(32)):
""" Precede each carriage return with some quantity of spaces.
While nesting `indented_output` contexts, be prepared
that if a line does not begin with a line feed character,
it shall print with unchanged indentation.
To keep the indentation as expected,
print last line feed character of a parent block
in the beginning of a child block.
"""
try:
original_stderr_write = sys.stderr.write
original_stdout_write = sys.stdout.write
def write_indented(write_call, data):
write_call.__call__(
data.replace('\n', '\n' + (space * indent)))
sys.stderr.write = functools.partial(
write_indented, original_stderr_write)
sys.stdout.write = functools.partial(
write_indented, original_stdout_write)
yield
finally:
sys.stderr.write = original_stderr_write
sys.stdout.write = original_stdout_write
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment