##// END OF EJS Templates
DOC: Add ipython_directive to developer docs
Skipper Seabold -
Show More
@@ -0,0 +1,427 b''
1 .. _ipython_directive:
2
3 ========================
4 Ipython Sphinx Directive
5 ========================
6
7 The ipython directive is a stateful ipython shell for embedding in
8 sphinx documents. It knows about standard ipython prompts, and
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
11 interpreter and the outputs from that interpreter will be inserted as
12 well. For example, code blocks like the following::
13
14 .. ipython::
15
16 In [136]: x = 2
17
18 In [137]: x**3
19 Out[137]: 8
20
21 will be rendered as
22
23 .. ipython::
24
25 In [136]: x = 2
26
27 In [137]: x**3
28 Out[137]: 8
29
30 .. note::
31
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
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
36 document that generates the rendered output.
37
38
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
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
43 left off.
44
45 .. ipython::
46
47 In [138]: z = x*3 # x is recalled from previous block
48
49 In [139]: z
50 Out[139]: 6
51
52 In [140]: print z
53 --------> print(z)
54 6
55
56 In [141]: q = z[) # this is a syntax error -- we trap ipy exceptions
57 ------------------------------------------------------------
58 File "<ipython console>", line 1
59 q = z[) # this is a syntax error -- we trap ipy exceptions
60 ^
61 SyntaxError: invalid syntax
62
63
64 The embedded interpreter supports some limited markup. For example,
65 you can put comments in your ipython sessions, which are reported
66 verbatim. There are some handy "pseudo-decorators" that let you
67 doctest the output. The inputs are fed to an embedded ipython
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
70 match on a doctest assertion, an error will be
71
72
73 .. ipython::
74
75 In [1]: x = 'hello world'
76
77 # this will raise an error if the ipython output is different
78 @doctest
79 In [2]: x.upper()
80 Out[2]: 'HELLO WORLD'
81
82 # some readline features cannot be supported, so we allow
83 # "verbatim" blocks, which are dumped in verbatim except prompts
84 # are continuously numbered
85 @verbatim
86 In [3]: x.st<TAB>
87 x.startswith x.strip
88
89
90 Multi-line input is supported.
91
92 .. ipython::
93
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'
96
97 In [131]: print url.split('&')
98 --------> print(url.split('&'))
99 ['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22',
100
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
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
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
107
108 .. ipython::
109
110 In [133]: import numpy.random
111
112 @suppress
113 In [134]: numpy.random.seed(2358)
114
115 @doctest
116 In [135]: numpy.random.rand(10,2)
117 Out[135]:
118 array([[ 0.64524308, 0.59943846],
119 [ 0.47102322, 0.8715456 ],
120 [ 0.29370834, 0.74776844],
121 [ 0.99539577, 0.1313423 ],
122 [ 0.16250302, 0.21103583],
123 [ 0.81626524, 0.1312433 ],
124 [ 0.67338089, 0.72302393],
125 [ 0.7566368 , 0.07033696],
126 [ 0.22591016, 0.77731835],
127 [ 0.0072729 , 0.34273127]])
128
129
130 Another demonstration of multi-line input and output
131
132 .. ipython::
133
134 In [106]: print x
135 --------> print(x)
136 jdh
137
138 In [109]: for i in range(10):
139 .....: print i
140 .....:
141 .....:
142 0
143 1
144 2
145 3
146 4
147 5
148 6
149 7
150 8
151 9
152
153
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,
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
158 rendered docs, but the commands will be executed in the embedded
159 interpreter and subsequent line numbers will be incremented to reflect
160 the inputs::
161
162
163 .. ipython::
164 :suppress:
165
166 In [144]: from pylab import *
167
168 In [145]: ion()
169
170 .. ipython::
171 :suppress:
172
173 In [144]: from pylab import *
174
175 In [145]: ion()
176
177 Likewise, you can set ``:doctest:`` or ``:verbatim:`` to apply these
178 settings to the entire block. For example,
179
180 .. ipython::
181 :verbatim:
182
183 In [9]: cd mpl/examples/
184 /home/jdhunter/mpl/examples
185
186 In [10]: pwd
187 Out[10]: '/home/jdhunter/mpl/examples'
188
189
190 In [14]: cd mpl/examples/<TAB>
191 mpl/examples/animation/ mpl/examples/misc/
192 mpl/examples/api/ mpl/examples/mplot3d/
193 mpl/examples/axes_grid/ mpl/examples/pylab_examples/
194 mpl/examples/event_handling/ mpl/examples/widgets
195
196 In [14]: cd mpl/examples/widgets/
197 /home/msierig/mpl/examples/widgets
198
199 In [15]: !wc *
200 2 12 77 README.txt
201 40 97 884 buttons.py
202 26 90 712 check_buttons.py
203 19 52 416 cursor.py
204 180 404 4882 menu.py
205 16 45 337 multicursor.py
206 36 106 916 radio_buttons.py
207 48 226 2082 rectangle_selector.py
208 43 118 1063 slider_demo.py
209 40 124 1088 span_selector.py
210 450 1274 12457 total
211
212 You can create one or more pyplot plots and insert them with the
213 ``@savefig`` decorator.
214
215 .. ipython::
216
217 @savefig plot_simple.png width=4in
218 In [151]: plot([1,2,3]);
219
220 # use a semicolon to suppress the output
221 @savefig hist_simple.png width=4in
222 In [151]: hist(np.random.randn(10000), 100);
223
224 In a subsequent session, we can update the current figure with some
225 text, and then resave
226
227 .. ipython::
228
229
230 In [151]: ylabel('number')
231
232 In [152]: title('normal distribution')
233
234 @savefig hist_with_text.png width=4in
235 In [153]: grid(True)
236
237 You can also have function definitions included in the source.
238
239 .. ipython::
240
241 In [3]: def square(x):
242 ...: """
243 ...: An overcomplicated square function as an example.
244 ...: """
245 ...: if x < 0:
246 ...: x = abs(x)
247 ...: y = x * x
248 ...: return y
249 ...:
250
251 Then call it from a subsequent section.
252
253 .. ipython::
254
255 In [4]: square(3)
256 Out [4]: 9
257
258 In [5]: square(-2)
259 Out [5]: 4
260
261
262 Writing Pure Python Code
263 ------------------------
264
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
267 following markup::
268
269 .. ipython:: python
270
271 foo = 'bar'
272 print foo
273 foo = 2
274 foo**2
275
276 Renders as
277
278 .. ipython:: python
279
280 foo = 'bar'
281 print foo
282 foo = 2
283 foo**2
284
285 We can even plot from python, using the savefig decorator, as well as, suppress
286 output with a semicolon
287
288 .. ipython:: python
289
290 @savefig plot_simple_python.png width=4in
291 plot([1,2,3]);
292
293 Similarly, std err is inserted
294
295 .. ipython:: python
296
297 foo = 'bar'
298 foo[)
299
300 Comments are handled and state is preserved
301
302 .. ipython:: python
303
304 # comments are handled
305 print foo
306
307 If you don't see the next code block then the options work.
308
309 .. ipython:: python
310 :suppress:
311
312 ioff()
313 ion()
314
315 Multi-line input is handled.
316
317 .. ipython:: python
318
319 line = 'Multi\
320 line &\
321 support &\
322 works'
323 print line.split('&')
324
325 Functions definitions are correctly parsed
326
327 .. ipython:: python
328
329 def square(x):
330 """
331 An overcomplicated square function as an example.
332 """
333 if x < 0:
334 x = abs(x)
335 y = x * x
336 return y
337
338 And persist across sessions
339
340 .. ipython:: python
341
342 print square(3)
343 print square(-2)
344
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
347 to use the doctest option.
348
349 Pseudo-Decorators
350 =================
351
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
354 block (eg ``verbatim`` and ``suppress``), and some only apply to the
355 line just below them (eg ``savefig``).
356
357 @suppress
358
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
361 ``..ipython`` block as a directive option with ``:suppress:``.
362
363 @verbatim
364
365 insert the input and output block in verbatim, but auto-increment
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.
368 Also, can be applied to the entire ``..ipython`` block as a
369 directive option with ``:verbatim:``.
370
371 @savefig OUTFILE [IMAGE_OPTIONS]
372
373 save the figure to the static directory and insert it into the
374 document, possibly binding it into a minipage and/or putting
375 code/figure label/references to associate the code and the
376 figure. Takes args to pass to the image directive (*scale*,
377 *width*, etc can be kwargs); see `image options
378 <http://docutils.sourceforge.net/docs/ref/rst/directives.html#image>`_
379 for details.
380
381 @doctest
382
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
385 match. Also, can be applied to the entire ``..ipython`` block as a
386 directive option with ``:doctest:``.
387
388 Configuration Options
389 =====================
390
391 ipython_savefig_dir
392
393 The directory in which to save the figures. This is relative to the
394 Sphinx source directory. The default is `html_static_path`.
395
396 ipython_rgxin
397
398 The compiled regular expression to denote the start of IPython input
399 lines. The default is re.compile('In \[(\d+)\]:\s?(.*)\s*'). You
400 shouldn't need to change this.
401
402 ipython_rgxout
403
404 The compiled regular expression to denote the start of IPython output
405 lines. The default is re.compile('Out\[(\d+)\]:\s?(.*)\s*'). You
406 shouldn't need to change this.
407
408
409 ipython_promptin
410
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
413 in the prompt.
414
415 ipython_promptout
416
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
419 in the prompt.
420
421 .. _ipython_literal:
422
423 Sphinx source for this tutorial
424 ===============================
425
426 .. literalinclude:: ipython_directive.rst
427
@@ -1,199 +1,200 b''
1 1 # -*- coding: utf-8 -*-
2 2 #
3 3 # IPython documentation build configuration file.
4 4
5 5 # NOTE: This file has been edited manually from the auto-generated one from
6 6 # sphinx. Do NOT delete and re-generate. If any changes from sphinx are
7 7 # needed, generate a scratch one and merge by hand any new fields needed.
8 8
9 9 #
10 10 # This file is execfile()d with the current directory set to its containing dir.
11 11 #
12 12 # The contents of this file are pickled, so don't put values in the namespace
13 13 # that aren't pickleable (module imports are okay, they're removed automatically).
14 14 #
15 15 # All configuration values have a default value; values that are commented out
16 16 # serve to show the default value.
17 17
18 18 import sys, os
19 19
20 20 # If your extensions are in another directory, add it here. If the directory
21 21 # is relative to the documentation root, use os.path.abspath to make it
22 22 # absolute, like shown here.
23 23 sys.path.insert(0, os.path.abspath('../sphinxext'))
24 24
25 25 # Import support for ipython console session syntax highlighting (lives
26 26 # in the sphinxext directory defined above)
27 27 import ipython_console_highlighting
28 28
29 29 # We load the ipython release info into a dict by explicit execution
30 30 iprelease = {}
31 31 execfile('../../IPython/core/release.py',iprelease)
32 32
33 33 # General configuration
34 34 # ---------------------
35 35
36 36 # Add any Sphinx extension module names here, as strings. They can be extensions
37 37 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
38 38 extensions = [
39 39 # 'matplotlib.sphinxext.mathmpl',
40 40 'matplotlib.sphinxext.only_directives',
41 41 # 'matplotlib.sphinxext.plot_directive',
42 42 'sphinx.ext.autodoc',
43 43 'sphinx.ext.doctest',
44 44 'inheritance_diagram',
45 45 'ipython_console_highlighting',
46 'ipython_directive',
46 47 'numpydoc', # to preprocess docstrings
47 48 'github', # for easy GitHub links
48 49 ]
49 50
50 51 # Add any paths that contain templates here, relative to this directory.
51 52 templates_path = ['_templates']
52 53
53 54 # The suffix of source filenames.
54 55 source_suffix = '.txt'
55 56
56 57 # The master toctree document.
57 58 master_doc = 'index'
58 59
59 60 # General substitutions.
60 61 project = 'IPython'
61 62 copyright = '2008, The IPython Development Team'
62 63
63 64 # ghissue config
64 65 github_project_url = "https://github.com/ipython/ipython"
65 66
66 67 # The default replacements for |version| and |release|, also used in various
67 68 # other places throughout the built documents.
68 69 #
69 70 # The full version, including alpha/beta/rc tags.
70 71 release = iprelease['version']
71 72 # The short X.Y version.
72 73 version = '.'.join(release.split('.',2)[:2])
73 74
74 75
75 76 # There are two options for replacing |today|: either, you set today to some
76 77 # non-false value, then it is used:
77 78 #today = ''
78 79 # Else, today_fmt is used as the format for a strftime call.
79 80 today_fmt = '%B %d, %Y'
80 81
81 82 # List of documents that shouldn't be included in the build.
82 83 #unused_docs = []
83 84
84 85 # List of directories, relative to source directories, that shouldn't be searched
85 86 # for source files.
86 87 exclude_dirs = ['attic']
87 88
88 89 # If true, '()' will be appended to :func: etc. cross-reference text.
89 90 #add_function_parentheses = True
90 91
91 92 # If true, the current module name will be prepended to all description
92 93 # unit titles (such as .. function::).
93 94 #add_module_names = True
94 95
95 96 # If true, sectionauthor and moduleauthor directives will be shown in the
96 97 # output. They are ignored by default.
97 98 #show_authors = False
98 99
99 100 # The name of the Pygments (syntax highlighting) style to use.
100 101 pygments_style = 'sphinx'
101 102
102 103
103 104 # Options for HTML output
104 105 # -----------------------
105 106
106 107 # The style sheet to use for HTML and HTML Help pages. A file of that name
107 108 # must exist either in Sphinx' static/ path, or in one of the custom paths
108 109 # given in html_static_path.
109 110 html_style = 'default.css'
110 111
111 112 # The name for this set of Sphinx documents. If None, it defaults to
112 113 # "<project> v<release> documentation".
113 114 #html_title = None
114 115
115 116 # The name of an image file (within the static path) to place at the top of
116 117 # the sidebar.
117 118 #html_logo = None
118 119
119 120 # Add any paths that contain custom static files (such as style sheets) here,
120 121 # relative to this directory. They are copied after the builtin static files,
121 122 # so a file named "default.css" will overwrite the builtin "default.css".
122 123 html_static_path = ['_static']
123 124
124 125 # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
125 126 # using the given strftime format.
126 127 html_last_updated_fmt = '%b %d, %Y'
127 128
128 129 # If true, SmartyPants will be used to convert quotes and dashes to
129 130 # typographically correct entities.
130 131 #html_use_smartypants = True
131 132
132 133 # Custom sidebar templates, maps document names to template names.
133 134 #html_sidebars = {}
134 135
135 136 # Additional templates that should be rendered to pages, maps page names to
136 137 # template names.
137 138 #html_additional_pages = {}
138 139
139 140 # If false, no module index is generated.
140 141 #html_use_modindex = True
141 142
142 143 # If true, the reST sources are included in the HTML build as _sources/<name>.
143 144 #html_copy_source = True
144 145
145 146 # If true, an OpenSearch description file will be output, and all pages will
146 147 # contain a <link> tag referring to it. The value of this option must be the
147 148 # base URL from which the finished HTML is served.
148 149 #html_use_opensearch = ''
149 150
150 151 # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
151 152 #html_file_suffix = ''
152 153
153 154 # Output file base name for HTML help builder.
154 155 htmlhelp_basename = 'ipythondoc'
155 156
156 157
157 158 # Options for LaTeX output
158 159 # ------------------------
159 160
160 161 # The paper size ('letter' or 'a4').
161 162 latex_paper_size = 'letter'
162 163
163 164 # The font size ('10pt', '11pt' or '12pt').
164 165 latex_font_size = '11pt'
165 166
166 167 # Grouping the document tree into LaTeX files. List of tuples
167 168 # (source start file, target name, title, author, document class [howto/manual]).
168 169
169 170 latex_documents = [
170 171 ('index', 'ipython.tex', 'IPython Documentation',
171 172 ur"""The IPython Development Team""", 'manual', True),
172 173 ('parallel/winhpc_index', 'winhpc_whitepaper.tex',
173 174 'Using IPython on Windows HPC Server 2008',
174 175 ur"Brian E. Granger", 'manual', True)
175 176 ]
176 177
177 178 # The name of an image file (relative to this directory) to place at the top of
178 179 # the title page.
179 180 #latex_logo = None
180 181
181 182 # For "manual" documents, if this is true, then toplevel headings are parts,
182 183 # not chapters.
183 184 #latex_use_parts = False
184 185
185 186 # Additional stuff for the LaTeX preamble.
186 187 #latex_preamble = ''
187 188
188 189 # Documents to append as an appendix to all manuals.
189 190 #latex_appendices = []
190 191
191 192 # If false, no module index is generated.
192 193 latex_use_modindex = True
193 194
194 195
195 196 # Cleanup
196 197 # -------
197 198 # delete release info to avoid pickling errors from sphinx
198 199
199 200 del iprelease
@@ -1,25 +1,26 b''
1 1 .. _developer_guide:
2 2
3 3 =========================
4 4 IPython developer's guide
5 5 =========================
6 6
7 7 .. toctree::
8 8 :maxdepth: 1
9 9
10 10 contributing.txt
11 11 gitwash/index.txt
12 12 coding_guide.txt
13 13 doc_guide.txt
14 14 testing.txt
15 15 release.txt
16 16 roadmap.txt
17 17 reorg.txt
18 18 messaging.txt
19 19 parallel_messages.txt
20 20 parallel_connections.txt
21 21 magic_blueprint.txt
22 22 ipgraph.txt
23 23 ipython_qt.txt
24 24 ipythonzmq.txt
25 25 notebook_todo.txt
26 ipython_directive.txt
General Comments 0
You need to be logged in to leave comments. Login now