On Fri, Jan 6, 2017 at 1:06 AM, H Krishnan <hetch...@gmail.com> wrote: > I tried replacing sys.displayhook with a function that does not print > newline but the newline still got inserted. So, I am not sure where the > newline is coming from. In any case, I could override sys.displayhook to add > a newline at the end and that seems to resolve my problem.
In Python 2 the newline is written depending on the value of sys.stdout.softspace. sys.displayhook initially calls Py_FlushLine, which resets the file's softspace to 0 via PyFile_SoftSpace and writes a newline if the previous value was non-zero. Next displayhook writes the repr, sets the softspace to 1 and calls Py_FlushLine again. The result you're seeing could occur if your filelike object doesn't have a dict or a property to allow setting the "softspace" attribute, as the following toy example demonstrates: import sys class File(object): def __init__(self, file): self._file = file self._sp_enabled = True self.softspace = 0 def write(self, string): return self._file.write(string) def __getattribute__(self, name): value = object.__getattribute__(self, name) if name == 'softspace': if not self._sp_enabled: raise AttributeError self._file.write('[get softspace <- %d]\n' % value) return value def __setattr__(self, name, value): if name == 'softspace': if not self._sp_enabled: raise AttributeError self._file.write('[set softspace -> %d]\n' % value) object.__setattr__(self, name, value) softspace enabled: >>> sys.stdout = File(sys.stdout) [set softspace -> 0] [get softspace <- 0] [set softspace -> 0] >>> 42 [get softspace <- 0] [set softspace -> 0] 42[get softspace <- 0] [set softspace -> 1] [get softspace <- 1] [set softspace -> 0] [get softspace <- 0] [set softspace -> 0] softspace disabled: >>> sys.stdout._sp_enabled = False >>> 42 42>>> 42 42>>> -- https://mail.python.org/mailman/listinfo/python-list