Reader small image

You're reading from  Learning IPython for Interactive Computing and Data Visualization, Second Edition

Product typeBook
Published inOct 2015
Reading LevelBeginner
Publisher
ISBN-139781783986989
Edition1st Edition
Languages
Right arrow
Author (1)
Cyrille Rossant
Cyrille Rossant
author image
Cyrille Rossant

Cyrille Rossant, PhD, is a neuroscience researcher and software engineer at University College London. He is a graduate of École Normale Supérieure, Paris, where he studied mathematics and computer science. He has also worked at Princeton University and Collège de France. While working on data science and software engineering projects, he gained experience in numerical computing, parallel computing, and high-performance data visualization. He is the author of Learning IPython for Interactive Computing and Data Visualization, Second Edition, Packt Publishing.
Read more about Cyrille Rossant

Right arrow

Creating a custom magic command in an IPython extension


IPython comes with a rich set of magic commands. You can get the complete list with the %lsmagic command. IPython also allows you to create your own magic commands. In this section, we will create a new cell magic that compiles and executes C++ code in the Notebook.

We first import the register_cell_magic function:

In [1]: from IPython.core.magic import register_cell_magic

To create a new cell magic, we create a function that takes a line (containing possible options) and a cell's contents as its arguments, and we decorate it with @register_cell_magic, as shown here:

In [2]: @register_cell_magic
        def cpp(line, cell):
            """Compile, execute C++ code, and return the
            standard output."""
            # We first retrieve the current IPython interpreter
            # instance.
            ip = get_ipython()

            # We define the source and executable filenames.
            source_filename = '_temp.cpp'
  ...
lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Learning IPython for Interactive Computing and Data Visualization, Second Edition
Published in: Oct 2015Publisher: ISBN-13: 9781783986989

Author (1)

author image
Cyrille Rossant

Cyrille Rossant, PhD, is a neuroscience researcher and software engineer at University College London. He is a graduate of École Normale Supérieure, Paris, where he studied mathematics and computer science. He has also worked at Princeton University and Collège de France. While working on data science and software engineering projects, he gained experience in numerical computing, parallel computing, and high-performance data visualization. He is the author of Learning IPython for Interactive Computing and Data Visualization, Second Edition, Packt Publishing.
Read more about Cyrille Rossant