How to print a unicode string?

damonwischik at gmail.com damonwischik at gmail.com
Fri Apr 18 22:18:12 EDT 2008


On Apr 19, 12:38 am, Damon Wischik wrote:
> I'd like to print out a unicode string.
>
> I'm running Python inside Emacs, which understands utf-8, so I want to
> force Python to send utf-8 to sys.stdout.

Thank you everyone who was sent suggestions. Here is my solution (for
making Python output utf-8, and persuading Emacs 22.2.1 with python-
mode to print it).

1. Set the registry key HKEY_CURRENT_USER\Software\GNU\Emacs\Home to
have value "d:\documents\home". This makes Emacs look for a .emacs
file in this directory (the home directory).

2. Put a file called .emacs file in the home directory. It should
include these lines:
(setenv "PYTHONPATH" "d:/documents/home")
(prefer-coding-system 'utf-8)
The first line means that python will look in my home directory for
libraries etc. The second line tells Emacs to default to utf-8 for its
buffers. Without the second line, Emacs may default to a different
coding, and it will not know what to do when it receives utf-8.

3. Put a file called sitecustomize.py in the home directory. This file
should contain these lines:
import codecs
import sys
sys.stdout = codecs.getwriter("UTF-8")(sys.stdout)

4. Now it should all work. If I enter
print u'La Pe\xf1a'
then it comes out with a n-tilde.

NB. An alternative solution is to edit site.py in the Python install
directory, and replace the line
    encoding = "ascii" # Default value set by _PyUnicode_Init()
with
    encoding = 'utf8'
But the trouble with this is that it will be overwritten if I install
a new version of Python.


NB. I also have these lines in my .emacs file, to load python-mode,
and to make it so that ctrl+enter executes the current paragraph:
; Python file association
(load "c:/program files/emacs-plugins/python-mode-1.0/python-mode.el")
(setq auto-mode-alist
      (cons '("\\.py$" . python-mode) auto-mode-alist))
(setq interpreter-mode-alist
      (cons '("python" . python-mode)
            interpreter-mode-alist))
(autoload 'python-mode "python-mode" "Python editing mode." t)
; Note: the command for invoking Python is specified at the end,
; as a custom variable.
;; DJW's command to select the current paragraph, then execute-region.
(defun py-execute-paragraph (vis)
  "Send the current paragraph to Python
Don't know what vis does."
  (interactive "P")
  (save-excursion
    (forward-paragraph)
    (let ((end (point)))
      (backward-paragraph)
      (py-execute-region (point) end ))))
(setq py-shell-switch-buffers-on-execute nil)
(global-set-key [(ctrl return)] 'py-execute-paragraph)

(custom-set-variables
  ;; custom-set-variables was added by Custom -- don't edit or cut/
paste it!
  ;; Your init file should contain only one such instance.
 '(py-python-command "c:/program files/Python25/python.exe"))


Damon.



More information about the Python-list mailing list