The basic IPython client: at the terminal, simply type ipython
:
$ ipython
Python 2.7.4 (default, Apr 19 2013, 18:28:01)
Type "copyright", "credits" or "license" for more information.
IPython 1.0.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]: print "hello world"
hello world
When executing code in IPython, all valid Python syntax works as-is, but IPython provides a number of features designed to make the interactive experience more fluid and efficient.
In the notebook, to run a cell of code, hit Shift-Enter
. This executes the cell and puts the cursor in the next cell below, or makes a new one if you are at the end. Alternately, you can use:
Alt-Enter
to force the creation of a new cell unconditionally (useful when inserting new content in the middle of an existing notebook).Control-Enter
executes the cell and keeps the cursor in the same cell, useful for quick experimentation of snippets that you don't need to keep permanently.print "Hello"
Hello
?
?
and ??
¶Typing object_name?
will print all sorts of details about any object, including docstrings, function definition lines (for call arguments) and constructor details for classes.
import collections
collections.namedtuple?
collections.Counter??
*int*?
An IPython quick reference card:
%quickref
Tab completion, especially for attributes, is a convenient way to explore the structure of any object you’re dealing with. Simply type object_name.<TAB>
to view the object’s attributes. Besides Python objects and keywords, tab completion also works on file and directory names.
collections.
collections.Counter
2+10
12
_+10
22
You can suppress the storage and rendering of output if you append ;
to the last cell (this comes in handy when plotting with matplotlib, for example):
10+20;
_
22
The output is stored in _N
and Out[N]
variables:
_10 == Out[10]
True
Out
{10: 12, 11: 22, 13: 22}
And the last three have shorthands for convenience:
print 'last output:', _
print 'next one :', __
print 'and next :', ___
last output: True next one : 22 and next : 22
In[11]
u'10+20;'
_i
u'In[11]'
_ii
u'In[11]'
print 'last input:', _i
print 'next one :', _ii
print 'and next :', _iii
last input: _ii next one : _i and next : In[11]
%history
print "Hi" print "Hello" ? import collections collections.namedtuple? collections.Counter?? collections.Counter?? *int*? *int*? %quickref 2+10 _+10 10+20; _ _8 == Out[8] _9 == Out[9] Out _10 == Out[10] %history -n 1-5 %history
Note: the commands below work on Linux or Macs, but may behave differently on Windows, as the underlying OS is different. IPython's ability to access the OS is still the same, it's just the syntax that varies per OS.
!pwd
/home/fperez/teach/bc/Lectures/04_IPythonNotebookIntroduction
files = !ls
print "My current directory's files:"
print files
My current directory's files: ['animation.m4v', 'Exercises.ipynb', 'IPython - beyond plain Python.ipynb', 'ipython-book.png', 'Markdown Cells.ipynb', 'mknbindex.py', 'Notebook Basics.ipynb', 'python-logo.svg', 'README.md', 'style.css', 'talktools.py']
!echo $files
[animation.m4v, Exercises.ipynb, IPython - beyond plain Python.ipynb, ipython-book.png, Markdown Cells.ipynb, mknbindex.py, Notebook Basics.ipynb, python-logo.svg, README.md, style.css, talktools.py]
!echo {files[0].upper()}
ANIMATION.M4V
The IPyhton 'magic' functions are a set of commands, invoked by prepending one or two %
signs to their name, that live in a namespace separate from your normal Python variables and provide a more command-like interface. They take flags with --
and arguments without quotes, parentheses or commas. The motivation behind this system is two-fold:
To provide an orthogonal namespace for controlling IPython itself and exposing other system-oriented functionality.
To expose a calling mode that requires minimal verbosity and typing while working interactively. Thus the inspiration taken from the classic Unix shell style for commands.
%magic
Line vs cell magics:
%timeit range(10)
1000000 loops, best of 3: 721 ns per loop
%%timeit
range(10)
range(100)
100000 loops, best of 3: 2.94 µs per loop
Line magics can be used even inside code blocks:
for i in range(5):
size = i*100
print 'size:',size,
%timeit range(size)
size: 0 1000000 loops, best of 3: 428 ns per loop size: 100 100000 loops, best of 3: 2.27 µs per loop size: 200 100000 loops, best of 3: 3.78 µs per loop size: 300 100000 loops, best of 3: 6.07 µs per loop size: 400 100000 loops, best of 3: 9.29 µs per loop
Magics can do anything they want with their input, so it doesn't have to be valid Python:
%%bash
echo "My shell is:" $SHELL
echo "My memory status is:"
free
My shell is: /bin/bash My memory status is: total used free shared buffers cached Mem: 7871672 7084132 787540 0 619832 2273128 -/+ buffers/cache: 4191172 3680500 Swap: 3905532 0 3905532
Another interesting cell magic: create any file you want locally from the notebook:
%%file test.txt
This is a test file!
It can contain anything I want...
more...
Overwriting test.txt
!cat test.txt
This is a test file! It can contain anything I want... more...
Let's see what other magics are currently defined in the system:
%lsmagic
Available line magics: %alias %alias_magic %autocall %automagic %autosave %bookmark %cd %clear %colors %config %connect_info %debug %dhist %dirs %doctest_mode %ed %edit %env %gui %hist %history %install_default_config %install_ext %install_profiles %killbgscripts %less %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %lsmagic %macro %magic %man %matplotlib %more %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %popd %pprint %precision %profile %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %rep %rerun %reset %reset_selective %run %save %sc %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode Available cell magics: %%! %%HTML %%SVG %%bash %%capture %%debug %%file %%html %%javascript %%latex %%perl %%prun %%pypy %%python %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefile Automagic is ON, % prefix IS NOT needed for line magics.
Not only can you input normal Python code, you can even paste straight from a Python or IPython shell session:
>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
... print b
... a, b = b, a+b
1 1 2 3 5 8
In [1]: for i in range(10):
...: print i,
...:
0 1 2 3 4 5 6 7 8 9
And when your code produces errors, you can control how they are displayed with the %xmode
magic:
%%file mod.py
def f(x):
return 1.0/(x-1)
def g(y):
return f(y+1)
Writing mod.py
Now let's call the function g
with an argument that would produce an error:
import mod
mod.g(0)
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-41-a54c5799f57e> in <module>() 1 import mod ----> 2 mod.g(0) /home/fperez/teach/ucb-bootcamp/Lectures/04_IPythonNotebookIntroduction/mod.py in g(y) 4 5 def g(y): ----> 6 return f(y+1) /home/fperez/teach/ucb-bootcamp/Lectures/04_IPythonNotebookIntroduction/mod.py in f(x) 1 2 def f(x): ----> 3 return 1.0/(x-1) 4 5 def g(y): ZeroDivisionError: float division by zero
%xmode plain
mod.g(0)
Traceback (most recent call last): File "<ipython-input-42-5a5bcec1553f>", line 2, in <module> mod.g(0) File "mod.py", line 6, in g return f(y+1) File "mod.py", line 3, in f return 1.0/(x-1) ZeroDivisionError: float division by zero
Exception reporting mode: Plain
%xmode verbose
mod.g(0)
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-43-81967cfaa0c3> in <module>() 1 get_ipython().magic(u'xmode verbose') ----> 2 mod.g(0) global mod.g = <function g at 0x2ff0140> /home/fperez/teach/ucb-bootcamp/Lectures/04_IPythonNotebookIntroduction/mod.py in g(y=0) 4 5 def g(y): ----> 6 return f(y+1) global f = <function f at 0x2ff00c8> y = 0 /home/fperez/teach/ucb-bootcamp/Lectures/04_IPythonNotebookIntroduction/mod.py in f(x=1) 1 2 def f(x): ----> 3 return 1.0/(x-1) x = 1 4 5 def g(y): ZeroDivisionError: float division by zero
Exception reporting mode: Verbose
The default %xmode
is "context", which shows additional context but not all local variables. Let's restore that one for the rest of our session.
%xmode context
Exception reporting mode: Context
Since 1.0 the IPython notebook web application support raw_input
which for example allow us to invoke the %debug
magic in the notebook:
mod.g(0)
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-45-5e708f13c839> in <module>() ----> 1 mod.g(0) /home/fperez/teach/ucb-bootcamp/Lectures/04_IPythonNotebookIntroduction/mod.py in g(y) 4 5 def g(y): ----> 6 return f(y+1) /home/fperez/teach/ucb-bootcamp/Lectures/04_IPythonNotebookIntroduction/mod.py in f(x) 1 2 def f(x): ----> 3 return 1.0/(x-1) 4 5 def g(y): ZeroDivisionError: float division by zero
%debug
> /home/fperez/teach/ucb-bootcamp/Lectures/04_IPythonNotebookIntroduction/mod.py(3)f() 2 def f(x): ----> 3 return 1.0/(x-1) 4 ipdb> ? Documented commands (type help <topic>): ======================================== EOF bt cont enable jump pdef psource run unt a c continue exit l pdoc q s until alias cl d h list pfile quit step up args clear debug help n pinfo r tbreak w b commands disable ignore next pinfo2 restart u whatis break condition down j p pp return unalias where Miscellaneous help topics: ========================== exec pdb Undocumented commands: ====================== retval rv ipdb> l 1 2 def f(x): ----> 3 return 1.0/(x-1) 4 5 def g(y): 6 return f(y+1) ipdb> u > /home/fperez/teach/ucb-bootcamp/Lectures/04_IPythonNotebookIntroduction/mod.py(6)g() 4 5 def g(y): ----> 6 return f(y+1) ipdb> d > /home/fperez/teach/ucb-bootcamp/Lectures/04_IPythonNotebookIntroduction/mod.py(3)f() 2 def f(x): ----> 3 return 1.0/(x-1) 4 ipdb> u > /home/fperez/teach/ucb-bootcamp/Lectures/04_IPythonNotebookIntroduction/mod.py(6)g() 4 5 def g(y): ----> 6 return f(y+1) ipdb> !print y 0 ipdb> d > /home/fperez/teach/ucb-bootcamp/Lectures/04_IPythonNotebookIntroduction/mod.py(3)f() 2 def f(x): ----> 3 return 1.0/(x-1) 4 ipdb> !print x 1 ipdb> !print x-1 0 ipdb> q
Don't foget to exit your debugging session. Raw input can of course be use to ask for user input:
enjoy = raw_input('Are you enjoying this tutorial ?')
print 'enjoy is :', enjoy
This imports numpy as np
and matplotlib's plotting routines as plt
, plus setting lots of other stuff for you to work interactivel very easily:
%pylab inline
Populating the interactive namespace from numpy and matplotlib
WARNING: pylab import has clobbered these variables: ['size', 'mod'] `%pylab --no-import-all` prevents importing * from pylab and numpy
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import gcf
x = np.linspace(0, 2*np.pi, 300)
y = np.sin(x**2)
plt.plot(x, y)
plt.title("A little chirp")
f = gcf() # let's keep the figure object around for later...
%connect_info
%qtconsole
%run talktools.py