IPython_log

IPythonとは

ひとことで言うとpythonのインタラクティブシェルの強化版 (公式tutorialgithub)

  • 補完機能の強化
  • イントロスペクションの強化
  • Magic Functionsという便利コマンドが使える
  • 履歴機能の強化
  • OSのシェルコマンドが使える

インストールと起動

$ pip install ipython
$ ipython
Python 2.7.5 (default, Mar  9 2014, 22:15:05)
Type "copyright", "credits" or "license" for more information.

IPython 3.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]:

補完機能

tabキーでimportできるモジュール補完。メソッドや、自分で定義した変数も補完できる。

In [1]: import c<tab>
cPickle      calendar     cgitb        cmd          codeop       commands     contextlib   copy_reg     ctypes       cv2
cProfile     cfmfile      chunk        code         collections  compileall   cookielib    crypt        curses       cythonmagic
cStringIO    cgi          cmath        codecs       colorsys     compiler     copy         csv          cv

イントロスペクション

importしたオブジェクトの後ろに”?“をつけてenterで、オブジェクトの説明を表示。”??“をつけると、より詳細な説明が表示される。

In [8]: import calendar

In [9]: calendar?
Type:        module
String form: <module 'calendar' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/calendar.pyc'>
File:        /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/calendar.py
Docstring:
Calendar printing functions

Note when comparing these calendars to the ones printed by cal(1): By
default, these calendars have Monday as the first day of the week, and
Sunday as the last (the European convention). Use setfirstweekday() to
set the first day of the week (0=Monday, 6=Sunday).

Magic functions

独自の便利コマンドが使えるようになるという話。prefixに”%“がついているコマンド。例えば”%timeit”を使うと実行時間を計測してくれる。 magic function 一覧

In [11]: %timeit range(10000)
The slowest run took 4.81 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 131 µs per loop

履歴機能

InとOutの数字を指定することで、履歴を呼び出せる。

In [16]: 45 * 4
Out[16]: 180

In [17]: Out[16] #outの16を呼び出した
Out[17]: 180

マジックメソッド”%history”を使って履歴をまとめて見ることも出来るし、直近の出力を、一つまえは”_”,二つまえは”__“、三つまえは”___“を使ってさかのぼることが出来る。

OSのシェルコマンドが使える

先頭に”!“をつけて実行することで使える。

In [27]: !date
2015年 5月 5日 火曜日 12時48分17秒 JST

In [28]: !uptime
12:48  up 1 day, 12:40, 2 users, load averages: 3.08 2.23 1.72