LoginSignup
96
93

More than 5 years have passed since last update.

ipythonの便利な使い方

Posted at

=================

まとめてみました。

%command という形式で色々出来る

magic functionと呼ぶ。
例えば、%timeitは実行時間がわかる

In [67]: %timeit [x for x in range(100) if x % 2 == 0]
10000 loops, best of 3: 21.3 us per loop

さらに、%%timeitのように%を増やすと、複数行コマンドになる

In [70]: %%timeit
    ...: a = 0
    ...: for i in range(100):
    ...:     a = max(a, random.random())
    ...: 
10000 loops, best of 3: 37.7 us per loop

オブジェクトに?, ??をつけると詳細がわかる

In [45]: os.path.exists?
Type:       function
String Form:<function exists at 0x10890be60>
File:       /Users/***
Definition: os.path.exists(path)
Docstring:  Test whether a path exists.  Returns False for broken symbolic links

In [46]: os.path.exists??
Type:       function
String Form:<function exists at 0x10890be60>
File:       /Users/***
Definition: os.path.exists(path)
Source:
def exists(path):
    """Test whether a path exists.  Returns False for broken symbolic links"""
    try:
        os.stat(path)
    except os.error:
        return False
    return True

%pfile objectとするとその関数が定義されているファイルを閲覧できる

magic functionにもできる

%pfile?
Type:       Magic function
String Form:<bound method NamespaceMagics.pfile of <IPython.core.magics.namespace.NamespaceMagics object at 0x10a9b2dd0>>
Namespace:  IPython internal
File:       /Users/***
Definition: %pfile(self, parameter_s='')
Docstring:
Print (or run through pager) the file where an object is defined.

The file opens at the line where the object definition begins. IPython
will honor the environment variable PAGER if set, and otherwise will
do its best to print the file in a convenient form.

If the given argument is not an object currently defined, IPython will
try to interpret it as a filename (automatically adding a .py extension
if needed). You can thus use %pfile as a syntax highlighting code
viewer.
Class Docstring:
method(function, instance)

Create a bound instance method object.

%runを活用する

%runコマンドは任意のスクリプトを実行することが出来ます。例えば、pdbを呼び出しつつ実行するには

In [1]: %run -d a.py

とします。一々起動せずとも以下のように直接実行してもいいですね。

% ipython3 -c 'run -d a.py'
Breakpoint 1 at /Users/***/a.py:1
NOTE: Enter 'c' at the ipdb>  prompt to start your script.
> /Users/hiro/***/a.py(1)<module>()
1---> 1 if __name__ == '__main__':
      2     a = 'py' * 5
      3     print(a)

ipdb>

ほかにも-tオプションで実行時間を表示したり、-pオプションでプロファイル付きで実行したりできます。

%editで複雑なコードもらくらく

シェル上で継続行が増えてくるような場合、editコマンドを使うとエディタが起動し、好きなだけコードを書く事が出来ます。ただしlogに残らないので注意。

ログを残す

せっかく書いたコードを保存しておくために、
%logstart, %logstopを使ってログをファイルに出力したり、%saveでhistoryをファイルに書き出すことが出来ます。

rubyやperlを実行する

知ってました?

In [23]: %%ruby
(1..4).each{|x| p x}
   ....:
1
2
3
4

--outオプションで出力を文字列として得る事が出来ます。

というか任意のコマンドを実行する

!を先頭につけるだけ。

In [1]: ! uname
Darwin

%debugであとからデバッグ

%debugコマンドを使えば、例外でtracebackしても後からエラー箇所に飛ぶことが可能です。

In [19]: def func(a):
    return a / 0
   ....:

In [20]: func(1)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-20-db72e56561b1> in <module>()
----> 1 func(1)

<ipython-input-19-82426e2f9c3c> in func(a)
      1 def func(a):
----> 2     return a / 0

ZeroDivisionError: division by zero

In [21]: %debug
> <ipython-input-19-82426e2f9c3c>(2)func()
      1 def func(a):
----> 2     return a / 0

ipdb>

%pageで中身を確認

%page <object>でobjectの中身をpretty printして眺める事が出来ます。lessみたいなもん。

忘れたら%quickref

必要最低限のcheetsheetを見ることが出来ます。

%whosで変数リスト

In [101]: %whos
In [102]: a = 1

In [103]: b = 2

In [104]: c = 'spam'

In [105]: def f(x):
   .....:     return x ** 2
   .....:

In [106]: %whos
Variable   Type        Data/Info
--------------------------------
a          int         1
b          int         2
c          str         spam
f          function    <function f at 0x1009b2440>
96
93
0

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
96
93