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