Set Python terminal encoding on Windows

I was unable to set the character encoding in the Python terminal on Windows. According to the official guide, this is a piece of cake:

# -*- coding: utf-8 -*- 

Ok, now testing:

 print '' 

Produces a piece of mojibake. What is doing wrong?

PS IDE is Visual Studio 2010, if it matters

+1
source share
4 answers

Update: see JF Sebastian's Answer for a better explanation and a better solution.

# -*- coding: utf-8 -*- sets the encoding of the source file, not the output encoding.

You need to encode the line immediately before printing it using the same encoding that your terminal uses. In your case, I assume that your code page is Cyrillic (cp866). Consequently,

 print ''.encode("cp866") 
+2
source

You must use unicode:

 print u'' 

or switch to python3 (default is unicode).

+3
source

It produces mojibake because '' is a bytestring literal in Python 2 (unless using from __future__ import unicode_literals ). You print utf-8 bytes (source code encoding) to a Windows console that uses some other character encoding (the encoding is different if you see mojibake):

 >>> print(u''.encode('utf-8').decode('cp866')) ╨╀╀╀╨║╨╕╨╣ 

The solution is to print Unicode instead as @JBernardo suggested :

 #!/usr/bin/env python # -*- coding: utf-8 -*- print(u'') 

It works if the console encoding supports Cyrillic letters, for example, if it is cp866 .

If you want to redirect the output to a file; you can use the PYTHONIOENCODING environment PYTHONIOENCODING to set the character encoding used by Python for I / O:

 Z:\> set PYTHONIOENCODING=utf-8 Z:\> python your_script.py > output.utf-8.txt 

If you want to print Unicode characters that cannot be represented using console coding ( OEM code page ), then you can install win-unicode-console Python package :

 Z:\> py -m pip install win_unicode_console Z:\> py -m run your_script.py 
+2
source

If someone else gets this page when searching, the easiest way is to set the code page of the Windows terminal

 CHCP 65001 

or for the power shell, run it with

 powershell.exe -NoExit /c "chcp.com 65001" 

from Is there a Windows command shell that will display Unicode characters?

0
source

Source: https://habr.com/ru/post/890504/


All Articles