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