{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": "## Creating a custom magic command in an IPython extension" }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": "from IPython.core.magic import register_cell_magic" }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": "@register_cell_magic\ndef cpp(line, cell):\n \"\"\"Compile, execute C++ code, and return the standard output.\"\"\"\n\n # We first retrieve the current IPython interpreter instance.\n ip = get_ipython()\n\n # We define the source and executable filenames.\n source_filename = '_temp.cpp'\n program_filename = '_temp'\n\n # We write the code to the C++ file.\n with open(source_filename, 'w') as f:\n f.write(cell)\n\n # We compile the C++ code into an executable.\n compile = ip.getoutput(\"g++ {0:s} -o {1:s}\".format(\n source_filename, program_filename))\n\n # We execute the executable and return the output.\n output = ip.getoutput('./{0:s}'.format(program_filename))\n\n print('\\n'.join(output))" }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": "Hello world!" }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": "%%cpp\n#include\nint main()\n{\n std::cout << \"Hello world!\";\n}" } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 0 }