{
 "metadata": {
  "name": ""
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "heading",
     "level": 1,
     "metadata": {},
     "source": [
      "Cell Magics in IPython"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "IPython has a system of commands we call 'magics' that provide effectively a mini command language that is orthogonal to the syntax of Python and is extensible by the user with new commands.  Magics are meant to be typed interactively, so they use command-line conventions, such as using whitespace for separating arguments, dashes for options and other conventions typical of a command-line environment.\n",
      "\n",
      "Magics come in two kinds:\n",
      "\n",
      "* Line magics: these are commands prepended by one `%` character and whose arguments only extend to the end of the current line.\n",
      "* Cell magics: these use *two* percent characters as a marker (`%%`), and they receive as argument *both* the current line where they are declared and the whole body of the cell.  Note that cell magics can *only* be used as the first line in a cell, and as a general principle they can't be 'stacked' (i.e. you can only use one cell magic per cell).  A few of them, because of how they operate, can be stacked, but that is something you will discover on a case by case basis.\n",
      "\n",
      "The `%lsmagic` magic is used to list all available magics, and it will show both line and cell magics currently defined:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%lsmagic"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "json": [
        "{\"cell\": {\"prun\": \"ExecutionMagics\", \"file\": \"Other\", \"!\": \"OSMagics\", \"capture\": \"ExecutionMagics\", \"timeit\": \"ExecutionMagics\", \"script\": \"ScriptMagics\", \"ruby\": \"Other\", \"system\": \"OSMagics\", \"perl\": \"Other\", \"HTML\": \"Other\", \"bash\": \"Other\", \"python\": \"Other\", \"SVG\": \"Other\", \"javascript\": \"DisplayMagics\", \"writefile\": \"OSMagics\", \"pypy\": \"Other\", \"python3\": \"Other\", \"latex\": \"DisplayMagics\", \"sx\": \"OSMagics\", \"svg\": \"DisplayMagics\", \"html\": \"DisplayMagics\", \"sh\": \"Other\", \"time\": \"ExecutionMagics\", \"debug\": \"ExecutionMagics\"}, \"line\": {\"psource\": \"NamespaceMagics\", \"logstart\": \"LoggingMagics\", \"popd\": \"OSMagics\", \"loadpy\": \"CodeMagics\", \"install_ext\": \"ExtensionMagics\", \"colors\": \"BasicMagics\", \"who_ls\": \"NamespaceMagics\", \"install_profiles\": \"DeprecatedMagics\", \"pprint\": \"BasicMagics\", \"save\": \"CodeMagics\", \"tb\": \"ExecutionMagics\", \"pylab\": \"PylabMagics\", \"killbgscripts\": \"ScriptMagics\", \"quickref\": \"BasicMagics\", \"magic\": \"BasicMagics\", \"dhist\": \"OSMagics\", \"edit\": \"KernelMagics\", \"logstop\": \"LoggingMagics\", \"gui\": \"BasicMagics\", \"alias_magic\": \"BasicMagics\", \"debug\": \"ExecutionMagics\", \"page\": \"BasicMagics\", \"logstate\": \"LoggingMagics\", \"ed\": \"Other\", \"pushd\": \"OSMagics\", \"timeit\": \"ExecutionMagics\", \"rehashx\": \"OSMagics\", \"hist\": \"Other\", \"qtconsole\": \"KernelMagics\", \"dirs\": \"OSMagics\", \"run\": \"ExecutionMagics\", \"reset_selective\": \"NamespaceMagics\", \"pinfo2\": \"NamespaceMagics\", \"matplotlib\": \"PylabMagics\", \"automagic\": \"AutoMagics\", \"doctest_mode\": \"KernelMagics\", \"logoff\": \"LoggingMagics\", \"reload_ext\": \"ExtensionMagics\", \"pdb\": \"ExecutionMagics\", \"load\": \"CodeMagics\", \"lsmagic\": \"BasicMagics\", \"autosave\": \"KernelMagics\", \"cd\": \"OSMagics\", \"pastebin\": \"CodeMagics\", \"prun\": \"ExecutionMagics\", \"autocall\": \"AutoMagics\", \"bookmark\": \"OSMagics\", \"connect_info\": \"KernelMagics\", \"system\": \"OSMagics\", \"whos\": \"NamespaceMagics\", \"toc\": \"TimerMagics\", \"unload_ext\": \"ExtensionMagics\", \"store\": \"StoreMagics\", \"more\": \"KernelMagics\", \"gist\": \"Other\", \"pdef\": \"NamespaceMagics\", \"precision\": \"BasicMagics\", \"pinfo\": \"NamespaceMagics\", \"pwd\": \"OSMagics\", \"psearch\": \"NamespaceMagics\", \"reset\": \"NamespaceMagics\", \"recall\": \"HistoryMagics\", \"xdel\": \"NamespaceMagics\", \"xmode\": \"BasicMagics\", \"rerun\": \"HistoryMagics\", \"logon\": \"LoggingMagics\", \"history\": \"HistoryMagics\", \"pycat\": \"OSMagics\", \"unalias\": \"OSMagics\", \"install_default_config\": \"DeprecatedMagics\", \"env\": \"OSMagics\", \"load_ext\": \"ExtensionMagics\", \"config\": \"ConfigMagics\", \"tic\": \"TimerMagics\", \"profile\": \"BasicMagics\", \"pfile\": \"NamespaceMagics\", \"less\": \"KernelMagics\", \"who\": \"NamespaceMagics\", \"notebook\": \"BasicMagics\", \"man\": \"KernelMagics\", \"sx\": \"OSMagics\", \"macro\": \"ExecutionMagics\", \"clear\": \"KernelMagics\", \"alias\": \"OSMagics\", \"time\": \"ExecutionMagics\", \"sc\": \"OSMagics\", \"rep\": \"Other\", \"pdoc\": \"NamespaceMagics\"}}"
       ],
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 1,
       "text": [
        "Available line magics:\n",
        "%alias  %alias_magic  %autocall  %automagic  %autosave  %bookmark  %cd  %clear  %colors  %config  %connect_info  %debug  %dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gist  %gui  %hist  %history  %install_default_config  %install_ext  %install_profiles  %killbgscripts  %less  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %lsmagic  %macro  %magic  %man  %matplotlib  %more  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %run  %save  %sc  %store  %sx  %system  %tb  %tic  %time  %timeit  %toc  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode\n",
        "\n",
        "Available cell magics:\n",
        "%%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %%latex  %%perl  %%prun  %%pypy  %%python  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile\n",
        "\n",
        "Automagic is ON, % prefix IS NOT needed for line magics."
       ]
      }
     ],
     "prompt_number": 1
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Since in the introductory section we already covered the most frequently used line magics, we will focus here on the cell magics, which offer a great amount of power.\n",
      "\n",
      "Let's load matplotlib and numpy so we can use numerics/plotting at will later on."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%matplotlib inline\n",
      "import numpy as np\n",
      "import matplotlib.pyplot as plt"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 2
    },
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "<!--====-->\n",
      "Some simple cell magics"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Timing the execution of code; the 'timeit' magic exists both in line and cell form:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%timeit np.linalg.eigvals(np.random.rand(100,100))"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "100 loops, best of 3: 6.05 ms per loop\n"
       ]
      }
     ],
     "prompt_number": 3
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%timeit a = np.random.rand(100, 100)\n",
      "np.linalg.eigvals(a)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "100 loops, best of 3: 6.07 ms per loop\n"
       ]
      }
     ],
     "prompt_number": 4
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "The `%%capture` magic can be used to capture the stdout/err of any block of python code, either to discard it (if it's noise to you) or to store it in a variable for later use:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%capture capt\n",
      "from __future__ import print_function\n",
      "import sys\n",
      "print('Hello stdout')\n",
      "print('and stderr', file=sys.stderr)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 5
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "capt.stdout, capt.stderr"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 6,
       "text": [
        "('Hello stdout\\n', 'and stderr\\n')"
       ]
      }
     ],
     "prompt_number": 6
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "capt.show()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "Hello stdout\n"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stderr",
       "text": [
        "and stderr\n"
       ]
      }
     ],
     "prompt_number": 7
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "The `%%writefile` magic is a very useful tool that writes the cell contents as a named file:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%writefile foo.py\n",
      "print('Hello world')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "Writing foo.py\n"
       ]
      }
     ],
     "prompt_number": 8
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%run foo"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "Hello world\n"
       ]
      }
     ],
     "prompt_number": 9
    },
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "<!--====-->\n",
      "Magics for running code under other interpreters"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "IPython has a `%%script` cell magic, which lets you run a cell in\n",
      "a subprocess of any interpreter on your system, such as: bash, ruby, perl, zsh, R, etc.\n",
      "\n",
      "It can even be a script of your own, which expects input on stdin."
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "To use it, simply pass a path or shell command to the program you want to run on the `%%script` line,\n",
      "and the rest of the cell will be run by that script, and stdout/err from the subprocess are captured and displayed."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%script python\n",
      "import sys\n",
      "print 'hello from Python %s' % sys.version"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "hello from Python 2.7.2 (default, Oct 11 2012, 20:14:37) \n",
        "[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)]\n"
       ]
      }
     ],
     "prompt_number": 10
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%script python3\n",
      "import sys\n",
      "print('hello from Python: %s' % sys.version)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "hello from Python: 3.3.1 (v3.3.1:d9893d13c628, Apr  6 2013, 11:07:11) \n",
        "[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]\n"
       ]
      }
     ],
     "prompt_number": 11
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "IPython also creates aliases for a few common interpreters, such as bash, ruby, perl, etc.\n",
      "\n",
      "These are all equivalent to `%%script <name>`"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%ruby\n",
      "puts \"Hello from Ruby #{RUBY_VERSION}\""
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "Hello from Ruby 1.9.3\n"
       ]
      }
     ],
     "prompt_number": 12
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%bash\n",
      "echo \"hello from $BASH\""
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "hello from /usr/local/bin/bash\n"
       ]
      }
     ],
     "prompt_number": 13
    },
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "Exercise: write your own script that numbers input lines"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Write a file, called `lnum.py`, such that the following cell works as shown (hint: don't forget about the executable bit!): "
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%script ./lnum.py\n",
      "my first line\n",
      "my second\n",
      "more"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "0: my first line\n",
        "1: my second\n",
        "2: more\n",
        "---- END ----\n"
       ]
      }
     ],
     "prompt_number": 29
    },
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "Capturing output"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "You can also capture stdout/err from these subprocesses into Python variables, instead of letting them go directly to stdout/err"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%bash\n",
      "echo \"hi, stdout\"\n",
      "echo \"hello, stderr\" >&2\n"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "hi, stdout\n"
       ]
      },
      {
       "output_type": "stream",
       "stream": "stderr",
       "text": [
        "hello, stderr\n"
       ]
      }
     ],
     "prompt_number": 30
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%bash --out output --err error\n",
      "echo \"hi, stdout\"\n",
      "echo \"hello, stderr\" >&2"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 31
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "print(error)\n",
      "print(output)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "hello, stderr\n",
        "\n",
        "hi, stdout\n",
        "\n"
       ]
      }
     ],
     "prompt_number": 32
    },
    {
     "cell_type": "heading",
     "level": 2,
     "metadata": {},
     "source": [
      "Background Scripts"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "These scripts can be run in the background, by adding the `--bg` flag.\n",
      "\n",
      "When you do this, output is discarded unless you use the `--out/err`\n",
      "flags to store output as above."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "%%ruby --bg --out ruby_lines\n",
      "for n in 1...10\n",
      "    sleep 1\n",
      "    puts \"line #{n}\"\n",
      "    STDOUT.flush\n",
      "end"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "Starting job # 0 in a separate thread.\n"
       ]
      }
     ],
     "prompt_number": 33
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "When you do store output of a background thread, these are the stdout/err *pipes*,\n",
      "rather than the text of the output."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "ruby_lines"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 34,
       "text": [
        "<open file '<fdopen>', mode 'rb' at 0x112cd55d0>"
       ]
      }
     ],
     "prompt_number": 34
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "print(ruby_lines.read())"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "line 1\n",
        "line 2\n",
        "line 3\n",
        "line 4\n",
        "line 5\n",
        "line 6\n",
        "line 7\n",
        "line 8\n",
        "line 9\n",
        "\n"
       ]
      }
     ],
     "prompt_number": 35
    }
   ],
   "metadata": {}
  }
 ]
}