IPython で Python とおしゃべりしてみる
Pythonでは標準でIDLEという対話シェルが入っている(バッテリ同梱哲学!)
しかし私たちには IPython という、より便利な対話シェルがある。IPythonでより饒舌にPythonと会話しようしよう。
今回は以下の環境にIPythonを導入する。
OS | Windows7 (x86) |
Python | 2.7.2 |
1. インストール
(1) pipを使う場合
pipが導入されていればコマンドプロンプトで以下のコマンドを実行すればインストールできる。
まずpyreadlineのインストール
pip install pyreadline
そしてipythonのインストール
pip install ipython
(2) インストーラを使う
pip を使ってない場合でも、インストーラが用意されているので簡単。
pyreadline project files : pyreadline
Download — IPython
2 おしゃべりおしゃべり
コマンドプロンプトからIPythonと入力すれば開始。
↓のように In と Out のプロンプトや、例外情報が色分けされて表示される!
(1) タブ補完
途中まで入力してタブキーを押せば補完あるいは候補を表示。
・候補が一つの場合は自動補完
In[1]: import urllib2
In[2]: ur
(Tabキー押下で自動補完)
In[2]: urllib2
・候補が複数ある場合は候補を表示
In[2]: urllib2.url
(Tabキー押下で候補表示)
urllib2.url2pathname urllib2.urlopen urllib2.urlparse
(2) オブジェクトの内容を教えてもらう
オブジェクトにクエスチョンマークを付加することでヘルプが表示できる。
In [1]: a = 'hello world' In [2]: a? Type: str Base Class: <type 'str'> String Form:hello world Namespace: Interactive Length: 11 Docstring: str(object) -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object. In [3]: a.find? Type: builtin_function_or_method Base Class: <type 'builtin_function_or_method'> String Form:<built-in method find of str object at 0x02473080> Namespace: Interactive Docstring: S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation.
(3) OS コマンドでおしゃべり
IPython では cd, ls, pwd などのOSコマンドがマジック関数として実装されているため、対話シェルを開いた状態でもカレントディレクトリの変更などが可能。
また、実際のOSコマンドも先頭に!を付けることで実行できる。
例えば、
!ipconfig
(4) あれ何の話してたっけ
↑↓で入力履歴をたどれるのはもちろん、入力・出力の履歴がオブジェクトとして呼び出せる。
オブジェクト名 | 説明 |
In | 入力した文字列のリスト |
Out | 出力文字列のディクショナリ(Keyは行番号、Valueは実際に出力した文字列) |
In [1]: a = 'Hello world !!' In [2]: b = 'IPython is good.' In [3]: a Out[3]: 'Hello world !!' In [4]: b Out[4]: 'IPython is good.' In [5]: Out Out[5]: {3: 'Hello world !!', 4: 'IPython is good.'} In [6]: In Out[6]: ['', u"a = 'Hello world !!'", u"b = 'IPython is good.'", u'a', u'b', u'Out', u'In']
入力情報はマジック関数 history で表示することもできます。
(5) その他の便利機能
whos : 変数の一覧表示
who_ls : 変数のリスト
In [6]: whos Variable Type Data/Info ------------------------------- a str hello world b function <function <lambda> at 0x02459C70> p list n=3 urllib2 module <module 'urllib2' from 'C<...>ython27\lib\urllib2.pyc'> In [7]: v = %who_ls In [8]: v Out[8]: ['a', 'b', 'p', 'urllib2']
run <スクリプト名> : Pythonスクリプトの実行
(6) ショートカット
コマンド | 説明 |
ctrl + a | カーソルを先頭に移動 |
ctrl + e | カーソルを末尾に移動 |
ctrl + u | 現在行を消去 |
ctrl + k | 現在行のカーソル以降を消去 |