##// END OF EJS Templates
DOC: extensions: add documentation for the bundled extensions
Pauli Virtanen -
Show More
@@ -0,0 +1,7 b''
1 .. _extensions_autoreload:
2
3 ==========
4 autoreload
5 ==========
6
7 .. automodule:: IPython.extensions.autoreload
@@ -0,0 +1,7 b''
1 .. _extensions_parallelmagic:
2
3 =============
4 parallelmagic
5 =============
6
7 .. automodule:: IPython.extensions.parallelmagic
@@ -0,0 +1,7 b''
1 .. _extensions_sympyprinting:
2
3 =============
4 sympyprinting
5 =============
6
7 .. automodule:: IPython.extensions.sympyprinting
@@ -1,299 +1,326 b''
1 1 # encoding: utf-8
2 """
3 =============
4 parallelmagic
5 =============
6
7 Magic command interface for interactive parallel work.
8
9 Usage
10 =====
11
12 ``%autopx``
13
14 @AUTOPX_DOC@
2 15
3 """Magic command interface for interactive parallel work."""
16 ``%px``
17
18 @PX_DOC@
19
20 ``%result``
21
22 @RESULT_DOC@
23
24 """
4 25
5 26 #-----------------------------------------------------------------------------
6 27 # Copyright (C) 2008-2009 The IPython Development Team
7 28 #
8 29 # Distributed under the terms of the BSD License. The full license is in
9 30 # the file COPYING, distributed as part of this software.
10 31 #-----------------------------------------------------------------------------
11 32
12 33 #-----------------------------------------------------------------------------
13 34 # Imports
14 35 #-----------------------------------------------------------------------------
15 36
16 37 import ast
17 38 import re
18 39
19 40 from IPython.core.plugin import Plugin
20 41 from IPython.utils.traitlets import Bool, Any, Instance
21 42 from IPython.testing.skipdoctest import skip_doctest
22 43
23 44 #-----------------------------------------------------------------------------
24 45 # Definitions of magic functions for use with IPython
25 46 #-----------------------------------------------------------------------------
26 47
27 48
28 49 NO_ACTIVE_VIEW = """
29 50 Use activate() on a DirectView object to activate it for magics.
30 51 """
31 52
32 53
33 54 class ParalleMagic(Plugin):
34 55 """A component to manage the %result, %px and %autopx magics."""
35 56
36 57 active_view = Instance('IPython.parallel.client.view.DirectView')
37 58 verbose = Bool(False, config=True)
38 59 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
39 60
40 61 def __init__(self, shell=None, config=None):
41 62 super(ParalleMagic, self).__init__(shell=shell, config=config)
42 63 self._define_magics()
43 64 # A flag showing if autopx is activated or not
44 65 self.autopx = False
45 66
46 67 def _define_magics(self):
47 68 """Define the magic functions."""
48 69 self.shell.define_magic('result', self.magic_result)
49 70 self.shell.define_magic('px', self.magic_px)
50 71 self.shell.define_magic('autopx', self.magic_autopx)
51 72
52 73 @skip_doctest
53 74 def magic_result(self, ipself, parameter_s=''):
54 75 """Print the result of command i on all engines..
55 76
56 77 To use this a :class:`DirectView` instance must be created
57 78 and then activated by calling its :meth:`activate` method.
58 79
59 80 Then you can do the following::
60 81
61 82 In [23]: %result
62 83 Out[23]:
63 84 <Results List>
64 85 [0] In [6]: a = 10
65 86 [1] In [6]: a = 10
66 87
67 88 In [22]: %result 6
68 89 Out[22]:
69 90 <Results List>
70 91 [0] In [6]: a = 10
71 92 [1] In [6]: a = 10
72 93 """
73 94 if self.active_view is None:
74 95 print NO_ACTIVE_VIEW
75 96 return
76 97
77 98 try:
78 99 index = int(parameter_s)
79 100 except:
80 101 index = None
81 102 result = self.active_view.get_result(index)
82 103 return result
83 104
84 105 @skip_doctest
85 106 def magic_px(self, ipself, parameter_s=''):
86 107 """Executes the given python command in parallel.
87 108
88 109 To use this a :class:`DirectView` instance must be created
89 110 and then activated by calling its :meth:`activate` method.
90 111
91 112 Then you can do the following::
92 113
93 114 In [24]: %px a = 5
94 115 Parallel execution on engine(s): all
95 116 Out[24]:
96 117 <Results List>
97 118 [0] In [7]: a = 5
98 119 [1] In [7]: a = 5
99 120 """
100 121
101 122 if self.active_view is None:
102 123 print NO_ACTIVE_VIEW
103 124 return
104 125 print "Parallel execution on engine(s): %s" % self.active_view.targets
105 126 result = self.active_view.execute(parameter_s, block=False)
106 127 if self.active_view.block:
107 128 result.get()
108 129 self._maybe_display_output(result)
109 130
110 131 @skip_doctest
111 132 def magic_autopx(self, ipself, parameter_s=''):
112 133 """Toggles auto parallel mode.
113 134
114 135 To use this a :class:`DirectView` instance must be created
115 136 and then activated by calling its :meth:`activate` method. Once this
116 137 is called, all commands typed at the command line are send to
117 138 the engines to be executed in parallel. To control which engine
118 139 are used, set the ``targets`` attributed of the multiengine client
119 140 before entering ``%autopx`` mode.
120 141
121 142 Then you can do the following::
122 143
123 144 In [25]: %autopx
124 145 %autopx to enabled
125 146
126 147 In [26]: a = 10
127 148 Parallel execution on engine(s): [0,1,2,3]
128 149 In [27]: print a
129 150 Parallel execution on engine(s): [0,1,2,3]
130 151 [stdout:0] 10
131 152 [stdout:1] 10
132 153 [stdout:2] 10
133 154 [stdout:3] 10
134 155
135 156
136 157 In [27]: %autopx
137 158 %autopx disabled
138 159 """
139 160 if self.autopx:
140 161 self._disable_autopx()
141 162 else:
142 163 self._enable_autopx()
143 164
144 165 def _enable_autopx(self):
145 166 """Enable %autopx mode by saving the original run_cell and installing
146 167 pxrun_cell.
147 168 """
148 169 if self.active_view is None:
149 170 print NO_ACTIVE_VIEW
150 171 return
151 172
152 173 # override run_cell and run_code
153 174 self._original_run_cell = self.shell.run_cell
154 175 self.shell.run_cell = self.pxrun_cell
155 176 self._original_run_code = self.shell.run_code
156 177 self.shell.run_code = self.pxrun_code
157 178
158 179 self.autopx = True
159 180 print "%autopx enabled"
160 181
161 182 def _disable_autopx(self):
162 183 """Disable %autopx by restoring the original InteractiveShell.run_cell.
163 184 """
164 185 if self.autopx:
165 186 self.shell.run_cell = self._original_run_cell
166 187 self.shell.run_code = self._original_run_code
167 188 self.autopx = False
168 189 print "%autopx disabled"
169 190
170 191 def _maybe_display_output(self, result):
171 192 """Maybe display the output of a parallel result.
172 193
173 194 If self.active_view.block is True, wait for the result
174 195 and display the result. Otherwise, this is a noop.
175 196 """
176 197 if isinstance(result.stdout, basestring):
177 198 # single result
178 199 stdouts = [result.stdout.rstrip()]
179 200 else:
180 201 stdouts = [s.rstrip() for s in result.stdout]
181 202
182 203 targets = self.active_view.targets
183 204 if isinstance(targets, int):
184 205 targets = [targets]
185 206 elif targets == 'all':
186 207 targets = self.active_view.client.ids
187 208
188 209 if any(stdouts):
189 210 for eid,stdout in zip(targets, stdouts):
190 211 print '[stdout:%i]'%eid, stdout
191 212
192 213
193 214 def pxrun_cell(self, raw_cell, store_history=True):
194 215 """drop-in replacement for InteractiveShell.run_cell.
195 216
196 217 This executes code remotely, instead of in the local namespace.
197 218
198 219 See InteractiveShell.run_cell for details.
199 220 """
200 221
201 222 if (not raw_cell) or raw_cell.isspace():
202 223 return
203 224
204 225 ipself = self.shell
205 226
206 227 with ipself.builtin_trap:
207 228 cell = ipself.prefilter_manager.prefilter_lines(raw_cell)
208 229
209 230 # Store raw and processed history
210 231 if store_history:
211 232 ipself.history_manager.store_inputs(ipself.execution_count,
212 233 cell, raw_cell)
213 234
214 235 # ipself.logger.log(cell, raw_cell)
215 236
216 237 cell_name = ipself.compile.cache(cell, ipself.execution_count)
217 238
218 239 try:
219 240 code_ast = ast.parse(cell, filename=cell_name)
220 241 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
221 242 # Case 1
222 243 ipself.showsyntaxerror()
223 244 ipself.execution_count += 1
224 245 return None
225 246 except NameError:
226 247 # ignore name errors, because we don't know the remote keys
227 248 pass
228 249
229 250 if store_history:
230 251 # Write output to the database. Does nothing unless
231 252 # history output logging is enabled.
232 253 ipself.history_manager.store_output(ipself.execution_count)
233 254 # Each cell is a *single* input, regardless of how many lines it has
234 255 ipself.execution_count += 1
235 256
236 257 if re.search(r'get_ipython\(\)\.magic\(u?"%?autopx', cell):
237 258 self._disable_autopx()
238 259 return False
239 260 else:
240 261 try:
241 262 result = self.active_view.execute(cell, block=False)
242 263 except:
243 264 ipself.showtraceback()
244 265 return True
245 266 else:
246 267 if self.active_view.block:
247 268 try:
248 269 result.get()
249 270 except:
250 271 self.shell.showtraceback()
251 272 return True
252 273 else:
253 274 self._maybe_display_output(result)
254 275 return False
255 276
256 277 def pxrun_code(self, code_obj):
257 278 """drop-in replacement for InteractiveShell.run_code.
258 279
259 280 This executes code remotely, instead of in the local namespace.
260 281
261 282 See InteractiveShell.run_code for details.
262 283 """
263 284 ipself = self.shell
264 285 # check code object for the autopx magic
265 286 if 'get_ipython' in code_obj.co_names and 'magic' in code_obj.co_names and \
266 287 any( [ isinstance(c, basestring) and 'autopx' in c for c in code_obj.co_consts ]):
267 288 self._disable_autopx()
268 289 return False
269 290 else:
270 291 try:
271 292 result = self.active_view.execute(code_obj, block=False)
272 293 except:
273 294 ipself.showtraceback()
274 295 return True
275 296 else:
276 297 if self.active_view.block:
277 298 try:
278 299 result.get()
279 300 except:
280 301 self.shell.showtraceback()
281 302 return True
282 303 else:
283 304 self._maybe_display_output(result)
284 305 return False
285 306
286 307
308 __doc__ = __doc__.replace('@AUTOPX_DOC@',
309 " " + ParalleMagic.magic_autopx.__doc__)
310 __doc__ = __doc__.replace('@PX_DOC@',
311 " " + ParalleMagic.magic_px.__doc__)
312 __doc__ = __doc__.replace('@RESULT_DOC@',
313 " " + ParalleMagic.magic_result.__doc__)
287 314
288 315
289 316 _loaded = False
290 317
291 318
292 319 def load_ipython_extension(ip):
293 320 """Load the extension in IPython."""
294 321 global _loaded
295 322 if not _loaded:
296 323 plugin = ParalleMagic(shell=ip, config=ip.config)
297 324 ip.plugin_manager.register_plugin('parallelmagic', plugin)
298 325 _loaded = True
299 326
@@ -1,91 +1,98 b''
1 """A print function that pretty prints sympy Basic objects.
1 """
2 A print function that pretty prints sympy Basic objects.
3
4 :moduleauthor: Brian Granger
5
6 Usage
7 =====
8
9 Once the extension is loaded, Sympy Basic objects are automatically
10 pretty-printed.
2 11
3 Authors:
4 * Brian Granger
5 12 """
6 13 #-----------------------------------------------------------------------------
7 14 # Copyright (C) 2008-2011 The IPython Development Team
8 15 #
9 16 # Distributed under the terms of the BSD License. The full license is in
10 17 # the file COPYING, distributed as part of this software.
11 18 #-----------------------------------------------------------------------------
12 19
13 20 #-----------------------------------------------------------------------------
14 21 # Imports
15 22 #-----------------------------------------------------------------------------
16 23
17 24 from IPython.lib.latextools import latex_to_png
18 25 from IPython.testing import decorators as dec
19 26 # use @dec.skipif_not_sympy to skip tests requiring sympy
20 27
21 28 try:
22 29 from sympy import pretty, latex
23 30 except ImportError:
24 31 pass
25 32
26 33
27 34 #-----------------------------------------------------------------------------
28 35 # Definitions of magic functions for use with IPython
29 36 #-----------------------------------------------------------------------------
30 37
31 38 def print_basic_unicode(o, p, cycle):
32 39 """A function to pretty print sympy Basic objects."""
33 40 if cycle:
34 41 return p.text('Basic(...)')
35 42 out = pretty(o, use_unicode=True)
36 43 if '\n' in out:
37 44 p.text(u'\n')
38 45 p.text(out)
39 46
40 47
41 48 def print_png(o):
42 49 """A function to display sympy expression using LaTex -> PNG."""
43 50 s = latex(o, mode='inline')
44 51 # mathtext does not understand certain latex flags, so we try to replace
45 52 # them with suitable subs.
46 53 s = s.replace('\\operatorname','')
47 54 s = s.replace('\\overline', '\\bar')
48 55 png = latex_to_png(s)
49 56 return png
50 57
51 58
52 59 def print_latex(o):
53 60 """A function to generate the latex representation of sympy expressions."""
54 61 s = latex(o, mode='equation', itex=True)
55 62 s = s.replace('\\dag','\\dagger')
56 63 return s
57 64
58 65
59 66 _loaded = False
60 67
61 68 def load_ipython_extension(ip):
62 69 """Load the extension in IPython."""
63 70 global _loaded
64 71 if not _loaded:
65 72 plaintext_formatter = ip.display_formatter.formatters['text/plain']
66 73
67 74 for cls in (object, tuple, list, set, frozenset, dict, str):
68 75 plaintext_formatter.for_type(cls, print_basic_unicode)
69 76
70 77 plaintext_formatter.for_type_by_name(
71 78 'sympy.core.basic', 'Basic', print_basic_unicode
72 79 )
73 80 plaintext_formatter.for_type_by_name(
74 81 'sympy.matrices.matrices', 'Matrix', print_basic_unicode
75 82 )
76 83
77 84 png_formatter = ip.display_formatter.formatters['image/png']
78 85
79 86 png_formatter.for_type_by_name(
80 87 'sympy.core.basic', 'Basic', print_png
81 88 )
82 89
83 90 latex_formatter = ip.display_formatter.formatters['text/latex']
84 91 latex_formatter.for_type_by_name(
85 92 'sympy.core.basic', 'Basic', print_latex
86 93 )
87 94 latex_formatter.for_type_by_name(
88 95 'sympy.matrices.matrices', 'Matrix', print_latex
89 96 )
90 97 _loaded = True
91 98
@@ -1,61 +1,71 b''
1 1 .. _extensions_overview:
2 2
3 3 ==================
4 4 IPython extensions
5 5 ==================
6 6
7 7 Configuration files are just the first level of customization that IPython
8 8 supports. The next level is that of extensions. An IPython extension is an
9 9 importable Python module that has a a few special function. By defining these
10 10 functions, users can customize IPython by accessing the actual runtime objects
11 11 of IPython. Here is a sample extension::
12 12
13 13 # myextension.py
14 14
15 15 def load_ipython_extension(ipython):
16 16 # The ``ipython`` argument is the currently active
17 17 # :class:`InteractiveShell` instance that can be used in any way.
18 18 # This allows you do to things like register new magics, plugins or
19 19 # aliases.
20 20
21 21 def unload_ipython_extension(ipython):
22 22 # If you want your extension to be unloadable, put that logic here.
23 23
24 24 This :func:`load_ipython_extension` function is called after your extension is
25 25 imported and the currently active :class:`InteractiveShell` instance is passed
26 26 as the only argument. You can do anything you want with IPython at that point.
27 27
28 28 The :func:`load_ipython_extension` will be called again is you load or reload
29 29 the extension again. It is up to the extension author to add code to manage
30 30 that.
31 31
32 32 You can put your extension modules anywhere you want, as long as they can be
33 33 imported by Python's standard import mechanism. However, to make it easy to
34 34 write extensions, you can also put your extensions in
35 35 ``os.path.join(self.ipython_dir, 'extensions')``. This directory is added to
36 36 ``sys.path`` automatically.
37 37
38 38 Using extensions
39 39 ================
40 40
41 41 There are two ways you can tell IPython to use your extension:
42 42
43 43 1. Listing it in a configuration file.
44 44 2. Using the ``%load_ext`` magic function.
45 45
46 46 To load an extension called :file:`myextension.py` add the following logic
47 47 to your configuration file::
48 48
49 49 c.InteractiveShellApp.extensions = [
50 50 'myextension'
51 51 ]
52 52
53 53 To load that same extension at runtime, use the ``%load_ext`` magic:
54 54
55 55 .. sourcecode:: ipython
56 56
57 57 In [1]: %load_ext myextension
58 58
59 59 To summarize, in conjunction with configuration files and profiles, IPython
60 60 extensions give you complete and flexible control over your IPython
61 61 setup.
62
63 Extensions bundled with IPython
64 ===============================
65
66 .. toctree::
67 :maxdepth: 1
68
69 autoreload
70 parallelmagic
71 sympyprinting
@@ -1,15 +1,15 b''
1 1 .. _config_index:
2 2
3 3 ===============================
4 4 Configuration and customization
5 5 ===============================
6 6
7 7 .. toctree::
8 8 :maxdepth: 2
9 9
10 10 overview.txt
11 extensions.txt
11 extensions/index.txt
12 12 plugins.txt
13 13 ipython.txt
14 14 editors.txt
15 15 old.txt
General Comments 0
You need to be logged in to leave comments. Login now