Hanfei Sun Hanfei Sun - 1 year ago 72
Python Question

Why UnicodeEncodeError raised only in emacs's python shell?

In emacs (use

command to call

>>> 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()
>>> 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)

In terminal:

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()
>>> data
>>> print(data)

Does anyone have ideas about the reason that unicode string of Python works in terminal but not in emacs

(Version information of emacs :
GNU Emacs 24.2.1 (x86_64-apple-darwin, NS apple-appkit-1038.36) of 2012-08-27 on bob.porkrind.org

Answer Source

The value of sys.getdefaultencoding() is not related to the stdout or shell you are executing in. The default encoding is just the internal encoding that is used to encode Unicode strings.

The shell you are printing to however does not necessarily have the same encoding. You can get the encoding of stdout from sys.stdout.encoding. Unfortunately, Python has no means to change that, so you’d have to find out yourself how to change the shell encoding (In the Windows console, it’s done using chcp for example).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download