|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "markdown", |
| 5 | + "metadata": {}, |
| 6 | + "source": [ |
| 7 | + "<img align=\"left\" style=\"padding-right:10px;\" src=\"figures/PDSH-cover-small.png\">\n", |
| 8 | + "*This notebook contains an excerpt from the [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/PythonDataScienceHandbook).*\n", |
| 9 | + "\n", |
| 10 | + "*The text is released under the [CC-BY-NC-ND license](https://creativecommons.org/licenses/by-nc-nd/3.0/us/legalcode), and code is released under the [MIT license](https://opensource.org/licenses/MIT). If you find this content useful, please support the work by [buying the book](http://shop.oreilly.com/product/0636920034919.do)!*" |
| 11 | + ] |
| 12 | + }, |
| 13 | + { |
| 14 | + "cell_type": "markdown", |
| 15 | + "metadata": {}, |
| 16 | + "source": [ |
| 17 | + "# IPython Magic Commands\n", |
| 18 | + "\n", |
| 19 | + "The previous two sections showed how IPython lets you use and explore Python efficiently and interactively.\n", |
| 20 | + "Here we'll begin discussing some of the enhancements that IPython adds on top of the normal Python syntax.\n", |
| 21 | + "These are known in IPython as *magic commands*, and are prefixed by the ``%`` character.\n", |
| 22 | + "These magic commands are designed to succinctly solve various common problems in standard data analysis.\n", |
| 23 | + "Magic commands come in two flavors: *line magics*, which are denoted by a single ``%`` prefix and operate on a single line of input, and *cell magics*, which are denoted by a double ``%%`` prefix and operate on multiple lines of input.\n", |
| 24 | + "We'll demonstrate and discuss a few brief examples here, and come back to more focused discussion of several useful magic commands later in the chapter." |
| 25 | + ] |
| 26 | + }, |
| 27 | + { |
| 28 | + "cell_type": "markdown", |
| 29 | + "metadata": {}, |
| 30 | + "source": [ |
| 31 | + "## Pasting Code Blocks: ``%paste`` and ``%cpaste``\n", |
| 32 | + "\n", |
| 33 | + "When working in the IPython interpreter, one common gotcha is that pasting multi-line code blocks can lead to unexpected errors, especially when indentation and interpreter markers are involved.\n", |
| 34 | + "A common case is that you find some example code on a website and want to paste it into your interpreter.\n", |
| 35 | + "Consider the following simple function:\n", |
| 36 | + "\n", |
| 37 | + "``` python\n", |
| 38 | + ">>> def donothing(x):\n", |
| 39 | + "... return x\n", |
| 40 | + "\n", |
| 41 | + "```\n", |
| 42 | + "The code is formatted as it would appear in the Python interpreter, and if you copy and paste this directly into IPython you get an error:\n", |
| 43 | + "\n", |
| 44 | + "```ipython\n", |
| 45 | + "In [2]: >>> def donothing(x):\n", |
| 46 | + " ...: ... return x\n", |
| 47 | + " ...: \n", |
| 48 | + " File \"<ipython-input-20-5a66c8964687>\", line 2\n", |
| 49 | + " ... return x\n", |
| 50 | + " ^\n", |
| 51 | + "SyntaxError: invalid syntax\n", |
| 52 | + "```\n", |
| 53 | + "\n", |
| 54 | + "In the direct paste, the interpreter is confused by the additional prompt characters.\n", |
| 55 | + "But never fear–IPython's ``%paste`` magic function is designed to handle this exact type of multi-line, marked-up input:\n", |
| 56 | + "\n", |
| 57 | + "```ipython\n", |
| 58 | + "In [3]: %paste\n", |
| 59 | + ">>> def donothing(x):\n", |
| 60 | + "... return x\n", |
| 61 | + "\n", |
| 62 | + "## -- End pasted text --\n", |
| 63 | + "```\n", |
| 64 | + "\n", |
| 65 | + "The ``%paste`` command both enters and executes the code, so now the function is ready to be used:\n", |
| 66 | + "\n", |
| 67 | + "```ipython\n", |
| 68 | + "In [4]: donothing(10)\n", |
| 69 | + "Out[4]: 10\n", |
| 70 | + "```\n", |
| 71 | + "\n", |
| 72 | + "A command with a similar intent is ``%cpaste``, which opens up an interactive multiline prompt in which you can paste one or more chunks of code to be executed in a batch:\n", |
| 73 | + "\n", |
| 74 | + "```ipython\n", |
| 75 | + "In [5]: %cpaste\n", |
| 76 | + "Pasting code; enter '--' alone on the line to stop or use Ctrl-D.\n", |
| 77 | + ":>>> def donothing(x):\n", |
| 78 | + ":... return x\n", |
| 79 | + ":--\n", |
| 80 | + "```\n", |
| 81 | + "\n", |
| 82 | + "These magic commands, like others we'll see, make available functionality that would be difficult or impossible in a standard Python interpreter." |
| 83 | + ] |
| 84 | + }, |
| 85 | + { |
| 86 | + "cell_type": "markdown", |
| 87 | + "metadata": {}, |
| 88 | + "source": [ |
| 89 | + "## Running External Code: ``%run``\n", |
| 90 | + "As you begin developing more extensive code, you will likely find yourself working in both IPython for interactive exploration, as well as a text editor to store code that you want to reuse.\n", |
| 91 | + "Rather than running this code in a new window, it can be convenient to run it within your IPython session.\n", |
| 92 | + "This can be done with the ``%run`` magic.\n", |
| 93 | + "\n", |
| 94 | + "For example, imagine you've created a ``myscript.py`` file with the following contents:\n", |
| 95 | + "\n", |
| 96 | + "```python\n", |
| 97 | + "#-------------------------------------\n", |
| 98 | + "# file: myscript.py\n", |
| 99 | + "\n", |
| 100 | + "def square(x):\n", |
| 101 | + " \"\"\"square a number\"\"\"\n", |
| 102 | + " return x ** 2\n", |
| 103 | + "\n", |
| 104 | + "for N in range(1, 4):\n", |
| 105 | + " print(N, \"squared is\", square(N))\n", |
| 106 | + "```\n", |
| 107 | + "\n", |
| 108 | + "You can execute this from your IPython session as follows:\n", |
| 109 | + "\n", |
| 110 | + "```ipython\n", |
| 111 | + "In [6]: %run myscript.py\n", |
| 112 | + "1 squared is 1\n", |
| 113 | + "2 squared is 4\n", |
| 114 | + "3 squared is 9\n", |
| 115 | + "```\n", |
| 116 | + "\n", |
| 117 | + "Note also that after you've run this script, any functions defined within it are available for use in your IPython session:\n", |
| 118 | + "\n", |
| 119 | + "```ipython\n", |
| 120 | + "In [7]: square(5)\n", |
| 121 | + "Out[7]: 25\n", |
| 122 | + "```\n", |
| 123 | + "\n", |
| 124 | + "There are several options to fine-tune how your code is run; you can see the documentation in the normal way, by typing **``%run?``** in the IPython interpreter." |
| 125 | + ] |
| 126 | + }, |
| 127 | + { |
| 128 | + "cell_type": "markdown", |
| 129 | + "metadata": {}, |
| 130 | + "source": [ |
| 131 | + "## Timing Code Execution: ``%timeit``\n", |
| 132 | + "Another example of a useful magic function is ``%timeit``, which will automatically determine the execution time of the single-line Python statement that follows it.\n", |
| 133 | + "For example, we may want to check the performance of a list comprehension:\n", |
| 134 | + "\n", |
| 135 | + "```ipython\n", |
| 136 | + "In [8]: %timeit L = [n ** 2 for n in range(1000)]\n", |
| 137 | + "1000 loops, best of 3: 325 µs per loop\n", |
| 138 | + "```\n", |
| 139 | + "\n", |
| 140 | + "The benefit of ``%timeit`` is that for short commands it will automatically perform multiple runs in order to attain more robust results.\n", |
| 141 | + "For multi line statements, adding a second ``%`` sign will turn this into a cell magic that can handle multiple lines of input.\n", |
| 142 | + "For example, here's the equivalent construction with a ``for``-loop:\n", |
| 143 | + "\n", |
| 144 | + "```ipython\n", |
| 145 | + "In [9]: %%timeit\n", |
| 146 | + " ...: L = []\n", |
| 147 | + " ...: for n in range(1000):\n", |
| 148 | + " ...: L.append(n ** 2)\n", |
| 149 | + " ...: \n", |
| 150 | + "1000 loops, best of 3: 373 µs per loop\n", |
| 151 | + "```\n", |
| 152 | + "\n", |
| 153 | + "We can immediately see that list comprehensions are about 10% faster than the equivalent ``for``-loop construction in this case.\n", |
| 154 | + "We'll explore ``%timeit`` and other approaches to timing and profiling code in [Profiling and Timing Code](01.07-Timing-and-Profiling.ipynb)." |
| 155 | + ] |
| 156 | + }, |
| 157 | + { |
| 158 | + "cell_type": "markdown", |
| 159 | + "metadata": {}, |
| 160 | + "source": [ |
| 161 | + "## Help on Magic Functions: ``?``, ``%magic``, and ``%lsmagic``\n", |
| 162 | + "\n", |
| 163 | + "Like normal Python functions, IPython magic functions have docstrings, and this useful\n", |
| 164 | + "documentation can be accessed in the standard manner.\n", |
| 165 | + "So, for example, to read the documentation of the ``%timeit`` magic simply type this:\n", |
| 166 | + "\n", |
| 167 | + "```ipython\n", |
| 168 | + "In [10]: %timeit?\n", |
| 169 | + "```\n", |
| 170 | + "\n", |
| 171 | + "Documentation for other functions can be accessed similarly.\n", |
| 172 | + "To access a general description of available magic functions, including some examples, you can type this:\n", |
| 173 | + "\n", |
| 174 | + "```ipython\n", |
| 175 | + "In [11]: %magic\n", |
| 176 | + "```\n", |
| 177 | + "\n", |
| 178 | + "For a quick and simple list of all available magic functions, type this:\n", |
| 179 | + "\n", |
| 180 | + "```ipython\n", |
| 181 | + "In [12]: %lsmagic\n", |
| 182 | + "```\n", |
| 183 | + "\n", |
| 184 | + "Finally, I'll mention that it is quite straightforward to define your own magic functions if you wish.\n", |
| 185 | + "We won't discuss it here, but if you are interested, see the references listed in [More IPython Resources](01.08-More-IPython-Resources.ipynb)." |
| 186 | + ] |
| 187 | + } |
| 188 | + ], |
| 189 | + "metadata": { |
| 190 | + "anaconda-cloud": {}, |
| 191 | + "kernelspec": { |
| 192 | + "display_name": "Python [default]", |
| 193 | + "language": "python", |
| 194 | + "name": "python3" |
| 195 | + }, |
| 196 | + "language_info": { |
| 197 | + "codemirror_mode": { |
| 198 | + "name": "ipython", |
| 199 | + "version": 3 |
| 200 | + }, |
| 201 | + "file_extension": ".py", |
| 202 | + "mimetype": "text/x-python", |
| 203 | + "name": "python", |
| 204 | + "nbconvert_exporter": "python", |
| 205 | + "pygments_lexer": "ipython3", |
| 206 | + "version": "3.5.1" |
| 207 | + } |
| 208 | + }, |
| 209 | + "nbformat": 4, |
| 210 | + "nbformat_minor": 0 |
| 211 | +} |
0 commit comments