Show More
@@ -1,654 +1,654 b'' | |||||
1 | .. _qtconsole: |
|
1 | .. _qtconsole: | |
2 |
|
2 | |||
3 | ========================= |
|
3 | ========================= | |
4 | A Qt Console for IPython |
|
4 | A Qt Console for IPython | |
5 | ========================= |
|
5 | ========================= | |
6 |
|
6 | |||
7 | To start the Qt Console:: |
|
7 | To start the Qt Console:: | |
8 |
|
8 | |||
9 | $> ipython qtconsole |
|
9 | $> ipython qtconsole | |
10 |
|
10 | |||
11 | We now have a version of IPython, using the new two-process :ref:`ZeroMQ Kernel |
|
11 | We now have a version of IPython, using the new two-process :ref:`ZeroMQ Kernel | |
12 | <ipythonzmq>`, running in a PyQt_ GUI. This is a very lightweight widget that |
|
12 | <ipythonzmq>`, running in a PyQt_ GUI. This is a very lightweight widget that | |
13 | largely feels like a terminal, but provides a number of enhancements only |
|
13 | largely feels like a terminal, but provides a number of enhancements only | |
14 | possible in a GUI, such as inline figures, proper multiline editing with syntax |
|
14 | possible in a GUI, such as inline figures, proper multiline editing with syntax | |
15 | highlighting, graphical calltips, and much more. |
|
15 | highlighting, graphical calltips, and much more. | |
16 |
|
16 | |||
17 | .. figure:: ../_images/qtconsole.png |
|
17 | .. figure:: ../_images/qtconsole.png | |
18 | :width: 400px |
|
18 | :width: 400px | |
19 | :alt: IPython Qt console with embedded plots |
|
19 | :alt: IPython Qt console with embedded plots | |
20 | :align: center |
|
20 | :align: center | |
21 | :target: ../_images/qtconsole.png |
|
21 | :target: ../_images/qtconsole.png | |
22 |
|
22 | |||
23 | The Qt console for IPython, using inline matplotlib plots. |
|
23 | The Qt console for IPython, using inline matplotlib plots. | |
24 |
|
24 | |||
25 | To get acquainted with the Qt console, type `%guiref` to see a quick |
|
25 | To get acquainted with the Qt console, type `%guiref` to see a quick | |
26 | introduction of its main features. |
|
26 | introduction of its main features. | |
27 |
|
27 | |||
28 | The Qt frontend has hand-coded emacs-style bindings for text navigation. This |
|
28 | The Qt frontend has hand-coded emacs-style bindings for text navigation. This | |
29 | is not yet configurable. |
|
29 | is not yet configurable. | |
30 |
|
30 | |||
31 | .. tip:: |
|
31 | .. tip:: | |
32 |
|
32 | |||
33 | Since the Qt console tries hard to behave like a terminal, by default it |
|
33 | Since the Qt console tries hard to behave like a terminal, by default it | |
34 | immediately executes single lines of input that are complete. If you want |
|
34 | immediately executes single lines of input that are complete. If you want | |
35 | to force multiline input, hit :kbd:`Ctrl-Enter` at the end of the first line |
|
35 | to force multiline input, hit :kbd:`Ctrl-Enter` at the end of the first line | |
36 | instead of :kbd:`Enter`, and it will open a new line for input. At any |
|
36 | instead of :kbd:`Enter`, and it will open a new line for input. At any | |
37 | point in a multiline block, you can force its execution (without having to |
|
37 | point in a multiline block, you can force its execution (without having to | |
38 | go to the bottom) with :kbd:`Shift-Enter`. |
|
38 | go to the bottom) with :kbd:`Shift-Enter`. | |
39 |
|
39 | |||
40 | ``%load`` |
|
40 | ``%load`` | |
41 | ========= |
|
41 | ========= | |
42 |
|
42 | |||
43 | The new ``%load`` magic (previously ``%loadpy``) takes any script, and pastes |
|
43 | The new ``%load`` magic (previously ``%loadpy``) takes any script, and pastes | |
44 | its contents as your next input, so you can edit it before executing. The |
|
44 | its contents as your next input, so you can edit it before executing. The | |
45 | script may be on your machine, but you can also specify an history range, or a |
|
45 | script may be on your machine, but you can also specify an history range, or a | |
46 | url, and it will download the script from the web. This is particularly useful |
|
46 | url, and it will download the script from the web. This is particularly useful | |
47 | for playing with examples from documentation, such as matplotlib. |
|
47 | for playing with examples from documentation, such as matplotlib. | |
48 |
|
48 | |||
49 | .. sourcecode:: ipython |
|
49 | .. sourcecode:: ipython | |
50 |
|
50 | |||
51 | In [6]: %load http://matplotlib.org/plot_directive/mpl_examples/mplot3d/contour3d_demo.py |
|
51 | In [6]: %load http://matplotlib.org/plot_directive/mpl_examples/mplot3d/contour3d_demo.py | |
52 |
|
52 | |||
53 | In [7]: from mpl_toolkits.mplot3d import axes3d |
|
53 | In [7]: from mpl_toolkits.mplot3d import axes3d | |
54 | ...: import matplotlib.pyplot as plt |
|
54 | ...: import matplotlib.pyplot as plt | |
55 | ...: |
|
55 | ...: | |
56 | ...: fig = plt.figure() |
|
56 | ...: fig = plt.figure() | |
57 | ...: ax = fig.add_subplot(111, projection='3d') |
|
57 | ...: ax = fig.add_subplot(111, projection='3d') | |
58 | ...: X, Y, Z = axes3d.get_test_data(0.05) |
|
58 | ...: X, Y, Z = axes3d.get_test_data(0.05) | |
59 | ...: cset = ax.contour(X, Y, Z) |
|
59 | ...: cset = ax.contour(X, Y, Z) | |
60 | ...: ax.clabel(cset, fontsize=9, inline=1) |
|
60 | ...: ax.clabel(cset, fontsize=9, inline=1) | |
61 | ...: |
|
61 | ...: | |
62 | ...: plt.show() |
|
62 | ...: plt.show() | |
63 |
|
63 | |||
64 | The ``%load`` magic can also load source code from objects in the user or |
|
64 | The ``%load`` magic can also load source code from objects in the user or | |
65 | global namespace by invoking the ``-n`` option. |
|
65 | global namespace by invoking the ``-n`` option. | |
66 |
|
66 | |||
67 | .. sourcecode:: ipython |
|
67 | .. sourcecode:: ipython | |
68 |
|
68 | |||
69 | In [1]: import hello_world |
|
69 | In [1]: import hello_world | |
70 | ...: %load -n hello_world.say_hello |
|
70 | ...: %load -n hello_world.say_hello | |
71 |
|
71 | |||
72 | In [3]: def say_hello() : |
|
72 | In [3]: def say_hello() : | |
73 | ...: print("Hello World!") |
|
73 | ...: print("Hello World!") | |
74 |
|
74 | |||
75 | Inline Matplotlib |
|
75 | Inline Matplotlib | |
76 | ================= |
|
76 | ================= | |
77 |
|
77 | |||
78 | One of the most exciting features of the QtConsole is embedded matplotlib |
|
78 | One of the most exciting features of the QtConsole is embedded matplotlib | |
79 | figures. You can use any standard matplotlib GUI backend |
|
79 | figures. You can use any standard matplotlib GUI backend | |
80 | to draw the figures, and since there is now a two-process model, there is no |
|
80 | to draw the figures, and since there is now a two-process model, there is no | |
81 | longer a conflict between user input and the drawing eventloop. |
|
81 | longer a conflict between user input and the drawing eventloop. | |
82 |
|
82 | |||
83 | .. image:: figs/besselj.png |
|
83 | .. image:: figs/besselj.png | |
84 | :width: 519px |
|
84 | :width: 519px | |
85 |
|
85 | |||
86 | .. _display: |
|
86 | .. _display: | |
87 |
|
87 | |||
88 | :func:`display` |
|
88 | :func:`display` | |
89 | *************** |
|
89 | *************** | |
90 |
|
90 | |||
91 | IPython provides a function :func:`display` for displaying rich representations |
|
91 | IPython provides a function :func:`display` for displaying rich representations | |
92 | of objects if they are available. The IPython display |
|
92 | of objects if they are available. The IPython display | |
93 | system provides a mechanism for specifying PNG or SVG (and more) |
|
93 | system provides a mechanism for specifying PNG or SVG (and more) | |
94 | representations of objects for GUI frontends. |
|
94 | representations of objects for GUI frontends. | |
95 | When you enable matplotlib integration via the ``%matplotlib`` magic, IPython registers |
|
95 | When you enable matplotlib integration via the ``%matplotlib`` magic, IPython registers | |
96 | convenient PNG and SVG renderers for matplotlib figures, so you can embed them |
|
96 | convenient PNG and SVG renderers for matplotlib figures, so you can embed them | |
97 | in your document by calling :func:`display` on one or more of them. This is |
|
97 | in your document by calling :func:`display` on one or more of them. This is | |
98 | especially useful for saving_ your work. |
|
98 | especially useful for saving_ your work. | |
99 |
|
99 | |||
100 | .. sourcecode:: ipython |
|
100 | .. sourcecode:: ipython | |
101 |
|
101 | |||
102 | In [4]: from IPython.display import display |
|
102 | In [4]: from IPython.display import display | |
103 |
|
103 | |||
104 | In [5]: plt.plot(range(5)) # plots in the matplotlib window |
|
104 | In [5]: plt.plot(range(5)) # plots in the matplotlib window | |
105 |
|
105 | |||
106 | In [6]: display(plt.gcf()) # embeds the current figure in the qtconsole |
|
106 | In [6]: display(plt.gcf()) # embeds the current figure in the qtconsole | |
107 |
|
107 | |||
108 | In [7]: display(*getfigs()) # embeds all active figures in the qtconsole |
|
108 | In [7]: display(*getfigs()) # embeds all active figures in the qtconsole | |
109 |
|
109 | |||
110 | If you have a reference to a matplotlib figure object, you can always display |
|
110 | If you have a reference to a matplotlib figure object, you can always display | |
111 | that specific figure: |
|
111 | that specific figure: | |
112 |
|
112 | |||
113 | .. sourcecode:: ipython |
|
113 | .. sourcecode:: ipython | |
114 |
|
114 | |||
115 | In [1]: f = plt.figure() |
|
115 | In [1]: f = plt.figure() | |
116 |
|
116 | |||
117 | In [2]: plt.plot(np.rand(100)) |
|
117 | In [2]: plt.plot(np.rand(100)) | |
118 | Out[2]: [<matplotlib.lines.Line2D at 0x7fc6ac03dd90>] |
|
118 | Out[2]: [<matplotlib.lines.Line2D at 0x7fc6ac03dd90>] | |
119 |
|
119 | |||
120 | In [3]: display(f) |
|
120 | In [3]: display(f) | |
121 |
|
121 | |||
122 | # Plot is shown here |
|
122 | # Plot is shown here | |
123 |
|
123 | |||
124 | In [4]: plt.title('A title') |
|
124 | In [4]: plt.title('A title') | |
125 | Out[4]: <matplotlib.text.Text at 0x7fc6ac023450> |
|
125 | Out[4]: <matplotlib.text.Text at 0x7fc6ac023450> | |
126 |
|
126 | |||
127 | In [5]: display(f) |
|
127 | In [5]: display(f) | |
128 |
|
128 | |||
129 | # Updated plot with title is shown here. |
|
129 | # Updated plot with title is shown here. | |
130 |
|
130 | |||
131 | .. _inline: |
|
131 | .. _inline: | |
132 |
|
132 | |||
133 | ``--matplotlib inline`` |
|
133 | ``--matplotlib inline`` | |
134 | *********************** |
|
134 | *********************** | |
135 |
|
135 | |||
136 | If you want to have all of your figures embedded in your session, instead of |
|
136 | If you want to have all of your figures embedded in your session, instead of | |
137 | calling :func:`display`, you can specify ``--matplotlib inline`` when you start the |
|
137 | calling :func:`display`, you can specify ``--matplotlib inline`` when you start the | |
138 | console, and each time you make a plot, it will show up in your document, as if |
|
138 | console, and each time you make a plot, it will show up in your document, as if | |
139 | you had called :func:`display(fig)`. |
|
139 | you had called :func:`display(fig)`. | |
140 |
|
140 | |||
141 | The inline backend can use either SVG or PNG figures (PNG being the default). |
|
141 | The inline backend can use either SVG or PNG figures (PNG being the default). | |
142 | It also supports the special key ``'retina'``, which is 2x PNG for high-DPI displays. |
|
142 | It also supports the special key ``'retina'``, which is 2x PNG for high-DPI displays. | |
143 | To switch between them, set the ``InlineBackend.figure_format`` configurable |
|
143 | To switch between them, set the ``InlineBackend.figure_format`` configurable | |
144 | in a config file, or via the ``%config`` magic: |
|
144 | in a config file, or via the ``%config`` magic: | |
145 |
|
145 | |||
146 | .. sourcecode:: ipython |
|
146 | .. sourcecode:: ipython | |
147 |
|
147 | |||
148 | In [10]: %config InlineBackend.figure_format = 'svg' |
|
148 | In [10]: %config InlineBackend.figure_format = 'svg' | |
149 |
|
149 | |||
150 | .. note:: |
|
150 | .. note:: | |
151 |
|
151 | |||
152 | Changing the inline figure format also affects calls to :func:`display` above, |
|
152 | Changing the inline figure format also affects calls to :func:`display` above, | |
153 | even if you are not using the inline backend for all figures. |
|
153 | even if you are not using the inline backend for all figures. | |
154 |
|
154 | |||
155 | By default, IPython closes all figures at the completion of each execution. This means you |
|
155 | By default, IPython closes all figures at the completion of each execution. This means you | |
156 | don't have to manually close figures, which is less convenient when figures aren't attached |
|
156 | don't have to manually close figures, which is less convenient when figures aren't attached | |
157 | to windows with an obvious close button. It also means that the first matplotlib call in |
|
157 | to windows with an obvious close button. It also means that the first matplotlib call in | |
158 | each cell will always create a new figure: |
|
158 | each cell will always create a new figure: | |
159 |
|
159 | |||
160 | .. sourcecode:: ipython |
|
160 | .. sourcecode:: ipython | |
161 |
|
161 | |||
162 | In [11]: plt.plot(range(100)) |
|
162 | In [11]: plt.plot(range(100)) | |
163 | <single-line plot> |
|
163 | <single-line plot> | |
164 |
|
164 | |||
165 | In [12]: plt.plot([1,3,2]) |
|
165 | In [12]: plt.plot([1,3,2]) | |
166 | <another single-line plot> |
|
166 | <another single-line plot> | |
167 |
|
167 | |||
168 |
|
168 | |||
169 | However, it does prevent the list of active figures surviving from one input cell to the |
|
169 | However, it does prevent the list of active figures surviving from one input cell to the | |
170 | next, so if you want to continue working with a figure, you must hold on to a reference to |
|
170 | next, so if you want to continue working with a figure, you must hold on to a reference to | |
171 | it: |
|
171 | it: | |
172 |
|
172 | |||
173 | .. sourcecode:: ipython |
|
173 | .. sourcecode:: ipython | |
174 |
|
174 | |||
175 | In [11]: fig = gcf() |
|
175 | In [11]: fig = gcf() | |
176 | ....: fig.plot(rand(100)) |
|
176 | ....: fig.plot(rand(100)) | |
177 | <plot> |
|
177 | <plot> | |
178 | In [12]: fig.title('Random Title') |
|
178 | In [12]: fig.title('Random Title') | |
179 | <redraw plot with title> |
|
179 | <redraw plot with title> | |
180 |
|
180 | |||
181 | This behavior is controlled by the :attr:`InlineBackend.close_figures` configurable, and |
|
181 | This behavior is controlled by the :attr:`InlineBackend.close_figures` configurable, and | |
182 | if you set it to False, via %config or config file, then IPython will *not* close figures, |
|
182 | if you set it to False, via %config or config file, then IPython will *not* close figures, | |
183 | and tools like :func:`gcf`, :func:`gca`, :func:`getfigs` will behave the same as they |
|
183 | and tools like :func:`gcf`, :func:`gca`, :func:`getfigs` will behave the same as they | |
184 | do with other backends. You will, however, have to manually close figures: |
|
184 | do with other backends. You will, however, have to manually close figures: | |
185 |
|
185 | |||
186 | .. sourcecode:: ipython |
|
186 | .. sourcecode:: ipython | |
187 |
|
187 | |||
188 | # close all active figures: |
|
188 | # close all active figures: | |
189 | In [13]: [ fig.close() for fig in getfigs() ] |
|
189 | In [13]: [ fig.close() for fig in getfigs() ] | |
190 |
|
190 | |||
191 |
|
191 | |||
192 |
|
192 | |||
193 | .. _saving: |
|
193 | .. _saving: | |
194 |
|
194 | |||
195 | Saving and Printing |
|
195 | Saving and Printing | |
196 | =================== |
|
196 | =================== | |
197 |
|
197 | |||
198 | IPythonQt has the ability to save your current session, as either HTML or |
|
198 | IPythonQt has the ability to save your current session, as either HTML or | |
199 | XHTML. If you have been using :func:`display` or inline_ matplotlib, your figures |
|
199 | XHTML. If you have been using :func:`display` or inline_ matplotlib, your figures | |
200 | will be PNG in HTML, or inlined as SVG in XHTML. PNG images have the option to |
|
200 | will be PNG in HTML, or inlined as SVG in XHTML. PNG images have the option to | |
201 | be either in an external folder, as in many browsers' "Webpage, Complete" |
|
201 | be either in an external folder, as in many browsers' "Webpage, Complete" | |
202 | option, or inlined as well, for a larger, but more portable file. |
|
202 | option, or inlined as well, for a larger, but more portable file. | |
203 |
|
203 | |||
204 | .. note:: |
|
204 | .. note:: | |
205 |
|
205 | |||
206 | Export to SVG+XHTML requires that you are using SVG figures, which is *not* |
|
206 | Export to SVG+XHTML requires that you are using SVG figures, which is *not* | |
207 | the default. To switch the inline figure format to use SVG during an active |
|
207 | the default. To switch the inline figure format to use SVG during an active | |
208 | session, do: |
|
208 | session, do: | |
209 |
|
209 | |||
210 | .. sourcecode:: ipython |
|
210 | .. sourcecode:: ipython | |
211 |
|
211 | |||
212 | In [10]: %config InlineBackend.figure_format = 'svg' |
|
212 | In [10]: %config InlineBackend.figure_format = 'svg' | |
213 |
|
213 | |||
214 | Or, you can add the same line (c.Inline... instead of %config Inline...) to |
|
214 | Or, you can add the same line (c.Inline... instead of %config Inline...) to | |
215 | your config files. |
|
215 | your config files. | |
216 |
|
216 | |||
217 | This will only affect figures plotted after making this call |
|
217 | This will only affect figures plotted after making this call | |
218 |
|
218 | |||
219 |
|
219 | |||
220 | The widget also exposes the ability to print directly, via the default print |
|
220 | The widget also exposes the ability to print directly, via the default print | |
221 | shortcut or context menu. |
|
221 | shortcut or context menu. | |
222 |
|
222 | |||
223 |
|
223 | |||
224 | .. Note:: |
|
224 | .. Note:: | |
225 |
|
225 | |||
226 | Saving is only available to richtext Qt widgets, which are used by default, |
|
226 | Saving is only available to richtext Qt widgets, which are used by default, | |
227 | but if you pass the ``--plain`` flag, saving will not be available to you. |
|
227 | but if you pass the ``--plain`` flag, saving will not be available to you. | |
228 |
|
228 | |||
229 |
|
229 | |||
230 | See these examples of :download:`png/html<figs/jn.html>` and |
|
230 | See these examples of :download:`png/html<figs/jn.html>` and | |
231 | :download:`svg/xhtml <figs/jn.xhtml>` output. Note that syntax highlighting |
|
231 | :download:`svg/xhtml <figs/jn.xhtml>` output. Note that syntax highlighting | |
232 | does not survive export. This is a known issue, and is being investigated. |
|
232 | does not survive export. This is a known issue, and is being investigated. | |
233 |
|
233 | |||
234 |
|
234 | |||
235 | Colors and Highlighting |
|
235 | Colors and Highlighting | |
236 | ======================= |
|
236 | ======================= | |
237 |
|
237 | |||
238 | Terminal IPython has always had some coloring, but never syntax |
|
238 | Terminal IPython has always had some coloring, but never syntax | |
239 | highlighting. There are a few simple color choices, specified by the ``colors`` |
|
239 | highlighting. There are a few simple color choices, specified by the ``colors`` | |
240 | flag or ``%colors`` magic: |
|
240 | flag or ``%colors`` magic: | |
241 |
|
241 | |||
242 | * LightBG for light backgrounds |
|
242 | * LightBG for light backgrounds | |
243 | * Linux for dark backgrounds |
|
243 | * Linux for dark backgrounds | |
244 | * NoColor for a simple colorless terminal |
|
244 | * NoColor for a simple colorless terminal | |
245 |
|
245 | |||
246 | The Qt widget has full support for the ``colors`` flag used in the terminal shell. |
|
246 | The Qt widget has full support for the ``colors`` flag used in the terminal shell. | |
247 |
|
247 | |||
248 | The Qt widget, however, has full syntax highlighting as you type, handled by |
|
248 | The Qt widget, however, has full syntax highlighting as you type, handled by | |
249 | the `pygments`_ library. The ``style`` argument exposes access to any style by |
|
249 | the `pygments`_ library. The ``style`` argument exposes access to any style by | |
250 | name that can be found by pygments, and there are several already |
|
250 | name that can be found by pygments, and there are several already | |
251 | installed. The ``colors`` argument, if unspecified, will be guessed based on |
|
251 | installed. The ``colors`` argument, if unspecified, will be guessed based on | |
252 | the chosen style. Similarly, there are default styles associated with each |
|
252 | the chosen style. Similarly, there are default styles associated with each | |
253 | ``colors`` option. |
|
253 | ``colors`` option. | |
254 |
|
254 | |||
255 |
|
255 | |||
256 | Screenshot of ``ipython qtconsole --colors=linux``, which uses the 'monokai' |
|
256 | Screenshot of ``ipython qtconsole --colors=linux``, which uses the 'monokai' | |
257 | theme by default: |
|
257 | theme by default: | |
258 |
|
258 | |||
259 | .. image:: figs/colors_dark.png |
|
259 | .. image:: figs/colors_dark.png | |
260 | :width: 627px |
|
260 | :width: 627px | |
261 |
|
261 | |||
262 | .. Note:: |
|
262 | .. Note:: | |
263 |
|
263 | |||
264 | Calling ``ipython qtconsole -h`` will show all the style names that |
|
264 | Calling ``ipython qtconsole -h`` will show all the style names that | |
265 | pygments can find on your system. |
|
265 | pygments can find on your system. | |
266 |
|
266 | |||
267 | You can also pass the filename of a custom CSS stylesheet, if you want to do |
|
267 | You can also pass the filename of a custom CSS stylesheet, if you want to do | |
268 | your own coloring, via the ``stylesheet`` argument. The default LightBG |
|
268 | your own coloring, via the ``stylesheet`` argument. The default LightBG | |
269 | stylesheet: |
|
269 | stylesheet: | |
270 |
|
270 | |||
271 | .. sourcecode:: css |
|
271 | .. sourcecode:: css | |
272 |
|
272 | |||
273 | QPlainTextEdit, QTextEdit { background-color: white; |
|
273 | QPlainTextEdit, QTextEdit { background-color: white; | |
274 | color: black ; |
|
274 | color: black ; | |
275 | selection-background-color: #ccc} |
|
275 | selection-background-color: #ccc} | |
276 | .error { color: red; } |
|
276 | .error { color: red; } | |
277 | .in-prompt { color: navy; } |
|
277 | .in-prompt { color: navy; } | |
278 | .in-prompt-number { font-weight: bold; } |
|
278 | .in-prompt-number { font-weight: bold; } | |
279 | .out-prompt { color: darkred; } |
|
279 | .out-prompt { color: darkred; } | |
280 | .out-prompt-number { font-weight: bold; } |
|
280 | .out-prompt-number { font-weight: bold; } | |
281 | /* .inverted is used to highlight selected completion */ |
|
281 | /* .inverted is used to highlight selected completion */ | |
282 | .inverted { background-color: black ; color: white; } |
|
282 | .inverted { background-color: black ; color: white; } | |
283 |
|
283 | |||
284 | Fonts |
|
284 | Fonts | |
285 | ===== |
|
285 | ===== | |
286 |
|
286 | |||
287 | The QtConsole has configurable via the ConsoleWidget. To change these, set the |
|
287 | The QtConsole has configurable via the ConsoleWidget. To change these, set the | |
288 | ``font_family`` or ``font_size`` traits of the ConsoleWidget. For instance, to |
|
288 | ``font_family`` or ``font_size`` traits of the ConsoleWidget. For instance, to | |
289 | use 9pt Anonymous Pro:: |
|
289 | use 9pt Anonymous Pro:: | |
290 |
|
290 | |||
291 | $> ipython qtconsole --ConsoleWidget.font_family="Anonymous Pro" --ConsoleWidget.font_size=9 |
|
291 | $> ipython qtconsole --ConsoleWidget.font_family="Anonymous Pro" --ConsoleWidget.font_size=9 | |
292 |
|
292 | |||
293 | Process Management |
|
293 | Process Management | |
294 | ================== |
|
294 | ================== | |
295 |
|
295 | |||
296 | With the two-process ZMQ model, the frontend does not block input during |
|
296 | With the two-process ZMQ model, the frontend does not block input during | |
297 | execution. This means that actions can be taken by the frontend while the |
|
297 | execution. This means that actions can be taken by the frontend while the | |
298 | Kernel is executing, or even after it crashes. The most basic such command is |
|
298 | Kernel is executing, or even after it crashes. The most basic such command is | |
299 | via 'Ctrl-.', which restarts the kernel. This can be done in the middle of a |
|
299 | via 'Ctrl-.', which restarts the kernel. This can be done in the middle of a | |
300 | blocking execution. The frontend can also know, via a heartbeat mechanism, that |
|
300 | blocking execution. The frontend can also know, via a heartbeat mechanism, that | |
301 | the kernel has died. This means that the frontend can safely restart the |
|
301 | the kernel has died. This means that the frontend can safely restart the | |
302 | kernel. |
|
302 | kernel. | |
303 |
|
303 | |||
304 | .. _multiple_consoles: |
|
304 | .. _multiple_consoles: | |
305 |
|
305 | |||
306 | Multiple Consoles |
|
306 | Multiple Consoles | |
307 | ***************** |
|
307 | ***************** | |
308 |
|
308 | |||
309 | Since the Kernel listens on the network, multiple frontends can connect to it. |
|
309 | Since the Kernel listens on the network, multiple frontends can connect to it. | |
310 | These do not have to all be qt frontends - any IPython frontend can connect and |
|
310 | These do not have to all be qt frontends - any IPython frontend can connect and | |
311 | run code. When you start ipython qtconsole, there will be an output line, |
|
311 | run code. When you start ipython qtconsole, there will be an output line, | |
312 | like:: |
|
312 | like:: | |
313 |
|
313 | |||
314 | [IPKernelApp] To connect another client to this kernel, use: |
|
314 | [IPKernelApp] To connect another client to this kernel, use: | |
315 | [IPKernelApp] --existing kernel-12345.json |
|
315 | [IPKernelApp] --existing kernel-12345.json | |
316 |
|
316 | |||
317 | Other frontends can connect to your kernel, and share in the execution. This is |
|
317 | Other frontends can connect to your kernel, and share in the execution. This is | |
318 | great for collaboration. The ``--existing`` flag means connect to a kernel |
|
318 | great for collaboration. The ``--existing`` flag means connect to a kernel | |
319 | that already exists. Starting other consoles |
|
319 | that already exists. Starting other consoles | |
320 | with that flag will not try to start their own kernel, but rather connect to |
|
320 | with that flag will not try to start their own kernel, but rather connect to | |
321 | yours. :file:`kernel-12345.json` is a small JSON file with the ip, port, and |
|
321 | yours. :file:`kernel-12345.json` is a small JSON file with the ip, port, and | |
322 | authentication information necessary to connect to your kernel. By default, this file |
|
322 | authentication information necessary to connect to your kernel. By default, this file | |
323 | will be in your default profile's security directory. If it is somewhere else, |
|
323 | will be in your default profile's security directory. If it is somewhere else, | |
324 | the output line will print the full path of the connection file, rather than |
|
324 | the output line will print the full path of the connection file, rather than | |
325 | just its filename. |
|
325 | just its filename. | |
326 |
|
326 | |||
327 | If you need to find the connection info to send, and don't know where your connection file |
|
327 | If you need to find the connection info to send, and don't know where your connection file | |
328 | lives, there are a couple of ways to get it. If you are already running an IPython console |
|
328 | lives, there are a couple of ways to get it. If you are already running an IPython console | |
329 | connected to the kernel, you can use the ``%connect_info`` magic to display the information |
|
329 | connected to the kernel, you can use the ``%connect_info`` magic to display the information | |
330 | necessary to connect another frontend to the kernel. |
|
330 | necessary to connect another frontend to the kernel. | |
331 |
|
331 | |||
332 | .. sourcecode:: ipython |
|
332 | .. sourcecode:: ipython | |
333 |
|
333 | |||
334 | In [2]: %connect_info |
|
334 | In [2]: %connect_info | |
335 | { |
|
335 | { | |
336 | "stdin_port":50255, |
|
336 | "stdin_port":50255, | |
337 | "ip":"127.0.0.1", |
|
337 | "ip":"127.0.0.1", | |
338 | "hb_port":50256, |
|
338 | "hb_port":50256, | |
339 | "key":"70be6f0f-1564-4218-8cda-31be40a4d6aa", |
|
339 | "key":"70be6f0f-1564-4218-8cda-31be40a4d6aa", | |
340 | "shell_port":50253, |
|
340 | "shell_port":50253, | |
341 | "iopub_port":50254 |
|
341 | "iopub_port":50254 | |
342 | } |
|
342 | } | |
343 |
|
343 | |||
344 | Paste the above JSON into a file, and connect with: |
|
344 | Paste the above JSON into a file, and connect with: | |
345 | $> ipython <app> --existing <file> |
|
345 | $> ipython <app> --existing <file> | |
346 | or, if you are local, you can connect with just: |
|
346 | or, if you are local, you can connect with just: | |
347 | $> ipython <app> --existing kernel-12345.json |
|
347 | $> ipython <app> --existing kernel-12345.json | |
348 | or even just: |
|
348 | or even just: | |
349 | $> ipython <app> --existing |
|
349 | $> ipython <app> --existing | |
350 | if this is the most recent IPython session you have started. |
|
350 | if this is the most recent IPython session you have started. | |
351 |
|
351 | |||
352 | Otherwise, you can find a connection file by name (and optionally profile) with |
|
352 | Otherwise, you can find a connection file by name (and optionally profile) with | |
353 | :func:`IPython.lib.kernel.find_connection_file`: |
|
353 | :func:`IPython.lib.kernel.find_connection_file`: | |
354 |
|
354 | |||
355 | .. sourcecode:: bash |
|
355 | .. sourcecode:: bash | |
356 |
|
356 | |||
357 | $> python -c "from IPython.lib.kernel import find_connection_file;\ |
|
357 | $> python -c "from IPython.lib.kernel import find_connection_file;\ | |
358 | print find_connection_file('kernel-12345.json')" |
|
358 | print find_connection_file('kernel-12345.json')" | |
359 | /home/you/.ipython/profile_default/security/kernel-12345.json |
|
359 | /home/you/.ipython/profile_default/security/kernel-12345.json | |
360 |
|
360 | |||
361 | And if you are using a particular IPython profile: |
|
361 | And if you are using a particular IPython profile: | |
362 |
|
362 | |||
363 | .. sourcecode:: bash |
|
363 | .. sourcecode:: bash | |
364 |
|
364 | |||
365 | $> python -c "from IPython.lib.kernel import find_connection_file;\ |
|
365 | $> python -c "from IPython.lib.kernel import find_connection_file;\ | |
366 | print find_connection_file('kernel-12345.json', profile='foo')" |
|
366 | print find_connection_file('kernel-12345.json', profile='foo')" | |
367 | /home/you/.ipython/profile_foo/security/kernel-12345.json |
|
367 | /home/you/.ipython/profile_foo/security/kernel-12345.json | |
368 |
|
368 | |||
369 | You can even launch a standalone kernel, and connect and disconnect Qt Consoles |
|
369 | You can even launch a standalone kernel, and connect and disconnect Qt Consoles | |
370 | from various machines. This lets you keep the same running IPython session |
|
370 | from various machines. This lets you keep the same running IPython session | |
371 | on your work machine (with matplotlib plots and everything), logging in from home, |
|
371 | on your work machine (with matplotlib plots and everything), logging in from home, | |
372 | cafΓ©s, etc.:: |
|
372 | cafΓ©s, etc.:: | |
373 |
|
373 | |||
374 | $> ipython kernel |
|
374 | $> ipython kernel | |
375 | [IPKernelApp] To connect another client to this kernel, use: |
|
375 | [IPKernelApp] To connect another client to this kernel, use: | |
376 | [IPKernelApp] --existing kernel-12345.json |
|
376 | [IPKernelApp] --existing kernel-12345.json | |
377 |
|
377 | |||
378 | This is actually exactly the same as the subprocess launched by the qtconsole, so |
|
378 | This is actually exactly the same as the subprocess launched by the qtconsole, so | |
379 | all the information about connecting to a standalone kernel is identical to that |
|
379 | all the information about connecting to a standalone kernel is identical to that | |
380 | of connecting to the kernel attached to a running console. |
|
380 | of connecting to the kernel attached to a running console. | |
381 |
|
381 | |||
382 | .. _kernel_security: |
|
382 | .. _kernel_security: | |
383 |
|
383 | |||
384 | Security |
|
384 | Security | |
385 | -------- |
|
385 | -------- | |
386 |
|
386 | |||
387 | .. warning:: |
|
387 | .. warning:: | |
388 |
|
388 | |||
389 | Since the ZMQ code currently has no encryption, listening on an |
|
389 | Since the ZMQ code currently has no encryption, listening on an | |
390 | external-facing IP is dangerous. You are giving any computer that can see |
|
390 | external-facing IP is dangerous. You are giving any computer that can see | |
391 | you on the network the ability to connect to your kernel, and view your traffic. |
|
391 | you on the network the ability to connect to your kernel, and view your traffic. | |
392 | Read the rest of this section before listening on external ports |
|
392 | Read the rest of this section before listening on external ports | |
393 | or running an IPython kernel on a shared machine. |
|
393 | or running an IPython kernel on a shared machine. | |
394 |
|
394 | |||
395 | By default (for security reasons), the kernel only listens on localhost, so you |
|
395 | By default (for security reasons), the kernel only listens on localhost, so you | |
396 | can only connect multiple frontends to the kernel from your local machine. You |
|
396 | can only connect multiple frontends to the kernel from your local machine. You | |
397 | can specify to listen on an external interface by specifying the ``ip`` |
|
397 | can specify to listen on an external interface by specifying the ``ip`` | |
398 | argument:: |
|
398 | argument:: | |
399 |
|
399 | |||
400 | $> ipython qtconsole --ip=192.168.1.123 |
|
400 | $> ipython qtconsole --ip=192.168.1.123 | |
401 |
|
401 | |||
402 | If you specify the ip as 0.0.0.0 or '*', that means all interfaces, so any |
|
402 | If you specify the ip as 0.0.0.0 or '*', that means all interfaces, so any | |
403 | computer that can see yours on the network can connect to the kernel. |
|
403 | computer that can see yours on the network can connect to the kernel. | |
404 |
|
404 | |||
405 | Messages are not encrypted, so users with access to the ports your kernel is using will be |
|
405 | Messages are not encrypted, so users with access to the ports your kernel is using will be | |
406 | able to see any output of the kernel. They will **NOT** be able to issue shell commands as |
|
406 | able to see any output of the kernel. They will **NOT** be able to issue shell commands as | |
407 | you due to message signatures, which are enabled by default as of IPython 0.12. |
|
407 | you due to message signatures, which are enabled by default as of IPython 0.12. | |
408 |
|
408 | |||
409 | .. warning:: |
|
409 | .. warning:: | |
410 |
|
410 | |||
411 | If you disable message signatures, then any user with access to the ports your |
|
411 | If you disable message signatures, then any user with access to the ports your | |
412 | kernel is listening on can issue arbitrary code as you. **DO NOT** disable message |
|
412 | kernel is listening on can issue arbitrary code as you. **DO NOT** disable message | |
413 | signatures unless you have a lot of trust in your environment. |
|
413 | signatures unless you have a lot of trust in your environment. | |
414 |
|
414 | |||
415 | The one security feature IPython does provide is protection from unauthorized execution. |
|
415 | The one security feature IPython does provide is protection from unauthorized execution. | |
416 | IPython's messaging system will sign messages with HMAC digests using a shared-key. The key |
|
416 | IPython's messaging system will sign messages with HMAC digests using a shared-key. The key | |
417 | is never sent over the network, it is only used to generate a unique hash for each message, |
|
417 | is never sent over the network, it is only used to generate a unique hash for each message, | |
418 | based on its content. When IPython receives a message, it will check that the digest |
|
418 | based on its content. When IPython receives a message, it will check that the digest | |
419 | matches, and discard the message. You can use any file that only you have access to to |
|
419 | matches, and discard the message. You can use any file that only you have access to to | |
420 | generate this key, but the default is just to generate a new UUID. You can generate a random |
|
420 | generate this key, but the default is just to generate a new UUID. You can generate a random | |
421 | private key with:: |
|
421 | private key with:: | |
422 |
|
422 | |||
423 | # generate 1024b of random data, and store in a file only you can read: |
|
423 | # generate 1024b of random data, and store in a file only you can read: | |
424 | # (assumes IPYTHONDIR is defined, otherwise use your IPython directory) |
|
424 | # (assumes IPYTHONDIR is defined, otherwise use your IPython directory) | |
425 | $> python -c "import os; print os.urandom(128).encode('base64')" > $IPYTHONDIR/sessionkey |
|
425 | $> python -c "import os; print os.urandom(128).encode('base64')" > $IPYTHONDIR/sessionkey | |
426 | $> chmod 600 $IPYTHONDIR/sessionkey |
|
426 | $> chmod 600 $IPYTHONDIR/sessionkey | |
427 |
|
427 | |||
428 | The *contents* of this file will be stored in the JSON connection file, so that file |
|
428 | The *contents* of this file will be stored in the JSON connection file, so that file | |
429 | contains everything you need to connect to and use a kernel. |
|
429 | contains everything you need to connect to and use a kernel. | |
430 |
|
430 | |||
431 | To use this generated key, simply specify the ``Session.keyfile`` configurable |
|
431 | To use this generated key, simply specify the ``Session.keyfile`` configurable | |
432 | in :file:`ipython_config.py` or at the command-line, as in:: |
|
432 | in :file:`ipython_config.py` or at the command-line, as in:: | |
433 |
|
433 | |||
434 | # instruct IPython to sign messages with that key, instead of a new UUID |
|
434 | # instruct IPython to sign messages with that key, instead of a new UUID | |
435 | $> ipython qtconsole --Session.keyfile=$IPYTHONDIR/sessionkey |
|
435 | $> ipython qtconsole --Session.keyfile=$IPYTHONDIR/sessionkey | |
436 |
|
436 | |||
437 | .. _ssh_tunnels: |
|
437 | .. _ssh_tunnels: | |
438 |
|
438 | |||
439 | SSH Tunnels |
|
439 | SSH Tunnels | |
440 | ----------- |
|
440 | ----------- | |
441 |
|
441 | |||
442 | Sometimes you want to connect to machines across the internet, or just across |
|
442 | Sometimes you want to connect to machines across the internet, or just across | |
443 | a LAN that either doesn't permit open ports or you don't trust the other |
|
443 | a LAN that either doesn't permit open ports or you don't trust the other | |
444 | machines on the network. To do this, you can use SSH tunnels. SSH tunnels |
|
444 | machines on the network. To do this, you can use SSH tunnels. SSH tunnels | |
445 | are a way to securely forward ports on your local machine to ports on another |
|
445 | are a way to securely forward ports on your local machine to ports on another | |
446 | machine, to which you have SSH access. |
|
446 | machine, to which you have SSH access. | |
447 |
|
447 | |||
448 | In simple cases, IPython's tools can forward ports over ssh by simply adding the |
|
448 | In simple cases, IPython's tools can forward ports over ssh by simply adding the | |
449 | ``--ssh=remote`` argument to the usual ``--existing...`` set of flags for connecting |
|
449 | ``--ssh=remote`` argument to the usual ``--existing...`` set of flags for connecting | |
450 | to a running kernel, after copying the JSON connection file (or its contents) to |
|
450 | to a running kernel, after copying the JSON connection file (or its contents) to | |
451 | the second computer. |
|
451 | the second computer. | |
452 |
|
452 | |||
453 | .. warning:: |
|
453 | .. warning:: | |
454 |
|
454 | |||
455 | Using SSH tunnels does *not* increase localhost security. In fact, when |
|
455 | Using SSH tunnels does *not* increase localhost security. In fact, when | |
456 | tunneling from one machine to another *both* machines have open |
|
456 | tunneling from one machine to another *both* machines have open | |
457 | ports on localhost available for connections to the kernel. |
|
457 | ports on localhost available for connections to the kernel. | |
458 |
|
458 | |||
459 | There are two primary models for using SSH tunnels with IPython. The first |
|
459 | There are two primary models for using SSH tunnels with IPython. The first | |
460 | is to have the Kernel listen only on localhost, and connect to it from |
|
460 | is to have the Kernel listen only on localhost, and connect to it from | |
461 | another machine on the same LAN. |
|
461 | another machine on the same LAN. | |
462 |
|
462 | |||
463 | First, let's start a kernel on machine **worker**, listening only |
|
463 | First, let's start a kernel on machine **worker**, listening only | |
464 | on loopback:: |
|
464 | on loopback:: | |
465 |
|
465 | |||
466 | user@worker $> ipython kernel |
|
466 | user@worker $> ipython kernel | |
467 | [IPKernelApp] To connect another client to this kernel, use: |
|
467 | [IPKernelApp] To connect another client to this kernel, use: | |
468 | [IPKernelApp] --existing kernel-12345.json |
|
468 | [IPKernelApp] --existing kernel-12345.json | |
469 |
|
469 | |||
470 | In this case, the IP that you would connect |
|
470 | In this case, the IP that you would connect | |
471 | to would still be 127.0.0.1, but you want to specify the additional ``--ssh`` argument |
|
471 | to would still be 127.0.0.1, but you want to specify the additional ``--ssh`` argument | |
472 | with the hostname of the kernel (in this example, it's 'worker'):: |
|
472 | with the hostname of the kernel (in this example, it's 'worker'):: | |
473 |
|
473 | |||
474 | user@client $> ipython qtconsole --ssh=worker --existing /path/to/kernel-12345.json |
|
474 | user@client $> ipython qtconsole --ssh=worker --existing /path/to/kernel-12345.json | |
475 |
|
475 | |||
476 | Which will write a new connection file with the forwarded ports, so you can reuse them:: |
|
476 | Which will write a new connection file with the forwarded ports, so you can reuse them:: | |
477 |
|
477 | |||
478 | [IPythonQtConsoleApp] To connect another client via this tunnel, use: |
|
478 | [IPythonQtConsoleApp] To connect another client via this tunnel, use: | |
479 | [IPythonQtConsoleApp] --existing kernel-12345-ssh.json |
|
479 | [IPythonQtConsoleApp] --existing kernel-12345-ssh.json | |
480 |
|
480 | |||
481 | Note again that this opens ports on the *client* machine that point to your kernel. |
|
481 | Note again that this opens ports on the *client* machine that point to your kernel. | |
482 |
|
482 | |||
483 | .. note:: |
|
483 | .. note:: | |
484 |
|
484 | |||
485 | the ssh argument is simply passed to openssh, so it can be fully specified ``user@host:port`` |
|
485 | the ssh argument is simply passed to openssh, so it can be fully specified ``user@host:port`` | |
486 | but it will also respect your aliases, etc. in :file:`.ssh/config` if you have any. |
|
486 | but it will also respect your aliases, etc. in :file:`.ssh/config` if you have any. | |
487 |
|
487 | |||
488 | The second pattern is for connecting to a machine behind a firewall across the internet |
|
488 | The second pattern is for connecting to a machine behind a firewall across the internet | |
489 | (or otherwise wide network). This time, we have a machine **login** that you have ssh access |
|
489 | (or otherwise wide network). This time, we have a machine **login** that you have ssh access | |
490 | to, which can see **kernel**, but **client** is on another network. The important difference |
|
490 | to, which can see **kernel**, but **client** is on another network. The important difference | |
491 | now is that **client** can see **login**, but *not* **worker**. So we need to forward ports from |
|
491 | now is that **client** can see **login**, but *not* **worker**. So we need to forward ports from | |
492 | client to worker *via* login. This means that the kernel must be started listening |
|
492 | client to worker *via* login. This means that the kernel must be started listening | |
493 | on external interfaces, so that its ports are visible to `login`:: |
|
493 | on external interfaces, so that its ports are visible to `login`:: | |
494 |
|
494 | |||
495 | user@worker $> ipython kernel --ip=0.0.0.0 |
|
495 | user@worker $> ipython kernel --ip=0.0.0.0 | |
496 | [IPKernelApp] To connect another client to this kernel, use: |
|
496 | [IPKernelApp] To connect another client to this kernel, use: | |
497 | [IPKernelApp] --existing kernel-12345.json |
|
497 | [IPKernelApp] --existing kernel-12345.json | |
498 |
|
498 | |||
499 | Which we can connect to from the client with:: |
|
499 | Which we can connect to from the client with:: | |
500 |
|
500 | |||
501 | user@client $> ipython qtconsole --ssh=login --ip=192.168.1.123 --existing /path/to/kernel-12345.json |
|
501 | user@client $> ipython qtconsole --ssh=login --ip=192.168.1.123 --existing /path/to/kernel-12345.json | |
502 |
|
502 | |||
503 | .. note:: |
|
503 | .. note:: | |
504 |
|
504 | |||
505 | The IP here is the address of worker as seen from *login*, and need only be specified if |
|
505 | The IP here is the address of worker as seen from *login*, and need only be specified if | |
506 | the kernel used the ambiguous 0.0.0.0 (all interfaces) address. If it had used |
|
506 | the kernel used the ambiguous 0.0.0.0 (all interfaces) address. If it had used | |
507 | 192.168.1.123 to start with, it would not be needed. |
|
507 | 192.168.1.123 to start with, it would not be needed. | |
508 |
|
508 | |||
509 |
|
509 | |||
510 | Manual SSH tunnels |
|
510 | Manual SSH tunnels | |
511 | ------------------ |
|
511 | ------------------ | |
512 |
|
512 | |||
513 | It's possible that IPython's ssh helper functions won't work for you, for various |
|
513 | It's possible that IPython's ssh helper functions won't work for you, for various | |
514 | reasons. You can still connect to remote machines, as long as you set up the tunnels |
|
514 | reasons. You can still connect to remote machines, as long as you set up the tunnels | |
515 | yourself. The basic format of forwarding a local port to a remote one is:: |
|
515 | yourself. The basic format of forwarding a local port to a remote one is:: | |
516 |
|
516 | |||
517 | [client] $> ssh <server> <localport>:<remoteip>:<remoteport> -f -N |
|
517 | [client] $> ssh <server> <localport>:<remoteip>:<remoteport> -f -N | |
518 |
|
518 | |||
519 | This will forward local connections to **localport** on client to **remoteip:remoteport** |
|
519 | This will forward local connections to **localport** on client to **remoteip:remoteport** | |
520 | *via* **server**. Note that remoteip is interpreted relative to *server*, not the client. |
|
520 | *via* **server**. Note that remoteip is interpreted relative to *server*, not the client. | |
521 | So if you have direct ssh access to the machine to which you want to forward connections, |
|
521 | So if you have direct ssh access to the machine to which you want to forward connections, | |
522 | then the server *is* the remote machine, and remoteip should be server's IP as seen from the |
|
522 | then the server *is* the remote machine, and remoteip should be server's IP as seen from the | |
523 | server itself, i.e. 127.0.0.1. Thus, to forward local port 12345 to remote port 54321 on |
|
523 | server itself, i.e. 127.0.0.1. Thus, to forward local port 12345 to remote port 54321 on | |
524 | a machine you can see, do:: |
|
524 | a machine you can see, do:: | |
525 |
|
525 | |||
526 | [client] $> ssh machine 12345:127.0.0.1:54321 -f -N |
|
526 | [client] $> ssh machine 12345:127.0.0.1:54321 -f -N | |
527 |
|
527 | |||
528 | But if your target is actually on a LAN at 192.168.1.123, behind another machine called **login**, |
|
528 | But if your target is actually on a LAN at 192.168.1.123, behind another machine called **login**, | |
529 | then you would do:: |
|
529 | then you would do:: | |
530 |
|
530 | |||
531 | [client] $> ssh login 12345:192.168.1.16:54321 -f -N |
|
531 | [client] $> ssh login 12345:192.168.1.16:54321 -f -N | |
532 |
|
532 | |||
533 | The ``-f -N`` on the end are flags that tell ssh to run in the background, |
|
533 | The ``-f -N`` on the end are flags that tell ssh to run in the background, | |
534 | and don't actually run any commands beyond creating the tunnel. |
|
534 | and don't actually run any commands beyond creating the tunnel. | |
535 |
|
535 | |||
536 | .. seealso:: |
|
536 | .. seealso:: | |
537 |
|
537 | |||
538 | A short discussion of ssh tunnels: http://www.revsys.com/writings/quicktips/ssh-tunnel.html |
|
538 | A short discussion of ssh tunnels: http://www.revsys.com/writings/quicktips/ssh-tunnel.html | |
539 |
|
539 | |||
540 |
|
540 | |||
541 |
|
541 | |||
542 | Stopping Kernels and Consoles |
|
542 | Stopping Kernels and Consoles | |
543 | ***************************** |
|
543 | ***************************** | |
544 |
|
544 | |||
545 | Since there can be many consoles per kernel, the shutdown mechanism and dialog |
|
545 | Since there can be many consoles per kernel, the shutdown mechanism and dialog | |
546 | are probably more complicated than you are used to. Since you don't always want |
|
546 | are probably more complicated than you are used to. Since you don't always want | |
547 | to shutdown a kernel when you close a window, you are given the option to just |
|
547 | to shutdown a kernel when you close a window, you are given the option to just | |
548 | close the console window or also close the Kernel and *all other windows*. Note |
|
548 | close the console window or also close the Kernel and *all other windows*. Note | |
549 | that this only refers to all other *local* windows, as remote Consoles are not |
|
549 | that this only refers to all other *local* windows, as remote Consoles are not | |
550 | allowed to shutdown the kernel, and shutdowns do not close Remote consoles (to |
|
550 | allowed to shutdown the kernel, and shutdowns do not close Remote consoles (to | |
551 | allow for saving, etc.). |
|
551 | allow for saving, etc.). | |
552 |
|
552 | |||
553 | Rules: |
|
553 | Rules: | |
554 |
|
554 | |||
555 | * Restarting the kernel automatically clears all *local* Consoles, and prompts remote |
|
555 | * Restarting the kernel automatically clears all *local* Consoles, and prompts remote | |
556 | Consoles about the reset. |
|
556 | Consoles about the reset. | |
557 | * Shutdown closes all *local* Consoles, and notifies remotes that |
|
557 | * Shutdown closes all *local* Consoles, and notifies remotes that | |
558 | the Kernel has been shutdown. |
|
558 | the Kernel has been shutdown. | |
559 | * Remote Consoles may not restart or shutdown the kernel. |
|
559 | * Remote Consoles may not restart or shutdown the kernel. | |
560 |
|
560 | |||
561 | Qt and the QtConsole |
|
561 | Qt and the QtConsole | |
562 | ==================== |
|
562 | ==================== | |
563 |
|
563 | |||
564 | An important part of working with the QtConsole when you are writing your own |
|
564 | An important part of working with the QtConsole when you are writing your own | |
565 | Qt code is to remember that user code (in the kernel) is *not* in the same |
|
565 | Qt code is to remember that user code (in the kernel) is *not* in the same | |
566 | process as the frontend. This means that there is not necessarily any Qt code |
|
566 | process as the frontend. This means that there is not necessarily any Qt code | |
567 | running in the kernel, and under most normal circumstances there isn't. If, |
|
567 | running in the kernel, and under most normal circumstances there isn't. If, | |
568 | however, you specify ``--matplotlib qt`` at the command-line, then there *will* be a |
|
568 | however, you specify ``--matplotlib qt`` at the command-line, then there *will* be a | |
569 | :class:`QCoreApplication` instance running in the kernel process along with |
|
569 | :class:`QCoreApplication` instance running in the kernel process along with | |
570 | user-code. To get a reference to this application, do: |
|
570 | user-code. To get a reference to this application, do: | |
571 |
|
571 | |||
572 | .. sourcecode:: python |
|
572 | .. sourcecode:: python | |
573 |
|
573 | |||
574 | from PyQt4 import QtCore |
|
574 | from PyQt4 import QtCore | |
575 | app = QtCore.QCoreApplication.instance() |
|
575 | app = QtCore.QCoreApplication.instance() | |
576 | # app will be None if there is no such instance |
|
576 | # app will be None if there is no such instance | |
577 |
|
577 | |||
578 | A common problem listed in the PyQt4 Gotchas_ is the fact that Python's garbage |
|
578 | A common problem listed in the PyQt4 Gotchas_ is the fact that Python's garbage | |
579 | collection will destroy Qt objects (Windows, etc.) once there is no longer a |
|
579 | collection will destroy Qt objects (Windows, etc.) once there is no longer a | |
580 | Python reference to them, so you have to hold on to them. For instance, in: |
|
580 | Python reference to them, so you have to hold on to them. For instance, in: | |
581 |
|
581 | |||
582 | .. sourcecode:: python |
|
582 | .. sourcecode:: python | |
583 |
|
583 | |||
584 | def make_window(): |
|
584 | def make_window(): | |
585 | win = QtGui.QMainWindow() |
|
585 | win = QtGui.QMainWindow() | |
586 |
|
586 | |||
587 | def make_and_return_window(): |
|
587 | def make_and_return_window(): | |
588 | win = QtGui.QMainWindow() |
|
588 | win = QtGui.QMainWindow() | |
589 | return win |
|
589 | return win | |
590 |
|
590 | |||
591 | :func:`make_window` will never draw a window, because garbage collection will |
|
591 | :func:`make_window` will never draw a window, because garbage collection will | |
592 | destroy it before it is drawn, whereas :func:`make_and_return_window` lets the |
|
592 | destroy it before it is drawn, whereas :func:`make_and_return_window` lets the | |
593 | caller decide when the window object should be destroyed. If, as a developer, |
|
593 | caller decide when the window object should be destroyed. If, as a developer, | |
594 | you know that you always want your objects to last as long as the process, you |
|
594 | you know that you always want your objects to last as long as the process, you | |
595 | can attach them to the QApplication instance itself: |
|
595 | can attach them to the QApplication instance itself: | |
596 |
|
596 | |||
597 | .. sourcecode:: python |
|
597 | .. sourcecode:: python | |
598 |
|
598 | |||
599 | # do this just once: |
|
599 | # do this just once: | |
600 | app = QtCore.QCoreApplication.instance() |
|
600 | app = QtCore.QCoreApplication.instance() | |
601 | app.references = set() |
|
601 | app.references = set() | |
602 | # then when you create Windows, add them to the set |
|
602 | # then when you create Windows, add them to the set | |
603 | def make_window(): |
|
603 | def make_window(): | |
604 | win = QtGui.QMainWindow() |
|
604 | win = QtGui.QMainWindow() | |
605 | app.references.add(win) |
|
605 | app.references.add(win) | |
606 |
|
606 | |||
607 | Now the QApplication itself holds a reference to ``win``, so it will never be |
|
607 | Now the QApplication itself holds a reference to ``win``, so it will never be | |
608 | garbage collected until the application itself is destroyed. |
|
608 | garbage collected until the application itself is destroyed. | |
609 |
|
609 | |||
610 | .. _Gotchas: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/gotchas.html#garbage-collection |
|
610 | .. _Gotchas: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/gotchas.html#garbage-collection | |
611 |
|
611 | |||
612 | Embedding the QtConsole in a Qt application |
|
612 | Embedding the QtConsole in a Qt application | |
613 | ******************************************* |
|
613 | ******************************************* | |
614 |
|
614 | |||
615 | In order to make the QtConsole available to an external Qt GUI application (just as |
|
615 | In order to make the QtConsole available to an external Qt GUI application (just as | |
616 | :func:`IPython.embed` enables one to embed a terminal session of IPython in a |
|
616 | :func:`IPython.embed` enables one to embed a terminal session of IPython in a | |
617 | command-line application), there are a few options: |
|
617 | command-line application), there are a few options: | |
618 |
|
618 | |||
619 | * First start IPython, and then start the external Qt application from IPython, |
|
619 | * First start IPython, and then start the external Qt application from IPython, | |
620 | as described above. Effectively, this embeds your application in IPython |
|
620 | as described above. Effectively, this embeds your application in IPython | |
621 | rather than the other way round. |
|
621 | rather than the other way round. | |
622 |
|
622 | |||
623 | * Use :class:`IPython.qt.console.rich_ipython_widget.RichIPythonWidget` in your |
|
623 | * Use :class:`IPython.qt.console.rich_ipython_widget.RichIPythonWidget` in your | |
624 | Qt application. This will embed the console widget in your GUI and start the |
|
624 | Qt application. This will embed the console widget in your GUI and start the | |
625 | kernel in a separate process, so code typed into the console cannot access |
|
625 | kernel in a separate process, so code typed into the console cannot access | |
626 | objects in your application. |
|
626 | objects in your application. | |
627 |
|
627 | |||
628 | * Start a standard IPython kernel in the process of the external Qt |
|
628 | * Start a standard IPython kernel in the process of the external Qt | |
629 |
application. |
|
629 | application. See :file:`examples/Embedding/ipkernel_qtapp.py` for an example. Due | |
630 | to IPython's two-process model, the QtConsole itself will live in another |
|
630 | to IPython's two-process model, the QtConsole itself will live in another | |
631 | process with its own QApplication, and thus cannot be embedded in the main |
|
631 | process with its own QApplication, and thus cannot be embedded in the main | |
632 | GUI. |
|
632 | GUI. | |
633 |
|
633 | |||
634 | * Start a special IPython kernel, the |
|
634 | * Start a special IPython kernel, the | |
635 | :class:`IPython.kernel.inprocess.ipkernel.InProcessKernel`, that allows a |
|
635 | :class:`IPython.kernel.inprocess.ipkernel.InProcessKernel`, that allows a | |
636 |
QtConsole in the same process. See :file:`examples/inprocess |
|
636 | QtConsole in the same process. See :file:`examples/Embedding/inprocess_qtconsole.py` | |
637 | for an example. While the QtConsole can now be embedded in the main GUI, one |
|
637 | for an example. While the QtConsole can now be embedded in the main GUI, one | |
638 | cannot connect to the kernel from other consoles as there are no real ZMQ |
|
638 | cannot connect to the kernel from other consoles as there are no real ZMQ | |
639 | sockets anymore. |
|
639 | sockets anymore. | |
640 |
|
640 | |||
641 | Regressions |
|
641 | Regressions | |
642 | =========== |
|
642 | =========== | |
643 |
|
643 | |||
644 | There are some features, where the qt console lags behind the Terminal |
|
644 | There are some features, where the qt console lags behind the Terminal | |
645 | frontend: |
|
645 | frontend: | |
646 |
|
646 | |||
647 | * !cmd input: Due to our use of pexpect, we cannot pass input to subprocesses |
|
647 | * !cmd input: Due to our use of pexpect, we cannot pass input to subprocesses | |
648 | launched using the '!' escape, so you should never call a command that |
|
648 | launched using the '!' escape, so you should never call a command that | |
649 | requires interactive input. For such cases, use the terminal IPython. This |
|
649 | requires interactive input. For such cases, use the terminal IPython. This | |
650 | will not be fixed, as abandoning pexpect would significantly degrade the |
|
650 | will not be fixed, as abandoning pexpect would significantly degrade the | |
651 | console experience. |
|
651 | console experience. | |
652 |
|
652 | |||
653 | .. _PyQt: http://www.riverbankcomputing.co.uk/software/pyqt/download |
|
653 | .. _PyQt: http://www.riverbankcomputing.co.uk/software/pyqt/download | |
654 | .. _pygments: http://pygments.org/ |
|
654 | .. _pygments: http://pygments.org/ |
@@ -1,978 +1,978 b'' | |||||
1 | ================= |
|
1 | ================= | |
2 | IPython reference |
|
2 | IPython reference | |
3 | ================= |
|
3 | ================= | |
4 |
|
4 | |||
5 | .. _command_line_options: |
|
5 | .. _command_line_options: | |
6 |
|
6 | |||
7 | Command-line usage |
|
7 | Command-line usage | |
8 | ================== |
|
8 | ================== | |
9 |
|
9 | |||
10 | You start IPython with the command:: |
|
10 | You start IPython with the command:: | |
11 |
|
11 | |||
12 | $ ipython [options] files |
|
12 | $ ipython [options] files | |
13 |
|
13 | |||
14 | If invoked with no options, it executes all the files listed in sequence |
|
14 | If invoked with no options, it executes all the files listed in sequence | |
15 | and drops you into the interpreter while still acknowledging any options |
|
15 | and drops you into the interpreter while still acknowledging any options | |
16 | you may have set in your ipython_config.py. This behavior is different from |
|
16 | you may have set in your ipython_config.py. This behavior is different from | |
17 | standard Python, which when called as python -i will only execute one |
|
17 | standard Python, which when called as python -i will only execute one | |
18 | file and ignore your configuration setup. |
|
18 | file and ignore your configuration setup. | |
19 |
|
19 | |||
20 | Please note that some of the configuration options are not available at |
|
20 | Please note that some of the configuration options are not available at | |
21 | the command line, simply because they are not practical here. Look into |
|
21 | the command line, simply because they are not practical here. Look into | |
22 | your configuration files for details on those. There are separate configuration |
|
22 | your configuration files for details on those. There are separate configuration | |
23 | files for each profile, and the files look like :file:`ipython_config.py` or |
|
23 | files for each profile, and the files look like :file:`ipython_config.py` or | |
24 | :file:`ipython_config_{frontendname}.py`. Profile directories look like |
|
24 | :file:`ipython_config_{frontendname}.py`. Profile directories look like | |
25 | :file:`profile_{profilename}` and are typically installed in the :envvar:`IPYTHONDIR` directory, |
|
25 | :file:`profile_{profilename}` and are typically installed in the :envvar:`IPYTHONDIR` directory, | |
26 | which defaults to :file:`$HOME/.ipython`. For Windows users, :envvar:`HOME` |
|
26 | which defaults to :file:`$HOME/.ipython`. For Windows users, :envvar:`HOME` | |
27 | resolves to :file:`C:\\Users\\{YourUserName}` in most instances. |
|
27 | resolves to :file:`C:\\Users\\{YourUserName}` in most instances. | |
28 |
|
28 | |||
29 | Command-line Options |
|
29 | Command-line Options | |
30 | -------------------- |
|
30 | -------------------- | |
31 |
|
31 | |||
32 | To see the options IPython accepts, use ``ipython --help`` (and you probably |
|
32 | To see the options IPython accepts, use ``ipython --help`` (and you probably | |
33 | should run the output through a pager such as ``ipython --help | less`` for |
|
33 | should run the output through a pager such as ``ipython --help | less`` for | |
34 | more convenient reading). This shows all the options that have a single-word |
|
34 | more convenient reading). This shows all the options that have a single-word | |
35 | alias to control them, but IPython lets you configure all of its objects from |
|
35 | alias to control them, but IPython lets you configure all of its objects from | |
36 | the command-line by passing the full class name and a corresponding value; type |
|
36 | the command-line by passing the full class name and a corresponding value; type | |
37 | ``ipython --help-all`` to see this full list. For example:: |
|
37 | ``ipython --help-all`` to see this full list. For example:: | |
38 |
|
38 | |||
39 | ipython --matplotlib qt |
|
39 | ipython --matplotlib qt | |
40 |
|
40 | |||
41 | is equivalent to:: |
|
41 | is equivalent to:: | |
42 |
|
42 | |||
43 | ipython --TerminalIPythonApp.matplotlib='qt' |
|
43 | ipython --TerminalIPythonApp.matplotlib='qt' | |
44 |
|
44 | |||
45 | Note that in the second form, you *must* use the equal sign, as the expression |
|
45 | Note that in the second form, you *must* use the equal sign, as the expression | |
46 | is evaluated as an actual Python assignment. While in the above example the |
|
46 | is evaluated as an actual Python assignment. While in the above example the | |
47 | short form is more convenient, only the most common options have a short form, |
|
47 | short form is more convenient, only the most common options have a short form, | |
48 | while any configurable variable in IPython can be set at the command-line by |
|
48 | while any configurable variable in IPython can be set at the command-line by | |
49 | using the long form. This long form is the same syntax used in the |
|
49 | using the long form. This long form is the same syntax used in the | |
50 | configuration files, if you want to set these options permanently. |
|
50 | configuration files, if you want to set these options permanently. | |
51 |
|
51 | |||
52 |
|
52 | |||
53 | Interactive use |
|
53 | Interactive use | |
54 | =============== |
|
54 | =============== | |
55 |
|
55 | |||
56 | IPython is meant to work as a drop-in replacement for the standard interactive |
|
56 | IPython is meant to work as a drop-in replacement for the standard interactive | |
57 | interpreter. As such, any code which is valid python should execute normally |
|
57 | interpreter. As such, any code which is valid python should execute normally | |
58 | under IPython (cases where this is not true should be reported as bugs). It |
|
58 | under IPython (cases where this is not true should be reported as bugs). It | |
59 | does, however, offer many features which are not available at a standard python |
|
59 | does, however, offer many features which are not available at a standard python | |
60 | prompt. What follows is a list of these. |
|
60 | prompt. What follows is a list of these. | |
61 |
|
61 | |||
62 |
|
62 | |||
63 | Caution for Windows users |
|
63 | Caution for Windows users | |
64 | ------------------------- |
|
64 | ------------------------- | |
65 |
|
65 | |||
66 | Windows, unfortunately, uses the '\\' character as a path separator. This is a |
|
66 | Windows, unfortunately, uses the '\\' character as a path separator. This is a | |
67 | terrible choice, because '\\' also represents the escape character in most |
|
67 | terrible choice, because '\\' also represents the escape character in most | |
68 | modern programming languages, including Python. For this reason, using '/' |
|
68 | modern programming languages, including Python. For this reason, using '/' | |
69 | character is recommended if you have problems with ``\``. However, in Windows |
|
69 | character is recommended if you have problems with ``\``. However, in Windows | |
70 | commands '/' flags options, so you can not use it for the root directory. This |
|
70 | commands '/' flags options, so you can not use it for the root directory. This | |
71 | means that paths beginning at the root must be typed in a contrived manner |
|
71 | means that paths beginning at the root must be typed in a contrived manner | |
72 | like: ``%copy \opt/foo/bar.txt \tmp`` |
|
72 | like: ``%copy \opt/foo/bar.txt \tmp`` | |
73 |
|
73 | |||
74 | .. _magic: |
|
74 | .. _magic: | |
75 |
|
75 | |||
76 | Magic command system |
|
76 | Magic command system | |
77 | -------------------- |
|
77 | -------------------- | |
78 |
|
78 | |||
79 | IPython will treat any line whose first character is a % as a special |
|
79 | IPython will treat any line whose first character is a % as a special | |
80 | call to a 'magic' function. These allow you to control the behavior of |
|
80 | call to a 'magic' function. These allow you to control the behavior of | |
81 | IPython itself, plus a lot of system-type features. They are all |
|
81 | IPython itself, plus a lot of system-type features. They are all | |
82 | prefixed with a % character, but parameters are given without |
|
82 | prefixed with a % character, but parameters are given without | |
83 | parentheses or quotes. |
|
83 | parentheses or quotes. | |
84 |
|
84 | |||
85 | Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not |
|
85 | Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not | |
86 | only the rest of the current line, but all lines below them as well, in the |
|
86 | only the rest of the current line, but all lines below them as well, in the | |
87 | current execution block. Cell magics can in fact make arbitrary modifications |
|
87 | current execution block. Cell magics can in fact make arbitrary modifications | |
88 | to the input they receive, which need not even be valid Python code at all. |
|
88 | to the input they receive, which need not even be valid Python code at all. | |
89 | They receive the whole block as a single string. |
|
89 | They receive the whole block as a single string. | |
90 |
|
90 | |||
91 | As a line magic example, the :magic:`cd` magic works just like the OS command of |
|
91 | As a line magic example, the :magic:`cd` magic works just like the OS command of | |
92 | the same name:: |
|
92 | the same name:: | |
93 |
|
93 | |||
94 | In [8]: %cd |
|
94 | In [8]: %cd | |
95 | /home/fperez |
|
95 | /home/fperez | |
96 |
|
96 | |||
97 | The following uses the builtin :magic:`timeit` in cell mode:: |
|
97 | The following uses the builtin :magic:`timeit` in cell mode:: | |
98 |
|
98 | |||
99 | In [10]: %%timeit x = range(10000) |
|
99 | In [10]: %%timeit x = range(10000) | |
100 | ...: min(x) |
|
100 | ...: min(x) | |
101 | ...: max(x) |
|
101 | ...: max(x) | |
102 | ...: |
|
102 | ...: | |
103 | 1000 loops, best of 3: 438 us per loop |
|
103 | 1000 loops, best of 3: 438 us per loop | |
104 |
|
104 | |||
105 | In this case, ``x = range(10000)`` is called as the line argument, and the |
|
105 | In this case, ``x = range(10000)`` is called as the line argument, and the | |
106 | block with ``min(x)`` and ``max(x)`` is called as the cell body. The |
|
106 | block with ``min(x)`` and ``max(x)`` is called as the cell body. The | |
107 | :magic:`timeit` magic receives both. |
|
107 | :magic:`timeit` magic receives both. | |
108 |
|
108 | |||
109 | If you have 'automagic' enabled (as it by default), you don't need to type in |
|
109 | If you have 'automagic' enabled (as it by default), you don't need to type in | |
110 | the single ``%`` explicitly for line magics; IPython will scan its internal |
|
110 | the single ``%`` explicitly for line magics; IPython will scan its internal | |
111 | list of magic functions and call one if it exists. With automagic on you can |
|
111 | list of magic functions and call one if it exists. With automagic on you can | |
112 | then just type ``cd mydir`` to go to directory 'mydir':: |
|
112 | then just type ``cd mydir`` to go to directory 'mydir':: | |
113 |
|
113 | |||
114 | In [9]: cd mydir |
|
114 | In [9]: cd mydir | |
115 | /home/fperez/mydir |
|
115 | /home/fperez/mydir | |
116 |
|
116 | |||
117 | Cell magics *always* require an explicit ``%%`` prefix, automagic |
|
117 | Cell magics *always* require an explicit ``%%`` prefix, automagic | |
118 | calling only works for line magics. |
|
118 | calling only works for line magics. | |
119 |
|
119 | |||
120 | The automagic system has the lowest possible precedence in name searches, so |
|
120 | The automagic system has the lowest possible precedence in name searches, so | |
121 | you can freely use variables with the same names as magic commands. If a magic |
|
121 | you can freely use variables with the same names as magic commands. If a magic | |
122 | command is 'shadowed' by a variable, you will need the explicit ``%`` prefix to |
|
122 | command is 'shadowed' by a variable, you will need the explicit ``%`` prefix to | |
123 | use it: |
|
123 | use it: | |
124 |
|
124 | |||
125 | .. sourcecode:: ipython |
|
125 | .. sourcecode:: ipython | |
126 |
|
126 | |||
127 | In [1]: cd ipython # %cd is called by automagic |
|
127 | In [1]: cd ipython # %cd is called by automagic | |
128 | /home/fperez/ipython |
|
128 | /home/fperez/ipython | |
129 |
|
129 | |||
130 | In [2]: cd=1 # now cd is just a variable |
|
130 | In [2]: cd=1 # now cd is just a variable | |
131 |
|
131 | |||
132 | In [3]: cd .. # and doesn't work as a function anymore |
|
132 | In [3]: cd .. # and doesn't work as a function anymore | |
133 | File "<ipython-input-3-9fedb3aff56c>", line 1 |
|
133 | File "<ipython-input-3-9fedb3aff56c>", line 1 | |
134 | cd .. |
|
134 | cd .. | |
135 | ^ |
|
135 | ^ | |
136 | SyntaxError: invalid syntax |
|
136 | SyntaxError: invalid syntax | |
137 |
|
137 | |||
138 |
|
138 | |||
139 | In [4]: %cd .. # but %cd always works |
|
139 | In [4]: %cd .. # but %cd always works | |
140 | /home/fperez |
|
140 | /home/fperez | |
141 |
|
141 | |||
142 | In [5]: del cd # if you remove the cd variable, automagic works again |
|
142 | In [5]: del cd # if you remove the cd variable, automagic works again | |
143 |
|
143 | |||
144 | In [6]: cd ipython |
|
144 | In [6]: cd ipython | |
145 |
|
145 | |||
146 | /home/fperez/ipython |
|
146 | /home/fperez/ipython | |
147 |
|
147 | |||
148 | Line magics, if they return a value, can be assigned to a variable using the syntax |
|
148 | Line magics, if they return a value, can be assigned to a variable using the syntax | |
149 | ``l = %sx ls`` (which in this particular case returns the result of `ls` as a python list). |
|
149 | ``l = %sx ls`` (which in this particular case returns the result of `ls` as a python list). | |
150 | See :ref:`below <manual_capture>` for more information. |
|
150 | See :ref:`below <manual_capture>` for more information. | |
151 |
|
151 | |||
152 | Type ``%magic`` for more information, including a list of all available magic |
|
152 | Type ``%magic`` for more information, including a list of all available magic | |
153 | functions at any time and their docstrings. You can also type |
|
153 | functions at any time and their docstrings. You can also type | |
154 | ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for |
|
154 | ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for | |
155 | information on the '?' system) to get information about any particular magic |
|
155 | information on the '?' system) to get information about any particular magic | |
156 | function you are interested in. |
|
156 | function you are interested in. | |
157 |
|
157 | |||
158 | The API documentation for the :mod:`IPython.core.magic` module contains the full |
|
158 | The API documentation for the :mod:`IPython.core.magic` module contains the full | |
159 | docstrings of all currently available magic commands. |
|
159 | docstrings of all currently available magic commands. | |
160 |
|
160 | |||
161 | .. seealso:: |
|
161 | .. seealso:: | |
162 |
|
162 | |||
163 | :doc:`magics` |
|
163 | :doc:`magics` | |
164 | A list of the line and cell magics available in IPython by default |
|
164 | A list of the line and cell magics available in IPython by default | |
165 |
|
165 | |||
166 | :ref:`defining_magics` |
|
166 | :ref:`defining_magics` | |
167 | How to define and register additional magic functions |
|
167 | How to define and register additional magic functions | |
168 |
|
168 | |||
169 |
|
169 | |||
170 | Access to the standard Python help |
|
170 | Access to the standard Python help | |
171 | ---------------------------------- |
|
171 | ---------------------------------- | |
172 |
|
172 | |||
173 | Simply type ``help()`` to access Python's standard help system. You can |
|
173 | Simply type ``help()`` to access Python's standard help system. You can | |
174 | also type ``help(object)`` for information about a given object, or |
|
174 | also type ``help(object)`` for information about a given object, or | |
175 | ``help('keyword')`` for information on a keyword. You may need to configure your |
|
175 | ``help('keyword')`` for information on a keyword. You may need to configure your | |
176 | PYTHONDOCS environment variable for this feature to work correctly. |
|
176 | PYTHONDOCS environment variable for this feature to work correctly. | |
177 |
|
177 | |||
178 | .. _dynamic_object_info: |
|
178 | .. _dynamic_object_info: | |
179 |
|
179 | |||
180 | Dynamic object information |
|
180 | Dynamic object information | |
181 | -------------------------- |
|
181 | -------------------------- | |
182 |
|
182 | |||
183 | Typing ``?word`` or ``word?`` prints detailed information about an object. If |
|
183 | Typing ``?word`` or ``word?`` prints detailed information about an object. If | |
184 | certain strings in the object are too long (e.g. function signatures) they get |
|
184 | certain strings in the object are too long (e.g. function signatures) they get | |
185 | snipped in the center for brevity. This system gives access variable types and |
|
185 | snipped in the center for brevity. This system gives access variable types and | |
186 | values, docstrings, function prototypes and other useful information. |
|
186 | values, docstrings, function prototypes and other useful information. | |
187 |
|
187 | |||
188 | If the information will not fit in the terminal, it is displayed in a pager |
|
188 | If the information will not fit in the terminal, it is displayed in a pager | |
189 | (``less`` if available, otherwise a basic internal pager). |
|
189 | (``less`` if available, otherwise a basic internal pager). | |
190 |
|
190 | |||
191 | Typing ``??word`` or ``word??`` gives access to the full information, including |
|
191 | Typing ``??word`` or ``word??`` gives access to the full information, including | |
192 | the source code where possible. Long strings are not snipped. |
|
192 | the source code where possible. Long strings are not snipped. | |
193 |
|
193 | |||
194 | The following magic functions are particularly useful for gathering |
|
194 | The following magic functions are particularly useful for gathering | |
195 | information about your working environment: |
|
195 | information about your working environment: | |
196 |
|
196 | |||
197 | * :magic:`pdoc` **<object>**: Print (or run through a pager if too long) the |
|
197 | * :magic:`pdoc` **<object>**: Print (or run through a pager if too long) the | |
198 | docstring for an object. If the given object is a class, it will |
|
198 | docstring for an object. If the given object is a class, it will | |
199 | print both the class and the constructor docstrings. |
|
199 | print both the class and the constructor docstrings. | |
200 | * :magic:`pdef` **<object>**: Print the call signature for any callable |
|
200 | * :magic:`pdef` **<object>**: Print the call signature for any callable | |
201 | object. If the object is a class, print the constructor information. |
|
201 | object. If the object is a class, print the constructor information. | |
202 | * :magic:`psource` **<object>**: Print (or run through a pager if too long) |
|
202 | * :magic:`psource` **<object>**: Print (or run through a pager if too long) | |
203 | the source code for an object. |
|
203 | the source code for an object. | |
204 | * :magic:`pfile` **<object>**: Show the entire source file where an object was |
|
204 | * :magic:`pfile` **<object>**: Show the entire source file where an object was | |
205 | defined via a pager, opening it at the line where the object |
|
205 | defined via a pager, opening it at the line where the object | |
206 | definition begins. |
|
206 | definition begins. | |
207 | * :magic:`who`/:magic:`whos`: These functions give information about identifiers |
|
207 | * :magic:`who`/:magic:`whos`: These functions give information about identifiers | |
208 | you have defined interactively (not things you loaded or defined |
|
208 | you have defined interactively (not things you loaded or defined | |
209 | in your configuration files). %who just prints a list of |
|
209 | in your configuration files). %who just prints a list of | |
210 | identifiers and %whos prints a table with some basic details about |
|
210 | identifiers and %whos prints a table with some basic details about | |
211 | each identifier. |
|
211 | each identifier. | |
212 |
|
212 | |||
213 | The dynamic object information functions (?/??, ``%pdoc``, |
|
213 | The dynamic object information functions (?/??, ``%pdoc``, | |
214 | ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as |
|
214 | ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as | |
215 | directly on variables. For example, after doing ``import os``, you can use |
|
215 | directly on variables. For example, after doing ``import os``, you can use | |
216 | ``os.path.abspath??``. |
|
216 | ``os.path.abspath??``. | |
217 |
|
217 | |||
218 | .. _readline: |
|
218 | .. _readline: | |
219 |
|
219 | |||
220 | Readline-based features |
|
220 | Readline-based features | |
221 | ----------------------- |
|
221 | ----------------------- | |
222 |
|
222 | |||
223 | These features require the GNU readline library, so they won't work if your |
|
223 | These features require the GNU readline library, so they won't work if your | |
224 | Python installation lacks readline support. We will first describe the default |
|
224 | Python installation lacks readline support. We will first describe the default | |
225 | behavior IPython uses, and then how to change it to suit your preferences. |
|
225 | behavior IPython uses, and then how to change it to suit your preferences. | |
226 |
|
226 | |||
227 |
|
227 | |||
228 | Command line completion |
|
228 | Command line completion | |
229 | +++++++++++++++++++++++ |
|
229 | +++++++++++++++++++++++ | |
230 |
|
230 | |||
231 | At any time, hitting TAB will complete any available python commands or |
|
231 | At any time, hitting TAB will complete any available python commands or | |
232 | variable names, and show you a list of the possible completions if |
|
232 | variable names, and show you a list of the possible completions if | |
233 | there's no unambiguous one. It will also complete filenames in the |
|
233 | there's no unambiguous one. It will also complete filenames in the | |
234 | current directory if no python names match what you've typed so far. |
|
234 | current directory if no python names match what you've typed so far. | |
235 |
|
235 | |||
236 |
|
236 | |||
237 | Search command history |
|
237 | Search command history | |
238 | ++++++++++++++++++++++ |
|
238 | ++++++++++++++++++++++ | |
239 |
|
239 | |||
240 | IPython provides two ways for searching through previous input and thus |
|
240 | IPython provides two ways for searching through previous input and thus | |
241 | reduce the need for repetitive typing: |
|
241 | reduce the need for repetitive typing: | |
242 |
|
242 | |||
243 | 1. Start typing, and then use the up and down arrow keys (or :kbd:`Ctrl-p` |
|
243 | 1. Start typing, and then use the up and down arrow keys (or :kbd:`Ctrl-p` | |
244 | and :kbd:`Ctrl-n`) to search through only the history items that match |
|
244 | and :kbd:`Ctrl-n`) to search through only the history items that match | |
245 | what you've typed so far. |
|
245 | what you've typed so far. | |
246 | 2. Hit :kbd:`Ctrl-r`: to open a search prompt. Begin typing and the system |
|
246 | 2. Hit :kbd:`Ctrl-r`: to open a search prompt. Begin typing and the system | |
247 | searches your history for lines that contain what you've typed so |
|
247 | searches your history for lines that contain what you've typed so | |
248 | far, completing as much as it can. |
|
248 | far, completing as much as it can. | |
249 |
|
249 | |||
250 | IPython will save your input history when it leaves and reload it next |
|
250 | IPython will save your input history when it leaves and reload it next | |
251 | time you restart it. By default, the history file is named |
|
251 | time you restart it. By default, the history file is named | |
252 | :file:`.ipython/profile_{name}/history.sqlite`. |
|
252 | :file:`.ipython/profile_{name}/history.sqlite`. | |
253 |
|
253 | |||
254 | Autoindent |
|
254 | Autoindent | |
255 | ++++++++++ |
|
255 | ++++++++++ | |
256 |
|
256 | |||
257 | IPython can recognize lines ending in ':' and indent the next line, |
|
257 | IPython can recognize lines ending in ':' and indent the next line, | |
258 | while also un-indenting automatically after 'raise' or 'return'. |
|
258 | while also un-indenting automatically after 'raise' or 'return'. | |
259 |
|
259 | |||
260 | This feature uses the readline library, so it will honor your |
|
260 | This feature uses the readline library, so it will honor your | |
261 | :file:`~/.inputrc` configuration (or whatever file your :envvar:`INPUTRC` environment variable points |
|
261 | :file:`~/.inputrc` configuration (or whatever file your :envvar:`INPUTRC` environment variable points | |
262 | to). Adding the following lines to your :file:`.inputrc` file can make |
|
262 | to). Adding the following lines to your :file:`.inputrc` file can make | |
263 | indenting/unindenting more convenient (M-i indents, M-u unindents):: |
|
263 | indenting/unindenting more convenient (M-i indents, M-u unindents):: | |
264 |
|
264 | |||
265 | # if you don't already have a ~/.inputrc file, you need this include: |
|
265 | # if you don't already have a ~/.inputrc file, you need this include: | |
266 | $include /etc/inputrc |
|
266 | $include /etc/inputrc | |
267 |
|
267 | |||
268 | $if Python |
|
268 | $if Python | |
269 | "\M-i": " " |
|
269 | "\M-i": " " | |
270 | "\M-u": "\d\d\d\d" |
|
270 | "\M-u": "\d\d\d\d" | |
271 | $endif |
|
271 | $endif | |
272 |
|
272 | |||
273 | Note that there are 4 spaces between the quote marks after "M-i" above. |
|
273 | Note that there are 4 spaces between the quote marks after "M-i" above. | |
274 |
|
274 | |||
275 | .. warning:: |
|
275 | .. warning:: | |
276 |
|
276 | |||
277 | Setting the above indents will cause problems with unicode text entry in |
|
277 | Setting the above indents will cause problems with unicode text entry in | |
278 | the terminal. |
|
278 | the terminal. | |
279 |
|
279 | |||
280 | .. warning:: |
|
280 | .. warning:: | |
281 |
|
281 | |||
282 | Autoindent is ON by default, but it can cause problems with the pasting of |
|
282 | Autoindent is ON by default, but it can cause problems with the pasting of | |
283 | multi-line indented code (the pasted code gets re-indented on each line). A |
|
283 | multi-line indented code (the pasted code gets re-indented on each line). A | |
284 | magic function %autoindent allows you to toggle it on/off at runtime. You |
|
284 | magic function %autoindent allows you to toggle it on/off at runtime. You | |
285 | can also disable it permanently on in your :file:`ipython_config.py` file |
|
285 | can also disable it permanently on in your :file:`ipython_config.py` file | |
286 | (set TerminalInteractiveShell.autoindent=False). |
|
286 | (set TerminalInteractiveShell.autoindent=False). | |
287 |
|
287 | |||
288 | If you want to paste multiple lines in the terminal, it is recommended that |
|
288 | If you want to paste multiple lines in the terminal, it is recommended that | |
289 | you use ``%paste``. |
|
289 | you use ``%paste``. | |
290 |
|
290 | |||
291 |
|
291 | |||
292 | Customizing readline behavior |
|
292 | Customizing readline behavior | |
293 | +++++++++++++++++++++++++++++ |
|
293 | +++++++++++++++++++++++++++++ | |
294 |
|
294 | |||
295 | All these features are based on the GNU readline library, which has an |
|
295 | All these features are based on the GNU readline library, which has an | |
296 | extremely customizable interface. Normally, readline is configured via a |
|
296 | extremely customizable interface. Normally, readline is configured via a | |
297 | :file:`.inputrc` file. IPython respects this, and you can also customise readline |
|
297 | :file:`.inputrc` file. IPython respects this, and you can also customise readline | |
298 | by setting the following :doc:`configuration </config/intro>` options: |
|
298 | by setting the following :doc:`configuration </config/intro>` options: | |
299 |
|
299 | |||
300 | * ``InteractiveShell.readline_parse_and_bind``: this holds a list of strings to be executed |
|
300 | * ``InteractiveShell.readline_parse_and_bind``: this holds a list of strings to be executed | |
301 | via a readline.parse_and_bind() command. The syntax for valid commands |
|
301 | via a readline.parse_and_bind() command. The syntax for valid commands | |
302 | of this kind can be found by reading the documentation for the GNU |
|
302 | of this kind can be found by reading the documentation for the GNU | |
303 | readline library, as these commands are of the kind which readline |
|
303 | readline library, as these commands are of the kind which readline | |
304 | accepts in its configuration file. |
|
304 | accepts in its configuration file. | |
305 | * ``InteractiveShell.readline_remove_delims``: a string of characters to be removed |
|
305 | * ``InteractiveShell.readline_remove_delims``: a string of characters to be removed | |
306 | from the default word-delimiters list used by readline, so that |
|
306 | from the default word-delimiters list used by readline, so that | |
307 | completions may be performed on strings which contain them. Do not |
|
307 | completions may be performed on strings which contain them. Do not | |
308 | change the default value unless you know what you're doing. |
|
308 | change the default value unless you know what you're doing. | |
309 |
|
309 | |||
310 | You will find the default values in your configuration file. |
|
310 | You will find the default values in your configuration file. | |
311 |
|
311 | |||
312 |
|
312 | |||
313 | Session logging and restoring |
|
313 | Session logging and restoring | |
314 | ----------------------------- |
|
314 | ----------------------------- | |
315 |
|
315 | |||
316 | You can log all input from a session either by starting IPython with the |
|
316 | You can log all input from a session either by starting IPython with the | |
317 | command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`) |
|
317 | command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`) | |
318 | or by activating the logging at any moment with the magic function :magic:`logstart`. |
|
318 | or by activating the logging at any moment with the magic function :magic:`logstart`. | |
319 |
|
319 | |||
320 | Log files can later be reloaded by running them as scripts and IPython |
|
320 | Log files can later be reloaded by running them as scripts and IPython | |
321 | will attempt to 'replay' the log by executing all the lines in it, thus |
|
321 | will attempt to 'replay' the log by executing all the lines in it, thus | |
322 | restoring the state of a previous session. This feature is not quite |
|
322 | restoring the state of a previous session. This feature is not quite | |
323 | perfect, but can still be useful in many cases. |
|
323 | perfect, but can still be useful in many cases. | |
324 |
|
324 | |||
325 | The log files can also be used as a way to have a permanent record of |
|
325 | The log files can also be used as a way to have a permanent record of | |
326 | any code you wrote while experimenting. Log files are regular text files |
|
326 | any code you wrote while experimenting. Log files are regular text files | |
327 | which you can later open in your favorite text editor to extract code or |
|
327 | which you can later open in your favorite text editor to extract code or | |
328 | to 'clean them up' before using them to replay a session. |
|
328 | to 'clean them up' before using them to replay a session. | |
329 |
|
329 | |||
330 | The :magic:`logstart` function for activating logging in mid-session is used as |
|
330 | The :magic:`logstart` function for activating logging in mid-session is used as | |
331 | follows:: |
|
331 | follows:: | |
332 |
|
332 | |||
333 | %logstart [log_name [log_mode]] |
|
333 | %logstart [log_name [log_mode]] | |
334 |
|
334 | |||
335 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
335 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
336 | current working directory, in 'rotate' mode (see below). |
|
336 | current working directory, in 'rotate' mode (see below). | |
337 |
|
337 | |||
338 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
338 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
339 | history up to that point and then continues logging. |
|
339 | history up to that point and then continues logging. | |
340 |
|
340 | |||
341 | %logstart takes a second optional parameter: logging mode. This can be |
|
341 | %logstart takes a second optional parameter: logging mode. This can be | |
342 | one of (note that the modes are given unquoted): |
|
342 | one of (note that the modes are given unquoted): | |
343 |
|
343 | |||
344 | * [over:] overwrite existing log_name. |
|
344 | * [over:] overwrite existing log_name. | |
345 | * [backup:] rename (if exists) to log_name~ and start log_name. |
|
345 | * [backup:] rename (if exists) to log_name~ and start log_name. | |
346 | * [append:] well, that says it. |
|
346 | * [append:] well, that says it. | |
347 | * [rotate:] create rotating logs log_name.1~, log_name.2~, etc. |
|
347 | * [rotate:] create rotating logs log_name.1~, log_name.2~, etc. | |
348 |
|
348 | |||
349 | The :magic:`logoff` and :magic:`logon` functions allow you to temporarily stop and |
|
349 | The :magic:`logoff` and :magic:`logon` functions allow you to temporarily stop and | |
350 | resume logging to a file which had previously been started with |
|
350 | resume logging to a file which had previously been started with | |
351 | %logstart. They will fail (with an explanation) if you try to use them |
|
351 | %logstart. They will fail (with an explanation) if you try to use them | |
352 | before logging has been started. |
|
352 | before logging has been started. | |
353 |
|
353 | |||
354 | .. _system_shell_access: |
|
354 | .. _system_shell_access: | |
355 |
|
355 | |||
356 | System shell access |
|
356 | System shell access | |
357 | ------------------- |
|
357 | ------------------- | |
358 |
|
358 | |||
359 | Any input line beginning with a ! character is passed verbatim (minus |
|
359 | Any input line beginning with a ! character is passed verbatim (minus | |
360 | the !, of course) to the underlying operating system. For example, |
|
360 | the !, of course) to the underlying operating system. For example, | |
361 | typing ``!ls`` will run 'ls' in the current directory. |
|
361 | typing ``!ls`` will run 'ls' in the current directory. | |
362 |
|
362 | |||
363 | .. _manual_capture: |
|
363 | .. _manual_capture: | |
364 |
|
364 | |||
365 | Manual capture of command output and magic output |
|
365 | Manual capture of command output and magic output | |
366 | ------------------------------------------------- |
|
366 | ------------------------------------------------- | |
367 |
|
367 | |||
368 | You can assign the result of a system command to a Python variable with the |
|
368 | You can assign the result of a system command to a Python variable with the | |
369 | syntax ``myfiles = !ls``. Similarly, the result of a magic (as long as it returns |
|
369 | syntax ``myfiles = !ls``. Similarly, the result of a magic (as long as it returns | |
370 | a value) can be assigned to a variable. For example, the syntax ``myfiles = %sx ls`` |
|
370 | a value) can be assigned to a variable. For example, the syntax ``myfiles = %sx ls`` | |
371 | is equivalent to the above system command example (the :magic:`sx` magic runs a shell command |
|
371 | is equivalent to the above system command example (the :magic:`sx` magic runs a shell command | |
372 | and captures the output). Each of these gets machine |
|
372 | and captures the output). Each of these gets machine | |
373 | readable output from stdout (e.g. without colours), and splits on newlines. To |
|
373 | readable output from stdout (e.g. without colours), and splits on newlines. To | |
374 | explicitly get this sort of output without assigning to a variable, use two |
|
374 | explicitly get this sort of output without assigning to a variable, use two | |
375 | exclamation marks (``!!ls``) or the :magic:`sx` magic command without an assignment. |
|
375 | exclamation marks (``!!ls``) or the :magic:`sx` magic command without an assignment. | |
376 | (However, ``!!`` commands cannot be assigned to a variable.) |
|
376 | (However, ``!!`` commands cannot be assigned to a variable.) | |
377 |
|
377 | |||
378 | The captured list in this example has some convenience features. ``myfiles.n`` or ``myfiles.s`` |
|
378 | The captured list in this example has some convenience features. ``myfiles.n`` or ``myfiles.s`` | |
379 | returns a string delimited by newlines or spaces, respectively. ``myfiles.p`` |
|
379 | returns a string delimited by newlines or spaces, respectively. ``myfiles.p`` | |
380 | produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items. |
|
380 | produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items. | |
381 | See :ref:`string_lists` for details. |
|
381 | See :ref:`string_lists` for details. | |
382 |
|
382 | |||
383 | IPython also allows you to expand the value of python variables when |
|
383 | IPython also allows you to expand the value of python variables when | |
384 | making system calls. Wrap variables or expressions in {braces}:: |
|
384 | making system calls. Wrap variables or expressions in {braces}:: | |
385 |
|
385 | |||
386 | In [1]: pyvar = 'Hello world' |
|
386 | In [1]: pyvar = 'Hello world' | |
387 | In [2]: !echo "A python variable: {pyvar}" |
|
387 | In [2]: !echo "A python variable: {pyvar}" | |
388 | A python variable: Hello world |
|
388 | A python variable: Hello world | |
389 | In [3]: import math |
|
389 | In [3]: import math | |
390 | In [4]: x = 8 |
|
390 | In [4]: x = 8 | |
391 | In [5]: !echo {math.factorial(x)} |
|
391 | In [5]: !echo {math.factorial(x)} | |
392 | 40320 |
|
392 | 40320 | |
393 |
|
393 | |||
394 | For simple cases, you can alternatively prepend $ to a variable name:: |
|
394 | For simple cases, you can alternatively prepend $ to a variable name:: | |
395 |
|
395 | |||
396 | In [6]: !echo $sys.argv |
|
396 | In [6]: !echo $sys.argv | |
397 | [/home/fperez/usr/bin/ipython] |
|
397 | [/home/fperez/usr/bin/ipython] | |
398 | In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $ |
|
398 | In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $ | |
399 | A system variable: /home/fperez |
|
399 | A system variable: /home/fperez | |
400 |
|
400 | |||
401 | Note that `$$` is used to represent a literal `$`. |
|
401 | Note that `$$` is used to represent a literal `$`. | |
402 |
|
402 | |||
403 | System command aliases |
|
403 | System command aliases | |
404 | ---------------------- |
|
404 | ---------------------- | |
405 |
|
405 | |||
406 | The :magic:`alias` magic function allows you to define magic functions which are in fact |
|
406 | The :magic:`alias` magic function allows you to define magic functions which are in fact | |
407 | system shell commands. These aliases can have parameters. |
|
407 | system shell commands. These aliases can have parameters. | |
408 |
|
408 | |||
409 | ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd' |
|
409 | ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd' | |
410 |
|
410 | |||
411 | Then, typing ``alias_name params`` will execute the system command 'cmd |
|
411 | Then, typing ``alias_name params`` will execute the system command 'cmd | |
412 | params' (from your underlying operating system). |
|
412 | params' (from your underlying operating system). | |
413 |
|
413 | |||
414 | You can also define aliases with parameters using %s specifiers (one per |
|
414 | You can also define aliases with parameters using %s specifiers (one per | |
415 | parameter). The following example defines the parts function as an |
|
415 | parameter). The following example defines the parts function as an | |
416 | alias to the command 'echo first %s second %s' where each %s will be |
|
416 | alias to the command 'echo first %s second %s' where each %s will be | |
417 | replaced by a positional parameter to the call to %parts:: |
|
417 | replaced by a positional parameter to the call to %parts:: | |
418 |
|
418 | |||
419 | In [1]: %alias parts echo first %s second %s |
|
419 | In [1]: %alias parts echo first %s second %s | |
420 | In [2]: parts A B |
|
420 | In [2]: parts A B | |
421 | first A second B |
|
421 | first A second B | |
422 | In [3]: parts A |
|
422 | In [3]: parts A | |
423 | ERROR: Alias <parts> requires 2 arguments, 1 given. |
|
423 | ERROR: Alias <parts> requires 2 arguments, 1 given. | |
424 |
|
424 | |||
425 | If called with no parameters, :magic:`alias` prints the table of currently |
|
425 | If called with no parameters, :magic:`alias` prints the table of currently | |
426 | defined aliases. |
|
426 | defined aliases. | |
427 |
|
427 | |||
428 | The :magic:`rehashx` magic allows you to load your entire $PATH as |
|
428 | The :magic:`rehashx` magic allows you to load your entire $PATH as | |
429 | ipython aliases. See its docstring for further details. |
|
429 | ipython aliases. See its docstring for further details. | |
430 |
|
430 | |||
431 |
|
431 | |||
432 | .. _dreload: |
|
432 | .. _dreload: | |
433 |
|
433 | |||
434 | Recursive reload |
|
434 | Recursive reload | |
435 | ---------------- |
|
435 | ---------------- | |
436 |
|
436 | |||
437 | The :mod:`IPython.lib.deepreload` module allows you to recursively reload a |
|
437 | The :mod:`IPython.lib.deepreload` module allows you to recursively reload a | |
438 | module: changes made to any of its dependencies will be reloaded without |
|
438 | module: changes made to any of its dependencies will be reloaded without | |
439 | having to exit. To start using it, do:: |
|
439 | having to exit. To start using it, do:: | |
440 |
|
440 | |||
441 | from IPython.lib.deepreload import reload as dreload |
|
441 | from IPython.lib.deepreload import reload as dreload | |
442 |
|
442 | |||
443 |
|
443 | |||
444 | Verbose and colored exception traceback printouts |
|
444 | Verbose and colored exception traceback printouts | |
445 | ------------------------------------------------- |
|
445 | ------------------------------------------------- | |
446 |
|
446 | |||
447 | IPython provides the option to see very detailed exception tracebacks, |
|
447 | IPython provides the option to see very detailed exception tracebacks, | |
448 | which can be especially useful when debugging large programs. You can |
|
448 | which can be especially useful when debugging large programs. You can | |
449 | run any Python file with the %run function to benefit from these |
|
449 | run any Python file with the %run function to benefit from these | |
450 | detailed tracebacks. Furthermore, both normal and verbose tracebacks can |
|
450 | detailed tracebacks. Furthermore, both normal and verbose tracebacks can | |
451 | be colored (if your terminal supports it) which makes them much easier |
|
451 | be colored (if your terminal supports it) which makes them much easier | |
452 | to parse visually. |
|
452 | to parse visually. | |
453 |
|
453 | |||
454 | See the magic :magic:`xmode` and :magic:`colors` functions for details. |
|
454 | See the magic :magic:`xmode` and :magic:`colors` functions for details. | |
455 |
|
455 | |||
456 | These features are basically a terminal version of Ka-Ping Yee's cgitb |
|
456 | These features are basically a terminal version of Ka-Ping Yee's cgitb | |
457 | module, now part of the standard Python library. |
|
457 | module, now part of the standard Python library. | |
458 |
|
458 | |||
459 |
|
459 | |||
460 | .. _input_caching: |
|
460 | .. _input_caching: | |
461 |
|
461 | |||
462 | Input caching system |
|
462 | Input caching system | |
463 | -------------------- |
|
463 | -------------------- | |
464 |
|
464 | |||
465 | IPython offers numbered prompts (In/Out) with input and output caching |
|
465 | IPython offers numbered prompts (In/Out) with input and output caching | |
466 | (also referred to as 'input history'). All input is saved and can be |
|
466 | (also referred to as 'input history'). All input is saved and can be | |
467 | retrieved as variables (besides the usual arrow key recall), in |
|
467 | retrieved as variables (besides the usual arrow key recall), in | |
468 | addition to the :magic:`rep` magic command that brings a history entry |
|
468 | addition to the :magic:`rep` magic command that brings a history entry | |
469 | up for editing on the next command line. |
|
469 | up for editing on the next command line. | |
470 |
|
470 | |||
471 | The following variables always exist: |
|
471 | The following variables always exist: | |
472 |
|
472 | |||
473 | * _i, _ii, _iii: store previous, next previous and next-next previous inputs. |
|
473 | * _i, _ii, _iii: store previous, next previous and next-next previous inputs. | |
474 | * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you |
|
474 | * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you | |
475 | overwrite In with a variable of your own, you can remake the assignment to the |
|
475 | overwrite In with a variable of your own, you can remake the assignment to the | |
476 | internal list with a simple ``In=_ih``. |
|
476 | internal list with a simple ``In=_ih``. | |
477 |
|
477 | |||
478 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
478 | Additionally, global variables named _i<n> are dynamically created (<n> | |
479 | being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``. |
|
479 | being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``. | |
480 |
|
480 | |||
481 | For example, what you typed at prompt 14 is available as ``_i14``, ``_ih[14]`` |
|
481 | For example, what you typed at prompt 14 is available as ``_i14``, ``_ih[14]`` | |
482 | and ``In[14]``. |
|
482 | and ``In[14]``. | |
483 |
|
483 | |||
484 | This allows you to easily cut and paste multi line interactive prompts |
|
484 | This allows you to easily cut and paste multi line interactive prompts | |
485 | by printing them out: they print like a clean string, without prompt |
|
485 | by printing them out: they print like a clean string, without prompt | |
486 | characters. You can also manipulate them like regular variables (they |
|
486 | characters. You can also manipulate them like regular variables (they | |
487 | are strings), modify or exec them. |
|
487 | are strings), modify or exec them. | |
488 |
|
488 | |||
489 | You can also re-execute multiple lines of input easily by using the |
|
489 | You can also re-execute multiple lines of input easily by using the | |
490 | magic :magic:`rerun` or :magic:`macro` functions. The macro system also allows you to re-execute |
|
490 | magic :magic:`rerun` or :magic:`macro` functions. The macro system also allows you to re-execute | |
491 | previous lines which include magic function calls (which require special |
|
491 | previous lines which include magic function calls (which require special | |
492 | processing). Type %macro? for more details on the macro system. |
|
492 | processing). Type %macro? for more details on the macro system. | |
493 |
|
493 | |||
494 | A history function :magic:`history` allows you to see any part of your input |
|
494 | A history function :magic:`history` allows you to see any part of your input | |
495 | history by printing a range of the _i variables. |
|
495 | history by printing a range of the _i variables. | |
496 |
|
496 | |||
497 | You can also search ('grep') through your history by typing |
|
497 | You can also search ('grep') through your history by typing | |
498 | ``%hist -g somestring``. This is handy for searching for URLs, IP addresses, |
|
498 | ``%hist -g somestring``. This is handy for searching for URLs, IP addresses, | |
499 | etc. You can bring history entries listed by '%hist -g' up for editing |
|
499 | etc. You can bring history entries listed by '%hist -g' up for editing | |
500 | with the %recall command, or run them immediately with :magic:`rerun`. |
|
500 | with the %recall command, or run them immediately with :magic:`rerun`. | |
501 |
|
501 | |||
502 | .. _output_caching: |
|
502 | .. _output_caching: | |
503 |
|
503 | |||
504 | Output caching system |
|
504 | Output caching system | |
505 | --------------------- |
|
505 | --------------------- | |
506 |
|
506 | |||
507 | For output that is returned from actions, a system similar to the input |
|
507 | For output that is returned from actions, a system similar to the input | |
508 | cache exists but using _ instead of _i. Only actions that produce a |
|
508 | cache exists but using _ instead of _i. Only actions that produce a | |
509 | result (NOT assignments, for example) are cached. If you are familiar |
|
509 | result (NOT assignments, for example) are cached. If you are familiar | |
510 | with Mathematica, IPython's _ variables behave exactly like |
|
510 | with Mathematica, IPython's _ variables behave exactly like | |
511 | Mathematica's % variables. |
|
511 | Mathematica's % variables. | |
512 |
|
512 | |||
513 | The following variables always exist: |
|
513 | The following variables always exist: | |
514 |
|
514 | |||
515 | * [_] (a single underscore): stores previous output, like Python's |
|
515 | * [_] (a single underscore): stores previous output, like Python's | |
516 | default interpreter. |
|
516 | default interpreter. | |
517 | * [__] (two underscores): next previous. |
|
517 | * [__] (two underscores): next previous. | |
518 | * [___] (three underscores): next-next previous. |
|
518 | * [___] (three underscores): next-next previous. | |
519 |
|
519 | |||
520 | Additionally, global variables named _<n> are dynamically created (<n> |
|
520 | Additionally, global variables named _<n> are dynamically created (<n> | |
521 | being the prompt counter), such that the result of output <n> is always |
|
521 | being the prompt counter), such that the result of output <n> is always | |
522 | available as _<n> (don't use the angle brackets, just the number, e.g. |
|
522 | available as _<n> (don't use the angle brackets, just the number, e.g. | |
523 | ``_21``). |
|
523 | ``_21``). | |
524 |
|
524 | |||
525 | These variables are also stored in a global dictionary (not a |
|
525 | These variables are also stored in a global dictionary (not a | |
526 | list, since it only has entries for lines which returned a result) |
|
526 | list, since it only has entries for lines which returned a result) | |
527 | available under the names _oh and Out (similar to _ih and In). So the |
|
527 | available under the names _oh and Out (similar to _ih and In). So the | |
528 | output from line 12 can be obtained as ``_12``, ``Out[12]`` or ``_oh[12]``. If you |
|
528 | output from line 12 can be obtained as ``_12``, ``Out[12]`` or ``_oh[12]``. If you | |
529 | accidentally overwrite the Out variable you can recover it by typing |
|
529 | accidentally overwrite the Out variable you can recover it by typing | |
530 | ``Out=_oh`` at the prompt. |
|
530 | ``Out=_oh`` at the prompt. | |
531 |
|
531 | |||
532 | This system obviously can potentially put heavy memory demands on your |
|
532 | This system obviously can potentially put heavy memory demands on your | |
533 | system, since it prevents Python's garbage collector from removing any |
|
533 | system, since it prevents Python's garbage collector from removing any | |
534 | previously computed results. You can control how many results are kept |
|
534 | previously computed results. You can control how many results are kept | |
535 | in memory with the configuration option ``InteractiveShell.cache_size``. |
|
535 | in memory with the configuration option ``InteractiveShell.cache_size``. | |
536 | If you set it to 0, output caching is disabled. You can also use the :magic:`reset` |
|
536 | If you set it to 0, output caching is disabled. You can also use the :magic:`reset` | |
537 | and :magic:`xdel` magics to clear large items from memory. |
|
537 | and :magic:`xdel` magics to clear large items from memory. | |
538 |
|
538 | |||
539 | Directory history |
|
539 | Directory history | |
540 | ----------------- |
|
540 | ----------------- | |
541 |
|
541 | |||
542 | Your history of visited directories is kept in the global list _dh, and |
|
542 | Your history of visited directories is kept in the global list _dh, and | |
543 | the magic :magic:`cd` command can be used to go to any entry in that list. The |
|
543 | the magic :magic:`cd` command can be used to go to any entry in that list. The | |
544 | :magic:`dhist` command allows you to view this history. Do ``cd -<TAB>`` to |
|
544 | :magic:`dhist` command allows you to view this history. Do ``cd -<TAB>`` to | |
545 | conveniently view the directory history. |
|
545 | conveniently view the directory history. | |
546 |
|
546 | |||
547 |
|
547 | |||
548 | Automatic parentheses and quotes |
|
548 | Automatic parentheses and quotes | |
549 | -------------------------------- |
|
549 | -------------------------------- | |
550 |
|
550 | |||
551 | These features were adapted from Nathan Gray's LazyPython. They are |
|
551 | These features were adapted from Nathan Gray's LazyPython. They are | |
552 | meant to allow less typing for common situations. |
|
552 | meant to allow less typing for common situations. | |
553 |
|
553 | |||
554 | Callable objects (i.e. functions, methods, etc) can be invoked like this |
|
554 | Callable objects (i.e. functions, methods, etc) can be invoked like this | |
555 | (notice the commas between the arguments):: |
|
555 | (notice the commas between the arguments):: | |
556 |
|
556 | |||
557 | In [1]: callable_ob arg1, arg2, arg3 |
|
557 | In [1]: callable_ob arg1, arg2, arg3 | |
558 | ------> callable_ob(arg1, arg2, arg3) |
|
558 | ------> callable_ob(arg1, arg2, arg3) | |
559 |
|
559 | |||
560 | .. note:: |
|
560 | .. note:: | |
561 | This feature is disabled by default. To enable it, use the ``%autocall`` |
|
561 | This feature is disabled by default. To enable it, use the ``%autocall`` | |
562 | magic command. The commands below with special prefixes will always work, |
|
562 | magic command. The commands below with special prefixes will always work, | |
563 | however. |
|
563 | however. | |
564 |
|
564 | |||
565 | You can force automatic parentheses by using '/' as the first character |
|
565 | You can force automatic parentheses by using '/' as the first character | |
566 | of a line. For example:: |
|
566 | of a line. For example:: | |
567 |
|
567 | |||
568 | In [2]: /globals # becomes 'globals()' |
|
568 | In [2]: /globals # becomes 'globals()' | |
569 |
|
569 | |||
570 | Note that the '/' MUST be the first character on the line! This won't work:: |
|
570 | Note that the '/' MUST be the first character on the line! This won't work:: | |
571 |
|
571 | |||
572 | In [3]: print /globals # syntax error |
|
572 | In [3]: print /globals # syntax error | |
573 |
|
573 | |||
574 | In most cases the automatic algorithm should work, so you should rarely |
|
574 | In most cases the automatic algorithm should work, so you should rarely | |
575 | need to explicitly invoke /. One notable exception is if you are trying |
|
575 | need to explicitly invoke /. One notable exception is if you are trying | |
576 | to call a function with a list of tuples as arguments (the parenthesis |
|
576 | to call a function with a list of tuples as arguments (the parenthesis | |
577 | will confuse IPython):: |
|
577 | will confuse IPython):: | |
578 |
|
578 | |||
579 | In [4]: zip (1,2,3),(4,5,6) # won't work |
|
579 | In [4]: zip (1,2,3),(4,5,6) # won't work | |
580 |
|
580 | |||
581 | but this will work:: |
|
581 | but this will work:: | |
582 |
|
582 | |||
583 | In [5]: /zip (1,2,3),(4,5,6) |
|
583 | In [5]: /zip (1,2,3),(4,5,6) | |
584 | ------> zip ((1,2,3),(4,5,6)) |
|
584 | ------> zip ((1,2,3),(4,5,6)) | |
585 | Out[5]: [(1, 4), (2, 5), (3, 6)] |
|
585 | Out[5]: [(1, 4), (2, 5), (3, 6)] | |
586 |
|
586 | |||
587 | IPython tells you that it has altered your command line by displaying |
|
587 | IPython tells you that it has altered your command line by displaying | |
588 | the new command line preceded by ``--->``. |
|
588 | the new command line preceded by ``--->``. | |
589 |
|
589 | |||
590 | You can force automatic quoting of a function's arguments by using ``,`` |
|
590 | You can force automatic quoting of a function's arguments by using ``,`` | |
591 | or ``;`` as the first character of a line. For example:: |
|
591 | or ``;`` as the first character of a line. For example:: | |
592 |
|
592 | |||
593 | In [1]: ,my_function /home/me # becomes my_function("/home/me") |
|
593 | In [1]: ,my_function /home/me # becomes my_function("/home/me") | |
594 |
|
594 | |||
595 | If you use ';' the whole argument is quoted as a single string, while ',' splits |
|
595 | If you use ';' the whole argument is quoted as a single string, while ',' splits | |
596 | on whitespace:: |
|
596 | on whitespace:: | |
597 |
|
597 | |||
598 | In [2]: ,my_function a b c # becomes my_function("a","b","c") |
|
598 | In [2]: ,my_function a b c # becomes my_function("a","b","c") | |
599 |
|
599 | |||
600 | In [3]: ;my_function a b c # becomes my_function("a b c") |
|
600 | In [3]: ;my_function a b c # becomes my_function("a b c") | |
601 |
|
601 | |||
602 | Note that the ',' or ';' MUST be the first character on the line! This |
|
602 | Note that the ',' or ';' MUST be the first character on the line! This | |
603 | won't work:: |
|
603 | won't work:: | |
604 |
|
604 | |||
605 | In [4]: x = ,my_function /home/me # syntax error |
|
605 | In [4]: x = ,my_function /home/me # syntax error | |
606 |
|
606 | |||
607 | IPython as your default Python environment |
|
607 | IPython as your default Python environment | |
608 | ========================================== |
|
608 | ========================================== | |
609 |
|
609 | |||
610 | Python honors the environment variable :envvar:`PYTHONSTARTUP` and will |
|
610 | Python honors the environment variable :envvar:`PYTHONSTARTUP` and will | |
611 | execute at startup the file referenced by this variable. If you put the |
|
611 | execute at startup the file referenced by this variable. If you put the | |
612 | following code at the end of that file, then IPython will be your working |
|
612 | following code at the end of that file, then IPython will be your working | |
613 | environment anytime you start Python:: |
|
613 | environment anytime you start Python:: | |
614 |
|
614 | |||
615 | import os, IPython |
|
615 | import os, IPython | |
616 | os.environ['PYTHONSTARTUP'] = '' # Prevent running this again |
|
616 | os.environ['PYTHONSTARTUP'] = '' # Prevent running this again | |
617 | IPython.start_ipython() |
|
617 | IPython.start_ipython() | |
618 | raise SystemExit |
|
618 | raise SystemExit | |
619 |
|
619 | |||
620 | The ``raise SystemExit`` is needed to exit Python when |
|
620 | The ``raise SystemExit`` is needed to exit Python when | |
621 | it finishes, otherwise you'll be back at the normal Python ``>>>`` |
|
621 | it finishes, otherwise you'll be back at the normal Python ``>>>`` | |
622 | prompt. |
|
622 | prompt. | |
623 |
|
623 | |||
624 | This is probably useful to developers who manage multiple Python |
|
624 | This is probably useful to developers who manage multiple Python | |
625 | versions and don't want to have correspondingly multiple IPython |
|
625 | versions and don't want to have correspondingly multiple IPython | |
626 | versions. Note that in this mode, there is no way to pass IPython any |
|
626 | versions. Note that in this mode, there is no way to pass IPython any | |
627 | command-line options, as those are trapped first by Python itself. |
|
627 | command-line options, as those are trapped first by Python itself. | |
628 |
|
628 | |||
629 | .. _Embedding: |
|
629 | .. _Embedding: | |
630 |
|
630 | |||
631 | Embedding IPython |
|
631 | Embedding IPython | |
632 | ================= |
|
632 | ================= | |
633 |
|
633 | |||
634 | You can start a regular IPython session with |
|
634 | You can start a regular IPython session with | |
635 |
|
635 | |||
636 | .. sourcecode:: python |
|
636 | .. sourcecode:: python | |
637 |
|
637 | |||
638 | import IPython |
|
638 | import IPython | |
639 | IPython.start_ipython(argv=[]) |
|
639 | IPython.start_ipython(argv=[]) | |
640 |
|
640 | |||
641 | at any point in your program. This will load IPython configuration, |
|
641 | at any point in your program. This will load IPython configuration, | |
642 | startup files, and everything, just as if it were a normal IPython session. |
|
642 | startup files, and everything, just as if it were a normal IPython session. | |
643 |
|
643 | |||
644 | It is also possible to embed an IPython shell in a namespace in your Python code. |
|
644 | It is also possible to embed an IPython shell in a namespace in your Python code. | |
645 | This allows you to evaluate dynamically the state of your code, |
|
645 | This allows you to evaluate dynamically the state of your code, | |
646 | operate with your variables, analyze them, etc. Note however that |
|
646 | operate with your variables, analyze them, etc. Note however that | |
647 | any changes you make to values while in the shell do not propagate back |
|
647 | any changes you make to values while in the shell do not propagate back | |
648 | to the running code, so it is safe to modify your values because you |
|
648 | to the running code, so it is safe to modify your values because you | |
649 | won't break your code in bizarre ways by doing so. |
|
649 | won't break your code in bizarre ways by doing so. | |
650 |
|
650 | |||
651 | .. note:: |
|
651 | .. note:: | |
652 |
|
652 | |||
653 | At present, embedding IPython cannot be done from inside IPython. |
|
653 | At present, embedding IPython cannot be done from inside IPython. | |
654 | Run the code samples below outside IPython. |
|
654 | Run the code samples below outside IPython. | |
655 |
|
655 | |||
656 | This feature allows you to easily have a fully functional python |
|
656 | This feature allows you to easily have a fully functional python | |
657 | environment for doing object introspection anywhere in your code with a |
|
657 | environment for doing object introspection anywhere in your code with a | |
658 | simple function call. In some cases a simple print statement is enough, |
|
658 | simple function call. In some cases a simple print statement is enough, | |
659 | but if you need to do more detailed analysis of a code fragment this |
|
659 | but if you need to do more detailed analysis of a code fragment this | |
660 | feature can be very valuable. |
|
660 | feature can be very valuable. | |
661 |
|
661 | |||
662 | It can also be useful in scientific computing situations where it is |
|
662 | It can also be useful in scientific computing situations where it is | |
663 | common to need to do some automatic, computationally intensive part and |
|
663 | common to need to do some automatic, computationally intensive part and | |
664 | then stop to look at data, plots, etc. |
|
664 | then stop to look at data, plots, etc. | |
665 | Opening an IPython instance will give you full access to your data and |
|
665 | Opening an IPython instance will give you full access to your data and | |
666 | functions, and you can resume program execution once you are done with |
|
666 | functions, and you can resume program execution once you are done with | |
667 | the interactive part (perhaps to stop again later, as many times as |
|
667 | the interactive part (perhaps to stop again later, as many times as | |
668 | needed). |
|
668 | needed). | |
669 |
|
669 | |||
670 | The following code snippet is the bare minimum you need to include in |
|
670 | The following code snippet is the bare minimum you need to include in | |
671 | your Python programs for this to work (detailed examples follow later):: |
|
671 | your Python programs for this to work (detailed examples follow later):: | |
672 |
|
672 | |||
673 | from IPython import embed |
|
673 | from IPython import embed | |
674 |
|
674 | |||
675 | embed() # this call anywhere in your program will start IPython |
|
675 | embed() # this call anywhere in your program will start IPython | |
676 |
|
676 | |||
677 | You can also embed an IPython *kernel*, for use with qtconsole, etc. via |
|
677 | You can also embed an IPython *kernel*, for use with qtconsole, etc. via | |
678 | ``IPython.embed_kernel()``. This should function work the same way, but you can |
|
678 | ``IPython.embed_kernel()``. This should function work the same way, but you can | |
679 | connect an external frontend (``ipython qtconsole`` or ``ipython console``), |
|
679 | connect an external frontend (``ipython qtconsole`` or ``ipython console``), | |
680 | rather than interacting with it in the terminal. |
|
680 | rather than interacting with it in the terminal. | |
681 |
|
681 | |||
682 | You can run embedded instances even in code which is itself being run at |
|
682 | You can run embedded instances even in code which is itself being run at | |
683 | the IPython interactive prompt with '%run <filename>'. Since it's easy |
|
683 | the IPython interactive prompt with '%run <filename>'. Since it's easy | |
684 | to get lost as to where you are (in your top-level IPython or in your |
|
684 | to get lost as to where you are (in your top-level IPython or in your | |
685 | embedded one), it's a good idea in such cases to set the in/out prompts |
|
685 | embedded one), it's a good idea in such cases to set the in/out prompts | |
686 | to something different for the embedded instances. The code examples |
|
686 | to something different for the embedded instances. The code examples | |
687 | below illustrate this. |
|
687 | below illustrate this. | |
688 |
|
688 | |||
689 | You can also have multiple IPython instances in your program and open |
|
689 | You can also have multiple IPython instances in your program and open | |
690 | them separately, for example with different options for data |
|
690 | them separately, for example with different options for data | |
691 | presentation. If you close and open the same instance multiple times, |
|
691 | presentation. If you close and open the same instance multiple times, | |
692 | its prompt counters simply continue from each execution to the next. |
|
692 | its prompt counters simply continue from each execution to the next. | |
693 |
|
693 | |||
694 | Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed` |
|
694 | Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed` | |
695 | module for more details on the use of this system. |
|
695 | module for more details on the use of this system. | |
696 |
|
696 | |||
697 | The following sample file illustrating how to use the embedding |
|
697 | The following sample file illustrating how to use the embedding | |
698 | functionality is provided in the examples directory as embed_class_long.py. |
|
698 | functionality is provided in the examples directory as embed_class_long.py. | |
699 | It should be fairly self-explanatory: |
|
699 | It should be fairly self-explanatory: | |
700 |
|
700 | |||
701 | .. literalinclude:: ../../../examples/Embedding/embed_class_long.py |
|
701 | .. literalinclude:: ../../../examples/Embedding/embed_class_long.py | |
702 | :language: python |
|
702 | :language: python | |
703 |
|
703 | |||
704 | Once you understand how the system functions, you can use the following |
|
704 | Once you understand how the system functions, you can use the following | |
705 | code fragments in your programs which are ready for cut and paste: |
|
705 | code fragments in your programs which are ready for cut and paste: | |
706 |
|
706 | |||
707 | .. literalinclude:: ../../../examples/Embedding/embed_class_short.py |
|
707 | .. literalinclude:: ../../../examples/Embedding/embed_class_short.py | |
708 | :language: python |
|
708 | :language: python | |
709 |
|
709 | |||
710 | Using the Python debugger (pdb) |
|
710 | Using the Python debugger (pdb) | |
711 | =============================== |
|
711 | =============================== | |
712 |
|
712 | |||
713 | Running entire programs via pdb |
|
713 | Running entire programs via pdb | |
714 | ------------------------------- |
|
714 | ------------------------------- | |
715 |
|
715 | |||
716 | pdb, the Python debugger, is a powerful interactive debugger which |
|
716 | pdb, the Python debugger, is a powerful interactive debugger which | |
717 | allows you to step through code, set breakpoints, watch variables, |
|
717 | allows you to step through code, set breakpoints, watch variables, | |
718 | etc. IPython makes it very easy to start any script under the control |
|
718 | etc. IPython makes it very easy to start any script under the control | |
719 | of pdb, regardless of whether you have wrapped it into a 'main()' |
|
719 | of pdb, regardless of whether you have wrapped it into a 'main()' | |
720 | function or not. For this, simply type ``%run -d myscript`` at an |
|
720 | function or not. For this, simply type ``%run -d myscript`` at an | |
721 | IPython prompt. See the :magic:`run` command's documentation for more details, including |
|
721 | IPython prompt. See the :magic:`run` command's documentation for more details, including | |
722 | how to control where pdb will stop execution first. |
|
722 | how to control where pdb will stop execution first. | |
723 |
|
723 | |||
724 | For more information on the use of the pdb debugger, see :ref:`debugger-commands` |
|
724 | For more information on the use of the pdb debugger, see :ref:`debugger-commands` | |
725 | in the Python documentation. |
|
725 | in the Python documentation. | |
726 |
|
726 | |||
727 |
|
727 | |||
728 | Post-mortem debugging |
|
728 | Post-mortem debugging | |
729 | --------------------- |
|
729 | --------------------- | |
730 |
|
730 | |||
731 | Going into a debugger when an exception occurs can be |
|
731 | Going into a debugger when an exception occurs can be | |
732 | extremely useful in order to find the origin of subtle bugs, because pdb |
|
732 | extremely useful in order to find the origin of subtle bugs, because pdb | |
733 | opens up at the point in your code which triggered the exception, and |
|
733 | opens up at the point in your code which triggered the exception, and | |
734 | while your program is at this point 'dead', all the data is still |
|
734 | while your program is at this point 'dead', all the data is still | |
735 | available and you can walk up and down the stack frame and understand |
|
735 | available and you can walk up and down the stack frame and understand | |
736 | the origin of the problem. |
|
736 | the origin of the problem. | |
737 |
|
737 | |||
738 | You can use the :magic:`debug` magic after an exception has occurred to start |
|
738 | You can use the :magic:`debug` magic after an exception has occurred to start | |
739 | post-mortem debugging. IPython can also call debugger every time your code |
|
739 | post-mortem debugging. IPython can also call debugger every time your code | |
740 | triggers an uncaught exception. This feature can be toggled with the :magic:`pdb` magic |
|
740 | triggers an uncaught exception. This feature can be toggled with the :magic:`pdb` magic | |
741 | command, or you can start IPython with the ``--pdb`` option. |
|
741 | command, or you can start IPython with the ``--pdb`` option. | |
742 |
|
742 | |||
743 | For a post-mortem debugger in your programs outside IPython, |
|
743 | For a post-mortem debugger in your programs outside IPython, | |
744 | put the following lines toward the top of your 'main' routine:: |
|
744 | put the following lines toward the top of your 'main' routine:: | |
745 |
|
745 | |||
746 | import sys |
|
746 | import sys | |
747 | from IPython.core import ultratb |
|
747 | from IPython.core import ultratb | |
748 | sys.excepthook = ultratb.FormattedTB(mode='Verbose', |
|
748 | sys.excepthook = ultratb.FormattedTB(mode='Verbose', | |
749 | color_scheme='Linux', call_pdb=1) |
|
749 | color_scheme='Linux', call_pdb=1) | |
750 |
|
750 | |||
751 | The mode keyword can be either 'Verbose' or 'Plain', giving either very |
|
751 | The mode keyword can be either 'Verbose' or 'Plain', giving either very | |
752 | detailed or normal tracebacks respectively. The color_scheme keyword can |
|
752 | detailed or normal tracebacks respectively. The color_scheme keyword can | |
753 | be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same |
|
753 | be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same | |
754 | options which can be set in IPython with ``--colors`` and ``--xmode``. |
|
754 | options which can be set in IPython with ``--colors`` and ``--xmode``. | |
755 |
|
755 | |||
756 | This will give any of your programs detailed, colored tracebacks with |
|
756 | This will give any of your programs detailed, colored tracebacks with | |
757 | automatic invocation of pdb. |
|
757 | automatic invocation of pdb. | |
758 |
|
758 | |||
759 | .. _pasting_with_prompts: |
|
759 | .. _pasting_with_prompts: | |
760 |
|
760 | |||
761 | Pasting of code starting with Python or IPython prompts |
|
761 | Pasting of code starting with Python or IPython prompts | |
762 | ======================================================= |
|
762 | ======================================================= | |
763 |
|
763 | |||
764 | IPython is smart enough to filter out input prompts, be they plain Python ones |
|
764 | IPython is smart enough to filter out input prompts, be they plain Python ones | |
765 | (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can |
|
765 | (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can | |
766 | therefore copy and paste from existing interactive sessions without worry. |
|
766 | therefore copy and paste from existing interactive sessions without worry. | |
767 |
|
767 | |||
768 | The following is a 'screenshot' of how things work, copying an example from the |
|
768 | The following is a 'screenshot' of how things work, copying an example from the | |
769 | standard Python tutorial:: |
|
769 | standard Python tutorial:: | |
770 |
|
770 | |||
771 | In [1]: >>> # Fibonacci series: |
|
771 | In [1]: >>> # Fibonacci series: | |
772 |
|
772 | |||
773 | In [2]: ... # the sum of two elements defines the next |
|
773 | In [2]: ... # the sum of two elements defines the next | |
774 |
|
774 | |||
775 | In [3]: ... a, b = 0, 1 |
|
775 | In [3]: ... a, b = 0, 1 | |
776 |
|
776 | |||
777 | In [4]: >>> while b < 10: |
|
777 | In [4]: >>> while b < 10: | |
778 | ...: ... print(b) |
|
778 | ...: ... print(b) | |
779 | ...: ... a, b = b, a+b |
|
779 | ...: ... a, b = b, a+b | |
780 | ...: |
|
780 | ...: | |
781 | 1 |
|
781 | 1 | |
782 | 1 |
|
782 | 1 | |
783 | 2 |
|
783 | 2 | |
784 | 3 |
|
784 | 3 | |
785 | 5 |
|
785 | 5 | |
786 | 8 |
|
786 | 8 | |
787 |
|
787 | |||
788 | And pasting from IPython sessions works equally well:: |
|
788 | And pasting from IPython sessions works equally well:: | |
789 |
|
789 | |||
790 | In [1]: In [5]: def f(x): |
|
790 | In [1]: In [5]: def f(x): | |
791 | ...: ...: "A simple function" |
|
791 | ...: ...: "A simple function" | |
792 | ...: ...: return x**2 |
|
792 | ...: ...: return x**2 | |
793 | ...: ...: |
|
793 | ...: ...: | |
794 |
|
794 | |||
795 | In [2]: f(3) |
|
795 | In [2]: f(3) | |
796 | Out[2]: 9 |
|
796 | Out[2]: 9 | |
797 |
|
797 | |||
798 | .. _gui_support: |
|
798 | .. _gui_support: | |
799 |
|
799 | |||
800 | GUI event loop support |
|
800 | GUI event loop support | |
801 | ====================== |
|
801 | ====================== | |
802 |
|
802 | |||
803 | .. versionadded:: 0.11 |
|
803 | .. versionadded:: 0.11 | |
804 | The ``%gui`` magic and :mod:`IPython.lib.inputhook`. |
|
804 | The ``%gui`` magic and :mod:`IPython.lib.inputhook`. | |
805 |
|
805 | |||
806 | IPython has excellent support for working interactively with Graphical User |
|
806 | IPython has excellent support for working interactively with Graphical User | |
807 | Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is |
|
807 | Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is | |
808 | implemented using Python's builtin ``PyOSInputHook`` hook. This implementation |
|
808 | implemented using Python's builtin ``PyOSInputHook`` hook. This implementation | |
809 | is extremely robust compared to our previous thread-based version. The |
|
809 | is extremely robust compared to our previous thread-based version. The | |
810 | advantages of this are: |
|
810 | advantages of this are: | |
811 |
|
811 | |||
812 | * GUIs can be enabled and disabled dynamically at runtime. |
|
812 | * GUIs can be enabled and disabled dynamically at runtime. | |
813 | * The active GUI can be switched dynamically at runtime. |
|
813 | * The active GUI can be switched dynamically at runtime. | |
814 | * In some cases, multiple GUIs can run simultaneously with no problems. |
|
814 | * In some cases, multiple GUIs can run simultaneously with no problems. | |
815 | * There is a developer API in :mod:`IPython.lib.inputhook` for customizing |
|
815 | * There is a developer API in :mod:`IPython.lib.inputhook` for customizing | |
816 | all of these things. |
|
816 | all of these things. | |
817 |
|
817 | |||
818 | For users, enabling GUI event loop integration is simple. You simple use the |
|
818 | For users, enabling GUI event loop integration is simple. You simple use the | |
819 | :magic:`gui` magic as follows:: |
|
819 | :magic:`gui` magic as follows:: | |
820 |
|
820 | |||
821 | %gui [GUINAME] |
|
821 | %gui [GUINAME] | |
822 |
|
822 | |||
823 | With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME`` |
|
823 | With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME`` | |
824 | arguments are ``wx``, ``qt``, ``gtk`` and ``tk``. |
|
824 | arguments are ``wx``, ``qt``, ``gtk`` and ``tk``. | |
825 |
|
825 | |||
826 | Thus, to use wxPython interactively and create a running :class:`wx.App` |
|
826 | Thus, to use wxPython interactively and create a running :class:`wx.App` | |
827 | object, do:: |
|
827 | object, do:: | |
828 |
|
828 | |||
829 | %gui wx |
|
829 | %gui wx | |
830 |
|
830 | |||
831 | You can also start IPython with an event loop set up using the :option:`--gui` |
|
831 | You can also start IPython with an event loop set up using the :option:`--gui` | |
832 | flag:: |
|
832 | flag:: | |
833 |
|
833 | |||
834 | $ ipython --gui=qt |
|
834 | $ ipython --gui=qt | |
835 |
|
835 | |||
836 | For information on IPython's matplotlib_ integration (and the ``matplotlib`` |
|
836 | For information on IPython's matplotlib_ integration (and the ``matplotlib`` | |
837 | mode) see :ref:`this section <matplotlib_support>`. |
|
837 | mode) see :ref:`this section <matplotlib_support>`. | |
838 |
|
838 | |||
839 | For developers that want to use IPython's GUI event loop integration in the |
|
839 | For developers that want to use IPython's GUI event loop integration in the | |
840 | form of a library, these capabilities are exposed in library form in the |
|
840 | form of a library, these capabilities are exposed in library form in the | |
841 | :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules. |
|
841 | :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules. | |
842 | Interested developers should see the module docstrings for more information, |
|
842 | Interested developers should see the module docstrings for more information, | |
843 | but there are a few points that should be mentioned here. |
|
843 | but there are a few points that should be mentioned here. | |
844 |
|
844 | |||
845 | First, the ``PyOSInputHook`` approach only works in command line settings |
|
845 | First, the ``PyOSInputHook`` approach only works in command line settings | |
846 | where readline is activated. The integration with various eventloops |
|
846 | where readline is activated. The integration with various eventloops | |
847 | is handled somewhat differently (and more simply) when using the standalone |
|
847 | is handled somewhat differently (and more simply) when using the standalone | |
848 | kernel, as in the qtconsole and notebook. |
|
848 | kernel, as in the qtconsole and notebook. | |
849 |
|
849 | |||
850 | Second, when using the ``PyOSInputHook`` approach, a GUI application should |
|
850 | Second, when using the ``PyOSInputHook`` approach, a GUI application should | |
851 | *not* start its event loop. Instead all of this is handled by the |
|
851 | *not* start its event loop. Instead all of this is handled by the | |
852 | ``PyOSInputHook``. This means that applications that are meant to be used both |
|
852 | ``PyOSInputHook``. This means that applications that are meant to be used both | |
853 | in IPython and as standalone apps need to have special code to detects how the |
|
853 | in IPython and as standalone apps need to have special code to detects how the | |
854 | application is being run. We highly recommend using IPython's support for this. |
|
854 | application is being run. We highly recommend using IPython's support for this. | |
855 | Since the details vary slightly between toolkits, we point you to the various |
|
855 | Since the details vary slightly between toolkits, we point you to the various | |
856 |
examples in our source directory :file:`examples/ |
|
856 | examples in our source directory :file:`examples/Embedding` that demonstrate | |
857 | these capabilities. |
|
857 | these capabilities. | |
858 |
|
858 | |||
859 | Third, unlike previous versions of IPython, we no longer "hijack" (replace |
|
859 | Third, unlike previous versions of IPython, we no longer "hijack" (replace | |
860 | them with no-ops) the event loops. This is done to allow applications that |
|
860 | them with no-ops) the event loops. This is done to allow applications that | |
861 | actually need to run the real event loops to do so. This is often needed to |
|
861 | actually need to run the real event loops to do so. This is often needed to | |
862 | process pending events at critical points. |
|
862 | process pending events at critical points. | |
863 |
|
863 | |||
864 | Finally, we also have a number of examples in our source directory |
|
864 | Finally, we also have a number of examples in our source directory | |
865 |
:file:`examples/ |
|
865 | :file:`examples/Embedding` that demonstrate these capabilities. | |
866 |
|
866 | |||
867 | PyQt and PySide |
|
867 | PyQt and PySide | |
868 | --------------- |
|
868 | --------------- | |
869 |
|
869 | |||
870 | .. attempt at explanation of the complete mess that is Qt support |
|
870 | .. attempt at explanation of the complete mess that is Qt support | |
871 |
|
871 | |||
872 | When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either |
|
872 | When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either | |
873 | PyQt4 or PySide. There are three options for configuration here, because |
|
873 | PyQt4 or PySide. There are three options for configuration here, because | |
874 | PyQt4 has two APIs for QString and QVariant - v1, which is the default on |
|
874 | PyQt4 has two APIs for QString and QVariant - v1, which is the default on | |
875 | Python 2, and the more natural v2, which is the only API supported by PySide. |
|
875 | Python 2, and the more natural v2, which is the only API supported by PySide. | |
876 | v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole |
|
876 | v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole | |
877 | uses v2, but you can still use any interface in your code, since the |
|
877 | uses v2, but you can still use any interface in your code, since the | |
878 | Qt frontend is in a different process. |
|
878 | Qt frontend is in a different process. | |
879 |
|
879 | |||
880 | The default will be to import PyQt4 without configuration of the APIs, thus |
|
880 | The default will be to import PyQt4 without configuration of the APIs, thus | |
881 | matching what most applications would expect. It will fall back of PySide if |
|
881 | matching what most applications would expect. It will fall back of PySide if | |
882 | PyQt4 is unavailable. |
|
882 | PyQt4 is unavailable. | |
883 |
|
883 | |||
884 | If specified, IPython will respect the environment variable ``QT_API`` used |
|
884 | If specified, IPython will respect the environment variable ``QT_API`` used | |
885 | by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires |
|
885 | by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires | |
886 | PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used, |
|
886 | PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used, | |
887 | and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for |
|
887 | and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for | |
888 | QString and QVariant, so ETS codes like MayaVi will also work with IPython. |
|
888 | QString and QVariant, so ETS codes like MayaVi will also work with IPython. | |
889 |
|
889 | |||
890 | If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``, |
|
890 | If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``, | |
891 | then IPython will ask matplotlib which Qt library to use (only if QT_API is |
|
891 | then IPython will ask matplotlib which Qt library to use (only if QT_API is | |
892 | *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or |
|
892 | *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or | |
893 | older, then IPython will always use PyQt4 without setting the v2 APIs, since |
|
893 | older, then IPython will always use PyQt4 without setting the v2 APIs, since | |
894 | neither v2 PyQt nor PySide work. |
|
894 | neither v2 PyQt nor PySide work. | |
895 |
|
895 | |||
896 | .. warning:: |
|
896 | .. warning:: | |
897 |
|
897 | |||
898 | Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set |
|
898 | Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set | |
899 | to work with IPython's qt integration, because otherwise PyQt4 will be |
|
899 | to work with IPython's qt integration, because otherwise PyQt4 will be | |
900 | loaded in an incompatible mode. |
|
900 | loaded in an incompatible mode. | |
901 |
|
901 | |||
902 | It also means that you must *not* have ``QT_API`` set if you want to |
|
902 | It also means that you must *not* have ``QT_API`` set if you want to | |
903 | use ``--gui=qt`` with code that requires PyQt4 API v1. |
|
903 | use ``--gui=qt`` with code that requires PyQt4 API v1. | |
904 |
|
904 | |||
905 |
|
905 | |||
906 | .. _matplotlib_support: |
|
906 | .. _matplotlib_support: | |
907 |
|
907 | |||
908 | Plotting with matplotlib |
|
908 | Plotting with matplotlib | |
909 | ======================== |
|
909 | ======================== | |
910 |
|
910 | |||
911 | matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_ |
|
911 | matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_ | |
912 | can produce plots on screen using a variety of GUI toolkits, including Tk, |
|
912 | can produce plots on screen using a variety of GUI toolkits, including Tk, | |
913 | PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for |
|
913 | PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for | |
914 | scientific computing, all with a syntax compatible with that of the popular |
|
914 | scientific computing, all with a syntax compatible with that of the popular | |
915 | Matlab program. |
|
915 | Matlab program. | |
916 |
|
916 | |||
917 | To start IPython with matplotlib support, use the ``--matplotlib`` switch. If |
|
917 | To start IPython with matplotlib support, use the ``--matplotlib`` switch. If | |
918 | IPython is already running, you can run the :magic:`matplotlib` magic. If no |
|
918 | IPython is already running, you can run the :magic:`matplotlib` magic. If no | |
919 | arguments are given, IPython will automatically detect your choice of |
|
919 | arguments are given, IPython will automatically detect your choice of | |
920 | matplotlib backend. You can also request a specific backend with |
|
920 | matplotlib backend. You can also request a specific backend with | |
921 | ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx', |
|
921 | ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx', | |
922 | 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid |
|
922 | 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid | |
923 | backend value, which produces static figures inlined inside the application |
|
923 | backend value, which produces static figures inlined inside the application | |
924 | window instead of matplotlib's interactive figures that live in separate |
|
924 | window instead of matplotlib's interactive figures that live in separate | |
925 | windows. |
|
925 | windows. | |
926 |
|
926 | |||
927 | .. _interactive_demos: |
|
927 | .. _interactive_demos: | |
928 |
|
928 | |||
929 | Interactive demos with IPython |
|
929 | Interactive demos with IPython | |
930 | ============================== |
|
930 | ============================== | |
931 |
|
931 | |||
932 | IPython ships with a basic system for running scripts interactively in |
|
932 | IPython ships with a basic system for running scripts interactively in | |
933 | sections, useful when presenting code to audiences. A few tags embedded |
|
933 | sections, useful when presenting code to audiences. A few tags embedded | |
934 | in comments (so that the script remains valid Python code) divide a file |
|
934 | in comments (so that the script remains valid Python code) divide a file | |
935 | into separate blocks, and the demo can be run one block at a time, with |
|
935 | into separate blocks, and the demo can be run one block at a time, with | |
936 | IPython printing (with syntax highlighting) the block before executing |
|
936 | IPython printing (with syntax highlighting) the block before executing | |
937 | it, and returning to the interactive prompt after each block. The |
|
937 | it, and returning to the interactive prompt after each block. The | |
938 | interactive namespace is updated after each block is run with the |
|
938 | interactive namespace is updated after each block is run with the | |
939 | contents of the demo's namespace. |
|
939 | contents of the demo's namespace. | |
940 |
|
940 | |||
941 | This allows you to show a piece of code, run it and then execute |
|
941 | This allows you to show a piece of code, run it and then execute | |
942 | interactively commands based on the variables just created. Once you |
|
942 | interactively commands based on the variables just created. Once you | |
943 | want to continue, you simply execute the next block of the demo. The |
|
943 | want to continue, you simply execute the next block of the demo. The | |
944 | following listing shows the markup necessary for dividing a script into |
|
944 | following listing shows the markup necessary for dividing a script into | |
945 | sections for execution as a demo: |
|
945 | sections for execution as a demo: | |
946 |
|
946 | |||
947 | .. literalinclude:: ../../../examples/IPython Kernel/example-demo.py |
|
947 | .. literalinclude:: ../../../examples/IPython Kernel/example-demo.py | |
948 | :language: python |
|
948 | :language: python | |
949 |
|
949 | |||
950 | In order to run a file as a demo, you must first make a Demo object out |
|
950 | In order to run a file as a demo, you must first make a Demo object out | |
951 | of it. If the file is named myscript.py, the following code will make a |
|
951 | of it. If the file is named myscript.py, the following code will make a | |
952 | demo:: |
|
952 | demo:: | |
953 |
|
953 | |||
954 | from IPython.lib.demo import Demo |
|
954 | from IPython.lib.demo import Demo | |
955 |
|
955 | |||
956 | mydemo = Demo('myscript.py') |
|
956 | mydemo = Demo('myscript.py') | |
957 |
|
957 | |||
958 | This creates the mydemo object, whose blocks you run one at a time by |
|
958 | This creates the mydemo object, whose blocks you run one at a time by | |
959 | simply calling the object with no arguments. Then call it to run each step |
|
959 | simply calling the object with no arguments. Then call it to run each step | |
960 | of the demo:: |
|
960 | of the demo:: | |
961 |
|
961 | |||
962 | mydemo() |
|
962 | mydemo() | |
963 |
|
963 | |||
964 | Demo objects can be |
|
964 | Demo objects can be | |
965 | restarted, you can move forward or back skipping blocks, re-execute the |
|
965 | restarted, you can move forward or back skipping blocks, re-execute the | |
966 | last block, etc. See the :mod:`IPython.lib.demo` module and the |
|
966 | last block, etc. See the :mod:`IPython.lib.demo` module and the | |
967 | :class:`~IPython.lib.demo.Demo` class for details. |
|
967 | :class:`~IPython.lib.demo.Demo` class for details. | |
968 |
|
968 | |||
969 | Limitations: These demos are limited to |
|
969 | Limitations: These demos are limited to | |
970 | fairly simple uses. In particular, you cannot break up sections within |
|
970 | fairly simple uses. In particular, you cannot break up sections within | |
971 | indented code (loops, if statements, function definitions, etc.) |
|
971 | indented code (loops, if statements, function definitions, etc.) | |
972 | Supporting something like this would basically require tracking the |
|
972 | Supporting something like this would basically require tracking the | |
973 | internal execution state of the Python interpreter, so only top-level |
|
973 | internal execution state of the Python interpreter, so only top-level | |
974 | divisions are allowed. If you want to be able to open an IPython |
|
974 | divisions are allowed. If you want to be able to open an IPython | |
975 | instance at an arbitrary point in a program, you can use IPython's |
|
975 | instance at an arbitrary point in a program, you can use IPython's | |
976 | :ref:`embedding facilities <Embedding>`. |
|
976 | :ref:`embedding facilities <Embedding>`. | |
977 |
|
977 | |||
978 | .. include:: ../links.txt |
|
978 | .. include:: ../links.txt |
General Comments 0
You need to be logged in to leave comments.
Login now