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