在发送到终端之前,Python2.7解释器使用什么编码方案对Unicode码位进行编码?

2024-06-16 12:24:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python2.7。我的终端的编码方案被设置为“utf-8”。Python的默认编码方案是“ascii”。在

>>> sys.getdefaultencoding()
'ascii'

当我写作的时候

^{pr2}$

正确的Unicode字符显示在我的终端上。我不知道python解释器在将Unicode代码点发送到终端之前使用什么编码方案对其进行编码。是UTF-8吗?但是python的默认编码方案被设置为“ascii”。它如何决定使用UTF-8编码。在

编辑:
我知道我可以自己指定如下编码:

>>> print(u'à'.encode('utf-8'))
à

但是我想知道当我不指定编码时它是如何工作的。在


Tags: 代码终端编辑编码sysasciiunicode字符
2条回答

显然,python从路径中的LC_CTYPE变量中获取sys.stdout的编码方案。在

ayush:~$ export LC_CTYPE=POSIX python
ayush:~$ python
Python 3.5.1 |Continuum Analytics, Inc.| (default, Dec  7 2015, 11:16:01) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.encoding
'ANSI_X3.4-1968'

Python尝试确定终端编码,并在打印到终端时使用该编码。sys.stdout.encoding包含检测到的编码。getdefaultencoding()是未指定编码时用于对Unicode字符串进行编码的编码。在

示例(Windows控制台中的Python 2):

>>> import sys
'ascii'
>>> sys.stdout.encoding
'cp437'

打印到终端使用sys.stdout.encoding。我使用在终端编码中无效的Unicode字符来查看错误消息中的编码:

^{pr2}$

这里我不指定编码,它使用默认值:

>>> u'\xc1'.encode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xc1' in position 0: ordinal not in range(128)

示例(Windows控制台中的Python 3):

>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
>>> sys.stdout.encoding
'cp437'

打印仍使用sys.stdout.encoding

>>> print('\xc1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\dev\Python35\lib\encodings\cp437.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\xc1' in position 0: character maps to <undefined>

但是编码默认值是Python 3的默认值utf-8

>>> '\xc1'.encode()
b'\xc3\x81'

重定向输出

重定向Python脚本的输出时,sys.stdout.encoding的值可以更改。这可以用PYTHONIOENCODING环境变量覆盖。在

Python2重定向不检测编码。它将默认为ascii

C:\>py -2 -c "import sys;print(sys.stdout.encoding)" | more
None

Python3使用ANSI编码(因Windows本地化版本而异):

C:\>py -3 -c "import sys;print(sys.stdout.encoding)" | more
cp1252

使用环境变量重写:

C:\>set PYTHONIOENCODING=utf8

C:\>py -2 -c "import sys;print(sys.stdout.encoding)" | more
utf8

C:\>py -3 -c "import sys;print(sys.stdout.encoding)"
utf8

相关问题 更多 >