##// END OF EJS Templates
nbconvert
David P. Sanders -
Show More
@@ -1,572 +1,583 b''
1 .. _htmlnotebook:
1 .. _htmlnotebook:
2
2
3 The IPython Notebook
3 The IPython Notebook
4 ====================
4 ====================
5
5
6 .. seealso::
6 .. seealso::
7
7
8 :ref:`Installation requirements <installnotebook>` for the Notebook.
8 :ref:`Installation requirements <installnotebook>` for the Notebook.
9
9
10 The IPython Notebook combines two components:
10 The IPython Notebook combines two components:
11
11
12 * A web application, called the *IPython Notebook web app*, for interactive authoring of literate computations, in which explanatory text, mathematics, computations and rich media output may be combined. Input and output are stored in persistent cells that may be edited in-place.
12 * A web application, called the *IPython Notebook web app*, for interactive authoring of literate computations, in which explanatory text, mathematics, computations and rich media output may be combined. Input and output are stored in persistent cells that may be edited in-place.
13
13
14 * Plain text documents, called *notebook documents*, or *notebooks*, for recording and distributing the results of the rich computations.
14 * Plain text documents, called *notebook documents*, or *notebooks*, for recording and distributing the results of the rich computations.
15
15
16 In the documentation, the distinction between the *N*otebook app and *n*otebook documents is made by capitalization.
16 In the documentation, the distinction between the *N*otebook app and *n*otebook documents is made by capitalization.
17
17
18 The Notebook app automatically saves the current state of the computation in the web browser to the corresponding notebook document.
18 The Notebook app automatically saves the current state of the computation in the web browser to the corresponding notebook document.
19
19
20 It is also common to refer to the current state of the computation, as represented by the sequence of input cells in the Notebook app, as a
20 It is also common to refer to the current state of the computation, as represented by the sequence of input cells in the Notebook app, as a
21 *notebook*. There is no problem with confounding these two concepts, since
21 *notebook*. There is no problem with confounding these two concepts, since
22 there is actually a one-to-one correspondence between what you see on the
22 there is actually a one-to-one correspondence between what you see on the
23 screen inside the app, and what is stored in the corresponding ``.ipynb`` notebook document.
23 screen inside the app, and what is stored in the corresponding ``.ipynb`` notebook document.
24
24
25
25
26
26
27 Features of the IPython Notebook web app
27 Features of the IPython Notebook web app
28 ----------------------------------------
28 ----------------------------------------
29
29
30 Some of the main
30 Some of the main
31 features of the IPython Notebook app include:
31 features of the IPython Notebook app include:
32
32
33 * Display rich data representations (e.g. HTML / LaTeX / SVG) in the browser as a result of computations.
33 * Display rich data representations (e.g. HTML / LaTeX / SVG) in the browser as a result of computations.
34 * Compose text cells using Markdown and HTML.
34 * Compose text cells using Markdown and HTML.
35 * Include mathematical equations, rendered directly in the browser by MathJax.
35 * Include mathematical equations, rendered directly in the browser by MathJax.
36 * Import standard Python scripts
36 * Import standard Python scripts
37 * In-browser editing, syntax highlighting, tab completion and autoindentation.
37 * In-browser editing, syntax highlighting, tab completion and autoindentation.
38 * Inline figures rendered by the ``matplotlib`` library with publication quality, in a range of formats (SVG / PDF / PNG).
38 * Inline figures rendered by the ``matplotlib`` library with publication quality, in a range of formats (SVG / PDF / PNG).
39
39
40 If you have ever used the Mathematica or SAGE notebooks (the latter is also
40 If you have ever used the Mathematica or SAGE notebooks (the latter is also
41 web-based__) you should feel right at home. If you have not, you will be
41 web-based__) you should feel right at home. If you have not, you will be
42 able to learn how to use the IPython Notebook in just a few minutes.
42 able to learn how to use the IPython Notebook in just a few minutes.
43
43
44 .. __: http://sagenb.org
44 .. __: http://sagenb.org
45
45
46
46
47 Notebook documents
47 Notebook documents
48 ------------------
48 ------------------
49
49
50 Notebook document files are just standard text files with the extension
50 Notebook document files are just standard text files with the extension
51 ``.ipynb``, stored in the working directory on your computer. This file can be easily put under version control and shared with colleagues.
51 ``.ipynb``, stored in the working directory on your computer. This file can be easily put under version control and shared with colleagues.
52
52
53 Despite the fact that the notebook documents are plain text files, they use
53 Despite the fact that the notebook documents are plain text files, they use
54 the JSON format in order to store a *complete*, *reproducible* copy of the
54 the JSON format in order to store a *complete*, *reproducible* copy of the
55 state of the computation as it is inside the Notebook app.
55 state of the computation as it is inside the Notebook app.
56 That is, they record all computations carried out and the results obtained in a literate way; inputs and outputs of computations can be freely mixed with descriptive text, mathematics, and HTML 5 objects.
56 That is, they record all computations carried out and the results obtained in a literate way; inputs and outputs of computations can be freely mixed with descriptive text, mathematics, and HTML 5 objects.
57
57
58 Notebooks may easily be exported to a range of static formats, including HTML (for example, for blog posts), PDF and slide shows.
58 Notebooks may easily be exported to a range of static formats, including HTML (for example, for blog posts), PDF and slide shows.
59 Furthermore, any publicly
59 Furthermore, any publicly
60 available notebook may be shared via the `IPython Notebook Viewer
60 available notebook may be shared via the `IPython Notebook Viewer
61 <http://nbviewer.ipython.org>`_ service, which will provide it as a static web
61 <http://nbviewer.ipython.org>`_ service, which will provide it as a static web
62 page. The results may thus be shared without having to install anything.
62 page. The results may thus be shared without having to install anything.
63
63
64
64
65 See :ref:`our installation documentation <install_index>` for directions on
65 See :ref:`our installation documentation <install_index>` for directions on
66 how to install the notebook and its dependencies.
66 how to install the notebook and its dependencies.
67
67
68 .. note::
68 .. note::
69
69
70 You can start more than one notebook server at the same time, if you want to
70 You can start more than one notebook server at the same time, if you want to
71 work on notebooks in different directories. By default the first notebook
71 work on notebooks in different directories. By default the first notebook
72 server starts on port 8888, and later notebook servers search for ports near
72 server starts on port 8888, and later notebook servers search for ports near
73 that one. You can also manually specify the port with the ``--port``
73 that one. You can also manually specify the port with the ``--port``
74 option.
74 option.
75
75
76
76
77 Running the IPython Notebook web app
77 Starting up the IPython Notebook web app
78 ====================================
78 ----------------------------------------
79
79
80 The Notebook web app is started with the command::
80 The Notebook web app is started with the command::
81
81
82 $ ipython notebook
82 $ ipython notebook
83
83
84 The landing page of the notebook server application, the *dashboard*, shows the notebooks currently available in the *working directory* (the directory from which the notebook was started).
84 The landing page of the notebook server application, the *dashboard*, shows the notebooks currently available in the *working directory* (the directory from which the notebook was started).
85 You can create new notebooks from the dashboard with the ``New Notebook``
85 You can create new notebooks from the dashboard with the ``New Notebook``
86 button, or open existing ones by clicking on their name.
86 button, or open existing ones by clicking on their name.
87 You can also drag and drop ``.ipynb`` notebooks and standard ``.py`` Python source code files into the notebook list area.
87 You can also drag and drop ``.ipynb`` notebooks and standard ``.py`` Python source code files into the notebook list area.
88
88
89 ``.py`` files will be imported into the IPython Notebook as a notebook with the same name, but an ``.ipynb`` extension, located in the working directory. The notebook will consist of a single cell containing all the
89 ``.py`` files will be imported into the IPython Notebook as a notebook with the same name, but an ``.ipynb`` extension, located in the working directory. The notebook will consist of a single cell containing all the
90 code in the ``.py`` file, which you can later manually partition into individual cells.
90 code in the ``.py`` file, which you can later manually partition into individual cells.
91
91
92 .. Alternatively, prior to importing the ``.py``, you can manually add ``# <nbformat>2</nbformat>`` at the start of the file, and then add separators for text and code cells, to get a cleaner import with the file already broken into individual cells.
92 .. Alternatively, prior to importing the ``.py``, you can manually add ``# <nbformat>2</nbformat>`` at the start of the file, and then add separators for text and code cells, to get a cleaner import with the file already broken into individual cells.
93
93
94
94
95 The IPython Notebook web app is based on a server-client structure.
95 The IPython Notebook web app is based on a server-client structure.
96 This server uses a two-process kernel architecture based on ZeroMQ, as well as Tornado for serving HTTP requests. Other clients may connect to the same underlying IPython kernel.
96 This server uses a two-process kernel architecture based on ZeroMQ, as well as Tornado for serving HTTP requests. Other clients may connect to the same underlying IPython kernel.
97
97
98
98
99 When you open or create a new notebook, your browser tab will reflect the name of that notebook, prefixed with "IPy".
99 When you open or create a new notebook, your browser tab will reflect the name of that notebook, prefixed with "IPy".
100 The URL is currently not meant to be human-readable and is not persistent across invocations of the notebook server; however, this will change in a future version of IPython.
100 The URL is currently not meant to be human-readable and is not persistent across invocations of the notebook server; however, this will change in a future version of IPython.
101
101
102
102
103 Notebook user interface
103 Notebook user interface
104 -----------------------
104 -----------------------
105
105
106 When you finally start editing a notebook document in the Notebook, you will be presented with the title of the notebook, a *menu bar*, a *toolbar* and an empty *input cell*.
106 When you finally start editing a notebook document in the Notebook, you will be presented with the title of the notebook, a *menu bar*, a *toolbar* and an empty *input cell*.
107
107
108 Notebook title
108 Notebook title
109 ~~~~~~~~~~~~~~
109 ~~~~~~~~~~~~~~
110 The title of the notebook document that is currently being edited is displayed at the top of the page, next to the ``IP[y]: Notebook`` logo. This title may be edited directly by clicking on it. The title is reflected in the name of the ``.ipynb`` notebook document file that is saved.
110 The title of the notebook document that is currently being edited is displayed at the top of the page, next to the ``IP[y]: Notebook`` logo. This title may be edited directly by clicking on it. The title is reflected in the name of the ``.ipynb`` notebook document file that is saved.
111
111
112 Menu bar
112 Menu bar
113 ~~~~~~~~
113 ~~~~~~~~
114 The menu bar presents different options that may be used to manipulate the way the Notebook functions.
114 The menu bar presents different options that may be used to manipulate the way the Notebook functions.
115
115
116 Toolbar
116 Toolbar
117 ~~~~~~~
117 ~~~~~~~
118 The tool bar gives handy icons for the most-used operations within the Notebook.
118 The tool bar gives handy icons for the most-used operations within the Notebook.
119
119
120
120
121 Input cells
121 Input cells
122 -----------
122 -----------
123 Input cells are the core of the functionality of the IPython Notebook.
123 Input cells are the core of the functionality of the IPython Notebook.
124 They are regions in the document where you can enter different types of text and commands. These regions are then executed using :kbd:`Shift-Enter`, at which point the Notebook executes the current input cell, displays the resulting output beneath it, and adds a new input cell below.
124 They are regions in the document where you can enter different types of text and commands. These regions are then executed using :kbd:`Shift-Enter`, at which point the Notebook executes the current input cell, displays the resulting output beneath it, and adds a new input cell below.
125
125
126 The notebook consists of a sequence of input cells,
126 The notebook consists of a sequence of input cells,
127 providing the means to direct the computational process.
127 providing the means to direct the computational process.
128
128
129
129
130 Basic workflow
130 Basic workflow
131 --------------
131 --------------
132 The normal workflow in a notebook is, then, quite similar to a standard IPython session, with the difference that you can edit cells in-place multiple
132 The normal workflow in a notebook is, then, quite similar to a standard IPython session, with the difference that you can edit cells in-place multiple
133 times until you obtain the desired results, rather than having to
133 times until you obtain the desired results, rather than having to
134 rerun separate scripts with the ``%run`` magic command. (Magic commands do, however, also work in the notebook; see below). Typically, you'll work on a problem in pieces,
134 rerun separate scripts with the ``%run`` magic command. (Magic commands do, however, also work in the notebook; see below). Typically, you'll work on a problem in pieces,
135 organizing related pieces into cells and moving forward as previous
135 organizing related pieces into cells and moving forward as previous
136 parts work correctly. This is much more convenient for interactive exploration than breaking up a computation into scripts that must be
136 parts work correctly. This is much more convenient for interactive exploration than breaking up a computation into scripts that must be
137 executed together, especially if parts of them take a long time to run
137 executed together, especially if parts of them take a long time to run
138
138
139 The only significant limitation that the notebook currently has, compared to the Qt console, is that it cannot run any code that
139 The only significant limitation that the notebook currently has, compared to the Qt console, is that it cannot run any code that
140 expects input from the kernel (such as scripts that call
140 expects input from the kernel (such as scripts that call
141 :func:`raw_input`). Very importantly, this means that the ``%debug``
141 :func:`raw_input`). Very importantly, this means that the ``%debug``
142 magic does *not* currently work in the notebook! This limitation will
142 magic does *not* currently work in the notebook! This limitation will
143 be overcome in the future, but in the meantime, there is a way to debug problems in the notebook: you can attach a Qt console to your existing notebook kernel, and run ``%debug`` from the Qt console.
143 be overcome in the future, but in the meantime, there is a way to debug problems in the notebook: you can attach a Qt console to your existing notebook kernel, and run ``%debug`` from the Qt console.
144 If your notebook is running on a local
144 If your notebook is running on a local
145 computer (i.e. if you are accessing it via your localhost address at ``127.0.0.1``), you can just type ``%qtconsole`` in the notebook and a Qt console will open up, connected to that same kernel.
145 computer (i.e. if you are accessing it via your localhost address at ``127.0.0.1``), you can just type ``%qtconsole`` in the notebook and a Qt console will open up, connected to that same kernel.
146
146
147 At certain moments, it may be necessary to interrupt a particularly long calculation, or even to kill the entire computational process. This may be achieved by interrupting or restarting the kernel, respectively.
147 At certain moments, it may be necessary to interrupt a particularly long calculation, or even to kill the entire computational process. This may be achieved by interrupting or restarting the kernel, respectively.
148 After a restart, all relevant cells must be re-evaluated
148 After a restart, all relevant cells must be re-evaluated
149
149
150
150
151 Saveing a notebook
151 A notebook may be downloaded in either ``.ipynb`` or raw ``.py`` form from the menu option ``File -> Download as``
152 ------------------
152 Choosing the ``.py`` option removes all output and saves the text cells
153
154 The `Download` button lets you save a notebook file to the Download area
155 configured by your web browser (particularly useful if you are running the
156 notebook server on a remote host and need a file locally).
157 But you can always export
158 the input part of a notebook to a plain python script by choosing Python format
159 in the `Download` drop list. This removes all output and saves the text cells
160 in comment areas. See ref:`below <notebook_format>` for more details on the
153 in comment areas. See ref:`below <notebook_format>` for more details on the
161 notebook format.
154 notebook format.
162
155
163
156
164 .. warning::
157 .. warning::
165
158
166 While in simple cases you can roundtrip a notebook to Python, edit the
159 While in simple cases you can "roundtrip" a notebook to Python, edit the
167 python file and import it back without loss of main content, this is in
160 Python file, and then import it back without loss of main content, this is in general *not guaranteed to work*. First, there is extra metadata
168 general *not guaranteed to work at all*. First, there is extra metadata
169 saved in the notebook that may not be saved to the ``.py`` format. And as
161 saved in the notebook that may not be saved to the ``.py`` format. And as
170 the notebook format evolves in complexity, there will be attributes of the
162 the notebook format evolves in complexity, there will be attributes of the
171 notebook that will not survive a roundtrip through the Python form. You
163 notebook that will not survive a roundtrip through the Python form. You
172 should think of the Python format as a way to output a script version of a
164 should think of the Python format as a way to output a script version of a
173 notebook and the import capabilities as a way to load existing code to get a
165 notebook and the import capabilities as a way to load existing code to get a
174 notebook started. But the Python version is *not* an alternate notebook
166 notebook started. But the Python version is *not* an alternate notebook
175 format.
167 format.
176
168
177
178 Importing or executing a notebook as a normal Python file
179 ---------------------------------------------------------
180
181 The native format of the notebook, a file with a ``.ipynb`` `extension, is a
182 JSON container of all the input and output of the notebook, and therefore not
183 valid Python by itself. This means that by default, you cannot directly
184 import a notebook from Python, nor execute it as a normal python script.
185
169
186 But if you want to be able to use notebooks also as regular Python files, you can start the notebook server with::
170 Keyboard shortcuts
187
171 ------------------
188 ipython notebook --script
172 All actions in the notebook can be achieved with the mouse, but we have also
189
173 added keyboard shortcuts for the most common ones, so that productive use of
190 or you can set this option permanently in your configuration file with::
174 the notebook can be achieved with minimal mouse intervention. The main
191
175 key bindings you need to remember are:
192 c.NotebookManager.save_script=True
193
194 This will instruct the notebook server to save the ``.py`` export of each
195 notebook, in addition to the ``.ipynb``, at every save. These are standard ``.py`` files, and so they can be
196 ``%run``, imported from regular IPython sessions or other notebooks, or
197 executed at the command-line. Since we export the raw
198 code you have typed, for these files to be importable from other code you will
199 have to avoid using syntax such as ``%magics`` and other IPython-specific
200 extensions to the language.
201
202 In regular practice, the standard way to differentiate importable code from the
203 'executable' part of a script is to put at the bottom::
204
176
205 if __name__ == '__main__':
177 * :kbd:`Shift-Enter`:
206 # rest of the code...
178 execute the current cell, show output (if any), and jump
179 to the next cell below. If :kbd:`Shift-Enter`
180 was invoked on the last input line, a new code cell will also be created. Note that in the notebook, simply using :kbd:`Enter` *never* forces execution, it simply inserts a new line in the current cell. Therefore, in the notebook you must always use :kbd:`Shift-Enter` to get execution (or use the mouse and click on the ``Run Selected`` button).
207
181
208 Since all cells in the notebook are run as top-level code, you'll need to
182 * :kbd:`Alt-Enter`:
209 similarly protect *all* cells that you do not want executed when other scripts
183 this combination is similar to the previous one, with the
210 try to import your notebook. A convenient shortand for this is to define early
184 exception that, if the next cell below is not empty, a new code cell will be
211 on::
185 added to the notebook, even if the cell execution happens not in the last cell. :kbd:`Alt-Enter`: is a shortcut for the sequence :kbd:`Shift-Enter`, :kbd:`Ctrl-m a`.
186
187 * :kbd:`Ctrl-Enter`:
188 execute the current cell in "terminal mode", where any
189 output is shown, but the cursor remains in the current cell. This is convenient to do quick in-place experiments, or query things like filesystem content, without creating additional cells that you may not want saved in your notebook.
212
190
213 script = __name__ == '__main__'
191 * :kbd:`Ctrl-m`:
192 this is the prefix for all other keybindings, which consist of an additional single letter or character. Type :kbd:`Ctrl-m h` (that is, the sole letter
193 :kbd:`h` after :kbd:`Ctrl-m`) and IPython will show you the remaining available keybindings.
214
194
215 and then on any cell that you need to protect, use::
216
195
217 if script:
218 # rest of the cell...
219
196
197
220
198
221 Cell types
199 Cell types
222 ----------
200 ----------
223 Each IPython input cell has a *cell type*.
201 Each IPython input cell has a *cell type*.
224 There is a restricted number of possible cell types, which may be set by using the cell type dropdown on the toolbar, or via the following keyboard shortcuts:
202 There is a restricted number of possible cell types, which may be set by using the cell type dropdown on the toolbar, or via the following keyboard shortcuts:
225
203
226 * **code**: :kbd:`Ctrl-m y`
204 * **code**: :kbd:`Ctrl-m y`
227 * **markdown**: :kbd:`Ctrl-m m`
205 * **markdown**: :kbd:`Ctrl-m m`
228 * **raw**: :kbd:`Ctrl-m t`
206 * **raw**: :kbd:`Ctrl-m t`
229 * **heading**: :kbd:`Ctrl-m 1` - :kbd:`Ctrl-m 6`
207 * **heading**: :kbd:`Ctrl-m 1` - :kbd:`Ctrl-m 6`
230
208
231
209
232 Code cells
210 Code cells
233 ~~~~~~~~~~
211 ~~~~~~~~~~
234 Code cells contain code written in some computer language, which is Python by default. When the cell is executed with :kbd:`Shift-Enter`, this code is executed, and the result returned by Python (or the corresponding language) after running the code will be displayed as its output.
212 Code cells contain code written in some computer language, which is Python by default. When the cell is executed with :kbd:`Shift-Enter`, this code is executed, and the result returned by Python (or the corresponding language) after running the code will be displayed as its output.
235
213
236 Code may be edited inline in the cell, with full syntax highlighting.
214 Code may be edited inline in the cell, with full syntax highlighting.
237
215
238
216
239 Rich text using Markdown
217 Rich text using Markdown
240 ~~~~~~~~~~~~~~~~~~~~~~~~
218 ~~~~~~~~~~~~~~~~~~~~~~~~
241 The computational process may be documented in a literate way using rich text.
219 The computational process may be documented in a literate way using rich text.
242 For this purpose, the Notebook provides markdown cells. Text is entered using Markdown_ syntax, allowing for italics, bold, ordered and unordered lists, etc. This is rendered using Markdown syntax to a rich HTML representation when the cell is executed. In this case, the output *replaces* the input cell.
220 For this purpose, the Notebook provides markdown cells. Text is entered using Markdown_ syntax, allowing for italics, bold, ordered and unordered lists, etc. This is rendered using Markdown syntax to a rich HTML representation when the cell is executed. In this case, the output *replaces* the input cell.
243
221
244 Within markdown cells, mathematics can be included in a straightforward manner using LaTeX notation: ``$...$`` for inline math and ``$$...$$`` for displayed math. Standard LaTeX environments, such as ``\begin{equation}...\end{equation}``, also work. New commands may be defined using standard LaTeX commands, placed anywhere in a markdown cell.
222 Within markdown cells, mathematics can be included in a straightforward manner using LaTeX notation: ``$...$`` for inline math and ``$$...$$`` for displayed math. Standard LaTeX environments, such as ``\begin{equation}...\end{equation}``, also work. New commands may be defined using standard LaTeX commands, placed anywhere in a markdown cell.
245
223
246 Raw cells
224 Raw cells
247 ~~~~~~~~~
225 ~~~~~~~~~
248 Raw cells provide a place to put additional information which is not evaluated by the Notebook. This can be used, for example, for extra information to be used when the notebook is exported to a certain format.
226 Raw cells provide a place to put additional information which is not evaluated by the Notebook. This can be used, for example, for extra information to be used when the notebook is exported to a certain format.
249
227
250
228
251 Magic commands
229 Magic commands
252 --------------
230 --------------
253 Magic commands, or *magics*, are one-word commands beginning with the symbol ``%``, which send commands to IPython itself (as opposed to standard Python commands which are exported to be run in a Python interpreter).
231 Magic commands, or *magics*, are one-word commands beginning with the symbol ``%``, which send commands to IPython itself (as opposed to standard Python commands which are exported to be run in a Python interpreter).
254
232
255 Magics control different elements of the way that the IPython notebook operates. They are entered into standard code cells and executed as usual with :kbd:`Shift-Enter`.
233 Magics control different elements of the way that the IPython notebook operates. They are entered into standard code cells and executed as usual with :kbd:`Shift-Enter`.
256
234
257 There are two types of magics: *line magics*, which begin with a single ``%`` and operate on a single line of the code cell; and *cell magics*, which begin with ``%%`` and operate on the entire contents of the cell.
235 There are two types of magics: *line magics*, which begin with a single ``%`` and operate on a single line of the code cell; and *cell magics*, which begin with ``%%`` and operate on the entire contents of the cell.
258
236
259 Line magics
237 Line magics
260 ˜˜˜˜˜˜˜˜˜˜˜
238 ˜˜˜˜˜˜˜˜˜˜˜
261 Some of the available line magics are the following:
239 Some of the available line magics are the following:
262
240
263 * ``%load``:
241 * ``%load``:
264 Loads a file and places its content into a new code cell.
242 Loads a file and places its content into a new code cell.
265
243
266 * ``%timeit``:
244 * ``%timeit``:
267 A simple way to time how long a single line of code takes to run
245 A simple way to time how long a single line of code takes to run
268
246
269 * ``%config``:
247 * ``%config``:
270 Configuration of the IPython Notebook
248 Configuration of the IPython Notebook
271
249
272 * ``%lsmagic``:
250 * ``%lsmagic``:
273 Provides a list of all available magic commands
251 Provides a list of all available magic commands
274
252
275 Cell magics
253 Cell magics
276 ˜˜˜˜˜˜˜˜˜˜˜
254 ˜˜˜˜˜˜˜˜˜˜˜
277
255
278 * ``%%bash``:
256 * ``%%bash``:
279 Send the contents of the code cell to be executed by ``bash``
257 Send the contents of the code cell to be executed by ``bash``
280
258
281 * ``%%file``:
259 * ``%%file``:
282 Writes a file with with contents of the cell. *Caution*: The file is ovewritten without asking.
260 Writes a file with with contents of the cell. *Caution*: The file is ovewritten without asking.
283
261
284 * ``%%R``:
262 * ``%%R``:
285 Execute the contents of the cell using the R language.
263 Execute the contents of the cell using the R language.
286
264
287 * ``%%cython``:
265 * ``%%cython``:
288 Execute the contents of the cell using ``Cython``.
266 Execute the contents of the cell using ``Cython``.
289
267
290
268
291
269
292 Plotting
270 Plotting
293 --------
271 --------
294 One major feature of the Notebook is the ability to capture the result of plots as inline output. IPython is designed to work seamlessly together with
272 One major feature of the Notebook is the ability to capture the result of plots as inline output. IPython is designed to work seamlessly together with
295 the ``%matplotlib`` plotting library. In order to set this up, the
273 the ``%matplotlib`` plotting library. In order to set this up, the
296 ``%matplotlib`` magic command must be run before any plotting takes place.
274 ``%matplotlib`` magic command must be run before any plotting takes place.
297
275
298 Note that ``%matplotlib`` only sets up IPython to work correctly with ``matplotlib``; it does not actually execute any ``import`` commands and does not add anything to the namespace.
276 Note that ``%matplotlib`` only sets up IPython to work correctly with ``matplotlib``; it does not actually execute any ``import`` commands and does not add anything to the namespace.
299
277
300 There is an alternative magic, ``%pylab``, which, in addition, also executes a sequence of standard ``import`` statements required for working with the
278 There is an alternative magic, ``%pylab``, which, in addition, also executes a sequence of standard ``import`` statements required for working with the
301 ``%matplotlib`` library. In particular, it automatically imports all names in the ``numpy`` and ``matplotlib`` packages to the namespace. A less invasive solution is ``%pylab --no-import-all``, which imports just the standard names
279 ``%matplotlib`` library. In particular, it automatically imports all names in the ``numpy`` and ``matplotlib`` packages to the namespace. A less invasive solution is ``%pylab --no-import-all``, which imports just the standard names
302 ``np`` for the ``numpy`` module and ``plt`` for the ``matplotlib.pyplot`` module.
280 ``np`` for the ``numpy`` module and ``plt`` for the ``matplotlib.pyplot`` module.
303
281
304 When the default ``%matplotlib`` or ``%pylab`` magics are used, the output of a plotting command is captured in a *separate* window. An alternative is to use::
282 When the default ``%matplotlib`` or ``%pylab`` magics are used, the output of a plotting command is captured in a *separate* window. An alternative is to use::
305 ``%matplotlib inline``
283 ``%matplotlib inline``
306 which captures the output inline within the notebook format. This has the benefit that the resulting plots will be stored in the notebook document.
284 which captures the output inline within the notebook format. This has the benefit that the resulting plots will be stored in the notebook document.
307
285
308 Converting notebooks to other formats using nbconvert
286
309 ------------------------------------------------------
287 Converting notebooks to other formats
288 -------------------------------------
289 Newly added in the 1.0 release of IPython is the ``nbconvert`` tool to convert a notebook document into another static format. This is a command line tool; at present, this functionality is not available to export directly from within the Notebook app. The syntax is::
290
291 ``$ ipython nbconvert notebook.ipynb``
292
293 for standard HTML output, or::
294
295 ``$ ipython nbconvert --format=FORMAT notebook.ipynb``
296
297 where ``FORMAT`` is the desired export format. Options for this format include:
298
299 * ``full_html``:
300 Standard HTML
301
302 * ``simple_html``:
303 A simplified version of HTML
304
305 * ``reveal``:
306 A format to be used with the ``reveal.js`` package for slideshow presentations.
307
308 * ``sphinx_howto``:
309 A standard documentation format.
310
311 * ``latex``:
312 Produces LaTeX output which may be compiled with ``pdflatex`` to PDF.
310
313
311
314
312 Configuration
315 Configuration
313 -------------
316 -------------
314
317 The IPython Notebook can be run with a variety of command line arguments.
315 The IPython notebook server can be run with a variety of command line arguments.
316 To see a list of available options enter::
318 To see a list of available options enter::
317
319
318 $ ipython notebook --help
320 $ ipython notebook --help
319
321
320 Defaults for these options can also be set by creating a file named
322 Defaults for these options can also be set by creating a file named
321 ``ipython_notebook_config.py`` in your IPython profile folder. The profile folder is a subfolder of your IPython directory; ``ipython locate`` will show you where it is located.
323 ``ipython_notebook_config.py`` in your IPython *profile folder*. The profile folder is a subfolder of your IPython directory; ``ipython locate`` will show you where it is located.
322
324
323 To create a new set of default configuration files, with lots of information on available options, use::
325 To create a new set of default configuration files, with lots of information on available options, use::
324
326
325 $ ipython profile create
327 $ ipython profile create
326
328
327 .. seealso:
329 .. seealso:
328
330
329 :ref:`config_overview`, in particular :ref:`Profiles`.
331 :ref:`config_overview`, in particular :ref:`Profiles`.
330
332
331
333
332 Keyboard shortcuts
333 ------------------
334
334
335 All actions in the notebook can be achieved with the mouse, but we have also
335 Importing or executing a notebook as a normal Python file
336 added keyboard shortcuts for the most common ones, so that productive use of
336 ---------------------------------------------------------
337 the notebook can be achieved with minimal mouse intervention. The main
338 key bindings you need to remember are:
339
337
340 * :kbd:`Shift-Enter`: execute the current cell (similar to the Qt console),
338 The native format of the notebook, a file with a ``.ipynb`` `extension, is a
341 show output (if any) and jump to the next cell below. If :kbd:`Shift-Enter`
339 JSON container of all the input and output of the notebook, and therefore not
342 was invoked on the last input line, a new code cell will also be created. Note
340 valid Python by itself. This means that by default, you cannot directly
343 that in the notebook, simply using :kbd:`Enter` *never* forces execution,
341 import a notebook from Python, nor execute it as a normal python script.
344 it simply inserts a new line in the current cell. Therefore, in the notebook
345 you must always use :kbd:`Shift-Enter` to get execution (or use the mouse and
346 click on the ``Run Selected`` button).
347
342
348 * :kbd:`Alt-Enter`: this combination is similar to the previous one, with the
343 But if you want to be able to use notebooks also as regular Python files, you can start the notebook server with::
349 exception that, if the next cell below is not empty, a new code cell will be
344
350 added to the notebook, even if the cell execution happens not in the last cell.
345 ipython notebook --script
351 In this regard, :kbd:`Alt-Enter`: is simply a shortcut for the :kbd:`Shift-Enter`,
346
352 :kbd:`Ctrl-m a` sequence.
347 or you can set this option permanently in your configuration file with::
353
348
354 * :kbd:`Ctrl-Enter`: execute the current cell in "terminal mode", where any
349 c.NotebookManager.save_script=True
355 output is shown but the cursor stays in the current cell, whose input
350
356 area is flushed empty. This is convenient to do quick in-place experiments
351 This will instruct the notebook server to save the ``.py`` export of each
357 or query things like filesystem content without creating additional cells you
352 notebook, in addition to the ``.ipynb``, at every save. These are standard
358 may not want saved in your notebook.
353 ``.py`` files, and so they can be ``%run``, imported from regular IPython
359
354 sessions or other notebooks, or executed at the command line. Since we export
360 * :kbd:`Ctrl-m`: this is the prefix for all other keybindings, which consist
355 the raw code you have typed, for these files to be importable from other code,
361 of an additional single letter. Type :kbd:`Ctrl-m h` (that is, the sole
356 you will have to avoid using syntax such as ``%magic``s and other IPython-specific extensions to the language.
362 letter :kbd:`h` after :kbd:`Ctrl-m`) and IPython will show you the remaining
357
363 available keybindings.
358 In regular practice, the standard way to differentiate importable code from the
359 'executable' part of a script is to put at the bottom::
360
361 if __name__ == '__main__':
362 # rest of the code...
363
364 Since all cells in the notebook are run as top-level code, you will need to
365 similarly protect *all* cells that you do not want executed when other scripts
366 try to import your notebook. A convenient shortand for this is to define early
367 on::
368
369 script = __name__ == '__main__'
370
371 and then on any cell that you need to protect, use::
372
373 if script:
374 # rest of the cell...
364
375
365
376
366 .. _notebook_security:
377 .. _notebook_security:
367
378
368 Security
379 Security
369 ========
380 ========
370
381
371 You can protect your notebook server with a simple single-password by
382 You can protect your notebook server with a simple single-password by
372 setting the :attr:`NotebookApp.password` configurable. You can prepare a
383 setting the :attr:`NotebookApp.password` configurable. You can prepare a
373 hashed password using the function :func:`IPython.lib.security.passwd`:
384 hashed password using the function :func:`IPython.lib.security.passwd`:
374
385
375 .. sourcecode:: ipython
386 .. sourcecode:: ipython
376
387
377 In [1]: from IPython.lib import passwd
388 In [1]: from IPython.lib import passwd
378 In [2]: passwd()
389 In [2]: passwd()
379 Enter password:
390 Enter password:
380 Verify password:
391 Verify password:
381 Out[2]: 'sha1:67c9e60bb8b6:9ffede0825894254b2e042ea597d771089e11aed'
392 Out[2]: 'sha1:67c9e60bb8b6:9ffede0825894254b2e042ea597d771089e11aed'
382
393
383 .. note::
394 .. note::
384
395
385 :func:`~IPython.lib.security.passwd` can also take the password as a string
396 :func:`~IPython.lib.security.passwd` can also take the password as a string
386 argument. **Do not** pass it as an argument inside an IPython session, as it
397 argument. **Do not** pass it as an argument inside an IPython session, as it
387 will be saved in your input history.
398 will be saved in your input history.
388
399
389 You can then add this to your :file:`ipython_notebook_config.py`, e.g.::
400 You can then add this to your :file:`ipython_notebook_config.py`, e.g.::
390
401
391 # Password to use for web authentication
402 # Password to use for web authentication
392 c.NotebookApp.password = u'sha1:67c9e60bb8b6:9ffede0825894254b2e042ea597d771089e11aed'
403 c.NotebookApp.password = u'sha1:67c9e60bb8b6:9ffede0825894254b2e042ea597d771089e11aed'
393
404
394 When using a password, it is a good idea to also use SSL, so that your password
405 When using a password, it is a good idea to also use SSL, so that your password
395 is not sent unencrypted by your browser. You can start the notebook to
406 is not sent unencrypted by your browser. You can start the notebook to
396 communicate via a secure protocol mode using a self-signed certificate by
407 communicate via a secure protocol mode using a self-signed certificate by
397 typing::
408 typing::
398
409
399 $ ipython notebook --certfile=mycert.pem
410 $ ipython notebook --certfile=mycert.pem
400
411
401 .. note::
412 .. note::
402
413
403 A self-signed certificate can be generated with openssl. For example, the
414 A self-signed certificate can be generated with openssl. For example, the
404 following command will create a certificate valid for 365 days with both
415 following command will create a certificate valid for 365 days with both
405 the key and certificate data written to the same file::
416 the key and certificate data written to the same file::
406
417
407 $ openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem
418 $ openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem
408
419
409 Your browser will warn you of a dangerous certificate because it is
420 Your browser will warn you of a dangerous certificate because it is
410 self-signed. If you want to have a fully compliant certificate that will not
421 self-signed. If you want to have a fully compliant certificate that will not
411 raise warnings, it is possible (but rather involved) to obtain one for free,
422 raise warnings, it is possible (but rather involved) to obtain one for free,
412 `as explained in detailed in this tutorial`__.
423 `as explained in detailed in this tutorial`__.
413
424
414 .. __: http://arstechnica.com/security/news/2009/12/how-to-get-set-with-a-secure-sertificate-for-free.ars
425 .. __: http://arstechnica.com/security/news/2009/12/how-to-get-set-with-a-secure-sertificate-for-free.ars
415
426
416 Keep in mind that when you enable SSL support, you'll need to access the
427 Keep in mind that when you enable SSL support, you'll need to access the
417 notebook server over ``https://``, not over plain ``http://``. The startup
428 notebook server over ``https://``, not over plain ``http://``. The startup
418 message from the server prints this, but it's easy to overlook and think the
429 message from the server prints this, but it's easy to overlook and think the
419 server is for some reason non-responsive.
430 server is for some reason non-responsive.
420
431
421 Quick how to's
432 Quick how to's
422 ==============
433 ==============
423
434
424 Connecting to an existing kernel
435 Connecting to an existing kernel
425 ---------------------------------
436 ---------------------------------
426
437
427 The notebook server always prints to the terminal the full details of
438 The notebook server always prints to the terminal the full details of
428 how to connect to each kernel, with lines like::
439 how to connect to each kernel, with lines like::
429
440
430 [IPKernelApp] To connect another client to this kernel, use:
441 [IPKernelApp] To connect another client to this kernel, use:
431 [IPKernelApp] --existing kernel-3bb93edd-6b5a-455c-99c8-3b658f45dde5.json
442 [IPKernelApp] --existing kernel-3bb93edd-6b5a-455c-99c8-3b658f45dde5.json
432
443
433 This is the name of a JSON file that contains all the port and
444 This is the name of a JSON file that contains all the port and
434 validation information necessary to connect to the kernel. You can
445 validation information necessary to connect to the kernel. You can
435 manually start a Qt console with::
446 manually start a Qt console with::
436
447
437 ipython qtconsole --existing kernel-3bb93edd-6b5a-455c-99c8-3b658f45dde5.json
448 ipython qtconsole --existing kernel-3bb93edd-6b5a-455c-99c8-3b658f45dde5.json
438
449
439 and if you only have a single kernel running, simply typing::
450 and if you only have a single kernel running, simply typing::
440
451
441 ipython qtconsole --existing
452 ipython qtconsole --existing
442
453
443 will automatically find it (it will always find the most recently
454 will automatically find it (it will always find the most recently
444 started kernel if there is more than one). You can also request this
455 started kernel if there is more than one). You can also request this
445 connection data by typing ``%connect_info``; this will print the same
456 connection data by typing ``%connect_info``; this will print the same
446 file information as well as the content of the JSON data structure it contains.
457 file information as well as the content of the JSON data structure it contains.
447
458
448
459
449 Running a public notebook server
460 Running a public notebook server
450 --------------------------------
461 --------------------------------
451
462
452 If you want to access your notebook server remotely with just a web browser,
463 If you want to access your notebook server remotely with just a web browser,
453 here is a quick set of instructions. Start by creating a certificate file and
464 here is a quick set of instructions. Start by creating a certificate file and
454 a hashed password as explained above. Then, create a custom profile for the
465 a hashed password as explained above. Then, create a custom profile for the
455 notebook. At the command line, type::
466 notebook. At the command line, type::
456
467
457 ipython profile create nbserver
468 ipython profile create nbserver
458
469
459 In the profile directory, edit the file ``ipython_notebook_config.py``. By
470 In the profile directory, edit the file ``ipython_notebook_config.py``. By
460 default the file has all fields commented, the minimum set you need to
471 default the file has all fields commented, the minimum set you need to
461 uncomment and edit is here::
472 uncomment and edit is here::
462
473
463 c = get_config()
474 c = get_config()
464
475
465 # Kernel config
476 # Kernel config
466 c.IPKernelApp.pylab = 'inline' # if you want plotting support always
477 c.IPKernelApp.pylab = 'inline' # if you want plotting support always
467
478
468 # Notebook config
479 # Notebook config
469 c.NotebookApp.certfile = u'/absolute/path/to/your/certificate/mycert.pem'
480 c.NotebookApp.certfile = u'/absolute/path/to/your/certificate/mycert.pem'
470 c.NotebookApp.ip = '*'
481 c.NotebookApp.ip = '*'
471 c.NotebookApp.open_browser = False
482 c.NotebookApp.open_browser = False
472 c.NotebookApp.password = u'sha1:bcd259ccf...your hashed password here'
483 c.NotebookApp.password = u'sha1:bcd259ccf...your hashed password here'
473 # It's a good idea to put it on a known, fixed port
484 # It's a good idea to put it on a known, fixed port
474 c.NotebookApp.port = 9999
485 c.NotebookApp.port = 9999
475
486
476 You can then start the notebook and access it later by pointing your browser to
487 You can then start the notebook and access it later by pointing your browser to
477 ``https://your.host.com:9999`` with ``ipython notebook --profile=nbserver``.
488 ``https://your.host.com:9999`` with ``ipython notebook --profile=nbserver``.
478
489
479 Running with a different URL prefix
490 Running with a different URL prefix
480 -----------------------------------
491 -----------------------------------
481
492
482 The notebook dashboard (i.e. the default landing page with an overview
493 The notebook dashboard (i.e. the default landing page with an overview
483 of all your notebooks) typically lives at a URL path of
494 of all your notebooks) typically lives at a URL path of
484 "http://localhost:8888/". If you want to have it, and the rest of the
495 "http://localhost:8888/". If you want to have it, and the rest of the
485 notebook, live under a sub-directory,
496 notebook, live under a sub-directory,
486 e.g. "http://localhost:8888/ipython/", you can do so with
497 e.g. "http://localhost:8888/ipython/", you can do so with
487 configuration options like these (see above for instructions about
498 configuration options like these (see above for instructions about
488 modifying ``ipython_notebook_config.py``)::
499 modifying ``ipython_notebook_config.py``)::
489
500
490 c.NotebookApp.base_project_url = '/ipython/'
501 c.NotebookApp.base_project_url = '/ipython/'
491 c.NotebookApp.base_kernel_url = '/ipython/'
502 c.NotebookApp.base_kernel_url = '/ipython/'
492 c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/static/'}
503 c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/static/'}
493
504
494 Using a different notebook store
505 Using a different notebook store
495 --------------------------------
506 --------------------------------
496
507
497 By default the notebook server stores notebooks as files in the working
508 By default the notebook server stores notebooks as files in the working
498 directory of the notebook server, also known as the ``notebook_dir``. This
509 directory of the notebook server, also known as the ``notebook_dir``. This
499 logic is implemented in the :class:`FileNotebookManager` class. However, the
510 logic is implemented in the :class:`FileNotebookManager` class. However, the
500 server can be configured to use a different notebook manager class, which can
511 server can be configured to use a different notebook manager class, which can
501 store the notebooks in a different format. Currently, we ship a
512 store the notebooks in a different format. Currently, we ship a
502 :class:`AzureNotebookManager` class that stores notebooks in Azure blob
513 :class:`AzureNotebookManager` class that stores notebooks in Azure blob
503 storage. This can be used by adding the following lines to your
514 storage. This can be used by adding the following lines to your
504 ``ipython_notebook_config.py`` file::
515 ``ipython_notebook_config.py`` file::
505
516
506 c.NotebookApp.notebook_manager_class = 'IPython.html.services.notebooks.azurenbmanager.AzureNotebookManager'
517 c.NotebookApp.notebook_manager_class = 'IPython.html.services.notebooks.azurenbmanager.AzureNotebookManager'
507 c.AzureNotebookManager.account_name = u'paste_your_account_name_here'
518 c.AzureNotebookManager.account_name = u'paste_your_account_name_here'
508 c.AzureNotebookManager.account_key = u'paste_your_account_key_here'
519 c.AzureNotebookManager.account_key = u'paste_your_account_key_here'
509 c.AzureNotebookManager.container = u'notebooks'
520 c.AzureNotebookManager.container = u'notebooks'
510
521
511 In addition to providing your Azure Blob Storage account name and key, you will
522 In addition to providing your Azure Blob Storage account name and key, you will
512 have to provide a container name; you can use multiple containers to organize
523 have to provide a container name; you can use multiple containers to organize
513 your Notebooks.
524 your Notebooks.
514
525
515 .. _notebook_format:
526 .. _notebook_format:
516
527
517 The notebook format
528 The notebook format
518 ===================
529 ===================
519
530
520 The notebooks themselves are JSON files with an ``ipynb`` extension, formatted
531 The notebooks themselves are JSON files with an ``ipynb`` extension, formatted
521 as legibly as possible with minimal extra indentation and cell content broken
532 as legibly as possible with minimal extra indentation and cell content broken
522 across lines to make them reasonably friendly to use in version-control
533 across lines to make them reasonably friendly to use in version-control
523 workflows. You should be very careful if you ever edit manually this JSON
534 workflows. You should be very careful if you ever edit manually this JSON
524 data, as it is extremely easy to corrupt its internal structure and make the
535 data, as it is extremely easy to corrupt its internal structure and make the
525 file impossible to load. In general, you should consider the notebook as a
536 file impossible to load. In general, you should consider the notebook as a
526 file meant only to be edited by IPython itself, not for hand-editing.
537 file meant only to be edited by IPython itself, not for hand-editing.
527
538
528 .. note::
539 .. note::
529
540
530 Binary data such as figures are directly saved in the JSON file. This
541 Binary data such as figures are directly saved in the JSON file. This
531 provides convenient single-file portability but means the files can be
542 provides convenient single-file portability but means the files can be
532 large and diffs of binary data aren't very meaningful. Since the binary
543 large and diffs of binary data aren't very meaningful. Since the binary
533 blobs are encoded in a single line they only affect one line of the diff
544 blobs are encoded in a single line they only affect one line of the diff
534 output, but they are typically very long lines. You can use the
545 output, but they are typically very long lines. You can use the
535 'ClearAll' button to remove all output from a notebook prior to
546 'ClearAll' button to remove all output from a notebook prior to
536 committing it to version control, if this is a concern.
547 committing it to version control, if this is a concern.
537
548
538 The notebook server can also generate a pure-python version of your notebook,
549 The notebook server can also generate a pure-python version of your notebook,
539 by clicking on the 'Download' button and selecting ``py`` as the format. This
550 by clicking on the 'Download' button and selecting ``py`` as the format. This
540 file will contain all the code cells from your notebook verbatim, and all text
551 file will contain all the code cells from your notebook verbatim, and all text
541 cells prepended with a comment marker. The separation between code and text
552 cells prepended with a comment marker. The separation between code and text
542 cells is indicated with special comments and there is a header indicating the
553 cells is indicated with special comments and there is a header indicating the
543 format version. All output is stripped out when exporting to python.
554 format version. All output is stripped out when exporting to python.
544
555
545 Here is an example of a simple notebook with one text cell and one code input
556 Here is an example of a simple notebook with one text cell and one code input
546 cell, when exported to python format::
557 cell, when exported to python format::
547
558
548 # <nbformat>2</nbformat>
559 # <nbformat>2</nbformat>
549
560
550 # <markdowncell>
561 # <markdowncell>
551
562
552 # A text cell
563 # A text cell
553
564
554 # <codecell>
565 # <codecell>
555
566
556 print "hello IPython"
567 print "hello IPython"
557
568
558
569
559 Known issues
570 Known issues
560 ============
571 ============
561
572
562 When behind a proxy, especially if your system or browser is set to autodetect
573 When behind a proxy, especially if your system or browser is set to autodetect
563 the proxy, the html notebook might fail to connect to the server's websockets,
574 the proxy, the html notebook might fail to connect to the server's websockets,
564 and present you with a warning at startup. In this case, you need to configure
575 and present you with a warning at startup. In this case, you need to configure
565 your system not to use the proxy for the server's address.
576 your system not to use the proxy for the server's address.
566
577
567 In Firefox, for example, go to the Preferences panel, Advanced section,
578 In Firefox, for example, go to the Preferences panel, Advanced section,
568 Network tab, click 'Settings...', and add the address of the notebook server
579 Network tab, click 'Settings...', and add the address of the notebook server
569 to the 'No proxy for' field.
580 to the 'No proxy for' field.
570
581
571
582
572 .. _Markdown: http://daringfireball.net/projects/markdown/basics
583 .. _Markdown: http://daringfireball.net/projects/markdown/basics
General Comments 0
You need to be logged in to leave comments. Login now