[Python-3000] Does Py3k's print offer any unicode encoding help?

Guido van Rossum guido at python.org
Fri Feb 15 18:24:40 CET 2008


On Thu, Feb 14, 2008 at 5:02 PM,  <skip at pobox.com> wrote:
>     Guido> You can hack around this for now by doing (before printing
>     Guido> anything)
>
>     Guido>   sys.stdout._encoding = 'utf-8'
>
>     Guido> but that ought to be a temporary hack until we've figured out the
>     Guido> right way to set it.
>
>  How about being able to reopen() an open file object, e.g.:
>
>     print(..., file=sys.stdout.reopen(encoding="utf-8")
>
>  ?

I think you're on to something. There's an API to access the
underlying (buffered) binary stream: sys.stdout.buffer. It's possible
to create a new TextIOWrapper on top of that:

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, "utf-8")

The only problem is that if the original TextIOWrapper is deleted or
closed, its close() method will close the underlying buffer object,
rendering sys.stdout useless. (Well, actually, the lowest-level raw
I/O object refuses to be closed if the file descriptor is 0, 1 or 2,
but is issues a warning and this is a close call. It would be better
if TextIOWrapper didn't explicitly close() when deleted. That requires
some redesign of the interaction between __del__() and close() in the
IOBase class. Maybe __del__() should just flush() instead of close()?

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-3000 mailing list