Jupyter magics

By August 11, 2018Data science

Jupyter notebooks have a series of built-in commands known as magic.  Magics are built into the Jupyter kernel being used (e.g. python) and perform various functions such as the following which tells the kernel to display matplotlib plots in the notebook rather than just creating them.

%matplotlib inline 

There are two different types of magics:

  • line magics, one-line commands, which all use a single $ symbol at the start of their names; and
  • cell magics, which change the behaviour of a Jupyter cell, and use two $ symbols at the start of their names.

Below is a list of some common magics and a short description of what they do.  A full list can be found at this link  https://ipython.readthedocs.io/en/stable/interactive/magics.html

Line magics

%alias

Define an alias for a system command

%alias alias_name cmd defines alias_name as an alias for cmd

%alias_magic

Create an alias for an existing magic

%alias_magic t time defines %t as an alias for %timeit

%cd

Change the working directory

%cd / changes the directory to the filesystem root directory

%debug

Activate the interactive debugger.

%load

Load code from a file into the current Jupyter session.
%load startup_script.py loads, and runs, the contents of startup_script.py

This is useful, for example, at the start of a notebook if you have a set of common modules or parameters you always wish to load. This list could be saved in ‘startup_script.py’

%load_ext

Load an iPython extension by its module name

 %logstart

Start logging.  By default logs are stored in ‘python_log.py’ in the current directory.

%logstart name saves the logs to a file called name.

You can also add a second parameter such as ‘append’, ‘backup’, ‘global’ or ‘rotate’

Related magics are %logon, %logoff, %logstate

%pip

Use PIP through Jupyter in order to install packages.

%pwd

Return the current working directory path.

Cell magics

%%bash

Run the contents of a cell in a bash subprocess

%%html

Render the cell as a block of HTML

%%javascript

Run the contents of a cell of javascript code

%%latex

Render the cell as latex

%%markdown

Render the cell as markdown