[Python-ideas] changing sys.stdout encoding

Nathan Schneider nathan at cmu.edu
Fri Jun 8 02:59:31 CEST 2012


On Thu, Jun 7, 2012 at 5:14 PM, Rurpy <rurpy at yahoo.com> wrote:
> On 06/07/2012 03:45 PM, Nick Coghlan wrote:
>> The interpreter uses the standard streams internally, and
>> they're one of the first things created during interpreter
>> startup. User provided code doesn't start running until well
>> after they're initialised.
>
> In other words, the stream objects referenced by sys.std*
> are opened before the user code runs?
>
> But if there are no operations on those streams until my
> user code runs, they are still in the same state they were
> after they were initialized, yes?
>
> So if one wanted to provide an "only before first use"
> set_encoding() function, why couldn't that function reexecute
> the codecs part of the initialization code a second time?
> Of course there would need to be some sort of flag that it
> could use to verify the stream was still in its initial state.
>
>> If user level code doesn't want those streams, it needs to
>> replace them with something else.
>
> Yes, this is what the code I googled up does:
>  import codecs
>  sys.stdout = codecs.getwriter(opts.encoding)(sys.stdout.buffer)

What if codecs contained convenience methods for stdin and stdout?
I.e. the above could be written more simply as

  import codecs
  codecs.encode_stdout(opts.encoding)

This is much more memorable than the current option, and would also
make life easier when working with fileinput (whose openhook argument
can be set to control encoding of input *file* streams, but when it
falls back to stdin this preference is ignored).

> But that code is not obvious to someone who has been able to do
> all his encoded IO (with the exception of sys.stdout) using just
> the encoding parameter of open().  Hence my question if some-
> thing like a set_encoding() method/function that would work on
> sys.stdout is feasible.  I don't see an answer to that in your
> statement above.
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas



More information about the Python-ideas mailing list