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