ひよっこ。

I want to…

Archive for 2012年1月5日

IPythonの拡張機能を作成する

Posted by hikaruworld : 2012 1月 5

bazaarのプラグインを書こうとしてIPythonを起動したら、
何故かIPythonのエクステンションの書き方を調べてしまったのでログとして残しておきます。

IPythonのextensionの書き方は公式サイトIPython extensionsが参考になります。
サンプルとなるエクステンションは、IPython/extensions以下を見るとよいかと思います。

IPythonでextensionを読み込ませるためには2つの手順が必要になります。

1. IPythonのロード設定

IPython起動時に指定したエクステンションをロードするようにProfileに設定を行います。
前回Profileについては簡単に触れていますが、
エクステンションをロードするときは以下のように設定します。

# A list of dotted module names of IPython extensions to load.
c.InteractiveShellApp.extensions = [
    'hello'
]

2.エクステンションの配備

上記のようにロード設定をした後には、
当然エクステンションを配備してあげる必要があります。
IPythonのエクステンションは

os.path.join(self.ipython_dir, 'extensions')

が認識されます。

つまり、ipython起動時に--ipython-dirを指定していない場合、
デフォルトでは$HOME/.config/ipythonが適用されますので、$HOME/.config/ipython/extensionsを作成すればよい事になります。
今回の例ではhelloというエクステンションを読み込んでいるので、ディレクトリ構成は以下のようになります。

$HOME/.config/ipython
└── extensions
    └── hello.py

※関連部分のみ抜粋

3.エクステンションの書き方

IPython起動時の処理

IPythonが起動/終了した場合に何か処理を行いたい場合、以下の関数を定義する事で自動で読み込まれます。

# 起動時の処理
def load_ipython_extension(ipython):
	pass

# 終了時の処理
def unload_ipython_extension(ipython):
	pass

引数で渡されるipythonはTerminalInteractiveShellやInteractiveShellAppなどのインスタンスになります。

マジックコマンドの設定

IPythonはマジックコマンドが定義されていて、色々便利ですよね。
マジックコマンドって何って人は%入力して<TAB>で一覧が確認出来ます。使い方は%XXX?で確認可能です。

In [3]: %
%alias                   %logstart                %pylab
%autocall                %logstate                %quickref
# いっぱいあるので以下省略。

In [3]: %pwd?
Type:       Magic function
Base Class: <type 'instancemethod'>
String Form:<bound method TerminalInteractiveShell.magic_pwd of <IPython.frontend.terminal.interactiveshell.TerminalInteractiveShell object at 0x1017a5ed0>>
Namespace:  IPython internal
File:       ~/.virtualenvs/bazaar/lib/python2.7/site-packages/IPython/core/magic.py
Definition: %pwd(self, parameter_s='')
Docstring:
Return the current working directory path.

Examples
--------
::

  In [9]: pwd
  Out[9]: '/home/tsuser/sprint/ipython'

で、本題。
エクステンションでも独自のマジックコマンドを定義する事が出来ます。
マジックコマンドを定義したい場合、

define_magic(magicname, func)

で登録する事が可能です。

たとえばsayというマジックコマンドを登録したい場合、この様に読み込ませます。

def say_impl(self, parameter_s=''):
	# sayコマンドの実体。引数はparameter_sに設定される。
    print 'Hello %s' % parameter_s

def load_ipython_extension(ipython):
	# ipythonが起動したタイミングで'say'というコマンドを定義する
	ipython.define_magic('say', say_impl)

これをipythonで起動して、実行するとこんな感じで表示されます。

In [1]: %say taro
Hello taro

マクロなどを定義したい場合はdefine_macro(name, themacro)という関数が準備されています。
自分は必要なかったので確認していませんが…。

以上です。
簡単ですね。日本語情報がないことをのぞけば….

Posted in program | タグ: , , | Leave a Comment »

ipython_config.pyの設定メモ

Posted by hikaruworld : 2012 1月 5

メモです。
大したカスタマイズしていませんが。

# -*- coding: utf-8 -*-
# Configuration file for ipython.

c = get_config()

# lines of code to run at IPython startup.
# 頻繁に利用するライブラリをimport
c.InteractiveShellApp.exec_lines = [
    'import os',
    'import sys',
    'import numpy'
]

#------------------------------------------------------------------------------
# TerminalInteractiveShell configuration
#------------------------------------------------------------------------------
# Set the editor used by IPython (default to $EDITOR/vi/notepad).
# c.TerminalInteractiveShell.editor = 'vi'
# デフォルトエディタをvimに
c.TerminalInteractiveShell.editor = '/usr/bin/vim'

# Enable auto setting the terminal title.
# Terminalにタイトル表示
c.TerminalInteractiveShell.term_title = True

# Automatically call the pdb debugger after every exception.
# エラー発生時にpdbを起動
c.TerminalInteractiveShell.pdb = True

#------------------------------------------------------------------------------
# PrefilterManager configuration
#------------------------------------------------------------------------------
# 複数行のスクリプトを有効化...何だけどなんかうまく行かん...
c.PrefilterManager.multi_line_specials = True

#------------------------------------------------------------------------------
# AliasManager configuration
#------------------------------------------------------------------------------
# lsやgrepをカラー設定
c.AliasManager.user_aliases = [
    ('ls', 'ls -G'),
    ('grep', 'grep --color-auto')
]

Posted in program | タグ: , , | Leave a Comment »