2013年11月20日水曜日

[Python] Mac OSX10.9でPythonのタブ補完を有効にする

Pythonでタブ補完とヒストリー表示をデフォルトで有効にするために、ホームディレクトリに .pythonstartup を作成します。

基本的には エキスパートPythonプログラミング に載っていたとおりですが、タブ補完が上手く動かなかったので、python tab completion Mac OSX 10.7 (Lion) を参考にスクリプトを書き換えました。

$ vi ~/.pythonstartup
# -*- encoding: utf-8 -*-
# Python Startup Script
import readline
import rlcompleter
import atexit
import os
# タブ補完の有効化
if 'libedit' in readline.__doc__:
    readline.parse_and_bind("bind ^I rl_complete")
else:
    readline.parse_and_bind("tab: complete")
# ヒストリーの表示
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
    readline.read_history_file(histfile)
except IOError:
    pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter, atexit

~/.bash_profile に PYTHONSTARTUP を追記する。

$ vi ~/.bash_profile
export PYTHONSTARTUP=~/.pythonstartup

変更を反映する。
$ source ~/.bash_profile


タブ補完が反映されるとこんな感じ。
>>> import sys
>>> sys.e[Tab]
sys.exc_clear(  sys.exc_type    sys.exec_prefix sys.exit(      
sys.exc_info(   sys.excepthook( sys.executable  sys.exitfunc(
>>> a = [1, 2, 3]
>>> a.i[Tab]
a.index(  a.insert(

Django の shell を使って作業を行うときに便利!

0 件のコメント:

コメントを投稿

Related Posts Plugin for WordPress, Blogger...