[Python-ideas] changing sys.stdout encoding

Rurpy rurpy at yahoo.com
Fri Jun 8 02:14:29 CEST 2012


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)
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.




More information about the Python-ideas mailing list