为什么UnicodeEncodeError只在emacs的python shell中引发?

在emacs中(使用run-
python命令调用
python3):

>>> sys.version
sys.version
'3.2.3 (v3.2.3:3d0686d90f55, Apr 10 2012, 11:25:50) \n[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]'
>>> sys.getdefaultencoding()
sys.getdefaultencoding()
'utf-8'
>>> data
data
'sp\xe4m'
>>> print(data)
print(data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character '\xe4' in position 2: ordinal not in range(128)

在终端:

~$python3
Python 3.2.3 (v3.2.3:3d0686d90f55, Apr 10 2012, 11:25:50)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> data='sp\xe4m'
>>> sys.getdefaultencoding()
'utf-8'
>>> data
'späm'
>>> print(data)
späm

有没有人有关于Python的unicode字符串在终端中工作但在emacs中不工作的原因的想法

(emacs的版本信息:2012-08-27的GNU Emacs 24.2.1(x86_64-apple-darwin,NS apple-appkit-1038.36)bob.porkrind.org)

最佳答案 sys.getdefaultencoding()的值与您正在执行的stdout或shell无关.默认编码只是用于编码Unicode字符串的内部编码.

但是,要打印的shell不一定具有相同的编码.您可以从sys.stdout.encoding获取stdout的编码.不幸的是,Python没有办法改变它,所以你必须自己找出如何更改shell编码(在Windows控制台中,它是使用chcp完成的).

点赞