Forcing prompt to be on newline when embedding Python with stdin/out redirection

H Krishnan hetchkay at gmail.com
Fri Jan 6 04:40:18 EST 2017


Hello Mr.Eryk,

Thanks for the detailed explanation. After I added attribute support to my
extension class for stdio, the problem was resolved.

Regards,
Krishnan


On Fri, Jan 6, 2017 at 9:24 AM, eryk sun <eryksun at gmail.com> wrote:

> On Fri, Jan 6, 2017 at 1:06 AM, H Krishnan <hetchkay at 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
>


More information about the Python-list mailing list