{ "metadata": { "name": "9932_06_02" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Chapter 6, example 2\n", "====================\n", "\n", "In this example, we show how to create a simple IPython extension that allows to write and evaluate C++ code directly in the notebook.\n", "\n", "The `cppmagic.py` script contains the following code:\n", "\n", " import IPython.core.magic as ipym\n", " \n", " @ipym.magics_class\n", " class CppMagics(ipym.Magics):\n", " @ipym.cell_magic\n", " def cpp(self, line, cell=None):\n", " \"\"\"Compile, execute C++ code, and return the standard output.\"\"\"\n", " # Define the source and executable filenames.\n", " source_filename = 'temp.cpp'\n", " program_filename = 'temp.exe'\n", " # Write the code contained in the cell to the C++ file.\n", " with open(source_filename, 'w') as f:\n", " f.write(cell)\n", " # Compile the C++ code into an executable.\n", " compile = self.shell.getoutput(\"g++ {0:s} -o {1:s}\".format(\n", " source_filename, program_filename))\n", " # Execute the executable and return the output.\n", " output = self.shell.getoutput(program_filename)\n", " return output\n", " \n", " def load_ipython_extension(ipython):\n", " ipython.register_magics(CppMagics)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%load_ext cppmagic" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "cpp?" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%cpp\n", "#include\n", "int main()\n", "{\n", " std::cout << \"Hello world!\";\n", "}" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 3, "text": [ "['Hello world!']" ] } ], "prompt_number": 3 } ], "metadata": {} } ] }