使Emacs在Python交互模式下使用UTF-8

Nat*_*ers 7 python emacs terminal encoding utf-8

当我从Mac OS的Terminal.app启动Python时,python将编码识别为UTF-8:

$ python3.0
Python 3.0.1 (r301:69556, May 18 2009, 16:44:01) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.encoding
'UTF-8'
Run Code Online (Sandbox Code Playgroud)

这对python2.5也是一样的.

但在Emacs中,编码是US-ASCII.

Python 3.0.1 (r301:69556, May 18 2009, 16:44:01) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.encoding
'US-ASCII'
Run Code Online (Sandbox Code Playgroud)

如何使Emacs与Python通信以便sys.stdout知道使用UTF-8?


编辑:由于我没有编辑接受的答案的代表,这正是在Aquaemacs 1.6,Mac OS 10.5.6上对我有用的.

在python-mode-hook中,我添加了该行

(setenv "LANG" "en_GB.UTF-8")
Run Code Online (Sandbox Code Playgroud)

显然,Mac OS需要"UTF-8",而dfa说Ubuntu需要"UTF8".

另外,我必须通过执行Cx RET p然后输入两次"utf-8"来设置输入/输出编码.我应该知道如何永久地设置它.

感谢dfa和Jouni共同帮助我找到答案.

这是我最后的python-mode-hook:

(add-hook 'python-mode-hook
  (lambda ()
        (set (make-variable-buffer-local 'beginning-of-defun-function)
             'py-beginning-of-def-or-class)
        (define-key py-mode-map "\C-c\C-z" 'py-shell)
        (setq outline-regexp "def\\|class ")
        (setenv "LANG" "en_GB.UTF-8"))) ; <-- *this* line is new
Run Code Online (Sandbox Code Playgroud)

dfa*_*dfa 7

检查你的环境变量:

$ LANG="en_US.UTF8" python -c "import sys; print sys.stdout.encoding"
UTF-8
$ LANG="en_US" python -c "import sys; print sys.stdout.encoding"  
ANSI_X3.4-1968
Run Code Online (Sandbox Code Playgroud)

在你的python钩子中,尝试:

(setenv "LANG" "en_US.UTF8")
Run Code Online (Sandbox Code Playgroud)