3. Line and Cell Magic commands#

Inside Jupyter cells, several so-called Magic commands can be used to configure operations. These commands begin with either %(line magic), %% (cell magic) or ! (run external system/unix command), and can be used to implement Jupyter or Environment specific commands or tools.

Some common examples include:

  • ! followed by a unix command line tool, e.g.:
    !ls lists all files in directory, !mkdir, !cat /proc/meminfo etc. These also work with %. I think the difference involves spawning a new process, vs. staying in-process.

  • !pip install pandas etc. are the usual way to install new python packages that are not yet in the base server. Note these are not persisted across starts. Similar !conda install gnuplot is a command to install new unix (mot nec. Python) libraries, comparable to the Linux/Debian apt-get install <packagename> or apt install <packagename>

  • %%capture suppresses output from this cell in the background (useful when installing per !pip or !conda)

  • %run <program.py>: run script

  • %%time measure execution time of cell.

  • %matplotlib inline allows graphics output from the matplotlib python package to be displayed inline.

  • %lsmagic shows all available magics.

Note

The !pip command can also be used to install from remote git repositories locations, e.g. !pip install git+https://github.com/team-ocean/veros.git@93943297dc441c444119b73893eaf69263a3ff2e, at specific branches.

Some further examples can be found here and here. The underlying iPython magic feature is documented here.

_images/Jupyter_Notebook_CheatSheet_Edureka.pdf

Fig. 3.1 Cheat-Sheet of some commands from https://www.edureka.co/blog/wp-content/uploads/2018/10/Jupyter_Notebook_CheatSheet_Edureka.pdf.#