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

7 投票
1 回答
2510 浏览
提问于 2025-04-15 11:43

当我从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'

这在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'

我该怎么做才能让Emacs和Python沟通,让sys.stdout知道要使用UTF-8编码呢?


补充说明:因为我没有权限编辑被接受的答案,所以这里是我在Aquaemacs 1.6和Mac OS 10.5.6上有效的做法。

在python-mode-hook里,我添加了这一行:

(setenv "LANG" "en_GB.UTF-8")

显然,Mac OS需要用“UTF-8”,而dfa说Ubuntu需要用“UTF8”。

另外,我还需要通过按C-x 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

1 个回答

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

在你的 Python 钩子里,试试这个:

(setenv "LANG" "en_US.UTF8")

撰写回答