When redirecting the output, sys.stdout
is not connected to a terminal and Python cannot determine the output encoding. When not directing the output, Python can detect that sys.stdout
is a TTY and will use the codec configured for that TTY when printing unicode.
Set the PYTHONIOENCODING environment variable to tell Python what encoding to use in such cases, or encode explicitly.