OS X での Python + readline

前にも書きましたが、Snow Leopard に入れ替えたので再度書いておくことにします。

OS X に標準で含まれる readline は、GNU のものではなく、NetBSD の editline を使っています。GPL のライセンス汚染を避けるためのようです*1。そのため、Pythonreadline モジュールを使おうとしても、一部の、しかし大切な機能が動作しません。Ctr-R が効かなかったり、日本語入力ができなかったり、履歴ファイルの読み込みに失敗したりします。

簡単な解決方法は、GNUreadline を自分で追加し、また Pythonreadline モジュールを自分で組み込むことです。以下の説明では、OS X に標準で入っている Python を仮定しています。

Snow Leopard の場合

  1. Fink を導入し、readline5-shlibs を install します*2
  2. Python readline から readline-2.6.4.tar.gz を落としてきて、install します*3
$ wget http://pypi.python.org/packages/source/r/readline/readline-2.6.4.tar.gz
$ tar zxvf readline-2.6.4.tar.gz
$ cd readlien-2.6.4
$ python setup.py build
$ sudo python setup.py install

Leopard の場合

基本的に Snow Leopard と同じ手順ですが、Pythonreadline は 2.5.1 を入れて下さい。

$ wget http://pypi.python.org/packages/source/r/readline/readline-2.5.1.tar.gz
$ tar zxvf readline-2.5.1.tar.gz
$ cd readlien-2.5.1
$ python setup.py build
$ sudo python setup.py install

~/.pystartup の中身

ちなみに、~/.pystartup に書いてある、自分の Python の設定は以下の通りです。OS X 標準の readline だと、こけます。filecompleter というモジュールは、非標準です*4

import atexit
import os
import sys
import readline
import filecompleter

historyPath = os.path.expanduser("~/.pyhistory")
readline.set_history_length(1000000)

def save_history(historyPath=historyPath):
    import readline
    readline.write_history_file(historyPath)
    
if os.path.exists(historyPath):
    readline.read_history_file(historyPath)

atexit.register(save_history)
readline.parse_and_bind('Tab: complete')

del atexit, readline, save_history, historyPath

(追記) easy_install を使うと、その名の通りもっと簡単にできるそうです http://d.hatena.ne.jp/tacke/20100531/1275311473

*1:"Some platforms, such as Mac OS X, do not ship with GNU readline installed. The readline extension module in the standard library of Mac 'system' Python uses NetBSD's editline (libedit) library instead, which is a readline replacement with a less restrictive software license." と、http://pypi.python.org/pypi/readline/ に書いてあります。

*2:Fink じゃなくても構いません。

*3:2010 年 4 月 28 日時点の最新版は、2.6.4 です。今後更新される可能性があります。

*4:この filecompleter を書かれた方は、自分のプログラムの師匠です。