Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launch console window pre-activated with chcp 65001 using python

I use a python library that prints out a Unicode character to windows console. If I call a function on the library that prints out Unicode character, it will throw an exception 'charmap' codec can't encode characters.

So this is what I tried to solve that error: Call "chcp 65001" windows console command from python using os.system("chcp 65001") before calling the library function.

I know there are questions similar to this and that is why I tried the above solution. It successfully calls the command on the console and tells me that it activated the code page.

However, the exception showed up again.

If I try to run the program again without closing the previous console, the program executes successfully without any exception. Which means the above console command takes effect after the first try.

My question is: is there a way to launch windows console by pre-activating Unicode support so that I don't have to call the program twice.

like image 450
ash Avatar asked Feb 05 '23 22:02

ash


2 Answers

Add /k chcp 65001 to the shortcut launching the cmd window. Alternatively, use Python 3.6 which uses Windows Unicode APIs to write to the console and ignores the code page. You do still need font support for what you are printing, however.

like image 53
Mark Tolonen Avatar answered May 07 '23 03:05

Mark Tolonen


Next settings works on Windows 8.1:

==> set "PYTHONIOENCODING=UTF-8"

==> chcp 65001
Active code page: 65001

==> type "%APPDATA%\Python\Python35\site-packages\usercustomize.py"
import win_unicode_console
win_unicode_console.enable()

Test:

==> python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> print (u'ěščřžýáíé ;ςερτυ яшертю ğüşi')
ěščřžýáíé ;ςερτυ яшертю ğüşi
>>>

Strings in test (senseless, just for demonstration):

  • ěščřžýáíé Latin, Central European
  • ;ςερτυ    Greek
  • яшертю    Cyrillic
  • ğüşi      Latin, Turkish
like image 37
JosefZ Avatar answered May 07 '23 04:05

JosefZ