How to use IPython

I'll show you how to use it to commemorate the release of IPython 2.0.

What's IPython shit

IPython is a powerful (really powerful) extension of Python's interactive interpreter. However, it is not just an extension, it has the following functions.

--Extended interactive shell --Separate interprocess communication model --Parallel computing mechanism

But first, again, I'll briefly describe how to use IPython's powerful interactive shell.

Let's install it first.

$ pip install ipython

Let's start it once it is installed.

$ ipython

You're no good because you're just relying on complement

Compared to Python's standard interactive shell, the power of IPython is first noticed by its rich complements. In the launched IPython shell, type ʻimport oand press the` key.

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

You have a wonderful and nifty complement candidate! Standard interactive shell completions haven't been very practical, but IPython completions are quite usable.

Let's try a little more. Enter ʻos.pa as ʻimport os and <TAB>

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

Even the imported modules are candidates for completion.

Of course, you can also complete variables that you have declared.

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

If you press <TAB> here, spam will be completed.

Furthermore, not only Python objects and keywords, but also file names and directory names are complemented.

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

This completion alone is more than enough to motivate you to use IPython.

I don't know what it means to be an introspection.

IPython makes it very easy to inspect objects. If you add ? to the object name and execute it like ʻobject_name?`, the information of the object will be displayed.

For example, it looks like the following.

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'.

Built-in modules and, of course, your own classes are OK. What is displayed is the set docstring, the function / method definition line, and in the case of a class, the constructor (?) Information can be displayed.

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.

You can also display more detailed information by using ?? instead of ?.

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

In addition, it is also possible to display only the specified information by using ** magic commands ** such as % pdoc,% pdef, % psource, and% pfile.

The magic command will be explained later.

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

Magic command, oh magic command. Will that make your life better?

I hope that you have realized the convenience of IPython even with the contents so far. However, you can use it even more conveniently by knowing the magic commands that we will introduce.

Magic commands are commands that can be used in the IPython shell and are roughly classified into the following two types.

--Line-oriented ** Line Magic ** A command with a % at the beginning, passing the contents of that one line to the command as an argument. --Cell-oriented ** Cell Magic ** A command prefixed with %% allows you to pass multiple lines, not just that line.

For example, the % timeit command can measure execution time.

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

This is a multi-line pattern.

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

In addition, the following built-in commands are available.

--Code related %run, %edit, %save, %macro, %recall --Shell related %colors, %xmode, %autoindent, %automagic --Other %reset, %timeit, %%file, %load, or %paste

You can check the magic command with % quickref, so let's see what the command means and what other commands there are.

Run and debug

Let's take a closer look at magic commands.

Use the % run magic command to run your favorite Python script and load the data directly into the interactive shell namespace. Unlike ʻimport`, this is reloaded each time it is executed, so any changes to the script will be reflected immediately.

The % run command has some special options, the -t option can be used to time script execution, and the -d option can be used to launch it in the pdb debugger.

Also, if an exception occurs during script execution, you can immediately start pdb and debug it by executing the % debug command. If you want to start pdb automatically when an exception occurs, you can toggle the behavior of automatic pdb startup with the % pdb command.

No matter how much history I traced, I never saw you shining. Of course, from now on.

IPython saves a history of inputs and outputs. This is also very convenient.

The easiest way to trace the history is to use the cursor keys ↑ `` ↓, but there are other, more sophisticated ways to access the history.

The input / output history is saved in the variables ʻIn and ʻOut with the prompt number as the key, so you can refer to it later.

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'

Also, the last three outputs are stored under the names _, __, ___, so they are easier to access.

You can also refer to the history with the % history command.

It's convenient to be able to use system shell commands from IPython, this crap.

System shell commands are easy to use, just prefix them with ! And run them.

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

Furthermore, you can also capture the output result as it is in the list as follows.

In [16]: files = !ls

reference

I think the last one was almost like a translation of the tutorial. http://ipython.org/ipython-doc/stable/interactive/tutorial.html

Recommended Posts

How to use IPython
How to use IPython Notebook
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use virtualenv
How to use Seaboan
How to use image-match
How to use shogun
How to use Virtualenv
How to use numpy.vectorize
How to use pytest_report_header
How to use partial
How to use Bio.Phylo
How to use SymPy
How to use x-means
How to use WikiExtractor.py
How to use virtualenv
How to use Matplotlib
How to use iptables
How to use numpy
How to use TokyoTechFes2015
How to use venv
How to use dictionary {}
How to use Pyenv
How to use list []
How to use python-kabusapi
How to use OptParse
How to use return
How to use dotenv
How to use pyenv-virtualenv
How to use Go.mod
How to use imutils
How to use import
How to use the IPython debugger (ipdb)
How to use Qt Designer
[IPython] How to Share IPython Notebook
How to use search sorted
python3: How to use bottle (2)
Understand how to use django-filter
How to use the generator
How to use FastAPI ③ OpenAPI
How to use Python argparse
How to use Pandas Rolling
[Note] How to use virtualenv
How to use redis-py Dictionaries
Python: How to use pydub
[Python] How to use checkio
[Go] How to use "... (3 periods)"
How to use Django's GeoIp2
[Python] How to use input ()
How to use the decorator
[Introduction] How to use open3d
How to use Python lambda
How to use Jupyter Notebook
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Google Colaboratory
How to use Python bytes
How to use the zip function