##// END OF EJS Templates
Take out literal include of source
Skipper Seabold -
Show More
@@ -1,427 +1,419 b''
1 .. _ipython_directive:
1 .. _ipython_directive:
2
2
3 ========================
3 ========================
4 Ipython Sphinx Directive
4 Ipython Sphinx Directive
5 ========================
5 ========================
6
6
7 The ipython directive is a stateful ipython shell for embedding in
7 The ipython directive is a stateful ipython shell for embedding in
8 sphinx documents. It knows about standard ipython prompts, and
8 sphinx documents. It knows about standard ipython prompts, and
9 extracts the input and output lines. These prompts will be renumbered
9 extracts the input and output lines. These prompts will be renumbered
10 starting at ``1``. The inputs will be fed to an embedded ipython
10 starting at ``1``. The inputs will be fed to an embedded ipython
11 interpreter and the outputs from that interpreter will be inserted as
11 interpreter and the outputs from that interpreter will be inserted as
12 well. For example, code blocks like the following::
12 well. For example, code blocks like the following::
13
13
14 .. ipython::
14 .. ipython::
15
15
16 In [136]: x = 2
16 In [136]: x = 2
17
17
18 In [137]: x**3
18 In [137]: x**3
19 Out[137]: 8
19 Out[137]: 8
20
20
21 will be rendered as
21 will be rendered as
22
22
23 .. ipython::
23 .. ipython::
24
24
25 In [136]: x = 2
25 In [136]: x = 2
26
26
27 In [137]: x**3
27 In [137]: x**3
28 Out[137]: 8
28 Out[137]: 8
29
29
30 .. note::
30 .. note::
31
31
32 This tutorial should be read side-by-side with the Sphinx source
32 This tutorial should be read side-by-side with the Sphinx source
33 for this document because otherwise you will see only the rendered
33 for this document because otherwise you will see only the rendered
34 output and not the code that generated it. Excepting the example
34 output and not the code that generated it. Excepting the example
35 above, we will not in general be showing the literal ReST in this
35 above, we will not in general be showing the literal ReST in this
36 document that generates the rendered output.
36 document that generates the rendered output.
37
37
38
38
39 The state from previous sessions is stored, and standard error is
39 The state from previous sessions is stored, and standard error is
40 trapped. At doc build time, ipython's output and std err will be
40 trapped. At doc build time, ipython's output and std err will be
41 inserted, and prompts will be renumbered. So the prompt below should
41 inserted, and prompts will be renumbered. So the prompt below should
42 be renumbered in the rendered docs, and pick up where the block above
42 be renumbered in the rendered docs, and pick up where the block above
43 left off.
43 left off.
44
44
45 .. ipython::
45 .. ipython::
46
46
47 In [138]: z = x*3 # x is recalled from previous block
47 In [138]: z = x*3 # x is recalled from previous block
48
48
49 In [139]: z
49 In [139]: z
50 Out[139]: 6
50 Out[139]: 6
51
51
52 In [140]: print z
52 In [140]: print z
53 --------> print(z)
53 --------> print(z)
54 6
54 6
55
55
56 In [141]: q = z[) # this is a syntax error -- we trap ipy exceptions
56 In [141]: q = z[) # this is a syntax error -- we trap ipy exceptions
57 ------------------------------------------------------------
57 ------------------------------------------------------------
58 File "<ipython console>", line 1
58 File "<ipython console>", line 1
59 q = z[) # this is a syntax error -- we trap ipy exceptions
59 q = z[) # this is a syntax error -- we trap ipy exceptions
60 ^
60 ^
61 SyntaxError: invalid syntax
61 SyntaxError: invalid syntax
62
62
63
63
64 The embedded interpreter supports some limited markup. For example,
64 The embedded interpreter supports some limited markup. For example,
65 you can put comments in your ipython sessions, which are reported
65 you can put comments in your ipython sessions, which are reported
66 verbatim. There are some handy "pseudo-decorators" that let you
66 verbatim. There are some handy "pseudo-decorators" that let you
67 doctest the output. The inputs are fed to an embedded ipython
67 doctest the output. The inputs are fed to an embedded ipython
68 session and the outputs from the ipython session are inserted into
68 session and the outputs from the ipython session are inserted into
69 your doc. If the output in your doc and in the ipython session don't
69 your doc. If the output in your doc and in the ipython session don't
70 match on a doctest assertion, an error will be
70 match on a doctest assertion, an error will be
71
71
72
72
73 .. ipython::
73 .. ipython::
74
74
75 In [1]: x = 'hello world'
75 In [1]: x = 'hello world'
76
76
77 # this will raise an error if the ipython output is different
77 # this will raise an error if the ipython output is different
78 @doctest
78 @doctest
79 In [2]: x.upper()
79 In [2]: x.upper()
80 Out[2]: 'HELLO WORLD'
80 Out[2]: 'HELLO WORLD'
81
81
82 # some readline features cannot be supported, so we allow
82 # some readline features cannot be supported, so we allow
83 # "verbatim" blocks, which are dumped in verbatim except prompts
83 # "verbatim" blocks, which are dumped in verbatim except prompts
84 # are continuously numbered
84 # are continuously numbered
85 @verbatim
85 @verbatim
86 In [3]: x.st<TAB>
86 In [3]: x.st<TAB>
87 x.startswith x.strip
87 x.startswith x.strip
88
88
89
89
90 Multi-line input is supported.
90 Multi-line input is supported.
91
91
92 .. ipython::
92 .. ipython::
93
93
94 In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\
94 In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\
95 .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv'
95 .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv'
96
96
97 In [131]: print url.split('&')
97 In [131]: print url.split('&')
98 --------> print(url.split('&'))
98 --------> print(url.split('&'))
99 ['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22',
99 ['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22',
100
100
101 You can do doctesting on multi-line output as well. Just be careful
101 You can do doctesting on multi-line output as well. Just be careful
102 when using non-deterministic inputs like random numbers in the ipython
102 when using non-deterministic inputs like random numbers in the ipython
103 directive, because your inputs are ruin through a live interpreter, so
103 directive, because your inputs are ruin through a live interpreter, so
104 if you are doctesting random output you will get an error. Here we
104 if you are doctesting random output you will get an error. Here we
105 "seed" the random number generator for deterministic output, and we
105 "seed" the random number generator for deterministic output, and we
106 suppress the seed line so it doesn't show up in the rendered output
106 suppress the seed line so it doesn't show up in the rendered output
107
107
108 .. ipython::
108 .. ipython::
109
109
110 In [133]: import numpy.random
110 In [133]: import numpy.random
111
111
112 @suppress
112 @suppress
113 In [134]: numpy.random.seed(2358)
113 In [134]: numpy.random.seed(2358)
114
114
115 @doctest
115 @doctest
116 In [135]: numpy.random.rand(10,2)
116 In [135]: numpy.random.rand(10,2)
117 Out[135]:
117 Out[135]:
118 array([[ 0.64524308, 0.59943846],
118 array([[ 0.64524308, 0.59943846],
119 [ 0.47102322, 0.8715456 ],
119 [ 0.47102322, 0.8715456 ],
120 [ 0.29370834, 0.74776844],
120 [ 0.29370834, 0.74776844],
121 [ 0.99539577, 0.1313423 ],
121 [ 0.99539577, 0.1313423 ],
122 [ 0.16250302, 0.21103583],
122 [ 0.16250302, 0.21103583],
123 [ 0.81626524, 0.1312433 ],
123 [ 0.81626524, 0.1312433 ],
124 [ 0.67338089, 0.72302393],
124 [ 0.67338089, 0.72302393],
125 [ 0.7566368 , 0.07033696],
125 [ 0.7566368 , 0.07033696],
126 [ 0.22591016, 0.77731835],
126 [ 0.22591016, 0.77731835],
127 [ 0.0072729 , 0.34273127]])
127 [ 0.0072729 , 0.34273127]])
128
128
129
129
130 Another demonstration of multi-line input and output
130 Another demonstration of multi-line input and output
131
131
132 .. ipython::
132 .. ipython::
133
133
134 In [106]: print x
134 In [106]: print x
135 --------> print(x)
135 --------> print(x)
136 jdh
136 jdh
137
137
138 In [109]: for i in range(10):
138 In [109]: for i in range(10):
139 .....: print i
139 .....: print i
140 .....:
140 .....:
141 .....:
141 .....:
142 0
142 0
143 1
143 1
144 2
144 2
145 3
145 3
146 4
146 4
147 5
147 5
148 6
148 6
149 7
149 7
150 8
150 8
151 9
151 9
152
152
153
153
154 Most of the "pseudo-decorators" can be used an options to ipython
154 Most of the "pseudo-decorators" can be used an options to ipython
155 mode. For example, to setup matplotlib pylab but suppress the output,
155 mode. For example, to setup matplotlib pylab but suppress the output,
156 you can do. When using the matplotlib ``use`` directive, it should
156 you can do. When using the matplotlib ``use`` directive, it should
157 occur before any import of pylab. This will not show up in the
157 occur before any import of pylab. This will not show up in the
158 rendered docs, but the commands will be executed in the embedded
158 rendered docs, but the commands will be executed in the embedded
159 interpreter and subsequent line numbers will be incremented to reflect
159 interpreter and subsequent line numbers will be incremented to reflect
160 the inputs::
160 the inputs::
161
161
162
162
163 .. ipython::
163 .. ipython::
164 :suppress:
164 :suppress:
165
165
166 In [144]: from pylab import *
166 In [144]: from pylab import *
167
167
168 In [145]: ion()
168 In [145]: ion()
169
169
170 .. ipython::
170 .. ipython::
171 :suppress:
171 :suppress:
172
172
173 In [144]: from pylab import *
173 In [144]: from pylab import *
174
174
175 In [145]: ion()
175 In [145]: ion()
176
176
177 Likewise, you can set ``:doctest:`` or ``:verbatim:`` to apply these
177 Likewise, you can set ``:doctest:`` or ``:verbatim:`` to apply these
178 settings to the entire block. For example,
178 settings to the entire block. For example,
179
179
180 .. ipython::
180 .. ipython::
181 :verbatim:
181 :verbatim:
182
182
183 In [9]: cd mpl/examples/
183 In [9]: cd mpl/examples/
184 /home/jdhunter/mpl/examples
184 /home/jdhunter/mpl/examples
185
185
186 In [10]: pwd
186 In [10]: pwd
187 Out[10]: '/home/jdhunter/mpl/examples'
187 Out[10]: '/home/jdhunter/mpl/examples'
188
188
189
189
190 In [14]: cd mpl/examples/<TAB>
190 In [14]: cd mpl/examples/<TAB>
191 mpl/examples/animation/ mpl/examples/misc/
191 mpl/examples/animation/ mpl/examples/misc/
192 mpl/examples/api/ mpl/examples/mplot3d/
192 mpl/examples/api/ mpl/examples/mplot3d/
193 mpl/examples/axes_grid/ mpl/examples/pylab_examples/
193 mpl/examples/axes_grid/ mpl/examples/pylab_examples/
194 mpl/examples/event_handling/ mpl/examples/widgets
194 mpl/examples/event_handling/ mpl/examples/widgets
195
195
196 In [14]: cd mpl/examples/widgets/
196 In [14]: cd mpl/examples/widgets/
197 /home/msierig/mpl/examples/widgets
197 /home/msierig/mpl/examples/widgets
198
198
199 In [15]: !wc *
199 In [15]: !wc *
200 2 12 77 README.txt
200 2 12 77 README.txt
201 40 97 884 buttons.py
201 40 97 884 buttons.py
202 26 90 712 check_buttons.py
202 26 90 712 check_buttons.py
203 19 52 416 cursor.py
203 19 52 416 cursor.py
204 180 404 4882 menu.py
204 180 404 4882 menu.py
205 16 45 337 multicursor.py
205 16 45 337 multicursor.py
206 36 106 916 radio_buttons.py
206 36 106 916 radio_buttons.py
207 48 226 2082 rectangle_selector.py
207 48 226 2082 rectangle_selector.py
208 43 118 1063 slider_demo.py
208 43 118 1063 slider_demo.py
209 40 124 1088 span_selector.py
209 40 124 1088 span_selector.py
210 450 1274 12457 total
210 450 1274 12457 total
211
211
212 You can create one or more pyplot plots and insert them with the
212 You can create one or more pyplot plots and insert them with the
213 ``@savefig`` decorator.
213 ``@savefig`` decorator.
214
214
215 .. ipython::
215 .. ipython::
216
216
217 @savefig plot_simple.png width=4in
217 @savefig plot_simple.png width=4in
218 In [151]: plot([1,2,3]);
218 In [151]: plot([1,2,3]);
219
219
220 # use a semicolon to suppress the output
220 # use a semicolon to suppress the output
221 @savefig hist_simple.png width=4in
221 @savefig hist_simple.png width=4in
222 In [151]: hist(np.random.randn(10000), 100);
222 In [151]: hist(np.random.randn(10000), 100);
223
223
224 In a subsequent session, we can update the current figure with some
224 In a subsequent session, we can update the current figure with some
225 text, and then resave
225 text, and then resave
226
226
227 .. ipython::
227 .. ipython::
228
228
229
229
230 In [151]: ylabel('number')
230 In [151]: ylabel('number')
231
231
232 In [152]: title('normal distribution')
232 In [152]: title('normal distribution')
233
233
234 @savefig hist_with_text.png width=4in
234 @savefig hist_with_text.png width=4in
235 In [153]: grid(True)
235 In [153]: grid(True)
236
236
237 You can also have function definitions included in the source.
237 You can also have function definitions included in the source.
238
238
239 .. ipython::
239 .. ipython::
240
240
241 In [3]: def square(x):
241 In [3]: def square(x):
242 ...: """
242 ...: """
243 ...: An overcomplicated square function as an example.
243 ...: An overcomplicated square function as an example.
244 ...: """
244 ...: """
245 ...: if x < 0:
245 ...: if x < 0:
246 ...: x = abs(x)
246 ...: x = abs(x)
247 ...: y = x * x
247 ...: y = x * x
248 ...: return y
248 ...: return y
249 ...:
249 ...:
250
250
251 Then call it from a subsequent section.
251 Then call it from a subsequent section.
252
252
253 .. ipython::
253 .. ipython::
254
254
255 In [4]: square(3)
255 In [4]: square(3)
256 Out [4]: 9
256 Out [4]: 9
257
257
258 In [5]: square(-2)
258 In [5]: square(-2)
259 Out [5]: 4
259 Out [5]: 4
260
260
261
261
262 Writing Pure Python Code
262 Writing Pure Python Code
263 ------------------------
263 ------------------------
264
264
265 Pure python code is supported by the optional argument `python`. In this pure
265 Pure python code is supported by the optional argument `python`. In this pure
266 python syntax you do not include the output from the python interpreter. The
266 python syntax you do not include the output from the python interpreter. The
267 following markup::
267 following markup::
268
268
269 .. ipython:: python
269 .. ipython:: python
270
270
271 foo = 'bar'
271 foo = 'bar'
272 print foo
272 print foo
273 foo = 2
273 foo = 2
274 foo**2
274 foo**2
275
275
276 Renders as
276 Renders as
277
277
278 .. ipython:: python
278 .. ipython:: python
279
279
280 foo = 'bar'
280 foo = 'bar'
281 print foo
281 print foo
282 foo = 2
282 foo = 2
283 foo**2
283 foo**2
284
284
285 We can even plot from python, using the savefig decorator, as well as, suppress
285 We can even plot from python, using the savefig decorator, as well as, suppress
286 output with a semicolon
286 output with a semicolon
287
287
288 .. ipython:: python
288 .. ipython:: python
289
289
290 @savefig plot_simple_python.png width=4in
290 @savefig plot_simple_python.png width=4in
291 plot([1,2,3]);
291 plot([1,2,3]);
292
292
293 Similarly, std err is inserted
293 Similarly, std err is inserted
294
294
295 .. ipython:: python
295 .. ipython:: python
296
296
297 foo = 'bar'
297 foo = 'bar'
298 foo[)
298 foo[)
299
299
300 Comments are handled and state is preserved
300 Comments are handled and state is preserved
301
301
302 .. ipython:: python
302 .. ipython:: python
303
303
304 # comments are handled
304 # comments are handled
305 print foo
305 print foo
306
306
307 If you don't see the next code block then the options work.
307 If you don't see the next code block then the options work.
308
308
309 .. ipython:: python
309 .. ipython:: python
310 :suppress:
310 :suppress:
311
311
312 ioff()
312 ioff()
313 ion()
313 ion()
314
314
315 Multi-line input is handled.
315 Multi-line input is handled.
316
316
317 .. ipython:: python
317 .. ipython:: python
318
318
319 line = 'Multi\
319 line = 'Multi\
320 line &\
320 line &\
321 support &\
321 support &\
322 works'
322 works'
323 print line.split('&')
323 print line.split('&')
324
324
325 Functions definitions are correctly parsed
325 Functions definitions are correctly parsed
326
326
327 .. ipython:: python
327 .. ipython:: python
328
328
329 def square(x):
329 def square(x):
330 """
330 """
331 An overcomplicated square function as an example.
331 An overcomplicated square function as an example.
332 """
332 """
333 if x < 0:
333 if x < 0:
334 x = abs(x)
334 x = abs(x)
335 y = x * x
335 y = x * x
336 return y
336 return y
337
337
338 And persist across sessions
338 And persist across sessions
339
339
340 .. ipython:: python
340 .. ipython:: python
341
341
342 print square(3)
342 print square(3)
343 print square(-2)
343 print square(-2)
344
344
345 Pretty much anything you can do with the ipython code, you can do with
345 Pretty much anything you can do with the ipython code, you can do with
346 with a simple python script. Obviously, though it doesn't make sense
346 with a simple python script. Obviously, though it doesn't make sense
347 to use the doctest option.
347 to use the doctest option.
348
348
349 Pseudo-Decorators
349 Pseudo-Decorators
350 =================
350 =================
351
351
352 Here are the supported decorators, and any optional arguments they
352 Here are the supported decorators, and any optional arguments they
353 take. Some of the decorators can be used as options to the entire
353 take. Some of the decorators can be used as options to the entire
354 block (eg ``verbatim`` and ``suppress``), and some only apply to the
354 block (eg ``verbatim`` and ``suppress``), and some only apply to the
355 line just below them (eg ``savefig``).
355 line just below them (eg ``savefig``).
356
356
357 @suppress
357 @suppress
358
358
359 execute the ipython input block, but suppress the input and output
359 execute the ipython input block, but suppress the input and output
360 block from the rendered output. Also, can be applied to the entire
360 block from the rendered output. Also, can be applied to the entire
361 ``..ipython`` block as a directive option with ``:suppress:``.
361 ``..ipython`` block as a directive option with ``:suppress:``.
362
362
363 @verbatim
363 @verbatim
364
364
365 insert the input and output block in verbatim, but auto-increment
365 insert the input and output block in verbatim, but auto-increment
366 the line numbers. Internally, the interpreter will be fed an empty
366 the line numbers. Internally, the interpreter will be fed an empty
367 string, so it is a no-op that keeps line numbering consistent.
367 string, so it is a no-op that keeps line numbering consistent.
368 Also, can be applied to the entire ``..ipython`` block as a
368 Also, can be applied to the entire ``..ipython`` block as a
369 directive option with ``:verbatim:``.
369 directive option with ``:verbatim:``.
370
370
371 @savefig OUTFILE [IMAGE_OPTIONS]
371 @savefig OUTFILE [IMAGE_OPTIONS]
372
372
373 save the figure to the static directory and insert it into the
373 save the figure to the static directory and insert it into the
374 document, possibly binding it into a minipage and/or putting
374 document, possibly binding it into a minipage and/or putting
375 code/figure label/references to associate the code and the
375 code/figure label/references to associate the code and the
376 figure. Takes args to pass to the image directive (*scale*,
376 figure. Takes args to pass to the image directive (*scale*,
377 *width*, etc can be kwargs); see `image options
377 *width*, etc can be kwargs); see `image options
378 <http://docutils.sourceforge.net/docs/ref/rst/directives.html#image>`_
378 <http://docutils.sourceforge.net/docs/ref/rst/directives.html#image>`_
379 for details.
379 for details.
380
380
381 @doctest
381 @doctest
382
382
383 Compare the pasted in output in the ipython block with the output
383 Compare the pasted in output in the ipython block with the output
384 generated at doc build time, and raise errors if they donÒ€ℒt
384 generated at doc build time, and raise errors if they donÒ€ℒt
385 match. Also, can be applied to the entire ``..ipython`` block as a
385 match. Also, can be applied to the entire ``..ipython`` block as a
386 directive option with ``:doctest:``.
386 directive option with ``:doctest:``.
387
387
388 Configuration Options
388 Configuration Options
389 =====================
389 =====================
390
390
391 ipython_savefig_dir
391 ipython_savefig_dir
392
392
393 The directory in which to save the figures. This is relative to the
393 The directory in which to save the figures. This is relative to the
394 Sphinx source directory. The default is `html_static_path`.
394 Sphinx source directory. The default is `html_static_path`.
395
395
396 ipython_rgxin
396 ipython_rgxin
397
397
398 The compiled regular expression to denote the start of IPython input
398 The compiled regular expression to denote the start of IPython input
399 lines. The default is re.compile('In \[(\d+)\]:\s?(.*)\s*'). You
399 lines. The default is re.compile('In \[(\d+)\]:\s?(.*)\s*'). You
400 shouldn't need to change this.
400 shouldn't need to change this.
401
401
402 ipython_rgxout
402 ipython_rgxout
403
403
404 The compiled regular expression to denote the start of IPython output
404 The compiled regular expression to denote the start of IPython output
405 lines. The default is re.compile('Out\[(\d+)\]:\s?(.*)\s*'). You
405 lines. The default is re.compile('Out\[(\d+)\]:\s?(.*)\s*'). You
406 shouldn't need to change this.
406 shouldn't need to change this.
407
407
408
408
409 ipython_promptin
409 ipython_promptin
410
410
411 The string to represent the IPython input prompt in the generated ReST.
411 The string to represent the IPython input prompt in the generated ReST.
412 The default is 'In [%d]:'. This expects that the line numbers are used
412 The default is 'In [%d]:'. This expects that the line numbers are used
413 in the prompt.
413 in the prompt.
414
414
415 ipython_promptout
415 ipython_promptout
416
416
417 The string to represent the IPython prompt in the generated ReST. The
417 The string to represent the IPython prompt in the generated ReST. The
418 default is 'Out [%d]:'. This expects that the line numbers are used
418 default is 'Out [%d]:'. This expects that the line numbers are used
419 in the prompt.
419 in the prompt.
420
421 .. _ipython_literal:
422
423 Sphinx source for this tutorial
424 ===============================
425
426 .. literalinclude:: ipython_directive.rst
427
General Comments 0
You need to be logged in to leave comments. Login now