Convenient use of ipython

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

I tried together.

You can do various things in the form of% command

Called a magic function. For example, % timeit knows the execution time

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

Furthermore, if you increase% like %% timeit, it becomes a multi-line command.

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

You can see the details by adding?, ?? to the object.

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

You can browse the file in which the function is defined by using % pfile object.

Can also be a 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.

Take advantage of% run

The % run command can execute any script. For example, to call and run pdb

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

will do. You can execute it directly as follows without starting it one by one.

% 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>

You can also use the -t option to display the execution time, and the -p option to execute with a profile.

Complicated code is easy with% edit

If you have more lines on the shell, you can use the edit command to launch the editor and write as much code as you like. However, note that it does not remain in the log.

Leave a log

In order to save the code I wrote You can use% logstart and% logstop to output the log to a file, and% save to write the history to a file.

Run ruby or perl

Did you know

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

You can get the output as a string with the --out option.

Or rather, execute an arbitrary command

Just add ! to the beginning.

In [1]: ! uname
Darwin

Debug later with% debug

If you use the % debug command, you can trace back with an exception and jump to the error location later.

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>

Check the contents with% page

You can pretty print the contents of the object with % page <object> and see it. It's like less.

If you forget% quickref

You can see the minimum required cheesesheet.

Variable list with% 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>

Recommended Posts

Convenient use of ipython
[Python Queue] Convenient use of Deque
Graceful use of MySQLdb
How to use IPython
Convenient library of Tensorflow TF-Slim
Convenient usage summary of Flask
How to use IPython Notebook
Use and integration of "Shodan"
Use Bokeh with IPython Notebook
Let's use usercustomize.py instead of sitecustomize.py
Summary of how to use pandas.DataFrame.loc
Let's use tomotopy instead of gensim
Proper use of Python visualization packages
Summary of how to use pyenv-virtualenv
Make full use of Python's str.format
Survey for practical use of BlockChain
Master the rich features of IPython
Efficient use of Linux file system
Mastering the rich features of IPython (2)
It is convenient to use Icecream instead of print when debugging.
Summary of how to use csvkit
[Python] Summary of how to use pandas
Use of constraints file added in pip 7.1
Use apache Spark with jupyter notebook (IPython notebook)
Use of virtualenv, Python's independent execution environment
How to calculate Use% of df command
[Python2.7] Summary of how to use unittest
R: Use Japanese instead of Japanese in scripts
I want to use IPython Qt Console
Use Django's Markdownx outside of site root
Jupyter Notebook Basics of how to use
List of Atom packages I really use
Basics of PyTorch (1) -How to use Tensor-
How to use the IPython debugger (ipdb)
Summary of how to use Python list
[Python2.7] Summary of how to use subprocess
[Question] How to use plot_surface of python