Set Python terminal encoding on Windows

后端 未结 4 2130
情歌与酒
情歌与酒 2020-12-22 04:25

I happened to fail to set character encoding in Python terminal on Windows. According to official guide, it\'s a piece of cake:

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


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-22 05:04

    It produces mojibake because '' is a bytestring literal in Python 2 (unless from __future__ import unicode_literals is used). You are printing utf-8 bytes (the source code encoding) to 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 e.g., if it is cp866.

    If you want to redirect the output to a file; you could use PYTHONIOENCODING environment variable 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 can't be represented using the console encoding (OEM code page) then you could install win-unicode-console Python package:

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

提交回复
热议问题