- 1 year ago
Python 3.8 Windows: print produces UnicodeEncodeError when piping
The UnicodeEncodeError
typically occurs when attempting to print Unicode characters to the console in Windows, especially when the console's default encoding is not compatible with the characters being printed.
To resolve this issue, you can try the following steps:
Set the
PYTHONIOENCODING
environment variable: Before running your Python script, set thePYTHONIOENCODING
environment variable to the desired encoding. For example, you can set it toutf-8
by running the following command in the command prompt:bashset PYTHONIOENCODING=utf-8
Use
sys.stdout.reconfigure()
(Python 3.7+): Starting from Python 3.7, you can use thesys.stdout.reconfigure()
method to change the default encoding of the standard output stream. Add the following line at the beginning of your script:pythonimport sys
sys.stdout.reconfigure(encoding='utf-8')
Use
io.TextIOWrapper
(Python 3.6 and earlier): If you're using an older version of Python, you can wrap the standard output stream withio.TextIOWrapper
to change its encoding. Here's an example:pythonimport sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
By setting the encoding appropriately or reconfiguring the standard output stream, you should be able to print Unicode characters without encountering the UnicodeEncodeError
when piping the output in Windows.