Skip to content

Instantly share code, notes, and snippets.

@jab
Forked from xhjkl/indent.py
Created September 28, 2020 18:46
Show Gist options
  • Save jab/bac1d7991493f49d99e41d2c2db177fd to your computer and use it in GitHub Desktop.
Save jab/bac1d7991493f49d99e41d2c2db177fd 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