Skip to content

Magic Cells

Magic Cells

Jupyter notebook code cells can contain special commands which are not valid Python code, but will affect the behavior of the notebook.

%matplotlib inline

One of the most popular magic commands is:

%matplotlib inline

Using this command at the start of a Jupyter notebook will produce matplotlib plots inline in cells of the notebook. Without %matplotlib inline, plots will jump out as external windows. A typical start to a Jupyter notebook using matplotlib is:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

%load

The %load command will load a Python module, webpage or file into a Jupyter notebook

In [5]:
# %load hello.py
def main():
    print('This code was run from a seperate Python file')
    print('Hello from the file hello.py')

if name == "main": main()

This code was run from a seperate Python file
Hello from the file hello.py

%run

The %run magic command followed by the name of a Python file will run the current Python file as a script. Suppose the file hello.py is created in the same directory as the running Jupyter notebook. The directory structure looks something like this:

| current_folder
---| notebook.ipynb
---| hello.py

In the file hello.py is the code:

print('This code was run from a separate Python file')
print('Hello from the file hello.py')

Within our Jupyter notebook, if we %run this file, we will get the output of the hello.py script in a Nupyter notebook output cell.

In [1]:
%run hello.py
This code was run from a seperate Python file
Hello from the file hello.py

Other usefull magic commands

Other usefull magic commands are:

magic command result
%pwd print the current working directory
%cd change the current working directory
%ls list the contents of the current directory
%history the history of the In [ ]: commands

You can list all of the available magic commands by typing and running %lsmagic in a Jupyter notebook code cell:

%lsmagic

The output will show all the available line magic commands that begin with the percent sign %.

Available line magics:
%alias  %alias_magic  %autocall  %automagic  %autosave ...
%dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gui ...
dir  %more  %mv  %notebook  %page  %pastebin  %pdb  %pdef ...
...

Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html ...
%%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg ...