Search code examples
pythonunicodepython-3.xstdout

How to set sys.stdout encoding in Python 3?


Setting the default output encoding in Python 2 is a well-known idiom:

sys.stdout = codecs.getwriter("utf-8")(sys.stdout)

This wraps the sys.stdout object in a codec writer that encodes output in UTF-8.

However, this technique does not work in Python 3 because sys.stdout.write() expects a str, but the result of encoding is bytes, and an error occurs when codecs tries to write the encoded bytes to the original sys.stdout.

What is the correct way to do this in Python 3?


Solution

  • Since Python 3.7 you can change the encoding of standard streams with reconfigure():

    sys.stdout.reconfigure(encoding='utf-8')
    

    You can also modify how encoding errors are handled by adding an errors parameter.