I’ve got a python script that outputs unicode to the console, and I’d like to redirect it to a file. Apparently, the redirect process in python involves converting the output to a string, so I get errors about inability to decode unicode characters.
So then, is there any way to perform a redirect into a file encoded in UTF-8?
When printing to the console, Python looks at
sys.stdout.encodingto determine the encoding to use to encode unicode objects before printing.When redirecting output to a file,
sys.stdout.encodingis None, so Python2 defaults to theasciiencoding. (In contrast, Python3 defaults toutf-8.) This often leads to an exception when printing unicode.You can avoid the error by explicitly encoding the unicode yourself before printing:
or you could redefine
sys.stdoutso all output is encoded inutf-8: