当我从 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
最佳答案
检查你的环境变量:
$ 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 钩子(Hook)中,尝试:
(setenv "LANG" "en_US.UTF8")
关于python - 使 Emacs 在 Python 交互模式下使用 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/888406/