LoginSignup
637
584

More than 5 years have passed since last update.

IPythonの使い方

Last updated at Posted at 2014-04-15

IPython 2.0のリリース記念に使い方を紹介します。

IPythonて何だよクソが

IPythonは、Pythonの対話型インタプリタを強力に(本当に強力に)拡張したものです。
といってもただの拡張に留まらず、大きく分けると以下の機能を持っています。

  • 拡張された対話型シェル
  • 分離型プロセス間通信モデル
  • 並列コンピューティング機構

ですが、まずここはやはり、IPythonの強力な対話型シェルについて使い方を簡単に書いていきます。

では、まずはインストールしましょう。

$ pip install ipython

インストールできたら起動しましょう。

$ ipython

補完に頼ってばかりだからお前はダメなんだよ

Pythonの標準の対話型シェルと比較して、IPythonの強力さがまず実感できるのは、その充実した補完機能です。
起動したIPythonのシェルで import o と入力して<TAB>キーを押してみましょう。

In [1]: import o
octavemagic  opcode      operator    optparse    os

すばらしく気の利いた補完候補が出ましたね!
標準の対話型シェルの補完はいまいち実用的ではありませんでしたが、IPythonの補完は相当使えます。

もう少し試してみましょう。import os として os.pa と入力し<TAB>

In [1]: import os
In [2]: os.pa
os.pardir          os.path            os.pathconf        os.pathconf_names  os.pathsep

インポートしたモジュールの中まで補完候補となっていますね。

もちろん、自分が宣言した変数なども補完できます。

In [3]: spam = 'Hello!'
In [4]: sp

ここで<TAB>を押すと、spamが補完されます。

更に、Pythonのオブジェクトやキーワードだけでなく、ファイル名やディレクトリ名も補完対象になります。

In [5]: .bash
.bash_history  .bash_profile  .bashrc

この補完機能だけでも、IPythonを利用する動機として十分過ぎるほどです。

イントロスペクションとか意味わかんねー言葉使いやがってナメてんのか

IPythonを使うと、オブジェクトの調査をとても楽に行うことができます。
object_name?のように、オブジェクト名に?を付けて実行すると、そのオブジェクトの情報が表示されます。

例えば以下のような感じです。

In [6]: spam?
Type:        str
String form: Hello
Length:      5
Docstring:
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.

組み込みモジュールや、もちろん自作のクラスなんかでもOKです。
表示されるのは、設定されているdocstringや、関数/メソッドの定義行、加えてクラスの場合にはコンストラクタ(?)の情報を表示することができます。

In [7]: os.path.join?
Type:        function
String form: <function join at 0x10c6592f0>
File:        /Users/mubae/.virtualenvs/py3/lib/python3.4/posixpath.py
Definition:  os.path.join(a, *p)
Docstring:
Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded.  An empty last part will result in a path that
ends with a separator.

また、?ではなく??とすると、より詳細な情報を表示することができます。

In [8]: os.path.join??
Type:        function
String form: <function join at 0x10c6592f0>
File:        /Users/mubae/.virtualenvs/py3/lib/python3.4/posixpath.py
Definition:  os.path.join(a, *p)
Source:
def join(a, *p):
   """Join two or more pathname components, inserting '/' as needed.
   If any component is an absolute path, all previous path components
   will be discarded.  An empty last part will result in a path that
   ends with a separator."""
   sep = _get_sep(a)
   path = a
   try:
       for b in p:
           if b.startswith(sep):
               path = b
           elif not path or path.endswith(sep):
               path += b
           else:
               path += sep + b
   except TypeError:
       valid_types = all(isinstance(s, (str, bytes, bytearray))
                         for s in (a, ) + p)
       if valid_types:
           # Must have a mixture of text and binary data
           raise TypeError("Can't mix strings and bytes in path "
                           "components.") from None
       raise
   return path

その他に、%pdoc%pdef%psource%pfile などの マジックコマンド を使うことで、指定した情報だけを表示させることも可能です。

マジックコマンドについては、改めて後で説明します。

In [9]: %pdoc os.path.join
Class docstring:
   Join two or more pathname components, inserting '/' as needed.
   If any component is an absolute path, all previous path components
   will be discarded.  An empty last part will result in a path that
   ends with a separator.
Call docstring:
   Call self as a function.
In [10]: %psource os.path.join
def join(a, *p):
   """Join two or more pathname components, inserting '/' as needed.
   If any component is an absolute path, all previous path components
   will be discarded.  An empty last part will result in a path that
   ends with a separator."""
   sep = _get_sep(a)
   path = a
   try:
       for b in p:
           if b.startswith(sep):
               path = b
           elif not path or path.endswith(sep):
               path += b
           else:
               path += sep + b
   except TypeError:
       valid_types = all(isinstance(s, (str, bytes, bytearray))
                         for s in (a, ) + p)
       if valid_types:
           # Must have a mixture of text and binary data
           raise TypeError("Can't mix strings and bytes in path "
                           "components.") from None
       raise
   return path

マジックコマンド、ああマジックコマンドね。それでお前の人生が良くなるの?

ここまでの内容でも、IPythonの便利さについて実感してもらえたかと思います。
しかし、これから紹介するマジックコマンドを知ることで、より一層便利に利用することができます。

マジックコマンドは、IPythonシェルで利用できるコマンドで、大きく以下の2種類に分類されます。

  • 行指向の ラインマジック
    頭に%のついたコマンドで、以降のその1行の内容を引数としてコマンドに渡します。
  • セル指向の セルマジック
    頭に%%のついたコマンドで、その行だけでなく、複数行を渡すことができます。

例えば%timeitコマンドは実行時間を計測できます。

In [1]: %timeit range(1000)
1000000 loops, best of 3: 804 ns per loop

こちらが複数行のパターン。

In [1]: %%timeit x = range(10000)
   ...: max(x)
   ...:
1000 loops, best of 3: 963 µs per loop

その他、組み込みのコマンドには以下のようなものが用意されています。

  • コード関連
    %run, %edit, %save, %macro, %recall
  • シェル関連
    %colors, %xmode, %autoindent, %automagic
  • その他
    %reset, %timeit, %%file, %load, or %paste

マジックコマンドは %quickref で確認できますので、コマンドの意味やその他にどんなコマンドがあるか見てみましょう。

実行とデバッグ

もう少しマジックコマンドを見ていきます。

%runマジックコマンドを使うと、好きなPythonスクリプトを実行し、データを直接対話型シェルの名前空間に読み込みます。
これはimportと異なり、実行するたびに再度読み込むため、スクリプトの変更があった場合にも即座に反映されます。

%runコマンドにはいくつかの特別なオプションがあり、-tオプションでスクリプトの実行時間を計測したり、-dオプションでpdbデバッガで起動することもできます。

また、スクリプトの実行で例外が発生したときは、%debugコマンドを実行することで即座にpdbを開始しデバッグすることができます。
もし補足していない例外が発生していない例外が発生したときに自動的にpdbを開始したいのであれば、%pdbコマンドで自動pdb起動の挙動をトグルできます。

いくら履歴を辿っても、お前が輝いていたときなんて一度もなかったんだよ。もちろんこれから先もずっとな。

IPythonは入力と出力の履歴を保存します。これがまたとても便利です。

履歴をたどる最も簡単な方法は、カーソルキーのを使うことですが、そのほかにも、より洗練された方法で履歴にアクセスすることができます。

入出力の履歴はそれぞれ、InOutという変数に、プロンプト番号をキーとして保存されていますので、後から参照することが可能です。

In [1]: pig = 'boo'

In [2]: pig.capitalize()
Out[2]: 'Boo'

In [3]: pig.upper()
Out[3]: 'BOO'

In [4]: In[3]
Out[4]: 'pig.upper()'

In [5]: Out[3]
Out[5]: 'BOO'

また、直近の3つの出力は、_, __, ___ という名前で保存されているので、より簡単にアクセスできます。

そのほか、%historyコマンドでも履歴を参照できます。

IPythonからシステムシェルのコマンドが使えるのは便利だね、このクズ野郎。

システムシェルのコマンドを使うのは簡単で、頭に!をつけて実行するだけです。

In [1]: !ping 2ch.net
PING 2ch.net (206.223.154.230): 56 data bytes
64 bytes from 206.223.154.230: icmp_seq=0 ttl=50 time=118.838 ms
64 bytes from 206.223.154.230: icmp_seq=1 ttl=50 time=118.843 ms
64 bytes from 206.223.154.230: icmp_seq=2 ttl=50 time=118.642 ms
64 bytes from 206.223.154.230: icmp_seq=3 ttl=50 time=118.378 ms

更に、以下のようにして出力結果をそのままリストにキャプチャすることもできます。

In [16]: files = !ls

参考

最後の方はほとんどチュートリアルのただの翻訳みたいになってた気がする。
http://ipython.org/ipython-doc/stable/interactive/tutorial.html

637
584
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
637
584