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