IPython magics and shell commands

Jupyter · Practical · 12 min

Magics give timing, profiling, reloading and shell access in one keyword, and appear constantly in notebooks you will read.

The IPython kernel adds magic commands that are not Python syntax:

  • Line magics start with % and apply to the rest of the line.
  • Cell magics start with %%, must be the first line of a cell, and apply to the whole cell.

The ones you will use most:

  • %timeit expr runs a statement many times and reports mean and spread; %%timeit times a cell.
  • %%time (or %time) measures a single run, wall and CPU time.
  • %run script.py runs a file in the notebook, leaving its variables available.
  • %pip install pkg installs into the kernel's environment.
  • %load_ext autoreload then %autoreload 2 reloads edited modules before each cell, essential when developing a package alongside a notebook.
  • %matplotlib inline or %matplotlib widget picks the plotting backend.
  • %who, %whos list variables; %env reads or sets environment variables.
  • %%writefile file.py saves the cell to a file; %%bash and %%html run or render other languages.
  • %debug opens a debugger at the last exception; %prun profiles.

Lines starting with `!` run shell commands: !ls data/. The output can be captured into Python: files = !ls *.csv, and Python values interpolate with braces: !echo {name}.

%lsmagic lists all magics and %timeit? shows help. Magics only work in IPython-based kernels, so notebooks full of them do not run as plain .py scripts.

Example

%load_ext autoreload
%autoreload 2

nums = list(range(10_000))
%timeit sum(nums)          # e.g. 290 µs ± 50 µs per loop (mean ± std. dev. of 7 runs, ...)
%time total = sum(x * x for x in nums)
print(total)               # 333283335000

name = "jupyter"
!echo hello {name}         # hello jupyter
files = !ls /
print(type(files).__name__, "usr" in files)   # SList True

%env APP_MODE=dev
import os
print(os.environ["APP_MODE"])                  # dev

Remember

  • % line magics apply to one line; %% cell magics to the whole cell
  • %timeit/%%time for timing, %run for scripts, %autoreload for live module edits
  • !cmd runs shell commands; x = !cmd captures output, {var} interpolates

Watch out for

  • Putting a %% cell magic anywhere but the first line of the cell, which raises an error.

Check yourself

  1. You edit a function in mymodule.py, but the notebook keeps using the old version after re-running `import mymodule`. What fixes this going forward?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: ipython.readthedocs.io/en/stable/interactive/magics.html