Hanfei Sun Hanfei Sun - 1 year ago 89
Python Question

Why UnicodeEncodeError raised only in emacs's python shell?

In emacs (use

run-python
command to call
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)


In terminal:

~$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


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