set encodeing in windows consol to utf8 in python

To set the encoding to UTF-8 in a Windows console while running a Python script, you can use the following code snippet at the beginning of your Python script:

main.py
import sys

if sys.platform.startswith('win'):
    # Enable UTF-8 encoding in Windows console
    # UTF-8 does not work properly in the default cmd.exe, it requires a console that supports it such as Windows Terminal
    # It might not work as expected in all Windows configurations
    # You can try setting the code page manually to UTF-8 using the command: chcp 65001
    # But it might not work correctly depending on the font used and other settings
    # Consider using a proper terminal emulator that supports UTF-8
    
    sys.stdout.encoding = 'utf-8'
    sys.stdin.encoding = 'utf-8'
    sys.stderr.encoding = 'utf-8'
629 chars
14 lines

Please note that the default cmd.exe in Windows may not fully support UTF-8 properly. For a better experience with UTF-8 encoding in Windows, you might want to consider using a terminal emulator like Windows Terminal, which fully supports UTF-8.

related categories

gistlibby LogSnag