As mentioned in python official docs:
On Windows, UTF-8 is used for the console device. Non-character
devices such as disk files and pipes use the system locale encoding
(i.e. the ANSI codepage). Non-console character devices such as NUL
(i.e. where isatty() returns True) use the value of the console input
and output codepages at startup, respectively for stdin and
stdout/stderr. This defaults to the system locale encoding if the
process is not initially attached to a console.
The special behaviour of the console can be overridden by setting the
environment variable PYTHONLEGACYWINDOWSSTDIO before starting Python.
In that case, the console codepages are used as for any other
character device.
Under all platforms, you can override the character encoding by
setting the PYTHONIOENCODING environment variable before starting
Python or by using the new -X utf8 command line option and PYTHONUTF8
environment variable. However, for the Windows console, this only
applies when PYTHONLEGACYWINDOWSSTDIO is also set.
It says that python use UTF-8 for console printing but ANSI for pipes.And IO redirection in powershell is actually a kind of pipes.So some utf-8 characters can't be encoded by ANSI,which causes the error.
There are three solutions:
by environment
$env:PYTHONIOENCODING="UTF-8"
by hard code
sys.stdout.reconfigure(encoding='utf-8')
by command
python -X utf8 test.py