I'll show you how to use it to commemorate the release of IPython 2.0.
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
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
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.
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
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.
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.
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.
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
I think the last one was almost like a translation of the tutorial. http://ipython.org/ipython-doc/stable/interactive/tutorial.html
Recommended Posts