Python: Set STDOUT Encoding to UTF-8

By Xah Lee. Date: . Last updated: .

Set Input/Output to UTF-8

There are several ways to set the stdin/stdout to UTF-8.

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.

python 3 unicode output error 2022-10-23
python 3 unicode output error 2022-10-23. Runs fine in Microsoft Windows terminal, but not when in emacs. The problem is that sys.stdout.encoding is CP-1252 (windows-1252), not UTF-8.

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("α")

Python Unicode