ipython Built-in line and cell magics


Magics whose name begins with just one % take as argument the rest of the line and are called line magics. Magics that begin with a double percent sign %% take a multi-line argument and are called cell magics.

A commonly used magic is %timeit, a wrapper around the Python's timeit.timeit function, for measuring the execution time of a piece of code.

In [35]: ra = [random.randint(0,1000) for r in range(1000)]
In [35]: %timeit sorted(ra)
1000 loops, best of 3: 507 µs per loop

An example of cell magic is %%bash (equivalent to %%script bash) for running the input as bash code

In [49]: %%bash
    ...: i=3
    ...: while [ $i -ge 0 ]
    ...: do
    ...: echo $i
    ...: i=$(($i-1))
    ...: done

Note that the end of a cell is marked by an empty line.

To view all built-in magics use %lsmagic

In [51]: %lsmagic
Available line magics:
%alias  %alias_magic  %autocall  %autoindent  %automagic  %bookmark  %cd  %cls
%colors  %config  %copy  %cpaste  %ddir  %debug  %dhist  %dirs  %doctest_mode  
%echo  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %load  
%load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic
%macro  %magic  %matplotlib  %mkdir  %notebook  %page  %paste  %pastebin  %pdb
%pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  
%prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %quickref  %recall  
%rehashx  %reload_ext  %ren  %rep  %rerun  %reset  %reset_selective  %rmdir  %run  
%save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  
%unload_ext  %who  %who_ls  %whos  %xdel  %xmode

Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%cmd  %%debug  %%file  %%html  
%%javascript  %%js  %%latex  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  
%%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile

Automagic is ON, % prefix IS NOT needed for line magics.

Note that by default 'automagic' is on, and therefore line magics can be called without % prefix (but cell functions still need a %% prefix).