None
Based on Introduction to IPYthon Notebook by Fernando Perez.
The basic IPython client: at the terminal, simply type ipython
:
$ ipython
Python 3.5.1 |Anaconda 4.0.0 (x86_64)| (default, Dec 7 2015, 11:24:55)
Type "copyright", "credits" or "license" for more information.
IPython 4.1.2 -- 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]:
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")
?
?
¶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 scipy.optimize
scipy.optimize.bisect?
scipy.optimize?
*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.
import math
math.
2 + 10
_ + 10
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;
_
The output is stored in _N
and Out[N]
variables:
Out[9]
_9
And the last three have shorthands for convenience:
print('last output:', _)
print('next one :', __)
print('and next :', ___)
In[11]
_i
_ii
print('last input:', _i)
print('next one :', _ii)
print('and next :', _iii)
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
files = !ls
print("My current directory's files:")
print(files)
The IPython '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)
%%timeit
range(10)
range(100)
Line magics can be used even inside code blocks:
for i in range(5):
size = i*100
print('size:',size)
%timeit range(size)
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 system uptime is:"
uptime
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...
!cat test.txt
Let's see what other magics are currently defined in the system:
%lsmagic
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
In [1]: for i in range(10):
...: print(i, end=' ')
...:
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)
Now let's call the function g
with an argument that would produce an error:
import mod
mod.g(0)
%xmode verbose
mod.g(0)
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. (Another option is %xmode plain
providing even less detail.)
%xmode 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)
%debug
Don't forget to exit your debugging session. Raw input can of course be use to ask for user input:
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:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
## Show plots inside the notebook as svg
%config InlineBackend.figure_formats = ['svg']
fig, ax = plt.subplots()
x = np.linspace(0, 2*np.pi, 300)
y = np.sin(x**2)
plt.plot(x, y)
plt.title("A little chirp")
We can also run an IPYthon notebook on a server, and connect to that notebook session remotely or from the local machine. This magic gives us some details:
%connect_info
So for example we can open a text-based ipython console connected to this session using:
!jupyter console --existing
Or open a QTConsole from here using
%qtconsole
The Jupyter Notebook has become a central tool for interactive data exploration and data analysis. I would agree that most data scientists will see the Jupyter notebook as the default place to start a data exploration, analysis and machine learning project.
Why is this so? The combination of annotation, code snippets, inlined results from computation or visualisation and the automatic logging of these steps in a notebook file can be of great use for research and development activities. A slightly longer summary is available here.
Some recent publications on the topic:
Brian Granger, Fernando Pérez. Jupyter: Thinking and Storytelling With Code and Data, Computing in Science & Engineering, vol. 23, no. 2, pp. 7-14, 1 March-April 2021, doi: 10.1109/MCSE.2021.3059263 Authorea preprint (2021)
Hans Fangohr, Marijan Beg, et al, Data exploration and analysis with Jupyter notebooks, Proceedings of the 17th International Conference on Accelerator and Large Experimental Physics Control Systems ICALEPCS2019, TUCPR02, doi: 10.18429/JACoW-ICALEPCS2019-TUCPR02 (pdf) (2020)
Marijan Beg; Juliette Belin; Thomas Kluyver; Alexander Konovalov; Min Ragan-Kelley; Nicolas Thiery; Hans Fangohr. Using Jupyter for Reproducible Scientific Workflows in Computing in Science & Engineering, vol. 23, no. 2, pp. 36-46, 1 March-April 2021, doi: 10.1109/MCSE.2021.3052101 arXiv preprint (2021)