what is best method to set sys.stdout to utf-8?

Terry Reedy tjreedy at udel.edu
Thu Mar 8 01:12:59 CET 2012

On 3/7/2012 3:57 PM, Peter Kleiweg wrote:
> In Python 3, there seem to be two ways to set sys.stdout to
> utf-8 after the script has started:
>      sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())
>      sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')
> I guess the second is better. At start-up, type(sys.stdout) is
> <class '_io.TextIOWrapper'>, and it's also after using the
> second method.
> After using the first method, type(sys.stdout) is changed to
> <class 'encodings.utf_8.StreamWriter'>.
> Should I always use the second method?

I would. The io module is more recent an partly replaces codecs. The 
latter remains for back compatibility and whatever it can do that io cannot.

Terry Jan Reedy

More information about the Python-list mailing list