Chapter 6, example 2

In this example, we show how to create a simple IPython extension that allows to write and evaluate C++ code directly in the notebook.

The cppmagic.py script contains the following code:

import IPython.core.magic as ipym

@ipym.magics_class
class CppMagics(ipym.Magics):
    @ipym.cell_magic
    def cpp(self, line, cell=None):
        """Compile, execute C++ code, and return the standard output."""
        # Define the source and executable filenames.
        source_filename = 'temp.cpp'
        program_filename = 'temp.exe'
        # Write the code contained in the cell to the C++ file.
        with open(source_filename, 'w') as f:
            f.write(cell)
        # Compile the C++ code into an executable.
        compile = self.shell.getoutput("g++ {0:s} -o {1:s}".format(
            source_filename, program_filename))
        # Execute the executable and return the output.
        output = self.shell.getoutput(program_filename)
        return output

def load_ipython_extension(ipython):
    ipython.register_magics(CppMagics)

We load the extension as if it was a simple Python module. The load_ipython_extension function is called with the IPython interpreter instance as an argument.


In [1]:
%load_ext cppmagic

In [2]:
cpp?

We now have access to the cpp cell magic, which allows to write C++ code in the notebook, compile it, execute it, and return the result.


In [3]:
%%cpp
#include<iostream>
int main()
{
    std::cout << "Hello world!";
}


Out[3]:
['Hello world!']