Python: Set STDOUT Encoding to UTF-8
Set Input/Output to UTF-8
There are several ways to set the stdin/stdout to UTF-8.
- In python code, add
sys.stdout.reconfigure(encoding="utf-8")
- By environment variable. Set
PYTHONIOENCODING
to"utf-8"
- By environment variable. Set
PYTHONUTF8
to1
- By python command option:
-X utf8
In python code
import sys sys.stdin.reconfigure(encoding="utf-8") sys.stdout.reconfigure(encoding="utf-8") print("α")
Set the environment variable
Set the environment variable
PYTHONIOENCODING
to
"utf-8"
on Microsoft Windows , you can run this PowerShell command:
[Environment]::SetEnvironmentVariable("PYTHONIOENCODING", "utf-8", "User")
Python output encoding error: cp1252.py
If you don't set the stdout to utf8, you may run into problems on Microsoft Windows in emacs.
Here's helpful code for debugging. They should all be "UTF-8"
.
import sys # sys._enablelegacywindowsfsencoding() print(sys.getfilesystemencoding()) print(sys.getdefaultencoding()) print(sys.stdout.encoding) # sys.getfilesystemencodeerrors() print("α")