当前位置:首页 > 操作系统 > MacOs

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

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

<code>>>> 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
'spxe4m'
>>> 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)
</code>

在终端:

<code>~$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='spxe4m'
>>> sys.getdefaultencoding()
'utf-8'
>>> data
'sp?m'
>>> print(data)
sp?m
</code>

有没有人有关于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完成的).


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐