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?
2to3now and it didn't suggest any changes for the given code.sys.stdout = codecs.getwriter("hex")(sys.stdout)inipythonto see what I mean...PowerShellredirection seems to re-encode everything toUTF-16, so if you're using redirection, you might need to use regularcmdinstead. I verifiedtype foo.txt > foo2.txtchanges aUTF-8foo.txtto aUTF-16foo2.txt, so what Python writes tostdoutisn't the last word. None of the solutions below worked for me because of this.