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