[Python-ideas] changing sys.stdout encoding

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Jun 12 16:25:32 CEST 2012

On 11 June 2012 15:21, Jim Jewett <jimjjewett at gmail.com> wrote:

> On Thu, Jun 7, 2012 at 5:00 PM, Mike Meyer <mwm at mired.org> wrote:
> > On Thu, Jun 7, 2012 at 4:48 PM, Rurpy <rurpy at yahoo.com> wrote:
> >> I suspect the vast majority of
> >> programmers are interested in a language that allows
> >> them to *effectively* get done what they need to,
> Agreed.
> The problem is that your use case gets hit by several special cases at
> once.
> Usually, you don't need to worry about encodings at all; the default
> is sufficient.  Obviously not the case for you.
> Usually, the answer is just to open a file (or stream) the way you
> want to.  sys.stdout is special because you don't open it.
> If you do want to change sys.stdout, usually the answer is to replace
> it with a different object.  Apparently (though I missed the reason
> why) that doesn't work for you, and you need to keep using the same
> underlying stream.

I also think I missed something in this thread. At the beginning of the
original thread it seemed that everyone was agreed that

  writer = codecs.getwriter(desired_encoding)
  sys.stdout = writer(sys.stdout.buffer)

was a reasonable solution (with the caveat that it should happen before any
output is written). Is there some reason why this is not a good approach?

The only problem I know of is that under Python 2.x it becomes an error to
print _already_ encoded strings (they get decoded as ascii before being
encoded) but that's probably not a problem for an application that takes a
disciplined approach to unicode.

> So at that point, replacing it with a wrapped version of itself
> probably *is* the simplest solution.
> The remaining problem is how to find the least bad way of doing that.
> Your solution does work.  Adding it as an example to the docs would
> probably be reasonable, but someone seems to have worked pretty hard
> at keeping the sys module documentation short.  I could personally
> support a wrap function on the sys.std* streams that took care of
> flushing before wrapping, but ... there is a cost, in that the API
> gets longer, and therefore harder to learn.
> > or applications
> > outside of those built for your system that have a "--encoding" type
> > flag?
> There are plenty of applications with an encoding flag; I'm not sure
> how often it applies to sys.std*, as opposed to named files.
> -jJ
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120612/63c3f120/attachment.html>

More information about the Python-ideas mailing list