2008年10月25日

Terminal上でのPythonのコード補完

コードの補完ができると結構便利です。
コード補完の設定は Python チュートリアルのキー割り当て に記述があります。
readlineの機能を利用します。
$HOME以下に.pystartupのような名前で以下のファイルを作成します。

import atexit
import os
import readline
import rlcompleter

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

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')
# Mac OS X 10.5(Leopard)のデフォルトの場合のみ以下
# readline.parse_and_bind ("bind ^I rl_complete")

del os, atexit, readline, rlcompleter, save_history, historyPath
.bashrc等に以下を記述します。
export PYTHONSTARTUP=${HOME}/.pystartup
Mac OS X 10.5(Leopard)のreadlineはGNU readlineでないです。
GNU readlineと同様の動作にしたい場合は他からGNU readlineをインストールする必要があります。
Finkの場合は readline5-shlibs をインストールした後で Python の readline モジュールをインストールする必要があります。
sudo fink install readline5-shlibs
curl -o 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
sudo python setup.py install
ためしにPythonインタプリタをTerminalで起動して以下の動作をためしてみてください。
import os
os.<TAB>
コード補完が効くようになります。

blog comments powered by Disqus