【Python】IPythonをつかう
IPython
Pythonをインストールすると、標準のインタラクティブシェルがすでに使えるようになっているが、 別のPythonインタラクティブシェルであるIPythonを使うとより快適にPythonコードを実行できる。
インストール
pip install ipython
んで
$ ipython2 bash-3.2$ ipython2 Python 2.7.6 (default, Sep 9 2014, 15:04:36) 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]:
IPythonではプロンプト上の入力部分がインタラクティブシェルのような>>>ではなく、In [1]のように入力回数をあらわすものになっている。
自動補完
In [1]: im<TAB>
↓
In [1]: import
複数の候補があると、一覧表示される。
In [1]: __<TAB> __ __builtin__ __name__ __IPYTHON__ __debug__ __package__ __IPYTHON__active __doc__ ___ __import__
情報の参照
IPython中で定義した変数の後に?や??を付加すると、様々な情報を取ってこれる。
In [12]: obj = 1
In [13]: obj?
Type: int
String form: 1
Docstring:
int(x=0) -> int or long
int(x, base=10) -> int or long
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is floating point, the conversion truncates towards zero.
If x is outside the integer range, the function returns a long instead.
If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base. The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
履歴を残す
標準インタラクティブシェルを終了すると、以前の実行履歴は消えてなくなってしまう。 IPythonは、逐次実行履歴をpythonファイルとして残しておける。
In [1]: %logstart log.py
Activating auto-logging. Current session state plus future input saved.
Filename : log.py
Mode : backup
Output logging : False
Raw input log : False
Timestamping : False
State : active
In [2]: print ('%logstartでログ開始')
%logstartでログ開始
In [3]: %logoff
Switching logging OFF
In [4]: print ('%logoffでログ一時中断')
%logoffでログ一時中断
In [5]: %logon
Switching logging ON
In [6]: print ('%logonで再開')
%logonで再開
In [7]: %logstop
In [8]: print ('%logstopでログ終了')
%logstopでログ終了
ログはこんな感じ↓
# IPython log file
get_ipython().magic(u'logstart log.py')
print ('%logstartでログ開始')
get_ipython().magic(u'logoff')
print ('%logonで再開')
get_ipython().magic(u'logstop')
シェルコマンドの実行
インタラクティブシェル上でシェルコマンドもできる。
!+[シェルコマンド]で使用可能。
In [18]: !ls Applications Sensor-Bin-MacOSX-v5.1.2.1 Desktop TEST Documents apatch Downloads bin Dropbox build Library dotfiles Movies ...