add an indent to a stream
Dave Brueck
dave at pythonapocrypha.com
Mon Mar 10 11:55:26 EST 2003
On Mon, 10 Mar 2003, Manuel M Garcia wrote:
> I often need to add an indent to a stream, usually so the output of
> pprint or traceback is indented so I can tell debugging output from my
> program's actual output.
>
> Below is a class to help do this. I think I got the details right.
> The 'print' statement, when used with commas, is more complicated than
> I thought.
>
> What is the exact rule for when the 'print' command inserts a space
> because of a comma? I guess it has something to do with the attribute
> 'softspace'.
Does the stream indenter have to worry about this? It's external to the
indenter, I think.
> class IndentStream:
> """Stream with indent at start of each line.
>
> Indent can be a string or
> the number of spaces you wish to indent.
>
> """
>
> def __init__(self, indent=' ', stream=None):
> if stream is None:
> self._stream = sys.stdout
> else:
> self._stream = stream
> try:
> indent = ' ' * indent
> except TypeError:
> pass
> self._indent = indent
> self._nl_indent = '\n' + indent
> self._indent_size = len(indent)
> self._comma = 0
> self.softspace = 0
>
> def write(self, s):
> comma = not s.endswith('\n')
> s = s.replace('\n', self._nl_indent)
> if not self._comma: s = self._indent + s
> if s.endswith(self._nl_indent): s = s[:-self._indent_size]
> self._stream.write(s)
> self._comma = comma
Doesn't the above behave the same as:
class IndentStream:
def __init__(self, indent=' ', stream=sys.stdout):
self.stream = stream
stream.write(indent)
self.indent = indent
def write(self, s):
self.stream.write(s.replace('\n', '\n' + self.indent))
??
-Dave
More information about the Python-list
mailing list