##// END OF EJS Templates
Initial refactoring of htmlnotebook.txt into 3 parts....
David P. Sanders -
Show More
@@ -0,0 +1,260 b''
1
2
3 .. _`nbconvert script`:
4
5 Converting notebooks to other formats
6 =====================================
7
8 Newly added in the 1.0 release of IPython is the ``nbconvert`` tool, which
9 allows you to convert an ``.ipynb`` notebook document file into various static
10 formats.
11
12 Currently, ``nbconvert`` is provided as a command line tool, run as a script
13 using IPython. In the future, a direct export capability from within the
14 IPython Notebook web app is planned.
15
16 The command-line syntax to run the ``nbconvert`` script is::
17
18 $ ipython nbconvert --format=FORMAT notebook.ipynb
19
20 This will convert the IPython document file ``notebook.ipynb`` into the output
21 format given by the ``FORMAT`` string.
22
23 The default output format is HTML, for which the ``--format`` modifier may be
24 omitted::
25
26 $ ipython nbconvert notebook.ipynb
27
28 The currently supported export formats are the following:
29
30 * HTML:
31
32 - **full_html**:
33 Standard HTML
34
35 - **simple_html**:
36 Simplified HTML
37
38 - **reveal**:
39 HTML slideshow presentation for use with the ``reveal.js`` package
40
41 * PDF:
42
43 - **sphinx_howto**:
44 The format for Sphinx_ HOWTOs; similar to an ``article`` in LaTeX
45
46 - **sphinx_manual**:
47 The format for Sphinx_ manuals; similar to a ``book`` in LaTeX
48
49 - **latex**:
50 An article formatted completely using LaTeX
51
52 * Markup:
53
54 - **rst**:
55 reStructuredText_ markup
56
57 - **markdown**:
58 Markdown_ markup
59
60 .. _Sphinx: http://sphinx-doc.org/
61 .. _reStructuredText: http://docutils.sourceforge.net/rst.html
62
63 * Python:
64
65 Comments out all the non-Python code to produce a ``.py`` Python
66 script with just the code content. Currently the output includes IPython
67 magics, and so can be run with ``ipython``, after changing the extension
68 of the script to ``.ipy``.
69
70 The files output file created by ``nbconvert`` will have the same base name as
71 the notebook and will be placed in the current working directory. Any
72 supporting files (graphics, etc) will be placed in a new directory with the
73 same base name as the notebook, suffixed with ``_files``::
74
75 $ ipython nbconvert notebook.ipynb
76 $ ls
77 notebook.ipynb notebook.html notebook_files/
78
79 Each of the options for PDF export produces as an intermediate step a LaTeX
80 ``.tex`` file with the same basename as the notebook, as well as individual
81 files for each figure, and ``.text`` files with textual output from running
82 code cells.
83
84 To actually produce the final PDF file, run the following commands::
85
86 $ ipython nbconvert --format=latex notebook.ipynb
87 $ pdflatex notebook
88
89 This requires a local installation of LaTeX on your machine.
90 The output is a PDF file ``notebook.pdf``, also placed inside the
91 ``nbconvert_build`` subdirectory.
92
93 Alternatively, the output may be sent to standard output with::
94
95 $ ipython nbconvert notebook.ipynb --stdout
96
97 Multiple notebooks can be specified from the command line::
98
99 $ ipython nbconvert notebook*.ipynb
100 $ ipython nbconvert notebook1.ipynb notebook2.ipynb
101
102 or via a list in a configuration file, say ``mycfg.py``, containing the text::
103
104 c = get_config()
105 c.NbConvertApp.notebooks = ["notebook1.ipynb", "notebook2.ipynb"]
106
107 and using the command::
108
109 $ ipython nbconvert --config mycfg.py
110
111
112 Extracting standard Python files from notebooks
113 -----------------------------------------------
114 ``.ipynb`` notebook document files are plain text files which store a
115 representation in JSON format of the contents of a notebook space. As such,
116 they are not valid ``.py`` Python scripts, and so can be neither imported
117 directly with ``import`` in Python, nor run directly as a standard Python
118 script (though both of these are possible with simple workarounds).
119
120
121 To extract the Python code from within a notebook document, the simplest
122 method is to use the ``File | Download as | Python (.py)`` menu item; the
123 resulting ``.py`` script will be downloaded to your browser's default
124 download location.
125
126 An alternative is to pass an argument to the IPython Notebook, from the moment
127 when it is originally started, specifying that whenever it saves an ``.ipynb``
128 notebook document, it should, at the same time, save the corresponding
129 ``.py`` script. To do so, you can execute the following command::
130
131 $ ipython notebook --script
132
133 or you can set this option permanently in your configuration file with::
134
135 c = get_config()
136 c.NotebookManager.save_script=True
137
138 The result is that standard ``.py`` files are also now generated, which
139 can be ``%run``, imported from regular IPython sessions or other notebooks, or
140 executed at the command line, as usual. Since the raw code you have typed is
141 exported, you must avoid using syntax such as IPython magics and other
142 IPython-specific extensions to the language for the files to be able to be
143 successfully imported.
144 .. or you can change the script's extension to ``.ipy`` and run it with::
145 ..
146 .. $ ipython script.ipy
147
148 In normal Python practice, the standard way to differentiate importable code
149 in a Python script from the "executable" part of a script is to use the
150 following idiom at the start of the executable part of the code::
151
152 if __name__ == '__main__'
153
154 # rest of the code...
155
156 Since all cells in the notebook are run as top-level code, you will need to
157 similarly protect *all* cells that you do not want executed when other scripts
158 try to import your notebook. A convenient shortand for this is to define
159 early on::
160
161 script = __name__ == '__main__'
162
163 Then in any cell that you need to protect, use::
164
165 if script:
166 # rest of the cell...
167
168
169
170 .. _notebook_format:
171
172 Notebook JSON file format
173 -------------------------
174 Notebook documents are JSON files with an ``.ipynb`` extension, formatted
175 as legibly as possible with minimal extra indentation and cell content broken
176 across lines to make them reasonably friendly to use in version-control
177 workflows. You should be very careful if you ever manually edit this JSON
178 data, as it is extremely easy to corrupt its internal structure and make the
179 file impossible to load. In general, you should consider the notebook as a
180 file meant only to be edited by the IPython Notebook app itself, not for
181 hand-editing.
182
183 .. note::
184
185 Binary data such as figures are also saved directly in the JSON file.
186 This provides convenient single-file portability, but means that the
187 files can be large; a ``diff`` of binary data is also not very
188 meaningful. Since the binary blobs are encoded in a single line, they
189 affect only one line of the ``diff`` output, but they are typically very
190 long lines. You can use the ``Cell | All Output | Clear`` menu option to
191 remove all output from a notebook prior to committing it to version
192 control, if this is a concern.
193
194 The notebook server can also generate a pure Python version of your notebook,
195 using the ``File | Download as`` menu option. The resulting ``.py`` file will
196 contain all the code cells from your notebook verbatim, and all Markdown cells
197 prepended with a comment marker. The separation between code and Markdown
198 cells is indicated with special comments and there is a header indicating the
199 format version. All output is removed when exporting to Python.
200
201 As an example, consider a simple notebook called ``simple.ipynb`` which
202 contains one Markdown cell, with the content ``The simplest notebook.``, one
203 code input cell with the content ``print "Hello, IPython!"``, and the
204 corresponding output.
205
206 The contents of the notebook document ``simple.ipynb`` is the following JSON
207 container::
208
209 {
210 "metadata": {
211 "name": "simple"
212 },
213 "nbformat": 3,
214 "nbformat_minor": 0,
215 "worksheets": [
216 {
217 "cells": [
218 {
219 "cell_type": "markdown",
220 "metadata": {},
221 "source": "The simplest notebook."
222 },
223 {
224 "cell_type": "code",
225 "collapsed": false,
226 "input": "print \"Hello, IPython\"",
227 "language": "python",
228 "metadata": {},
229 "outputs": [
230 {
231 "output_type": "stream",
232 "stream": "stdout",
233 "text": "Hello, IPython\n"
234 }
235 ],
236 "prompt_number": 1
237 }
238 ],
239 "metadata": {}
240 }
241 ]
242 }
243
244
245 The corresponding Python script is::
246
247 # -*- coding: utf-8 -*-
248 # <nbformat>3.0</nbformat>
249
250 # <markdowncell>
251
252 # The simplest notebook.
253
254 # <codecell>
255
256 print "Hello, IPython"
257
258 Note that indeed the output of the code cell, which is present in the JSON
259 container, has been removed in the ``.py`` script.
260
This diff has been collapsed as it changes many lines, (564 lines changed) Show them Hide them
@@ -0,0 +1,564 b''
1 .. _htmlnotebook:
2
3 The IPython Notebook
4 ====================
5
6 The IPython Notebook is part of the IPython package, which aims to provide a
7 powerful, interactive approach to scientific computation.
8 The IPython Notebook extends the previous text-console-based approach, and the
9 later Qt console, in a qualitatively new diretion, providing a web-based
10 application suitable for capturing the whole scientific computation process.
11
12 .. seealso::
13
14 :ref:`Installation requirements <installnotebook>` for the Notebook.
15
16
17 .. Basic structure
18 .. ---------------
19
20 Introduction
21 ------------
22
23 The IPython Notebook combines two components:
24
25 * **The IPython Notebook web application**:
26
27 The *IPython Notebook web app* is a browser-based tool for interactive
28 authoring of literate computations, in which explanatory text,
29 mathematics, computations and rich media output may be combined. Input
30 and output are stored in persistent cells that may be edited in-place.
31
32 * **Notebook documents**:
33
34 *Notebook documents*, or *notebooks*, are plain text documents which
35 record all inputs and outputs of the computations, interspersed with
36 text, mathematics and HTML 5 representations of objects, in a literate
37 style.
38
39 Since the similarity in names can lead to some confusion, in this
40 documentation we will use capitalization of the word "notebook" to
41 distinguish the *N*otebook app and *n*otebook documents, thinking of the
42 Notebook app as being a proper noun. We will also always refer to the
43 "Notebook app" when we are referring to the browser-based interface,
44 and usually to "notebook documents", instead of "notebooks", for added
45 precision.
46
47 We refer to the current state of the computational process taking place in the
48 Notebook app, i.e. the (numbered) sequence of input and output cells, as the
49 *notebook space*. Notebook documents provide an *exact*, *one-to-one* record
50 of all the content in the notebook space, as a plain text file in JSON format.
51 The Notebook app automatically saves, at certain intervals, the contents of
52 the notebook space to a notebook document stored on disk, with the same name
53 as the title of the notebook space, and the file extension ``.ipynb``. For
54 this reason, there is no confusion about using the same word "notebook" for
55 both the notebook space and the corresonding notebook document, since they are
56 really one and the same concept (we could say that they are "isomorphic").
57
58
59 Main features of the IPython Notebook web app
60 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
61
62 The main features of the IPython Notebook app include:
63
64 * In-browser editing for code, with automatic syntax highlighting and
65 indentation and tab completion/introspection.
66
67 * Literate combination of code with rich text using the Markdown_ markup
68 language.
69
70 * Mathematics is easily included within the Markdown using LaTeX notation, and
71 rendered natively by MathJax_.
72
73 * Displays rich data representations (e.g. HTML / LaTeX / SVG) as the result
74 of computations.
75
76 * Publication-quality figures in a range of formats (SVG / PNG), rendered by
77 the matplotlib_ library, may be included inline and exported.
78
79
80 .. _MathJax: http://www.mathjax.org/
81 .. _matplotlib: http://matplotlib.org/
82 .. _Markdown: http://daringfireball.net/projects/markdown/syntax
83
84
85 Notebook documents
86 ~~~~~~~~~~~~~~~~~~
87
88 Notebook document files are just standard, ASCII-coded text files with the
89 extension ``.ipynb``, stored in the working directory on your computer.
90 Since the contents of the files are just plain text, they can be easily
91 version-controlled and shared with colleagues.
92
93 Internally, notebook document files use the JSON_ format, allowing them to
94 store a *complete*, *reproducible*, *one-to-one* copy of the state of the
95 computational state as it is inside the Notebook app. All computations
96 carried out, and the corresponding results obtained, can be combined in
97 a literate way, interleaving executable code with rich text, mathematics,
98 and HTML 5 representations of objects.
99
100 .. _JSON: http://en.wikipedia.org/wiki/JSON
101
102 Notebooks may easily be exported to a range of static formats, including
103 HTML (for example, for blog posts), PDF and slide shows, via the
104 newly-included `nbconvert script`_ functionality.
105
106 Furthermore, any ``.ipynb`` notebook document with a publicly-available
107 URL can be shared via the `IPython Notebook Viewer`_ service. This service
108 loads the notebook document from the URL which will
109 provide it as a static web page. The results may thus be shared with a
110 colleague, or as a public blog post, without other users needing to install
111 IPython themselves.
112
113 See the :ref:`installation documentation <install_index>` for directions on
114 how to install the notebook and its dependencies.
115
116 .. _`Ipython Notebook Viewer`: http://nbviewer.ipython.org
117
118 .. note::
119
120 You can start more than one notebook server at the same time, if you want
121 to work on notebooks in different directories. By default the first
122 notebook server starts on port 8888, and later notebook servers search for
123 ports near that one. You can also manually specify the port with the
124 ``--port`` option.
125
126
127 Basic workflow in the IPython Notebook web app
128 ----------------------------------------------
129
130 Starting up
131 ~~~~~~~~~~~~
132
133 You can start running the Notebook web app using the following command::
134
135 $ ipython notebook
136
137 (Here, and in the sequel, the initial ``$`` represents the shell prompt,
138 indicating that the command is to be run from the command line in a shell.)
139
140 The landing page of the IPython Notebook application, the *dashboard*, shows
141 the notebooks currently available in the *working directory* (the directory
142 from which the notebook was started).
143 You can create new notebooks from the dashboard with the ``New Notebook``
144 button, or open existing ones by clicking on their name.
145 You can also drag and drop ``.ipynb`` notebooks and standard ``.py`` Python
146 source code files into the notebook list area.
147
148
149 You can open an existing notebook directly, without having to go via the
150 dashboard, with:
151
152 ipython notebook my_notebook
153
154 The `.ipynb` extension is assumed if no extension is given.
155
156 The `File | Open...` menu option will open the dashboard in a new browser tab,
157 to allow you to select a current notebook
158 from the working directory or to create a new notebook
159
160
161
162 Notebook user interface
163 ~~~~~~~~~~~~~~~~~~~~~~~
164
165 When you open a new notebook document in the Notebook, you will be presented
166 with the title associated to the notebook space/document, a *menu bar*, a
167 *toolbar* and an empty *input cell*.
168
169 Notebook title
170 ^^^^^^^^^^^^^^
171 The title of the notebook document that is currently being edited is displayed
172 at the top of the page, next to the ``IP[y]: Notebook`` logo. This title may
173 be edited directly by clicking on it. The title is reflected in the name of
174 the ``.ipynb`` notebook document file that is saved.
175
176 Menu bar
177 ^^^^^^^^
178 The menu bar presents different options that may be used to manipulate the way
179 the Notebook functions.
180
181 Toolbar
182 ^^^^^^^
183 The tool bar gives a quick way of accessing the most-used operations within
184 the Notebook, by clicking on an icon.
185
186
187 Creating a new notebook document
188 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
189
190 A new notebook space/document may be created at any time, either from the
191 dashboard, or using the `File | New` menu option from within an active
192 notebook. The new notebook is created within the same working directory and
193 will open in a new browser tab. It will also be reflected as a new entry in
194 the notebook list on the dashboard.
195
196
197 Structure of a notebook document
198 --------------------------------
199
200 Input cells
201 ~~~~~~~~~~~
202 Input cells are at the core of the functionality of the IPython Notebook.
203 They are regions in the document in which you can enter different types of
204 text and commands. To *execute* or *run* the *current cell*, i.e. the cell
205 under the cursor, you can use the :kbd:`Shift-Enter` key combination.
206 This tells the Notebook app to perform the relevant operation for each type of
207 cell (see below), and then to display the resulting output.
208
209 The notebook consists of a sequence of input cells, labelled ``In[n]``, which
210 may be executed in a non-linear way, and outputs ``Out[n]``, where ``n`` is a
211 number which denotes the order in which the cells were executed over the
212 history of the computational process. The contents of all of these cells are
213 accessible as Python variables with the same names, forming a complete record
214 of the history of the computation.
215
216
217
218 Input cell types
219 ~~~~~~~~~~~~~~~~
220 Each IPython input cell has a *cell type*, of which there is a restricted
221 number. The type of a cell may be set by using the cell type dropdown on the
222 toolbar, or via the following keyboard shortcuts:
223
224 * **code**: :kbd:`Ctrl-m y`
225 * **markdown**: :kbd:`Ctrl-m m`
226 * **raw**: :kbd:`Ctrl-m t`
227 * **heading**: :kbd:`Ctrl-m 1` - :kbd:`Ctrl-m 6`
228
229 Upon initial creation, each input cell is by default a code cell.
230
231
232 Code cells
233 ^^^^^^^^^^
234 A *code input cell* allows you to edit code inline within the cell, with full
235 syntax highlighting and autocompletion/introspection. By default, the language
236 associated to a code cell is Python, but other languages, such as ``julia``
237 and ``R``, can be handled using magic commands (see below).
238
239 When a code cell is executed with :kbd:`Shift-Enter`, the code that it
240 contains is transparently exported and run in that language (with automatic
241 compiling, etc., if necessary). The result that is returned from this
242 computation is then displayed in the notebook space as the cell's
243 *output*. If this output is of a textual nature, it is placed into a
244 numbered *output cell*. However, many other possible forms of output are also
245 possible, including ``matplotlib`` figures and HTML tables (as used, for
246 example, in the ``pandas`` data analyis package). This is known as IPython's
247 *rich display* capability.
248
249
250 Markdown cells
251 ^^^^^^^^^^^^^^
252 You can document the computational process in a literate way, alternating
253 descriptive text with code, using *rich text*. In IPython this is accomplished
254 by marking up text with the Markdown language. The corresponding cells are
255 called *Markdown input cells*. The Markdown language provides a simple way to
256 perform this text markup, that is, to specify which parts of the text should
257 be emphasized (italics), bold, form lists, etc.
258
259
260 When a Markdown input cell is executed, the Markdown code is converted into
261 the corresponding formatted rich text. This output then *replaces* the
262 original Markdown input cell, leaving just the visually-significant marked up
263 rich text. Markdown allows arbitrary HTML code for formatting.
264
265 Within Markdown cells, you can also include *mathematics* in a straightforward
266 way, using standard LaTeX notation: ``$...$`` for inline mathematics and
267 ``$$...$$`` for displayed mathematics. When the Markdown cell is executed,
268 the LaTeX portions are automatically rendered in the HTML output as equations
269 with high quality typography. This is made possible by MathJax_, which
270 supports a `large subset`_ of LaTeX functionality
271
272 .. _`large subset`: http://docs.mathjax.org/en/latest/tex.html
273
274 Standard mathematics environments defined by LaTeX and AMS-LaTeX (the
275 `amsmath` package) also work, such as
276 ``\begin{equation}...\end{equation}``, and ``\begin{align}...\end{align}``.
277 New LaTeX macros may be defined using standard methods,
278 such as ``\newcommand``, by placing them anywhere *between math delimiters* in
279 a Markdown cell. These definitions are then available throughout the rest of
280 the IPython session. (Note, however, that more care must be taken when using
281 the `nbconvert script`_ to output to LaTeX).
282
283 Raw input cells
284 ~~~~~~~~~~~~~~~
285 *Raw* input cells provide a place in which you can put additional information
286 which you do not want to evaluated by the Notebook. This can be used, for
287 example, to include extra information that is needed when exporting to a
288 certain format. The output after evaluating a raw cell is just a verbatim copy
289 of the input.
290
291 Heading cells
292 ~~~~~~~~~~~~~
293 You can provide a conceptual structure for your computational document as a
294 whole using different levels of headings; there are 6 levels available, from
295 level 1 (top level) down to level 6 (paragraph). These can be used later for
296 constructing tables of contents, etc.
297
298 As with Markdown cells, a heading input cell is replaced by a rich text
299 rendering of the heading when the cell is executed.
300
301
302 Basic workflow
303 --------------
304 The normal workflow in a notebook is, then, quite similar to a standard
305 IPython session, with the difference that you can edit cells in-place multiple
306 times until you obtain the desired results, rather than having to
307 rerun separate scripts with the ``%run`` magic command. (Magic commands do,
308 however, also work in the notebook; see below).
309
310 Typically, you will work on a computational problem in pieces, organizing
311 related ideas into cells and moving forward once previous parts work
312 correctly. This is much more convenient for interactive exploration than
313 breaking up a computation into scripts that must be executed together, as was
314 previously necessary, especially if parts of them take a long time to run
315
316 The only significant limitation that the Notebook currently has, compared to
317 the Qt console, is that it cannot run any code that expects input from the
318 kernel (such as scripts that call :func:`raw_input`). Very importantly, this
319 means that the ``%debug`` magic does *not* currently work in the notebook!
320
321 This limitation will be overcome in the future, but in the meantime, there is
322 a simple solution for debugging: you can attach a Qt console to your existing
323 notebook kernel, and run ``%debug`` from the Qt console.
324 If your notebook is running on a local computer (i.e. if you are accessing it
325 via your localhost address at ``127.0.0.1``), then you can just type
326 ``%qtconsole`` in the notebook and a Qt console will open up, connected to
327 that same kernel.
328
329 At certain moments, it may be necessary to interrupt a calculation which is
330 taking too long to complete. This may be done with the ``Kernel | Interrupt``
331 menu option, or the :kbd:``Ctrl-i`` keyboard shortcut.
332 Similarly, it may be necessary or desirable to restart the whole computational
333 process, with the ``Kernel | Restart`` menu option or :kbd:``Ctrl-.``
334 shortcut. This gives an equivalent state to loading the notebook document
335 afresh.
336
337
338 .. warning::
339
340 While in simple cases you can "roundtrip" a notebook to Python, edit the
341 Python file, and then import it back without loss of main content, this is
342 in general *not guaranteed to work*. First, there is extra metadata
343 saved in the notebook that may not be saved to the ``.py`` format. And as
344 the notebook format evolves in complexity, there will be attributes of the
345 notebook that will not survive a roundtrip through the Python form. You
346 should think of the Python format as a way to output a script version of a
347 notebook and the import capabilities as a way to load existing code to get
348 a notebook started. But the Python version is *not* an alternate notebook
349 format.
350
351
352 Keyboard shortcuts
353 ~~~~~~~~~~~~~~~~~~
354 All actions in the notebook can be achieved with the mouse, but keyboard
355 shortcuts are also available for the most common ones, so that productive use
356 of the notebook can be achieved with minimal mouse usage. The main shortcuts
357 to remember are the following:
358
359 * :kbd:`Shift-Enter`:
360
361 Execute the current cell, show output (if any), and jump to the next cell
362 below. If :kbd:`Shift-Enter` is invoked on the last input cell, a new code
363 cell will also be created. Note that in the notebook, typing :kbd:`Enter`
364 on its own *never* forces execution, but rather just inserts a new line in
365 the current input cell. In the Notebook it is thus always necessary to use
366 :kbd:`Shift-Enter` to execute the cell (or use the ``Cell | Run`` menu
367 item).
368
369 * :kbd:`Ctrl-Enter`:
370 Execute the current cell as if it were in "terminal mode", where any
371 output is shown, but the cursor *remains* in the current cell. This is
372 convenient for doing quick experiments in place, or for querying things
373 like filesystem content, without needing to create additional cells that
374 you may not want to be saved in the notebook.
375
376 * :kbd:`Alt-Enter`:
377 Executes the current cell, shows the output, and inserts a *new* input
378 cell between the current cell and the adjacent cell (if one exists). This
379 is thus a shortcut for the sequence :kbd:`Shift-Enter`, :kbd:`Ctrl-m a`.
380 (:kbd:`Ctrl-m a` adds a new cell above the current one.)
381
382 * :kbd:`Ctrl-m`:
383 This is the prefix for *all* other shortcuts, which consist of :kbd:`Ctrl-m`
384 followed by a single letter or character. For example, if you type
385 :kbd:`Ctrl-m h` (that is, the sole letter :kbd:`h` after :kbd:`Ctrl-m`),
386 IPython will show you all the available keyboard shortcuts.
387
388
389 Magic commands
390 --------------
391 Magic commands, or *magics*, are commands for controlling IPython itself.
392 They all begin with ``%`` and are entered into code input cells; the code
393 cells are executed as usual with :kbd:`Shift-Enter`.
394
395 The magic commands call special functions defined by IPython which manipulate
396 the computational state in certain ways.
397
398 There are two types of magics:
399
400 - **line magics**:
401
402 These begin with a single ``%`` and take as arguments the rest of the
403 *same line* of the code cell. Any other lines of the code cell are
404 treated as if they were part of a standard code cell.
405
406 - **cell magics**:
407
408 These begin with ``%%`` and operate on the *entire* remaining contents
409 of the code cell.
410
411 Line magics
412 ~~~~~~~~~~~
413 Some of the available line magics are the following:
414
415 * ``%load filename``:
416
417 Loads the contents of the file ``filename`` into a new code cell. This
418 can be a URL for a remote file.
419
420 * ``%timeit code``:
421
422 An easy way to time how long the single line of code ``code`` takes to
423 run
424
425 * ``%config``:
426
427 Configuration of the IPython Notebook
428
429 * ``%lsmagic``:
430
431 Provides a list of all available magic commands
432
433 Cell magics
434 ~~~~~~~~~~~
435
436 * ``%%latex``:
437
438 Renders the entire contents of the cell in LaTeX, without needing to use
439 explicit LaTeX delimiters.
440
441 * ``%%bash``:
442
443 The code cell is executed by sending it to be executed by ``bash``. The
444 output of the ``bash`` commands is captured and displayed in the
445 notebook.
446
447 * ``%%file filename``:
448
449 Writes the contents of the cell to the file ``filename``.
450 **Caution**: The file is over-written without warning!
451
452 * ``%%R``:
453
454 Execute the contents of the cell using the R language.
455
456 * ``%%timeit``:
457
458 Version of ``%timeit`` which times the entire block of code in the
459 current code cell.
460
461
462
463 Several of the cell magics provide functionality to manipulate the filesystem
464 of a remote server to which you otherwise do not have access.
465
466
467 Plotting
468 --------
469 One major feature of the Notebook is the ability to interact with
470 plots that are the output of running code cells. IPython is designed to work
471 seamlessly with the ``matplotlib`` plotting library to provide this
472 functionality.
473
474 To set this up, before any plotting is performed you must execute the
475 ``%matplotlib`` magic command. This performs the necessary behind-the-scenes
476 setup for IPython to work correctly hand in hand with ``matplotlib``; it does
477 *not*, however, actually execute any Python ``import`` commands, that is, no
478 names are added to the namespace.
479
480 For more agile *interactive* use of the notebook space, an alternative magic,
481 ``%pylab``, is provided. This does the same work as the ``%matplotlib`` magic,
482 but *in addition* it automatically executes a standard sequence of ``import``
483 statements required to work with the ``%matplotlib`` library, importing the
484 following names into the namespace:
485
486 ``numpy`` as ``np``; ``matplotlib.pyplot`` as ``plt``;
487 ``matplotlib``, ``pylab`` and ``mlab`` from ``matplotlib``; and *all names*
488 from within ``numpy`` and ``pylab``.
489
490 However, the use of ``%pylab`` is discouraged, since names coming from
491 different packages may collide. In general, the use of ``from package import
492 *`` is discouraged. A better option is then::
493
494 %pylab --no-import-all
495
496 which imports the names listed above, but does *not* perform this
497 ``import *`` imports.
498
499 If the ``%matplotlib`` or ``%pylab` magics are called without an argument, the
500 output of a plotting command is displayed using the default ``matplotlib``
501 backend in a separate window. Alternatively, the backend can be explicitly
502 requested using, for example::
503
504 %matplotlib gtk
505
506 A particularly interesting backend is the ``inline`` backend.
507 This is applicable only for the IPython Notebook and the IPython Qtconsole.
508 It can be invoked as follows::
509
510 %matplotlib inline
511
512 With this backend, output of plotting commands is displayed *inline* within
513 the notebook format, directly below the input cell that produced it. The
514 resulting plots will then also be stored in the notebook document. This
515 provides a key part of the functionality for reproducibility_ that the IPython
516 Notebook provides.
517
518 .. _reproducibility: https://en.wikipedia.org/wiki/Reproducibility
519
520
521
522 Configuring the IPython Notebook
523 --------------------------------
524 The IPython Notebook can be run with a variety of command line arguments.
525 To see a list of available options enter::
526
527 $ ipython notebook --help
528
529 Defaults for these options can also be set by creating a file named
530 ``ipython_notebook_config.py`` in your IPython *profile folder*. The profile
531 folder is a subfolder of your IPython directory; to find out where it is
532 located, run::
533
534 $ ipython locate
535
536 To create a new set of default configuration files, with lots of information
537 on available options, use::
538
539 $ ipython profile create
540
541 .. seealso:
542
543 :ref:`config_overview`, in particular :ref:`Profiles`.
544
545
546 Importing `.py` files
547 ----------------------
548
549
550 ``.py`` files will be imported into the IPython Notebook as a notebook with
551 the same basename, but an ``.ipynb`` extension, located in the working
552 directory. The notebook created will have just one cell, which will contain
553 all the code in the ``.py`` file. You can later manually partition this into
554 individual cells using the ``Edit | Split Cell`` menu option, or the
555 :kbd:`Ctrl-m -` keyboard shortcut.
556
557 .. Alternatively, prior to importing the ``.py``, you can manually add ``# <
558 nbformat>2</nbformat>`` at the start of the file, and then add separators for
559 text and code cells, to get a cleaner import with the file already broken into
560 individual cells.
561
562
563
564 .. _Markdown: http://daringfireball.net/projects/markdown/basics
@@ -0,0 +1,182 b''
1 .. _working_remotely.txt
2
3 Working remotely
4 ================
5
6
7 The IPython Notebook web app is based on a server-client structure.
8 This server uses a two-process kernel architecture based on ZeroMQ, as well as
9 Tornado for serving HTTP requests. Other clients may connect to the same
10 underlying IPython kernel; see below.
11
12 .. _notebook_security:
13
14 Security
15 --------
16
17 You can protect your Notebook server with a simple single password by
18 setting the :attr:`NotebookApp.password` configurable. You can prepare a
19 hashed password using the function :func:`IPython.lib.security.passwd`:
20
21 .. sourcecode:: ipython
22
23 In [1]: from IPython.lib import passwd
24 In [2]: passwd()
25 Enter password:
26 Verify password:
27 Out[2]: 'sha1:67c9e60bb8b6:9ffede0825894254b2e042ea597d771089e11aed'
28
29 .. note::
30
31 :func:`~IPython.lib.security.passwd` can also take the password as a string
32 argument. **Do not** pass it as an argument inside an IPython session, as it
33 will be saved in your input history.
34
35 You can then add this to your :file:`ipython_notebook_config.py`, e.g.::
36
37 # Password to use for web authentication
38 c = get_config()
39 c.NotebookApp.password =
40 u'sha1:67c9e60bb8b6:9ffede0825894254b2e042ea597d771089e11aed'
41
42 When using a password, it is a good idea to also use SSL, so that your
43 password is not sent unencrypted by your browser. You can start the notebook
44 to communicate via a secure protocol mode using a self-signed certificate with
45 the command::
46
47 $ ipython notebook --certfile=mycert.pem
48
49 .. note::
50
51 A self-signed certificate can be generated with ``openssl``. For example,
52 the following command will create a certificate valid for 365 days with
53 both the key and certificate data written to the same file::
54
55 $ openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.
56 pem -out mycert.pem
57
58 Your browser will warn you of a dangerous certificate because it is
59 self-signed. If you want to have a fully compliant certificate that will not
60 raise warnings, it is possible (but rather involved) to obtain one,
61 `as explained in detailed in this tutorial`__.
62
63 .. __: http://arstechnica.com/security/news/2009/12/how-to-get-set-with-a-
64 secure-sertificate-for-free.ars
65
66 Keep in mind that when you enable SSL support, you will need to access the
67 notebook server over ``https://``, not over plain ``http://``. The startup
68 message from the server prints this, but it is easy to overlook and think the
69 server is for some reason non-responsive.
70
71
72 Connecting to an existing kernel
73 ---------------------------------
74
75 The notebook server always prints to the terminal the full details of
76 how to connect to each kernel, with messages such as the following::
77
78 [IPKernelApp] To connect another client to this kernel, use:
79 [IPKernelApp] --existing kernel-3bb93edd-6b5a-455c-99c8-3b658f45dde5.json
80
81 This long string is the name of a JSON file that contains all the port and
82 validation information necessary to connect to the kernel. You can then, for
83 example, manually start a Qt console connected to the *same* kernel with::
84
85 $ ipython qtconsole --existing
86 kernel-3bb93edd-6b5a-455c-99c8-3b658f45dde5.json
87
88 If you have only a single kernel running, simply typing::
89
90 $ ipython qtconsole --existing
91
92 will automatically find it. (It will always find the most recently
93 started kernel if there is more than one.) You can also request this
94 connection data by typing ``%connect_info``; this will print the same
95 file information as well as the content of the JSON data structure it
96 contains.
97
98
99 Running a public notebook server
100 --------------------------------
101
102 If you want to access your notebook server remotely via a web browser,
103 you can do the following.
104
105 Start by creating a certificate file and a hashed password, as explained
106 above. Then create a custom profile for the notebook, with the following
107 command line, type::
108
109 $ ipython profile create nbserver
110
111 In the profile directory just created, edit the file
112 ``ipython_notebook_config.py``. By default, the file has all fields
113 commented; the minimum set you need to uncomment and edit is the following::
114
115 c = get_config()
116
117 # Kernel config
118 c.IPKernelApp.pylab = 'inline' # if you want plotting support always
119
120 # Notebook config
121 c.NotebookApp.certfile = u'/absolute/path/to/your/certificate/mycert.pem'
122 c.NotebookApp.ip = '*'
123 c.NotebookApp.open_browser = False
124 c.NotebookApp.password = u'sha1:bcd259ccf...[your hashed password here]'
125 # It is a good idea to put it on a known, fixed port
126 c.NotebookApp.port = 9999
127
128 You can then start the notebook and access it later by pointing your browser
129 to ``https://your.host.com:9999`` with ``ipython notebook
130 --profile=nbserver``.
131
132 Running with a different URL prefix
133 -----------------------------------
134
135 The notebook dashboard (the landing page with an overview
136 of the notebooks in your working directory) typically lives at the URL
137 ``http://localhost:8888/``. If you prefer that it lives, together with the
138 rest of the notebook, under a sub-directory,
139 e.g. ``http://localhost:8888/ipython/``, you can do so with
140 configuration options like the following (see above for instructions about
141 modifying ``ipython_notebook_config.py``)::
142
143 c.NotebookApp.base_project_url = '/ipython/'
144 c.NotebookApp.base_kernel_url = '/ipython/'
145 c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/static/'}
146
147 Using a different notebook store
148 --------------------------------
149
150 By default, the Notebook app stores the notebook documents that it saves as
151 files in the working directory of the Notebook app, also known as the
152 ``notebook_dir``. This logic is implemented in the
153 :class:`FileNotebookManager` class. However, the server can be configured to
154 use a different notebook manager class, which can
155 store the notebooks in a different format.
156
157 Currently, we ship a :class:`AzureNotebookManager` class that stores notebooks
158 in Azure blob storage. This can be used by adding the following lines to your
159 ``ipython_notebook_config.py`` file::
160
161 c.NotebookApp.notebook_manager_class =
162 'IPython.html.services.notebooks.azurenbmanager.AzureNotebookManager'
163 c.AzureNotebookManager.account_name = u'paste_your_account_name_here'
164 c.AzureNotebookManager.account_key = u'paste_your_account_key_here'
165 c.AzureNotebookManager.container = u'notebooks'
166
167 In addition to providing your Azure Blob Storage account name and key, you
168 will have to provide a container name; you can use multiple containers to
169 organize your notebooks.
170
171
172 Known issues
173 ------------
174
175 When behind a proxy, especially if your system or browser is set to autodetect
176 the proxy, the Notebook app might fail to connect to the server's websockets,
177 and present you with a warning at startup. In this case, you need to configure
178 your system not to use the proxy for the server's address.
179
180 For example, in Firefox, go to the Preferences panel, Advanced section,
181 Network tab, click 'Settings...', and add the address of the notebook server
182 to the 'No proxy for' field.
@@ -10,6 +10,8 b' Using IPython for interactive work'
10 reference
10 reference
11 shell
11 shell
12 qtconsole
12 qtconsole
13 htmlnotebook
13 notebook
14 converting_notebooks
15 working_remotely
14
16
15
17
General Comments 0
You need to be logged in to leave comments. Login now