[Python-ideas] Replacing the standard IO streams (was Re: changing sys.stdout encoding)

MRAB python at mrabarnett.plus.com
Sun Jun 10 20:12:55 CEST 2012


On 10/06/2012 17:41, Stephen J. Turnbull wrote:
> ^^^^^^^[[[[[[[[[@[@Nick Coghlan writes:
>   >  On Mon, Jun 11, 2012 at 12:34 AM, Serhiy Storchaka<storchaka at gmail.com>  wrote:
>
>   >  >  open(sys.stdin.fileno()) is not guaranteed to work if the input or output
>   >  >  have occurred before.
> [...]
>
>   >  Right, but the point of this discussion is to document the cleanest
>   >  available way for an application to change these settings at
>   >  *application start* (e.g. to support an "--encoding" parameter). Yes,
>   >  there are potential issues if you use any of these mechanisms while
>   >  there is data in the buffers,
>
> +1
>
> The OP's problem is a real one.  His use case (the "--encoding"
> parameter) seems to be the most likely one in production use, so the
> loss of buffered data issue should rarely come up.  Changing encodings
> on the fly offers plenty of ways to lose data besides incomplete
> buffers, anyway.
>
> I am a little concerned with MRAB's report that
>
>      import sys
>      print("hello")
>      sys.stdout.flush()
>      sys.stdout = open(sys.stdout.fileno(), 'w', encoding='utf-8')
>      print("hello")
>
> doesn't work as expected, though.  (It does work for me on Mac OS X,
> both as above -- of course there are no '\r's in the output -- and
> with 'print("hello", end="\r\n")'.)
>
That's actually Python 3.1. From Python 3.2 it's slightly different,
but still not quite right:

Python 3.1:     "hello\r\nhello\r\r\n"
Python 3.2:     "hello\nhello\r\n"
Python 3.3.0a4: "hello\nhello\r\n"

All on Windows.



More information about the Python-ideas mailing list