Show More
@@ -1,3731 +1,3731 b'' | |||||
1 | """Magic functions for InteractiveShell. |
|
1 | """Magic functions for InteractiveShell. | |
2 | """ |
|
2 | """ | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
6 | # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu> | |
7 | # Copyright (C) 2008 The IPython Development Team |
|
7 | # Copyright (C) 2008 The IPython Development Team | |
8 |
|
8 | |||
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # Imports |
|
13 | # Imports | |
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 |
|
15 | |||
16 | import __builtin__ as builtin_mod |
|
16 | import __builtin__ as builtin_mod | |
17 | import bdb |
|
17 | import bdb | |
18 | import gc |
|
18 | import gc | |
19 | import inspect |
|
19 | import inspect | |
20 | import io |
|
20 | import io | |
21 | import json |
|
21 | import json | |
22 | import os |
|
22 | import os | |
23 | import re |
|
23 | import re | |
24 | import sys |
|
24 | import sys | |
25 | import time |
|
25 | import time | |
26 | from StringIO import StringIO |
|
26 | from StringIO import StringIO | |
27 | from pprint import pformat |
|
27 | from pprint import pformat | |
28 | from urllib2 import urlopen |
|
28 | from urllib2 import urlopen | |
29 |
|
29 | |||
30 | # cProfile was added in Python2.5 |
|
30 | # cProfile was added in Python2.5 | |
31 | try: |
|
31 | try: | |
32 | import cProfile as profile |
|
32 | import cProfile as profile | |
33 | import pstats |
|
33 | import pstats | |
34 | except ImportError: |
|
34 | except ImportError: | |
35 | # profile isn't bundled by default in Debian for license reasons |
|
35 | # profile isn't bundled by default in Debian for license reasons | |
36 | try: |
|
36 | try: | |
37 | import profile, pstats |
|
37 | import profile, pstats | |
38 | except ImportError: |
|
38 | except ImportError: | |
39 | profile = pstats = None |
|
39 | profile = pstats = None | |
40 |
|
40 | |||
41 | from IPython.config.application import Application |
|
41 | from IPython.config.application import Application | |
42 | from IPython.core import debugger, oinspect |
|
42 | from IPython.core import debugger, oinspect | |
43 | from IPython.core import magic_arguments, page |
|
43 | from IPython.core import magic_arguments, page | |
44 | from IPython.core.error import UsageError, StdinNotImplementedError, TryNext |
|
44 | from IPython.core.error import UsageError, StdinNotImplementedError, TryNext | |
45 | from IPython.core.macro import Macro |
|
45 | from IPython.core.macro import Macro | |
46 | from IPython.core.magic import (Bunch, Magics, compress_dhist, |
|
46 | from IPython.core.magic import (Bunch, Magics, compress_dhist, | |
47 | on_off, needs_local_scope, |
|
47 | on_off, needs_local_scope, | |
48 | register_magics, line_magic, cell_magic) |
|
48 | register_magics, line_magic, cell_magic) | |
49 | from IPython.core.prefilter import ESC_MAGIC |
|
49 | from IPython.core.prefilter import ESC_MAGIC | |
50 | from IPython.testing.skipdoctest import skip_doctest |
|
50 | from IPython.testing.skipdoctest import skip_doctest | |
51 | from IPython.utils import openpy |
|
51 | from IPython.utils import openpy | |
52 | from IPython.utils import py3compat |
|
52 | from IPython.utils import py3compat | |
53 | from IPython.utils.encoding import DEFAULT_ENCODING |
|
53 | from IPython.utils.encoding import DEFAULT_ENCODING | |
54 | from IPython.utils.io import file_read, nlprint |
|
54 | from IPython.utils.io import file_read, nlprint | |
55 | from IPython.utils.ipstruct import Struct |
|
55 | from IPython.utils.ipstruct import Struct | |
56 | from IPython.utils.module_paths import find_mod |
|
56 | from IPython.utils.module_paths import find_mod | |
57 | from IPython.utils.path import get_py_filename, unquote_filename |
|
57 | from IPython.utils.path import get_py_filename, unquote_filename | |
58 | from IPython.utils.process import abbrev_cwd |
|
58 | from IPython.utils.process import abbrev_cwd | |
59 | from IPython.utils.terminal import set_term_title |
|
59 | from IPython.utils.terminal import set_term_title | |
60 | from IPython.utils.text import format_screen |
|
60 | from IPython.utils.text import format_screen | |
61 | from IPython.utils.timing import clock, clock2 |
|
61 | from IPython.utils.timing import clock, clock2 | |
62 | from IPython.utils.warn import warn, error |
|
62 | from IPython.utils.warn import warn, error | |
63 |
|
63 | |||
64 | #----------------------------------------------------------------------------- |
|
64 | #----------------------------------------------------------------------------- | |
65 | # Magic implementation classes |
|
65 | # Magic implementation classes | |
66 | #----------------------------------------------------------------------------- |
|
66 | #----------------------------------------------------------------------------- | |
67 |
|
67 | |||
68 | @register_magics |
|
68 | @register_magics | |
69 | class UserMagics(Magics): |
|
69 | class UserMagics(Magics): | |
70 | """Placeholder for user-defined magics to be added at runtime. |
|
70 | """Placeholder for user-defined magics to be added at runtime. | |
71 |
|
71 | |||
72 | All magics are eventually merged into a single namespace at runtime, but we |
|
72 | All magics are eventually merged into a single namespace at runtime, but we | |
73 | use this class to isolate the magics defined dynamically by the user into |
|
73 | use this class to isolate the magics defined dynamically by the user into | |
74 | their own class. |
|
74 | their own class. | |
75 | """ |
|
75 | """ | |
76 |
|
76 | |||
77 |
|
77 | |||
78 | @register_magics |
|
78 | @register_magics | |
79 | class BasicMagics(Magics): |
|
79 | class BasicMagics(Magics): | |
80 | """Magics that provide central IPython functionality. |
|
80 | """Magics that provide central IPython functionality. | |
81 |
|
81 | |||
82 | These are various magics that don't fit into specific categories but that |
|
82 | These are various magics that don't fit into specific categories but that | |
83 | are all part of the base 'IPython experience'.""" |
|
83 | are all part of the base 'IPython experience'.""" | |
84 |
|
84 | |||
85 | def _lsmagic(self): |
|
85 | def _lsmagic(self): | |
86 | mesc = ESC_MAGIC |
|
86 | mesc = ESC_MAGIC | |
87 | cesc = mesc*2 |
|
87 | cesc = mesc*2 | |
88 | mman = self.shell.magics_manager |
|
88 | mman = self.shell.magics_manager | |
89 | magics = mman.lsmagic() |
|
89 | magics = mman.lsmagic() | |
90 | out = ['Available line magics:', |
|
90 | out = ['Available line magics:', | |
91 | mesc + (' '+mesc).join(magics['line']), |
|
91 | mesc + (' '+mesc).join(magics['line']), | |
92 | '', |
|
92 | '', | |
93 | 'Available cell magics:', |
|
93 | 'Available cell magics:', | |
94 | cesc + (' '+cesc).join(magics['cell']), |
|
94 | cesc + (' '+cesc).join(magics['cell']), | |
95 | '', |
|
95 | '', | |
96 | mman.auto_status()] |
|
96 | mman.auto_status()] | |
97 | return '\n'.join(out) |
|
97 | return '\n'.join(out) | |
98 |
|
98 | |||
99 | @line_magic |
|
99 | @line_magic | |
100 | def lsmagic(self, parameter_s=''): |
|
100 | def lsmagic(self, parameter_s=''): | |
101 | """List currently available magic functions.""" |
|
101 | """List currently available magic functions.""" | |
102 | print self._lsmagic() |
|
102 | print self._lsmagic() | |
103 |
|
103 | |||
104 | @line_magic |
|
104 | @line_magic | |
105 | def magic(self, parameter_s=''): |
|
105 | def magic(self, parameter_s=''): | |
106 | """Print information about the magic function system. |
|
106 | """Print information about the magic function system. | |
107 |
|
107 | |||
108 | Supported formats: -latex, -brief, -rest |
|
108 | Supported formats: -latex, -brief, -rest | |
109 | """ |
|
109 | """ | |
110 |
|
110 | |||
111 | mode = '' |
|
111 | mode = '' | |
112 | try: |
|
112 | try: | |
113 | mode = parameter_s.split()[0][1:] |
|
113 | mode = parameter_s.split()[0][1:] | |
114 | if mode == 'rest': |
|
114 | if mode == 'rest': | |
115 | rest_docs = [] |
|
115 | rest_docs = [] | |
116 | except: |
|
116 | except: | |
117 | pass |
|
117 | pass | |
118 |
|
118 | |||
119 | magic_docs = [] |
|
119 | magic_docs = [] | |
120 | escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC*2) |
|
120 | escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC*2) | |
121 | magics = self.shell.magics_manager.magics |
|
121 | magics = self.shell.magics_manager.magics | |
122 |
|
122 | |||
123 | for mtype in ('line', 'cell'): |
|
123 | for mtype in ('line', 'cell'): | |
124 | escape = escapes[mtype] |
|
124 | escape = escapes[mtype] | |
125 | for fname, fn in magics: |
|
125 | for fname, fn in magics[mtype].iteritems(): | |
126 |
|
126 | |||
127 | if mode == 'brief': |
|
127 | if mode == 'brief': | |
128 | # only first line |
|
128 | # only first line | |
129 | if fn.__doc__: |
|
129 | if fn.__doc__: | |
130 | fndoc = fn.__doc__.split('\n',1)[0] |
|
130 | fndoc = fn.__doc__.split('\n',1)[0] | |
131 | else: |
|
131 | else: | |
132 | fndoc = 'No documentation' |
|
132 | fndoc = 'No documentation' | |
133 | else: |
|
133 | else: | |
134 | if fn.__doc__: |
|
134 | if fn.__doc__: | |
135 | fndoc = fn.__doc__.rstrip() |
|
135 | fndoc = fn.__doc__.rstrip() | |
136 | else: |
|
136 | else: | |
137 | fndoc = 'No documentation' |
|
137 | fndoc = 'No documentation' | |
138 |
|
138 | |||
139 | if mode == 'rest': |
|
139 | if mode == 'rest': | |
140 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' % |
|
140 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' % | |
141 | (escape, fname, fndoc)) |
|
141 | (escape, fname, fndoc)) | |
142 | else: |
|
142 | else: | |
143 | magic_docs.append('%s%s:\n\t%s\n' % |
|
143 | magic_docs.append('%s%s:\n\t%s\n' % | |
144 | (escape, fname, fndoc)) |
|
144 | (escape, fname, fndoc)) | |
145 |
|
145 | |||
146 |
|
146 | |||
147 | magic_docs = ''.join(magic_docs) |
|
147 | magic_docs = ''.join(magic_docs) | |
148 |
|
148 | |||
149 | if mode == 'rest': |
|
149 | if mode == 'rest': | |
150 | return "".join(rest_docs) |
|
150 | return "".join(rest_docs) | |
151 |
|
151 | |||
152 | if mode == 'latex': |
|
152 | if mode == 'latex': | |
153 | print self.format_latex(magic_docs) |
|
153 | print self.format_latex(magic_docs) | |
154 | return |
|
154 | return | |
155 | else: |
|
155 | else: | |
156 | magic_docs = format_screen(magic_docs) |
|
156 | magic_docs = format_screen(magic_docs) | |
157 | if mode == 'brief': |
|
157 | if mode == 'brief': | |
158 | return magic_docs |
|
158 | return magic_docs | |
159 |
|
159 | |||
160 | out = [""" |
|
160 | out = [""" | |
161 | IPython's 'magic' functions |
|
161 | IPython's 'magic' functions | |
162 | =========================== |
|
162 | =========================== | |
163 |
|
163 | |||
164 | The magic function system provides a series of functions which allow you to |
|
164 | The magic function system provides a series of functions which allow you to | |
165 | control the behavior of IPython itself, plus a lot of system-type |
|
165 | control the behavior of IPython itself, plus a lot of system-type | |
166 | features. All these functions are prefixed with a % character, but parameters |
|
166 | features. All these functions are prefixed with a % character, but parameters | |
167 | are given without parentheses or quotes. |
|
167 | are given without parentheses or quotes. | |
168 |
|
168 | |||
169 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
169 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
170 | %automagic function), you don't need to type in the % explicitly. By default, |
|
170 | %automagic function), you don't need to type in the % explicitly. By default, | |
171 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
171 | IPython ships with automagic on, so you should only rarely need the % escape. | |
172 |
|
172 | |||
173 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
173 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
174 | to 'mydir', if it exists. |
|
174 | to 'mydir', if it exists. | |
175 |
|
175 | |||
176 | For a list of the available magic functions, use %lsmagic. For a description |
|
176 | For a list of the available magic functions, use %lsmagic. For a description | |
177 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
177 | of any of them, type %magic_name?, e.g. '%cd?'. | |
178 |
|
178 | |||
179 | Currently the magic system has the following functions:""", |
|
179 | Currently the magic system has the following functions:""", | |
180 | magic_docs, |
|
180 | magic_docs, | |
181 | "Summary of magic functions (from %slsmagic):", |
|
181 | "Summary of magic functions (from %slsmagic):", | |
182 | self._lsmagic(), |
|
182 | self._lsmagic(), | |
183 | ] |
|
183 | ] | |
184 | page.page('\n'.join(out)) |
|
184 | page.page('\n'.join(out)) | |
185 |
|
185 | |||
186 |
|
186 | |||
187 | @line_magic |
|
187 | @line_magic | |
188 | def page(self, parameter_s=''): |
|
188 | def page(self, parameter_s=''): | |
189 | """Pretty print the object and display it through a pager. |
|
189 | """Pretty print the object and display it through a pager. | |
190 |
|
190 | |||
191 | %page [options] OBJECT |
|
191 | %page [options] OBJECT | |
192 |
|
192 | |||
193 | If no object is given, use _ (last output). |
|
193 | If no object is given, use _ (last output). | |
194 |
|
194 | |||
195 | Options: |
|
195 | Options: | |
196 |
|
196 | |||
197 | -r: page str(object), don't pretty-print it.""" |
|
197 | -r: page str(object), don't pretty-print it.""" | |
198 |
|
198 | |||
199 | # After a function contributed by Olivier Aubert, slightly modified. |
|
199 | # After a function contributed by Olivier Aubert, slightly modified. | |
200 |
|
200 | |||
201 | # Process options/args |
|
201 | # Process options/args | |
202 | opts, args = self.parse_options(parameter_s, 'r') |
|
202 | opts, args = self.parse_options(parameter_s, 'r') | |
203 | raw = 'r' in opts |
|
203 | raw = 'r' in opts | |
204 |
|
204 | |||
205 | oname = args and args or '_' |
|
205 | oname = args and args or '_' | |
206 | info = self._ofind(oname) |
|
206 | info = self._ofind(oname) | |
207 | if info['found']: |
|
207 | if info['found']: | |
208 | txt = (raw and str or pformat)( info['obj'] ) |
|
208 | txt = (raw and str or pformat)( info['obj'] ) | |
209 | page.page(txt) |
|
209 | page.page(txt) | |
210 | else: |
|
210 | else: | |
211 | print 'Object `%s` not found' % oname |
|
211 | print 'Object `%s` not found' % oname | |
212 |
|
212 | |||
213 | @line_magic |
|
213 | @line_magic | |
214 | def profile(self, parameter_s=''): |
|
214 | def profile(self, parameter_s=''): | |
215 | """Print your currently active IPython profile.""" |
|
215 | """Print your currently active IPython profile.""" | |
216 | from IPython.core.application import BaseIPythonApplication |
|
216 | from IPython.core.application import BaseIPythonApplication | |
217 | if BaseIPythonApplication.initialized(): |
|
217 | if BaseIPythonApplication.initialized(): | |
218 | print BaseIPythonApplication.instance().profile |
|
218 | print BaseIPythonApplication.instance().profile | |
219 | else: |
|
219 | else: | |
220 | error("profile is an application-level value, but you don't appear to be in an IPython application") |
|
220 | error("profile is an application-level value, but you don't appear to be in an IPython application") | |
221 |
|
221 | |||
222 | @line_magic |
|
222 | @line_magic | |
223 | def pprint(self, parameter_s=''): |
|
223 | def pprint(self, parameter_s=''): | |
224 | """Toggle pretty printing on/off.""" |
|
224 | """Toggle pretty printing on/off.""" | |
225 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
225 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
226 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
226 | ptformatter.pprint = bool(1 - ptformatter.pprint) | |
227 | print 'Pretty printing has been turned', \ |
|
227 | print 'Pretty printing has been turned', \ | |
228 | ['OFF','ON'][ptformatter.pprint] |
|
228 | ['OFF','ON'][ptformatter.pprint] | |
229 |
|
229 | |||
230 | @line_magic |
|
230 | @line_magic | |
231 | def colors(self, parameter_s=''): |
|
231 | def colors(self, parameter_s=''): | |
232 | """Switch color scheme for prompts, info system and exception handlers. |
|
232 | """Switch color scheme for prompts, info system and exception handlers. | |
233 |
|
233 | |||
234 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
234 | Currently implemented schemes: NoColor, Linux, LightBG. | |
235 |
|
235 | |||
236 | Color scheme names are not case-sensitive. |
|
236 | Color scheme names are not case-sensitive. | |
237 |
|
237 | |||
238 | Examples |
|
238 | Examples | |
239 | -------- |
|
239 | -------- | |
240 | To get a plain black and white terminal:: |
|
240 | To get a plain black and white terminal:: | |
241 |
|
241 | |||
242 | %colors nocolor |
|
242 | %colors nocolor | |
243 | """ |
|
243 | """ | |
244 | def color_switch_err(name): |
|
244 | def color_switch_err(name): | |
245 | warn('Error changing %s color schemes.\n%s' % |
|
245 | warn('Error changing %s color schemes.\n%s' % | |
246 | (name,sys.exc_info()[1])) |
|
246 | (name,sys.exc_info()[1])) | |
247 |
|
247 | |||
248 |
|
248 | |||
249 | new_scheme = parameter_s.strip() |
|
249 | new_scheme = parameter_s.strip() | |
250 | if not new_scheme: |
|
250 | if not new_scheme: | |
251 | raise UsageError( |
|
251 | raise UsageError( | |
252 | "%colors: you must specify a color scheme. See '%colors?'") |
|
252 | "%colors: you must specify a color scheme. See '%colors?'") | |
253 | return |
|
253 | return | |
254 | # local shortcut |
|
254 | # local shortcut | |
255 | shell = self.shell |
|
255 | shell = self.shell | |
256 |
|
256 | |||
257 | import IPython.utils.rlineimpl as readline |
|
257 | import IPython.utils.rlineimpl as readline | |
258 |
|
258 | |||
259 | if not shell.colors_force and \ |
|
259 | if not shell.colors_force and \ | |
260 | not readline.have_readline and sys.platform == "win32": |
|
260 | not readline.have_readline and sys.platform == "win32": | |
261 | msg = """\ |
|
261 | msg = """\ | |
262 | Proper color support under MS Windows requires the pyreadline library. |
|
262 | Proper color support under MS Windows requires the pyreadline library. | |
263 | You can find it at: |
|
263 | You can find it at: | |
264 | http://ipython.org/pyreadline.html |
|
264 | http://ipython.org/pyreadline.html | |
265 | Gary's readline needs the ctypes module, from: |
|
265 | Gary's readline needs the ctypes module, from: | |
266 | http://starship.python.net/crew/theller/ctypes |
|
266 | http://starship.python.net/crew/theller/ctypes | |
267 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
267 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
268 |
|
268 | |||
269 | Defaulting color scheme to 'NoColor'""" |
|
269 | Defaulting color scheme to 'NoColor'""" | |
270 | new_scheme = 'NoColor' |
|
270 | new_scheme = 'NoColor' | |
271 | warn(msg) |
|
271 | warn(msg) | |
272 |
|
272 | |||
273 | # readline option is 0 |
|
273 | # readline option is 0 | |
274 | if not shell.colors_force and not shell.has_readline: |
|
274 | if not shell.colors_force and not shell.has_readline: | |
275 | new_scheme = 'NoColor' |
|
275 | new_scheme = 'NoColor' | |
276 |
|
276 | |||
277 | # Set prompt colors |
|
277 | # Set prompt colors | |
278 | try: |
|
278 | try: | |
279 | shell.prompt_manager.color_scheme = new_scheme |
|
279 | shell.prompt_manager.color_scheme = new_scheme | |
280 | except: |
|
280 | except: | |
281 | color_switch_err('prompt') |
|
281 | color_switch_err('prompt') | |
282 | else: |
|
282 | else: | |
283 | shell.colors = \ |
|
283 | shell.colors = \ | |
284 | shell.prompt_manager.color_scheme_table.active_scheme_name |
|
284 | shell.prompt_manager.color_scheme_table.active_scheme_name | |
285 | # Set exception colors |
|
285 | # Set exception colors | |
286 | try: |
|
286 | try: | |
287 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
287 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
288 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
288 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
289 | except: |
|
289 | except: | |
290 | color_switch_err('exception') |
|
290 | color_switch_err('exception') | |
291 |
|
291 | |||
292 | # Set info (for 'object?') colors |
|
292 | # Set info (for 'object?') colors | |
293 | if shell.color_info: |
|
293 | if shell.color_info: | |
294 | try: |
|
294 | try: | |
295 | shell.inspector.set_active_scheme(new_scheme) |
|
295 | shell.inspector.set_active_scheme(new_scheme) | |
296 | except: |
|
296 | except: | |
297 | color_switch_err('object inspector') |
|
297 | color_switch_err('object inspector') | |
298 | else: |
|
298 | else: | |
299 | shell.inspector.set_active_scheme('NoColor') |
|
299 | shell.inspector.set_active_scheme('NoColor') | |
300 |
|
300 | |||
301 | @line_magic |
|
301 | @line_magic | |
302 | def xmode(self, parameter_s=''): |
|
302 | def xmode(self, parameter_s=''): | |
303 | """Switch modes for the exception handlers. |
|
303 | """Switch modes for the exception handlers. | |
304 |
|
304 | |||
305 | Valid modes: Plain, Context and Verbose. |
|
305 | Valid modes: Plain, Context and Verbose. | |
306 |
|
306 | |||
307 | If called without arguments, acts as a toggle.""" |
|
307 | If called without arguments, acts as a toggle.""" | |
308 |
|
308 | |||
309 | def xmode_switch_err(name): |
|
309 | def xmode_switch_err(name): | |
310 | warn('Error changing %s exception modes.\n%s' % |
|
310 | warn('Error changing %s exception modes.\n%s' % | |
311 | (name,sys.exc_info()[1])) |
|
311 | (name,sys.exc_info()[1])) | |
312 |
|
312 | |||
313 | shell = self.shell |
|
313 | shell = self.shell | |
314 | new_mode = parameter_s.strip().capitalize() |
|
314 | new_mode = parameter_s.strip().capitalize() | |
315 | try: |
|
315 | try: | |
316 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
316 | shell.InteractiveTB.set_mode(mode=new_mode) | |
317 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
317 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
318 | except: |
|
318 | except: | |
319 | xmode_switch_err('user') |
|
319 | xmode_switch_err('user') | |
320 |
|
320 | |||
321 | @line_magic |
|
321 | @line_magic | |
322 | def quickref(self,arg): |
|
322 | def quickref(self,arg): | |
323 | """ Show a quick reference sheet """ |
|
323 | """ Show a quick reference sheet """ | |
324 | import IPython.core.usage |
|
324 | import IPython.core.usage | |
325 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
325 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
326 | page.page(qr) |
|
326 | page.page(qr) | |
327 |
|
327 | |||
328 | @line_magic |
|
328 | @line_magic | |
329 | def doctest_mode(self, parameter_s=''): |
|
329 | def doctest_mode(self, parameter_s=''): | |
330 | """Toggle doctest mode on and off. |
|
330 | """Toggle doctest mode on and off. | |
331 |
|
331 | |||
332 | This mode is intended to make IPython behave as much as possible like a |
|
332 | This mode is intended to make IPython behave as much as possible like a | |
333 | plain Python shell, from the perspective of how its prompts, exceptions |
|
333 | plain Python shell, from the perspective of how its prompts, exceptions | |
334 | and output look. This makes it easy to copy and paste parts of a |
|
334 | and output look. This makes it easy to copy and paste parts of a | |
335 | session into doctests. It does so by: |
|
335 | session into doctests. It does so by: | |
336 |
|
336 | |||
337 | - Changing the prompts to the classic ``>>>`` ones. |
|
337 | - Changing the prompts to the classic ``>>>`` ones. | |
338 | - Changing the exception reporting mode to 'Plain'. |
|
338 | - Changing the exception reporting mode to 'Plain'. | |
339 | - Disabling pretty-printing of output. |
|
339 | - Disabling pretty-printing of output. | |
340 |
|
340 | |||
341 | Note that IPython also supports the pasting of code snippets that have |
|
341 | Note that IPython also supports the pasting of code snippets that have | |
342 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
342 | leading '>>>' and '...' prompts in them. This means that you can paste | |
343 | doctests from files or docstrings (even if they have leading |
|
343 | doctests from files or docstrings (even if they have leading | |
344 | whitespace), and the code will execute correctly. You can then use |
|
344 | whitespace), and the code will execute correctly. You can then use | |
345 | '%history -t' to see the translated history; this will give you the |
|
345 | '%history -t' to see the translated history; this will give you the | |
346 | input after removal of all the leading prompts and whitespace, which |
|
346 | input after removal of all the leading prompts and whitespace, which | |
347 | can be pasted back into an editor. |
|
347 | can be pasted back into an editor. | |
348 |
|
348 | |||
349 | With these features, you can switch into this mode easily whenever you |
|
349 | With these features, you can switch into this mode easily whenever you | |
350 | need to do testing and changes to doctests, without having to leave |
|
350 | need to do testing and changes to doctests, without having to leave | |
351 | your existing IPython session. |
|
351 | your existing IPython session. | |
352 | """ |
|
352 | """ | |
353 |
|
353 | |||
354 | # Shorthands |
|
354 | # Shorthands | |
355 | shell = self.shell |
|
355 | shell = self.shell | |
356 | pm = shell.prompt_manager |
|
356 | pm = shell.prompt_manager | |
357 | meta = shell.meta |
|
357 | meta = shell.meta | |
358 | disp_formatter = self.shell.display_formatter |
|
358 | disp_formatter = self.shell.display_formatter | |
359 | ptformatter = disp_formatter.formatters['text/plain'] |
|
359 | ptformatter = disp_formatter.formatters['text/plain'] | |
360 | # dstore is a data store kept in the instance metadata bag to track any |
|
360 | # dstore is a data store kept in the instance metadata bag to track any | |
361 | # changes we make, so we can undo them later. |
|
361 | # changes we make, so we can undo them later. | |
362 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
362 | dstore = meta.setdefault('doctest_mode',Struct()) | |
363 | save_dstore = dstore.setdefault |
|
363 | save_dstore = dstore.setdefault | |
364 |
|
364 | |||
365 | # save a few values we'll need to recover later |
|
365 | # save a few values we'll need to recover later | |
366 | mode = save_dstore('mode',False) |
|
366 | mode = save_dstore('mode',False) | |
367 | save_dstore('rc_pprint',ptformatter.pprint) |
|
367 | save_dstore('rc_pprint',ptformatter.pprint) | |
368 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
368 | save_dstore('xmode',shell.InteractiveTB.mode) | |
369 | save_dstore('rc_separate_out',shell.separate_out) |
|
369 | save_dstore('rc_separate_out',shell.separate_out) | |
370 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
370 | save_dstore('rc_separate_out2',shell.separate_out2) | |
371 | save_dstore('rc_prompts_pad_left',pm.justify) |
|
371 | save_dstore('rc_prompts_pad_left',pm.justify) | |
372 | save_dstore('rc_separate_in',shell.separate_in) |
|
372 | save_dstore('rc_separate_in',shell.separate_in) | |
373 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
373 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |
374 | save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template)) |
|
374 | save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template)) | |
375 |
|
375 | |||
376 | if mode == False: |
|
376 | if mode == False: | |
377 | # turn on |
|
377 | # turn on | |
378 | pm.in_template = '>>> ' |
|
378 | pm.in_template = '>>> ' | |
379 | pm.in2_template = '... ' |
|
379 | pm.in2_template = '... ' | |
380 | pm.out_template = '' |
|
380 | pm.out_template = '' | |
381 |
|
381 | |||
382 | # Prompt separators like plain python |
|
382 | # Prompt separators like plain python | |
383 | shell.separate_in = '' |
|
383 | shell.separate_in = '' | |
384 | shell.separate_out = '' |
|
384 | shell.separate_out = '' | |
385 | shell.separate_out2 = '' |
|
385 | shell.separate_out2 = '' | |
386 |
|
386 | |||
387 | pm.justify = False |
|
387 | pm.justify = False | |
388 |
|
388 | |||
389 | ptformatter.pprint = False |
|
389 | ptformatter.pprint = False | |
390 | disp_formatter.plain_text_only = True |
|
390 | disp_formatter.plain_text_only = True | |
391 |
|
391 | |||
392 | shell.magic('xmode Plain') |
|
392 | shell.magic('xmode Plain') | |
393 | else: |
|
393 | else: | |
394 | # turn off |
|
394 | # turn off | |
395 | pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates |
|
395 | pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates | |
396 |
|
396 | |||
397 | shell.separate_in = dstore.rc_separate_in |
|
397 | shell.separate_in = dstore.rc_separate_in | |
398 |
|
398 | |||
399 | shell.separate_out = dstore.rc_separate_out |
|
399 | shell.separate_out = dstore.rc_separate_out | |
400 | shell.separate_out2 = dstore.rc_separate_out2 |
|
400 | shell.separate_out2 = dstore.rc_separate_out2 | |
401 |
|
401 | |||
402 | pm.justify = dstore.rc_prompts_pad_left |
|
402 | pm.justify = dstore.rc_prompts_pad_left | |
403 |
|
403 | |||
404 | ptformatter.pprint = dstore.rc_pprint |
|
404 | ptformatter.pprint = dstore.rc_pprint | |
405 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
405 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |
406 |
|
406 | |||
407 | shell.magic('xmode ' + dstore.xmode) |
|
407 | shell.magic('xmode ' + dstore.xmode) | |
408 |
|
408 | |||
409 | # Store new mode and inform |
|
409 | # Store new mode and inform | |
410 | dstore.mode = bool(1-int(mode)) |
|
410 | dstore.mode = bool(1-int(mode)) | |
411 | mode_label = ['OFF','ON'][dstore.mode] |
|
411 | mode_label = ['OFF','ON'][dstore.mode] | |
412 | print 'Doctest mode is:', mode_label |
|
412 | print 'Doctest mode is:', mode_label | |
413 |
|
413 | |||
414 | @line_magic |
|
414 | @line_magic | |
415 | def gui(self, parameter_s=''): |
|
415 | def gui(self, parameter_s=''): | |
416 | """Enable or disable IPython GUI event loop integration. |
|
416 | """Enable or disable IPython GUI event loop integration. | |
417 |
|
417 | |||
418 | %gui [GUINAME] |
|
418 | %gui [GUINAME] | |
419 |
|
419 | |||
420 | This magic replaces IPython's threaded shells that were activated |
|
420 | This magic replaces IPython's threaded shells that were activated | |
421 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
421 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
422 | can now be enabled at runtime and keyboard |
|
422 | can now be enabled at runtime and keyboard | |
423 | interrupts should work without any problems. The following toolkits |
|
423 | interrupts should work without any problems. The following toolkits | |
424 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: |
|
424 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: | |
425 |
|
425 | |||
426 | %gui wx # enable wxPython event loop integration |
|
426 | %gui wx # enable wxPython event loop integration | |
427 | %gui qt4|qt # enable PyQt4 event loop integration |
|
427 | %gui qt4|qt # enable PyQt4 event loop integration | |
428 | %gui gtk # enable PyGTK event loop integration |
|
428 | %gui gtk # enable PyGTK event loop integration | |
429 | %gui gtk3 # enable Gtk3 event loop integration |
|
429 | %gui gtk3 # enable Gtk3 event loop integration | |
430 | %gui tk # enable Tk event loop integration |
|
430 | %gui tk # enable Tk event loop integration | |
431 | %gui OSX # enable Cocoa event loop integration |
|
431 | %gui OSX # enable Cocoa event loop integration | |
432 | # (requires %matplotlib 1.1) |
|
432 | # (requires %matplotlib 1.1) | |
433 | %gui # disable all event loop integration |
|
433 | %gui # disable all event loop integration | |
434 |
|
434 | |||
435 | WARNING: after any of these has been called you can simply create |
|
435 | WARNING: after any of these has been called you can simply create | |
436 | an application object, but DO NOT start the event loop yourself, as |
|
436 | an application object, but DO NOT start the event loop yourself, as | |
437 | we have already handled that. |
|
437 | we have already handled that. | |
438 | """ |
|
438 | """ | |
439 | opts, arg = self.parse_options(parameter_s, '') |
|
439 | opts, arg = self.parse_options(parameter_s, '') | |
440 | if arg=='': arg = None |
|
440 | if arg=='': arg = None | |
441 | try: |
|
441 | try: | |
442 | return self.enable_gui(arg) |
|
442 | return self.enable_gui(arg) | |
443 | except Exception as e: |
|
443 | except Exception as e: | |
444 | # print simple error message, rather than traceback if we can't |
|
444 | # print simple error message, rather than traceback if we can't | |
445 | # hook up the GUI |
|
445 | # hook up the GUI | |
446 | error(str(e)) |
|
446 | error(str(e)) | |
447 |
|
447 | |||
448 | @skip_doctest |
|
448 | @skip_doctest | |
449 | @line_magic |
|
449 | @line_magic | |
450 | def precision(self, s=''): |
|
450 | def precision(self, s=''): | |
451 | """Set floating point precision for pretty printing. |
|
451 | """Set floating point precision for pretty printing. | |
452 |
|
452 | |||
453 | Can set either integer precision or a format string. |
|
453 | Can set either integer precision or a format string. | |
454 |
|
454 | |||
455 | If numpy has been imported and precision is an int, |
|
455 | If numpy has been imported and precision is an int, | |
456 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
456 | numpy display precision will also be set, via ``numpy.set_printoptions``. | |
457 |
|
457 | |||
458 | If no argument is given, defaults will be restored. |
|
458 | If no argument is given, defaults will be restored. | |
459 |
|
459 | |||
460 | Examples |
|
460 | Examples | |
461 | -------- |
|
461 | -------- | |
462 | :: |
|
462 | :: | |
463 |
|
463 | |||
464 | In [1]: from math import pi |
|
464 | In [1]: from math import pi | |
465 |
|
465 | |||
466 | In [2]: %precision 3 |
|
466 | In [2]: %precision 3 | |
467 | Out[2]: u'%.3f' |
|
467 | Out[2]: u'%.3f' | |
468 |
|
468 | |||
469 | In [3]: pi |
|
469 | In [3]: pi | |
470 | Out[3]: 3.142 |
|
470 | Out[3]: 3.142 | |
471 |
|
471 | |||
472 | In [4]: %precision %i |
|
472 | In [4]: %precision %i | |
473 | Out[4]: u'%i' |
|
473 | Out[4]: u'%i' | |
474 |
|
474 | |||
475 | In [5]: pi |
|
475 | In [5]: pi | |
476 | Out[5]: 3 |
|
476 | Out[5]: 3 | |
477 |
|
477 | |||
478 | In [6]: %precision %e |
|
478 | In [6]: %precision %e | |
479 | Out[6]: u'%e' |
|
479 | Out[6]: u'%e' | |
480 |
|
480 | |||
481 | In [7]: pi**10 |
|
481 | In [7]: pi**10 | |
482 | Out[7]: 9.364805e+04 |
|
482 | Out[7]: 9.364805e+04 | |
483 |
|
483 | |||
484 | In [8]: %precision |
|
484 | In [8]: %precision | |
485 | Out[8]: u'%r' |
|
485 | Out[8]: u'%r' | |
486 |
|
486 | |||
487 | In [9]: pi**10 |
|
487 | In [9]: pi**10 | |
488 | Out[9]: 93648.047476082982 |
|
488 | Out[9]: 93648.047476082982 | |
489 | """ |
|
489 | """ | |
490 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
490 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
491 | ptformatter.float_precision = s |
|
491 | ptformatter.float_precision = s | |
492 | return ptformatter.float_format |
|
492 | return ptformatter.float_format | |
493 |
|
493 | |||
494 | @magic_arguments.magic_arguments() |
|
494 | @magic_arguments.magic_arguments() | |
495 | @magic_arguments.argument( |
|
495 | @magic_arguments.argument( | |
496 | '-e', '--export', action='store_true', default=False, |
|
496 | '-e', '--export', action='store_true', default=False, | |
497 | help='Export IPython history as a notebook. The filename argument ' |
|
497 | help='Export IPython history as a notebook. The filename argument ' | |
498 | 'is used to specify the notebook name and format. For example ' |
|
498 | 'is used to specify the notebook name and format. For example ' | |
499 | 'a filename of notebook.ipynb will result in a notebook name ' |
|
499 | 'a filename of notebook.ipynb will result in a notebook name ' | |
500 | 'of "notebook" and a format of "xml". Likewise using a ".json" ' |
|
500 | 'of "notebook" and a format of "xml". Likewise using a ".json" ' | |
501 | 'or ".py" file extension will write the notebook in the json ' |
|
501 | 'or ".py" file extension will write the notebook in the json ' | |
502 | 'or py formats.' |
|
502 | 'or py formats.' | |
503 | ) |
|
503 | ) | |
504 | @magic_arguments.argument( |
|
504 | @magic_arguments.argument( | |
505 | '-f', '--format', |
|
505 | '-f', '--format', | |
506 | help='Convert an existing IPython notebook to a new format. This option ' |
|
506 | help='Convert an existing IPython notebook to a new format. This option ' | |
507 | 'specifies the new format and can have the values: xml, json, py. ' |
|
507 | 'specifies the new format and can have the values: xml, json, py. ' | |
508 | 'The target filename is chosen automatically based on the new ' |
|
508 | 'The target filename is chosen automatically based on the new ' | |
509 | 'format. The filename argument gives the name of the source file.' |
|
509 | 'format. The filename argument gives the name of the source file.' | |
510 | ) |
|
510 | ) | |
511 | @magic_arguments.argument( |
|
511 | @magic_arguments.argument( | |
512 | 'filename', type=unicode, |
|
512 | 'filename', type=unicode, | |
513 | help='Notebook name or filename' |
|
513 | help='Notebook name or filename' | |
514 | ) |
|
514 | ) | |
515 | @line_magic |
|
515 | @line_magic | |
516 | def notebook(self, s): |
|
516 | def notebook(self, s): | |
517 | """Export and convert IPython notebooks. |
|
517 | """Export and convert IPython notebooks. | |
518 |
|
518 | |||
519 | This function can export the current IPython history to a notebook file |
|
519 | This function can export the current IPython history to a notebook file | |
520 | or can convert an existing notebook file into a different format. For |
|
520 | or can convert an existing notebook file into a different format. For | |
521 | example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". |
|
521 | example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". | |
522 | To export the history to "foo.py" do "%notebook -e foo.py". To convert |
|
522 | To export the history to "foo.py" do "%notebook -e foo.py". To convert | |
523 | "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible |
|
523 | "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible | |
524 | formats include (json/ipynb, py). |
|
524 | formats include (json/ipynb, py). | |
525 | """ |
|
525 | """ | |
526 | args = magic_arguments.parse_argstring(self.magic_notebook, s) |
|
526 | args = magic_arguments.parse_argstring(self.magic_notebook, s) | |
527 |
|
527 | |||
528 | from IPython.nbformat import current |
|
528 | from IPython.nbformat import current | |
529 | args.filename = unquote_filename(args.filename) |
|
529 | args.filename = unquote_filename(args.filename) | |
530 | if args.export: |
|
530 | if args.export: | |
531 | fname, name, format = current.parse_filename(args.filename) |
|
531 | fname, name, format = current.parse_filename(args.filename) | |
532 | cells = [] |
|
532 | cells = [] | |
533 | hist = list(self.shell.history_manager.get_range()) |
|
533 | hist = list(self.shell.history_manager.get_range()) | |
534 | for session, prompt_number, input in hist[:-1]: |
|
534 | for session, prompt_number, input in hist[:-1]: | |
535 | cells.append(current.new_code_cell(prompt_number=prompt_number, |
|
535 | cells.append(current.new_code_cell(prompt_number=prompt_number, | |
536 | input=input)) |
|
536 | input=input)) | |
537 | worksheet = current.new_worksheet(cells=cells) |
|
537 | worksheet = current.new_worksheet(cells=cells) | |
538 | nb = current.new_notebook(name=name,worksheets=[worksheet]) |
|
538 | nb = current.new_notebook(name=name,worksheets=[worksheet]) | |
539 | with io.open(fname, 'w', encoding='utf-8') as f: |
|
539 | with io.open(fname, 'w', encoding='utf-8') as f: | |
540 | current.write(nb, f, format); |
|
540 | current.write(nb, f, format); | |
541 | elif args.format is not None: |
|
541 | elif args.format is not None: | |
542 | old_fname, old_name, old_format = current.parse_filename(args.filename) |
|
542 | old_fname, old_name, old_format = current.parse_filename(args.filename) | |
543 | new_format = args.format |
|
543 | new_format = args.format | |
544 | if new_format == u'xml': |
|
544 | if new_format == u'xml': | |
545 | raise ValueError('Notebooks cannot be written as xml.') |
|
545 | raise ValueError('Notebooks cannot be written as xml.') | |
546 | elif new_format == u'ipynb' or new_format == u'json': |
|
546 | elif new_format == u'ipynb' or new_format == u'json': | |
547 | new_fname = old_name + u'.ipynb' |
|
547 | new_fname = old_name + u'.ipynb' | |
548 | new_format = u'json' |
|
548 | new_format = u'json' | |
549 | elif new_format == u'py': |
|
549 | elif new_format == u'py': | |
550 | new_fname = old_name + u'.py' |
|
550 | new_fname = old_name + u'.py' | |
551 | else: |
|
551 | else: | |
552 | raise ValueError('Invalid notebook format: %s' % new_format) |
|
552 | raise ValueError('Invalid notebook format: %s' % new_format) | |
553 | with io.open(old_fname, 'r', encoding='utf-8') as f: |
|
553 | with io.open(old_fname, 'r', encoding='utf-8') as f: | |
554 | nb = current.read(f, old_format) |
|
554 | nb = current.read(f, old_format) | |
555 | with io.open(new_fname, 'w', encoding='utf-8') as f: |
|
555 | with io.open(new_fname, 'w', encoding='utf-8') as f: | |
556 | current.write(nb, f, new_format) |
|
556 | current.write(nb, f, new_format) | |
557 |
|
557 | |||
558 |
|
558 | |||
559 | # Used for exception handling in magic_edit |
|
559 | # Used for exception handling in magic_edit | |
560 | class MacroToEdit(ValueError): pass |
|
560 | class MacroToEdit(ValueError): pass | |
561 |
|
561 | |||
562 |
|
562 | |||
563 | @register_magics |
|
563 | @register_magics | |
564 | class CodeMagics(Magics): |
|
564 | class CodeMagics(Magics): | |
565 | """Magics related to code management (loading, saving, editing, ...).""" |
|
565 | """Magics related to code management (loading, saving, editing, ...).""" | |
566 |
|
566 | |||
567 | @line_magic |
|
567 | @line_magic | |
568 | def save(self, parameter_s=''): |
|
568 | def save(self, parameter_s=''): | |
569 | """Save a set of lines or a macro to a given filename. |
|
569 | """Save a set of lines or a macro to a given filename. | |
570 |
|
570 | |||
571 | Usage:\\ |
|
571 | Usage:\\ | |
572 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
572 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
573 |
|
573 | |||
574 | Options: |
|
574 | Options: | |
575 |
|
575 | |||
576 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
576 | -r: use 'raw' input. By default, the 'processed' history is used, | |
577 | so that magics are loaded in their transformed version to valid |
|
577 | so that magics are loaded in their transformed version to valid | |
578 | Python. If this option is given, the raw input as typed as the |
|
578 | Python. If this option is given, the raw input as typed as the | |
579 | command line is used instead. |
|
579 | command line is used instead. | |
580 |
|
580 | |||
581 | This function uses the same syntax as %history for input ranges, |
|
581 | This function uses the same syntax as %history for input ranges, | |
582 | then saves the lines to the filename you specify. |
|
582 | then saves the lines to the filename you specify. | |
583 |
|
583 | |||
584 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
584 | It adds a '.py' extension to the file if you don't do so yourself, and | |
585 | it asks for confirmation before overwriting existing files.""" |
|
585 | it asks for confirmation before overwriting existing files.""" | |
586 |
|
586 | |||
587 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
587 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
588 | fname, codefrom = unquote_filename(args[0]), " ".join(args[1:]) |
|
588 | fname, codefrom = unquote_filename(args[0]), " ".join(args[1:]) | |
589 | if not fname.endswith('.py'): |
|
589 | if not fname.endswith('.py'): | |
590 | fname += '.py' |
|
590 | fname += '.py' | |
591 | if os.path.isfile(fname): |
|
591 | if os.path.isfile(fname): | |
592 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
592 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
593 | if ans.lower() not in ['y','yes']: |
|
593 | if ans.lower() not in ['y','yes']: | |
594 | print 'Operation cancelled.' |
|
594 | print 'Operation cancelled.' | |
595 | return |
|
595 | return | |
596 | try: |
|
596 | try: | |
597 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) |
|
597 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) | |
598 | except (TypeError, ValueError) as e: |
|
598 | except (TypeError, ValueError) as e: | |
599 | print e.args[0] |
|
599 | print e.args[0] | |
600 | return |
|
600 | return | |
601 | with io.open(fname,'w', encoding="utf-8") as f: |
|
601 | with io.open(fname,'w', encoding="utf-8") as f: | |
602 | f.write(u"# coding: utf-8\n") |
|
602 | f.write(u"# coding: utf-8\n") | |
603 | f.write(py3compat.cast_unicode(cmds)) |
|
603 | f.write(py3compat.cast_unicode(cmds)) | |
604 | print 'The following commands were written to file `%s`:' % fname |
|
604 | print 'The following commands were written to file `%s`:' % fname | |
605 | print cmds |
|
605 | print cmds | |
606 |
|
606 | |||
607 | @line_magic |
|
607 | @line_magic | |
608 | def pastebin(self, parameter_s=''): |
|
608 | def pastebin(self, parameter_s=''): | |
609 | """Upload code to Github's Gist paste bin, returning the URL. |
|
609 | """Upload code to Github's Gist paste bin, returning the URL. | |
610 |
|
610 | |||
611 | Usage:\\ |
|
611 | Usage:\\ | |
612 | %pastebin [-d "Custom description"] 1-7 |
|
612 | %pastebin [-d "Custom description"] 1-7 | |
613 |
|
613 | |||
614 | The argument can be an input history range, a filename, or the name of a |
|
614 | The argument can be an input history range, a filename, or the name of a | |
615 | string or macro. |
|
615 | string or macro. | |
616 |
|
616 | |||
617 | Options: |
|
617 | Options: | |
618 |
|
618 | |||
619 | -d: Pass a custom description for the gist. The default will say |
|
619 | -d: Pass a custom description for the gist. The default will say | |
620 | "Pasted from IPython". |
|
620 | "Pasted from IPython". | |
621 | """ |
|
621 | """ | |
622 | opts, args = self.parse_options(parameter_s, 'd:') |
|
622 | opts, args = self.parse_options(parameter_s, 'd:') | |
623 |
|
623 | |||
624 | try: |
|
624 | try: | |
625 | code = self.shell.find_user_code(args) |
|
625 | code = self.shell.find_user_code(args) | |
626 | except (ValueError, TypeError) as e: |
|
626 | except (ValueError, TypeError) as e: | |
627 | print e.args[0] |
|
627 | print e.args[0] | |
628 | return |
|
628 | return | |
629 |
|
629 | |||
630 | post_data = json.dumps({ |
|
630 | post_data = json.dumps({ | |
631 | "description": opts.get('d', "Pasted from IPython"), |
|
631 | "description": opts.get('d', "Pasted from IPython"), | |
632 | "public": True, |
|
632 | "public": True, | |
633 | "files": { |
|
633 | "files": { | |
634 | "file1.py": { |
|
634 | "file1.py": { | |
635 | "content": code |
|
635 | "content": code | |
636 | } |
|
636 | } | |
637 | } |
|
637 | } | |
638 | }).encode('utf-8') |
|
638 | }).encode('utf-8') | |
639 |
|
639 | |||
640 | response = urlopen("https://api.github.com/gists", post_data) |
|
640 | response = urlopen("https://api.github.com/gists", post_data) | |
641 | response_data = json.loads(response.read().decode('utf-8')) |
|
641 | response_data = json.loads(response.read().decode('utf-8')) | |
642 | return response_data['html_url'] |
|
642 | return response_data['html_url'] | |
643 |
|
643 | |||
644 | @line_magic |
|
644 | @line_magic | |
645 | def loadpy(self, arg_s): |
|
645 | def loadpy(self, arg_s): | |
646 | """Load a .py python script into the GUI console. |
|
646 | """Load a .py python script into the GUI console. | |
647 |
|
647 | |||
648 | This magic command can either take a local filename or a url:: |
|
648 | This magic command can either take a local filename or a url:: | |
649 |
|
649 | |||
650 | %loadpy myscript.py |
|
650 | %loadpy myscript.py | |
651 | %loadpy http://www.example.com/myscript.py |
|
651 | %loadpy http://www.example.com/myscript.py | |
652 | """ |
|
652 | """ | |
653 | arg_s = unquote_filename(arg_s) |
|
653 | arg_s = unquote_filename(arg_s) | |
654 | remote_url = arg_s.startswith(('http://', 'https://')) |
|
654 | remote_url = arg_s.startswith(('http://', 'https://')) | |
655 | local_url = not remote_url |
|
655 | local_url = not remote_url | |
656 | if local_url and not arg_s.endswith('.py'): |
|
656 | if local_url and not arg_s.endswith('.py'): | |
657 | # Local files must be .py; for remote URLs it's possible that the |
|
657 | # Local files must be .py; for remote URLs it's possible that the | |
658 | # fetch URL doesn't have a .py in it (many servers have an opaque |
|
658 | # fetch URL doesn't have a .py in it (many servers have an opaque | |
659 | # URL, such as scipy-central.org). |
|
659 | # URL, such as scipy-central.org). | |
660 | raise ValueError('%%loadpy only works with .py files: %s' % arg_s) |
|
660 | raise ValueError('%%loadpy only works with .py files: %s' % arg_s) | |
661 |
|
661 | |||
662 | # openpy takes care of finding the source encoding (per PEP 263) |
|
662 | # openpy takes care of finding the source encoding (per PEP 263) | |
663 | if remote_url: |
|
663 | if remote_url: | |
664 | contents = openpy.read_py_url(arg_s, skip_encoding_cookie=True) |
|
664 | contents = openpy.read_py_url(arg_s, skip_encoding_cookie=True) | |
665 | else: |
|
665 | else: | |
666 | contents = openpy.read_py_file(arg_s, skip_encoding_cookie=True) |
|
666 | contents = openpy.read_py_file(arg_s, skip_encoding_cookie=True) | |
667 |
|
667 | |||
668 | self.set_next_input(contents) |
|
668 | self.set_next_input(contents) | |
669 |
|
669 | |||
670 | def _find_edit_target(self, args, opts, last_call): |
|
670 | def _find_edit_target(self, args, opts, last_call): | |
671 | """Utility method used by magic_edit to find what to edit.""" |
|
671 | """Utility method used by magic_edit to find what to edit.""" | |
672 |
|
672 | |||
673 | def make_filename(arg): |
|
673 | def make_filename(arg): | |
674 | "Make a filename from the given args" |
|
674 | "Make a filename from the given args" | |
675 | arg = unquote_filename(arg) |
|
675 | arg = unquote_filename(arg) | |
676 | try: |
|
676 | try: | |
677 | filename = get_py_filename(arg) |
|
677 | filename = get_py_filename(arg) | |
678 | except IOError: |
|
678 | except IOError: | |
679 | # If it ends with .py but doesn't already exist, assume we want |
|
679 | # If it ends with .py but doesn't already exist, assume we want | |
680 | # a new file. |
|
680 | # a new file. | |
681 | if arg.endswith('.py'): |
|
681 | if arg.endswith('.py'): | |
682 | filename = arg |
|
682 | filename = arg | |
683 | else: |
|
683 | else: | |
684 | filename = None |
|
684 | filename = None | |
685 | return filename |
|
685 | return filename | |
686 |
|
686 | |||
687 | # Set a few locals from the options for convenience: |
|
687 | # Set a few locals from the options for convenience: | |
688 | opts_prev = 'p' in opts |
|
688 | opts_prev = 'p' in opts | |
689 | opts_raw = 'r' in opts |
|
689 | opts_raw = 'r' in opts | |
690 |
|
690 | |||
691 | # custom exceptions |
|
691 | # custom exceptions | |
692 | class DataIsObject(Exception): pass |
|
692 | class DataIsObject(Exception): pass | |
693 |
|
693 | |||
694 | # Default line number value |
|
694 | # Default line number value | |
695 | lineno = opts.get('n',None) |
|
695 | lineno = opts.get('n',None) | |
696 |
|
696 | |||
697 | if opts_prev: |
|
697 | if opts_prev: | |
698 | args = '_%s' % last_call[0] |
|
698 | args = '_%s' % last_call[0] | |
699 | if not self.shell.user_ns.has_key(args): |
|
699 | if not self.shell.user_ns.has_key(args): | |
700 | args = last_call[1] |
|
700 | args = last_call[1] | |
701 |
|
701 | |||
702 | # use last_call to remember the state of the previous call, but don't |
|
702 | # use last_call to remember the state of the previous call, but don't | |
703 | # let it be clobbered by successive '-p' calls. |
|
703 | # let it be clobbered by successive '-p' calls. | |
704 | try: |
|
704 | try: | |
705 | last_call[0] = self.shell.displayhook.prompt_count |
|
705 | last_call[0] = self.shell.displayhook.prompt_count | |
706 | if not opts_prev: |
|
706 | if not opts_prev: | |
707 | last_call[1] = args |
|
707 | last_call[1] = args | |
708 | except: |
|
708 | except: | |
709 | pass |
|
709 | pass | |
710 |
|
710 | |||
711 | # by default this is done with temp files, except when the given |
|
711 | # by default this is done with temp files, except when the given | |
712 | # arg is a filename |
|
712 | # arg is a filename | |
713 | use_temp = True |
|
713 | use_temp = True | |
714 |
|
714 | |||
715 | data = '' |
|
715 | data = '' | |
716 |
|
716 | |||
717 | # First, see if the arguments should be a filename. |
|
717 | # First, see if the arguments should be a filename. | |
718 | filename = make_filename(args) |
|
718 | filename = make_filename(args) | |
719 | if filename: |
|
719 | if filename: | |
720 | use_temp = False |
|
720 | use_temp = False | |
721 | elif args: |
|
721 | elif args: | |
722 | # Mode where user specifies ranges of lines, like in %macro. |
|
722 | # Mode where user specifies ranges of lines, like in %macro. | |
723 | data = self.shell.extract_input_lines(args, opts_raw) |
|
723 | data = self.shell.extract_input_lines(args, opts_raw) | |
724 | if not data: |
|
724 | if not data: | |
725 | try: |
|
725 | try: | |
726 | # Load the parameter given as a variable. If not a string, |
|
726 | # Load the parameter given as a variable. If not a string, | |
727 | # process it as an object instead (below) |
|
727 | # process it as an object instead (below) | |
728 |
|
728 | |||
729 | #print '*** args',args,'type',type(args) # dbg |
|
729 | #print '*** args',args,'type',type(args) # dbg | |
730 | data = eval(args, self.shell.user_ns) |
|
730 | data = eval(args, self.shell.user_ns) | |
731 | if not isinstance(data, basestring): |
|
731 | if not isinstance(data, basestring): | |
732 | raise DataIsObject |
|
732 | raise DataIsObject | |
733 |
|
733 | |||
734 | except (NameError,SyntaxError): |
|
734 | except (NameError,SyntaxError): | |
735 | # given argument is not a variable, try as a filename |
|
735 | # given argument is not a variable, try as a filename | |
736 | filename = make_filename(args) |
|
736 | filename = make_filename(args) | |
737 | if filename is None: |
|
737 | if filename is None: | |
738 | warn("Argument given (%s) can't be found as a variable " |
|
738 | warn("Argument given (%s) can't be found as a variable " | |
739 | "or as a filename." % args) |
|
739 | "or as a filename." % args) | |
740 | return |
|
740 | return | |
741 | use_temp = False |
|
741 | use_temp = False | |
742 |
|
742 | |||
743 | except DataIsObject: |
|
743 | except DataIsObject: | |
744 | # macros have a special edit function |
|
744 | # macros have a special edit function | |
745 | if isinstance(data, Macro): |
|
745 | if isinstance(data, Macro): | |
746 | raise MacroToEdit(data) |
|
746 | raise MacroToEdit(data) | |
747 |
|
747 | |||
748 | # For objects, try to edit the file where they are defined |
|
748 | # For objects, try to edit the file where they are defined | |
749 | try: |
|
749 | try: | |
750 | filename = inspect.getabsfile(data) |
|
750 | filename = inspect.getabsfile(data) | |
751 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
751 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
752 | # class created by %edit? Try to find source |
|
752 | # class created by %edit? Try to find source | |
753 | # by looking for method definitions instead, the |
|
753 | # by looking for method definitions instead, the | |
754 | # __module__ in those classes is FakeModule. |
|
754 | # __module__ in those classes is FakeModule. | |
755 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
755 | attrs = [getattr(data, aname) for aname in dir(data)] | |
756 | for attr in attrs: |
|
756 | for attr in attrs: | |
757 | if not inspect.ismethod(attr): |
|
757 | if not inspect.ismethod(attr): | |
758 | continue |
|
758 | continue | |
759 | filename = inspect.getabsfile(attr) |
|
759 | filename = inspect.getabsfile(attr) | |
760 | if filename and 'fakemodule' not in filename.lower(): |
|
760 | if filename and 'fakemodule' not in filename.lower(): | |
761 | # change the attribute to be the edit target instead |
|
761 | # change the attribute to be the edit target instead | |
762 | data = attr |
|
762 | data = attr | |
763 | break |
|
763 | break | |
764 |
|
764 | |||
765 | datafile = 1 |
|
765 | datafile = 1 | |
766 | except TypeError: |
|
766 | except TypeError: | |
767 | filename = make_filename(args) |
|
767 | filename = make_filename(args) | |
768 | datafile = 1 |
|
768 | datafile = 1 | |
769 | warn('Could not find file where `%s` is defined.\n' |
|
769 | warn('Could not find file where `%s` is defined.\n' | |
770 | 'Opening a file named `%s`' % (args,filename)) |
|
770 | 'Opening a file named `%s`' % (args,filename)) | |
771 | # Now, make sure we can actually read the source (if it was in |
|
771 | # Now, make sure we can actually read the source (if it was in | |
772 | # a temp file it's gone by now). |
|
772 | # a temp file it's gone by now). | |
773 | if datafile: |
|
773 | if datafile: | |
774 | try: |
|
774 | try: | |
775 | if lineno is None: |
|
775 | if lineno is None: | |
776 | lineno = inspect.getsourcelines(data)[1] |
|
776 | lineno = inspect.getsourcelines(data)[1] | |
777 | except IOError: |
|
777 | except IOError: | |
778 | filename = make_filename(args) |
|
778 | filename = make_filename(args) | |
779 | if filename is None: |
|
779 | if filename is None: | |
780 | warn('The file `%s` where `%s` was defined cannot ' |
|
780 | warn('The file `%s` where `%s` was defined cannot ' | |
781 | 'be read.' % (filename,data)) |
|
781 | 'be read.' % (filename,data)) | |
782 | return |
|
782 | return | |
783 | use_temp = False |
|
783 | use_temp = False | |
784 |
|
784 | |||
785 | if use_temp: |
|
785 | if use_temp: | |
786 | filename = self.shell.mktempfile(data) |
|
786 | filename = self.shell.mktempfile(data) | |
787 | print 'IPython will make a temporary file named:',filename |
|
787 | print 'IPython will make a temporary file named:',filename | |
788 |
|
788 | |||
789 | return filename, lineno, use_temp |
|
789 | return filename, lineno, use_temp | |
790 |
|
790 | |||
791 | def _edit_macro(self,mname,macro): |
|
791 | def _edit_macro(self,mname,macro): | |
792 | """open an editor with the macro data in a file""" |
|
792 | """open an editor with the macro data in a file""" | |
793 | filename = self.shell.mktempfile(macro.value) |
|
793 | filename = self.shell.mktempfile(macro.value) | |
794 | self.shell.hooks.editor(filename) |
|
794 | self.shell.hooks.editor(filename) | |
795 |
|
795 | |||
796 | # and make a new macro object, to replace the old one |
|
796 | # and make a new macro object, to replace the old one | |
797 | mfile = open(filename) |
|
797 | mfile = open(filename) | |
798 | mvalue = mfile.read() |
|
798 | mvalue = mfile.read() | |
799 | mfile.close() |
|
799 | mfile.close() | |
800 | self.shell.user_ns[mname] = Macro(mvalue) |
|
800 | self.shell.user_ns[mname] = Macro(mvalue) | |
801 |
|
801 | |||
802 | @line_magic |
|
802 | @line_magic | |
803 | def ed(self, parameter_s=''): |
|
803 | def ed(self, parameter_s=''): | |
804 | """Alias to %edit.""" |
|
804 | """Alias to %edit.""" | |
805 | return self.magic_edit(parameter_s) |
|
805 | return self.magic_edit(parameter_s) | |
806 |
|
806 | |||
807 | @skip_doctest |
|
807 | @skip_doctest | |
808 | @line_magic |
|
808 | @line_magic | |
809 | def edit(self, parameter_s='',last_call=['','']): |
|
809 | def edit(self, parameter_s='',last_call=['','']): | |
810 | """Bring up an editor and execute the resulting code. |
|
810 | """Bring up an editor and execute the resulting code. | |
811 |
|
811 | |||
812 | Usage: |
|
812 | Usage: | |
813 | %edit [options] [args] |
|
813 | %edit [options] [args] | |
814 |
|
814 | |||
815 | %edit runs IPython's editor hook. The default version of this hook is |
|
815 | %edit runs IPython's editor hook. The default version of this hook is | |
816 | set to call the editor specified by your $EDITOR environment variable. |
|
816 | set to call the editor specified by your $EDITOR environment variable. | |
817 | If this isn't found, it will default to vi under Linux/Unix and to |
|
817 | If this isn't found, it will default to vi under Linux/Unix and to | |
818 | notepad under Windows. See the end of this docstring for how to change |
|
818 | notepad under Windows. See the end of this docstring for how to change | |
819 | the editor hook. |
|
819 | the editor hook. | |
820 |
|
820 | |||
821 | You can also set the value of this editor via the |
|
821 | You can also set the value of this editor via the | |
822 | ``TerminalInteractiveShell.editor`` option in your configuration file. |
|
822 | ``TerminalInteractiveShell.editor`` option in your configuration file. | |
823 | This is useful if you wish to use a different editor from your typical |
|
823 | This is useful if you wish to use a different editor from your typical | |
824 | default with IPython (and for Windows users who typically don't set |
|
824 | default with IPython (and for Windows users who typically don't set | |
825 | environment variables). |
|
825 | environment variables). | |
826 |
|
826 | |||
827 | This command allows you to conveniently edit multi-line code right in |
|
827 | This command allows you to conveniently edit multi-line code right in | |
828 | your IPython session. |
|
828 | your IPython session. | |
829 |
|
829 | |||
830 | If called without arguments, %edit opens up an empty editor with a |
|
830 | If called without arguments, %edit opens up an empty editor with a | |
831 | temporary file and will execute the contents of this file when you |
|
831 | temporary file and will execute the contents of this file when you | |
832 | close it (don't forget to save it!). |
|
832 | close it (don't forget to save it!). | |
833 |
|
833 | |||
834 |
|
834 | |||
835 | Options: |
|
835 | Options: | |
836 |
|
836 | |||
837 | -n <number>: open the editor at a specified line number. By default, |
|
837 | -n <number>: open the editor at a specified line number. By default, | |
838 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
838 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
839 | you can configure this by providing your own modified hook if your |
|
839 | you can configure this by providing your own modified hook if your | |
840 | favorite editor supports line-number specifications with a different |
|
840 | favorite editor supports line-number specifications with a different | |
841 | syntax. |
|
841 | syntax. | |
842 |
|
842 | |||
843 | -p: this will call the editor with the same data as the previous time |
|
843 | -p: this will call the editor with the same data as the previous time | |
844 | it was used, regardless of how long ago (in your current session) it |
|
844 | it was used, regardless of how long ago (in your current session) it | |
845 | was. |
|
845 | was. | |
846 |
|
846 | |||
847 | -r: use 'raw' input. This option only applies to input taken from the |
|
847 | -r: use 'raw' input. This option only applies to input taken from the | |
848 | user's history. By default, the 'processed' history is used, so that |
|
848 | user's history. By default, the 'processed' history is used, so that | |
849 | magics are loaded in their transformed version to valid Python. If |
|
849 | magics are loaded in their transformed version to valid Python. If | |
850 | this option is given, the raw input as typed as the command line is |
|
850 | this option is given, the raw input as typed as the command line is | |
851 | used instead. When you exit the editor, it will be executed by |
|
851 | used instead. When you exit the editor, it will be executed by | |
852 | IPython's own processor. |
|
852 | IPython's own processor. | |
853 |
|
853 | |||
854 | -x: do not execute the edited code immediately upon exit. This is |
|
854 | -x: do not execute the edited code immediately upon exit. This is | |
855 | mainly useful if you are editing programs which need to be called with |
|
855 | mainly useful if you are editing programs which need to be called with | |
856 | command line arguments, which you can then do using %run. |
|
856 | command line arguments, which you can then do using %run. | |
857 |
|
857 | |||
858 |
|
858 | |||
859 | Arguments: |
|
859 | Arguments: | |
860 |
|
860 | |||
861 | If arguments are given, the following possibilities exist: |
|
861 | If arguments are given, the following possibilities exist: | |
862 |
|
862 | |||
863 | - If the argument is a filename, IPython will load that into the |
|
863 | - If the argument is a filename, IPython will load that into the | |
864 | editor. It will execute its contents with execfile() when you exit, |
|
864 | editor. It will execute its contents with execfile() when you exit, | |
865 | loading any code in the file into your interactive namespace. |
|
865 | loading any code in the file into your interactive namespace. | |
866 |
|
866 | |||
867 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". |
|
867 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". | |
868 | The syntax is the same as in the %history magic. |
|
868 | The syntax is the same as in the %history magic. | |
869 |
|
869 | |||
870 | - If the argument is a string variable, its contents are loaded |
|
870 | - If the argument is a string variable, its contents are loaded | |
871 | into the editor. You can thus edit any string which contains |
|
871 | into the editor. You can thus edit any string which contains | |
872 | python code (including the result of previous edits). |
|
872 | python code (including the result of previous edits). | |
873 |
|
873 | |||
874 | - If the argument is the name of an object (other than a string), |
|
874 | - If the argument is the name of an object (other than a string), | |
875 | IPython will try to locate the file where it was defined and open the |
|
875 | IPython will try to locate the file where it was defined and open the | |
876 | editor at the point where it is defined. You can use `%edit function` |
|
876 | editor at the point where it is defined. You can use `%edit function` | |
877 | to load an editor exactly at the point where 'function' is defined, |
|
877 | to load an editor exactly at the point where 'function' is defined, | |
878 | edit it and have the file be executed automatically. |
|
878 | edit it and have the file be executed automatically. | |
879 |
|
879 | |||
880 | - If the object is a macro (see %macro for details), this opens up your |
|
880 | - If the object is a macro (see %macro for details), this opens up your | |
881 | specified editor with a temporary file containing the macro's data. |
|
881 | specified editor with a temporary file containing the macro's data. | |
882 | Upon exit, the macro is reloaded with the contents of the file. |
|
882 | Upon exit, the macro is reloaded with the contents of the file. | |
883 |
|
883 | |||
884 | Note: opening at an exact line is only supported under Unix, and some |
|
884 | Note: opening at an exact line is only supported under Unix, and some | |
885 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
885 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
886 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
886 | '+NUMBER' parameter necessary for this feature. Good editors like | |
887 | (X)Emacs, vi, jed, pico and joe all do. |
|
887 | (X)Emacs, vi, jed, pico and joe all do. | |
888 |
|
888 | |||
889 | After executing your code, %edit will return as output the code you |
|
889 | After executing your code, %edit will return as output the code you | |
890 | typed in the editor (except when it was an existing file). This way |
|
890 | typed in the editor (except when it was an existing file). This way | |
891 | you can reload the code in further invocations of %edit as a variable, |
|
891 | you can reload the code in further invocations of %edit as a variable, | |
892 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
892 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
893 | the output. |
|
893 | the output. | |
894 |
|
894 | |||
895 | Note that %edit is also available through the alias %ed. |
|
895 | Note that %edit is also available through the alias %ed. | |
896 |
|
896 | |||
897 | This is an example of creating a simple function inside the editor and |
|
897 | This is an example of creating a simple function inside the editor and | |
898 | then modifying it. First, start up the editor:: |
|
898 | then modifying it. First, start up the editor:: | |
899 |
|
899 | |||
900 | In [1]: ed |
|
900 | In [1]: ed | |
901 | Editing... done. Executing edited code... |
|
901 | Editing... done. Executing edited code... | |
902 | Out[1]: 'def foo():\\n print "foo() was defined in an editing |
|
902 | Out[1]: 'def foo():\\n print "foo() was defined in an editing | |
903 | session"\\n' |
|
903 | session"\\n' | |
904 |
|
904 | |||
905 | We can then call the function foo():: |
|
905 | We can then call the function foo():: | |
906 |
|
906 | |||
907 | In [2]: foo() |
|
907 | In [2]: foo() | |
908 | foo() was defined in an editing session |
|
908 | foo() was defined in an editing session | |
909 |
|
909 | |||
910 | Now we edit foo. IPython automatically loads the editor with the |
|
910 | Now we edit foo. IPython automatically loads the editor with the | |
911 | (temporary) file where foo() was previously defined:: |
|
911 | (temporary) file where foo() was previously defined:: | |
912 |
|
912 | |||
913 | In [3]: ed foo |
|
913 | In [3]: ed foo | |
914 | Editing... done. Executing edited code... |
|
914 | Editing... done. Executing edited code... | |
915 |
|
915 | |||
916 | And if we call foo() again we get the modified version:: |
|
916 | And if we call foo() again we get the modified version:: | |
917 |
|
917 | |||
918 | In [4]: foo() |
|
918 | In [4]: foo() | |
919 | foo() has now been changed! |
|
919 | foo() has now been changed! | |
920 |
|
920 | |||
921 | Here is an example of how to edit a code snippet successive |
|
921 | Here is an example of how to edit a code snippet successive | |
922 | times. First we call the editor:: |
|
922 | times. First we call the editor:: | |
923 |
|
923 | |||
924 | In [5]: ed |
|
924 | In [5]: ed | |
925 | Editing... done. Executing edited code... |
|
925 | Editing... done. Executing edited code... | |
926 | hello |
|
926 | hello | |
927 | Out[5]: "print 'hello'\\n" |
|
927 | Out[5]: "print 'hello'\\n" | |
928 |
|
928 | |||
929 | Now we call it again with the previous output (stored in _):: |
|
929 | Now we call it again with the previous output (stored in _):: | |
930 |
|
930 | |||
931 | In [6]: ed _ |
|
931 | In [6]: ed _ | |
932 | Editing... done. Executing edited code... |
|
932 | Editing... done. Executing edited code... | |
933 | hello world |
|
933 | hello world | |
934 | Out[6]: "print 'hello world'\\n" |
|
934 | Out[6]: "print 'hello world'\\n" | |
935 |
|
935 | |||
936 | Now we call it with the output #8 (stored in _8, also as Out[8]):: |
|
936 | Now we call it with the output #8 (stored in _8, also as Out[8]):: | |
937 |
|
937 | |||
938 | In [7]: ed _8 |
|
938 | In [7]: ed _8 | |
939 | Editing... done. Executing edited code... |
|
939 | Editing... done. Executing edited code... | |
940 | hello again |
|
940 | hello again | |
941 | Out[7]: "print 'hello again'\\n" |
|
941 | Out[7]: "print 'hello again'\\n" | |
942 |
|
942 | |||
943 |
|
943 | |||
944 | Changing the default editor hook: |
|
944 | Changing the default editor hook: | |
945 |
|
945 | |||
946 | If you wish to write your own editor hook, you can put it in a |
|
946 | If you wish to write your own editor hook, you can put it in a | |
947 | configuration file which you load at startup time. The default hook |
|
947 | configuration file which you load at startup time. The default hook | |
948 | is defined in the IPython.core.hooks module, and you can use that as a |
|
948 | is defined in the IPython.core.hooks module, and you can use that as a | |
949 | starting example for further modifications. That file also has |
|
949 | starting example for further modifications. That file also has | |
950 | general instructions on how to set a new hook for use once you've |
|
950 | general instructions on how to set a new hook for use once you've | |
951 | defined it.""" |
|
951 | defined it.""" | |
952 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
952 | opts,args = self.parse_options(parameter_s,'prxn:') | |
953 |
|
953 | |||
954 | try: |
|
954 | try: | |
955 | filename, lineno, is_temp = self._find_edit_target(args, opts, last_call) |
|
955 | filename, lineno, is_temp = self._find_edit_target(args, opts, last_call) | |
956 | except MacroToEdit as e: |
|
956 | except MacroToEdit as e: | |
957 | self._edit_macro(args, e.args[0]) |
|
957 | self._edit_macro(args, e.args[0]) | |
958 | return |
|
958 | return | |
959 |
|
959 | |||
960 | # do actual editing here |
|
960 | # do actual editing here | |
961 | print 'Editing...', |
|
961 | print 'Editing...', | |
962 | sys.stdout.flush() |
|
962 | sys.stdout.flush() | |
963 | try: |
|
963 | try: | |
964 | # Quote filenames that may have spaces in them |
|
964 | # Quote filenames that may have spaces in them | |
965 | if ' ' in filename: |
|
965 | if ' ' in filename: | |
966 | filename = "'%s'" % filename |
|
966 | filename = "'%s'" % filename | |
967 | self.shell.hooks.editor(filename,lineno) |
|
967 | self.shell.hooks.editor(filename,lineno) | |
968 | except TryNext: |
|
968 | except TryNext: | |
969 | warn('Could not open editor') |
|
969 | warn('Could not open editor') | |
970 | return |
|
970 | return | |
971 |
|
971 | |||
972 | # XXX TODO: should this be generalized for all string vars? |
|
972 | # XXX TODO: should this be generalized for all string vars? | |
973 | # For now, this is special-cased to blocks created by cpaste |
|
973 | # For now, this is special-cased to blocks created by cpaste | |
974 | if args.strip() == 'pasted_block': |
|
974 | if args.strip() == 'pasted_block': | |
975 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
975 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
976 |
|
976 | |||
977 | if 'x' in opts: # -x prevents actual execution |
|
977 | if 'x' in opts: # -x prevents actual execution | |
978 |
|
978 | |||
979 | else: |
|
979 | else: | |
980 | print 'done. Executing edited code...' |
|
980 | print 'done. Executing edited code...' | |
981 | if 'r' in opts: # Untranslated IPython code |
|
981 | if 'r' in opts: # Untranslated IPython code | |
982 | self.shell.run_cell(file_read(filename), |
|
982 | self.shell.run_cell(file_read(filename), | |
983 | store_history=False) |
|
983 | store_history=False) | |
984 | else: |
|
984 | else: | |
985 | self.shell.safe_execfile(filename, self.shell.user_ns, |
|
985 | self.shell.safe_execfile(filename, self.shell.user_ns, | |
986 | self.shell.user_ns) |
|
986 | self.shell.user_ns) | |
987 |
|
987 | |||
988 | if is_temp: |
|
988 | if is_temp: | |
989 | try: |
|
989 | try: | |
990 | return open(filename).read() |
|
990 | return open(filename).read() | |
991 | except IOError,msg: |
|
991 | except IOError,msg: | |
992 | if msg.filename == filename: |
|
992 | if msg.filename == filename: | |
993 | warn('File not found. Did you forget to save?') |
|
993 | warn('File not found. Did you forget to save?') | |
994 | return |
|
994 | return | |
995 | else: |
|
995 | else: | |
996 | self.shell.showtraceback() |
|
996 | self.shell.showtraceback() | |
997 |
|
997 | |||
998 |
|
998 | |||
999 | @register_magics |
|
999 | @register_magics | |
1000 | class ConfigMagics(Magics): |
|
1000 | class ConfigMagics(Magics): | |
1001 |
|
1001 | |||
1002 | def __init__(self, shell): |
|
1002 | def __init__(self, shell): | |
1003 | super(ConfigMagics, self).__init__(shell) |
|
1003 | super(ConfigMagics, self).__init__(shell) | |
1004 | self.configurables = [] |
|
1004 | self.configurables = [] | |
1005 |
|
1005 | |||
1006 | @line_magic |
|
1006 | @line_magic | |
1007 | def config(self, s): |
|
1007 | def config(self, s): | |
1008 | """configure IPython |
|
1008 | """configure IPython | |
1009 |
|
1009 | |||
1010 | %config Class[.trait=value] |
|
1010 | %config Class[.trait=value] | |
1011 |
|
1011 | |||
1012 | This magic exposes most of the IPython config system. Any |
|
1012 | This magic exposes most of the IPython config system. Any | |
1013 | Configurable class should be able to be configured with the simple |
|
1013 | Configurable class should be able to be configured with the simple | |
1014 | line:: |
|
1014 | line:: | |
1015 |
|
1015 | |||
1016 | %config Class.trait=value |
|
1016 | %config Class.trait=value | |
1017 |
|
1017 | |||
1018 | Where `value` will be resolved in the user's namespace, if it is an |
|
1018 | Where `value` will be resolved in the user's namespace, if it is an | |
1019 | expression or variable name. |
|
1019 | expression or variable name. | |
1020 |
|
1020 | |||
1021 | Examples |
|
1021 | Examples | |
1022 | -------- |
|
1022 | -------- | |
1023 |
|
1023 | |||
1024 | To see what classes are available for config, pass no arguments:: |
|
1024 | To see what classes are available for config, pass no arguments:: | |
1025 |
|
1025 | |||
1026 | In [1]: %config |
|
1026 | In [1]: %config | |
1027 | Available objects for config: |
|
1027 | Available objects for config: | |
1028 | TerminalInteractiveShell |
|
1028 | TerminalInteractiveShell | |
1029 | HistoryManager |
|
1029 | HistoryManager | |
1030 | PrefilterManager |
|
1030 | PrefilterManager | |
1031 | AliasManager |
|
1031 | AliasManager | |
1032 | IPCompleter |
|
1032 | IPCompleter | |
1033 | PromptManager |
|
1033 | PromptManager | |
1034 | DisplayFormatter |
|
1034 | DisplayFormatter | |
1035 |
|
1035 | |||
1036 | To view what is configurable on a given class, just pass the class |
|
1036 | To view what is configurable on a given class, just pass the class | |
1037 | name:: |
|
1037 | name:: | |
1038 |
|
1038 | |||
1039 | In [2]: %config IPCompleter |
|
1039 | In [2]: %config IPCompleter | |
1040 | IPCompleter options |
|
1040 | IPCompleter options | |
1041 | ----------------- |
|
1041 | ----------------- | |
1042 | IPCompleter.omit__names=<Enum> |
|
1042 | IPCompleter.omit__names=<Enum> | |
1043 | Current: 2 |
|
1043 | Current: 2 | |
1044 | Choices: (0, 1, 2) |
|
1044 | Choices: (0, 1, 2) | |
1045 | Instruct the completer to omit private method names |
|
1045 | Instruct the completer to omit private method names | |
1046 | Specifically, when completing on ``object.<tab>``. |
|
1046 | Specifically, when completing on ``object.<tab>``. | |
1047 | When 2 [default]: all names that start with '_' will be excluded. |
|
1047 | When 2 [default]: all names that start with '_' will be excluded. | |
1048 | When 1: all 'magic' names (``__foo__``) will be excluded. |
|
1048 | When 1: all 'magic' names (``__foo__``) will be excluded. | |
1049 | When 0: nothing will be excluded. |
|
1049 | When 0: nothing will be excluded. | |
1050 | IPCompleter.merge_completions=<CBool> |
|
1050 | IPCompleter.merge_completions=<CBool> | |
1051 | Current: True |
|
1051 | Current: True | |
1052 | Whether to merge completion results into a single list |
|
1052 | Whether to merge completion results into a single list | |
1053 | If False, only the completion results from the first non-empty completer |
|
1053 | If False, only the completion results from the first non-empty completer | |
1054 | will be returned. |
|
1054 | will be returned. | |
1055 | IPCompleter.limit_to__all__=<CBool> |
|
1055 | IPCompleter.limit_to__all__=<CBool> | |
1056 | Current: False |
|
1056 | Current: False | |
1057 | Instruct the completer to use __all__ for the completion |
|
1057 | Instruct the completer to use __all__ for the completion | |
1058 | Specifically, when completing on ``object.<tab>``. |
|
1058 | Specifically, when completing on ``object.<tab>``. | |
1059 | When True: only those names in obj.__all__ will be included. |
|
1059 | When True: only those names in obj.__all__ will be included. | |
1060 | When False [default]: the __all__ attribute is ignored |
|
1060 | When False [default]: the __all__ attribute is ignored | |
1061 | IPCompleter.greedy=<CBool> |
|
1061 | IPCompleter.greedy=<CBool> | |
1062 | Current: False |
|
1062 | Current: False | |
1063 | Activate greedy completion |
|
1063 | Activate greedy completion | |
1064 | This will enable completion on elements of lists, results of function calls, |
|
1064 | This will enable completion on elements of lists, results of function calls, | |
1065 | etc., but can be unsafe because the code is actually evaluated on TAB. |
|
1065 | etc., but can be unsafe because the code is actually evaluated on TAB. | |
1066 |
|
1066 | |||
1067 | but the real use is in setting values:: |
|
1067 | but the real use is in setting values:: | |
1068 |
|
1068 | |||
1069 | In [3]: %config IPCompleter.greedy = True |
|
1069 | In [3]: %config IPCompleter.greedy = True | |
1070 |
|
1070 | |||
1071 | and these values are read from the user_ns if they are variables:: |
|
1071 | and these values are read from the user_ns if they are variables:: | |
1072 |
|
1072 | |||
1073 | In [4]: feeling_greedy=False |
|
1073 | In [4]: feeling_greedy=False | |
1074 |
|
1074 | |||
1075 | In [5]: %config IPCompleter.greedy = feeling_greedy |
|
1075 | In [5]: %config IPCompleter.greedy = feeling_greedy | |
1076 |
|
1076 | |||
1077 | """ |
|
1077 | """ | |
1078 | from IPython.config.loader import Config |
|
1078 | from IPython.config.loader import Config | |
1079 | # some IPython objects are Configurable, but do not yet have |
|
1079 | # some IPython objects are Configurable, but do not yet have | |
1080 | # any configurable traits. Exclude them from the effects of |
|
1080 | # any configurable traits. Exclude them from the effects of | |
1081 | # this magic, as their presence is just noise: |
|
1081 | # this magic, as their presence is just noise: | |
1082 | configurables = [ c for c in self.shell.configurables |
|
1082 | configurables = [ c for c in self.shell.configurables | |
1083 | if c.__class__.class_traits(config=True) ] |
|
1083 | if c.__class__.class_traits(config=True) ] | |
1084 | classnames = [ c.__class__.__name__ for c in configurables ] |
|
1084 | classnames = [ c.__class__.__name__ for c in configurables ] | |
1085 |
|
1085 | |||
1086 | line = s.strip() |
|
1086 | line = s.strip() | |
1087 | if not line: |
|
1087 | if not line: | |
1088 | # print available configurable names |
|
1088 | # print available configurable names | |
1089 | print "Available objects for config:" |
|
1089 | print "Available objects for config:" | |
1090 | for name in classnames: |
|
1090 | for name in classnames: | |
1091 | print " ", name |
|
1091 | print " ", name | |
1092 | return |
|
1092 | return | |
1093 | elif line in classnames: |
|
1093 | elif line in classnames: | |
1094 | # `%config TerminalInteractiveShell` will print trait info for |
|
1094 | # `%config TerminalInteractiveShell` will print trait info for | |
1095 | # TerminalInteractiveShell |
|
1095 | # TerminalInteractiveShell | |
1096 | c = configurables[classnames.index(line)] |
|
1096 | c = configurables[classnames.index(line)] | |
1097 | cls = c.__class__ |
|
1097 | cls = c.__class__ | |
1098 | help = cls.class_get_help(c) |
|
1098 | help = cls.class_get_help(c) | |
1099 | # strip leading '--' from cl-args: |
|
1099 | # strip leading '--' from cl-args: | |
1100 | help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) |
|
1100 | help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) | |
1101 | print help |
|
1101 | print help | |
1102 | return |
|
1102 | return | |
1103 | elif '=' not in line: |
|
1103 | elif '=' not in line: | |
1104 | raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line) |
|
1104 | raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line) | |
1105 |
|
1105 | |||
1106 |
|
1106 | |||
1107 | # otherwise, assume we are setting configurables. |
|
1107 | # otherwise, assume we are setting configurables. | |
1108 | # leave quotes on args when splitting, because we want |
|
1108 | # leave quotes on args when splitting, because we want | |
1109 | # unquoted args to eval in user_ns |
|
1109 | # unquoted args to eval in user_ns | |
1110 | cfg = Config() |
|
1110 | cfg = Config() | |
1111 | exec "cfg."+line in locals(), self.shell.user_ns |
|
1111 | exec "cfg."+line in locals(), self.shell.user_ns | |
1112 |
|
1112 | |||
1113 | for configurable in configurables: |
|
1113 | for configurable in configurables: | |
1114 | try: |
|
1114 | try: | |
1115 | configurable.update_config(cfg) |
|
1115 | configurable.update_config(cfg) | |
1116 | except Exception as e: |
|
1116 | except Exception as e: | |
1117 | error(e) |
|
1117 | error(e) | |
1118 |
|
1118 | |||
1119 |
|
1119 | |||
1120 | @register_magics |
|
1120 | @register_magics | |
1121 | class NamespaceMagics(Magics): |
|
1121 | class NamespaceMagics(Magics): | |
1122 | """Magics to manage various aspects of the user's namespace. |
|
1122 | """Magics to manage various aspects of the user's namespace. | |
1123 |
|
1123 | |||
1124 | These include listing variables, introspecting into them, etc. |
|
1124 | These include listing variables, introspecting into them, etc. | |
1125 | """ |
|
1125 | """ | |
1126 |
|
1126 | |||
1127 | @line_magic |
|
1127 | @line_magic | |
1128 | def pinfo(self, parameter_s='', namespaces=None): |
|
1128 | def pinfo(self, parameter_s='', namespaces=None): | |
1129 | """Provide detailed information about an object. |
|
1129 | """Provide detailed information about an object. | |
1130 |
|
1130 | |||
1131 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
1131 | '%pinfo object' is just a synonym for object? or ?object.""" | |
1132 |
|
1132 | |||
1133 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
1133 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
1134 |
|
1134 | |||
1135 |
|
1135 | |||
1136 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
1136 | # detail_level: 0 -> obj? , 1 -> obj?? | |
1137 | detail_level = 0 |
|
1137 | detail_level = 0 | |
1138 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
1138 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
1139 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
1139 | # happen if the user types 'pinfo foo?' at the cmd line. | |
1140 | pinfo,qmark1,oname,qmark2 = \ |
|
1140 | pinfo,qmark1,oname,qmark2 = \ | |
1141 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
1141 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
1142 | if pinfo or qmark1 or qmark2: |
|
1142 | if pinfo or qmark1 or qmark2: | |
1143 | detail_level = 1 |
|
1143 | detail_level = 1 | |
1144 | if "*" in oname: |
|
1144 | if "*" in oname: | |
1145 | self.magic_psearch(oname) |
|
1145 | self.magic_psearch(oname) | |
1146 | else: |
|
1146 | else: | |
1147 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
1147 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
1148 | namespaces=namespaces) |
|
1148 | namespaces=namespaces) | |
1149 |
|
1149 | |||
1150 | @line_magic |
|
1150 | @line_magic | |
1151 | def pinfo2(self, parameter_s='', namespaces=None): |
|
1151 | def pinfo2(self, parameter_s='', namespaces=None): | |
1152 | """Provide extra detailed information about an object. |
|
1152 | """Provide extra detailed information about an object. | |
1153 |
|
1153 | |||
1154 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
1154 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
1155 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
1155 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
1156 | namespaces=namespaces) |
|
1156 | namespaces=namespaces) | |
1157 |
|
1157 | |||
1158 | @skip_doctest |
|
1158 | @skip_doctest | |
1159 | @line_magic |
|
1159 | @line_magic | |
1160 | def pdef(self, parameter_s='', namespaces=None): |
|
1160 | def pdef(self, parameter_s='', namespaces=None): | |
1161 | """Print the definition header for any callable object. |
|
1161 | """Print the definition header for any callable object. | |
1162 |
|
1162 | |||
1163 | If the object is a class, print the constructor information. |
|
1163 | If the object is a class, print the constructor information. | |
1164 |
|
1164 | |||
1165 | Examples |
|
1165 | Examples | |
1166 | -------- |
|
1166 | -------- | |
1167 | :: |
|
1167 | :: | |
1168 |
|
1168 | |||
1169 | In [3]: %pdef urllib.urlopen |
|
1169 | In [3]: %pdef urllib.urlopen | |
1170 | urllib.urlopen(url, data=None, proxies=None) |
|
1170 | urllib.urlopen(url, data=None, proxies=None) | |
1171 | """ |
|
1171 | """ | |
1172 | self._inspect('pdef',parameter_s, namespaces) |
|
1172 | self._inspect('pdef',parameter_s, namespaces) | |
1173 |
|
1173 | |||
1174 | @line_magic |
|
1174 | @line_magic | |
1175 | def pdoc(self, parameter_s='', namespaces=None): |
|
1175 | def pdoc(self, parameter_s='', namespaces=None): | |
1176 | """Print the docstring for an object. |
|
1176 | """Print the docstring for an object. | |
1177 |
|
1177 | |||
1178 | If the given object is a class, it will print both the class and the |
|
1178 | If the given object is a class, it will print both the class and the | |
1179 | constructor docstrings.""" |
|
1179 | constructor docstrings.""" | |
1180 | self._inspect('pdoc',parameter_s, namespaces) |
|
1180 | self._inspect('pdoc',parameter_s, namespaces) | |
1181 |
|
1181 | |||
1182 | @line_magic |
|
1182 | @line_magic | |
1183 | def psource(self, parameter_s='', namespaces=None): |
|
1183 | def psource(self, parameter_s='', namespaces=None): | |
1184 | """Print (or run through pager) the source code for an object.""" |
|
1184 | """Print (or run through pager) the source code for an object.""" | |
1185 | self._inspect('psource',parameter_s, namespaces) |
|
1185 | self._inspect('psource',parameter_s, namespaces) | |
1186 |
|
1186 | |||
1187 | @line_magic |
|
1187 | @line_magic | |
1188 | def pfile(self, parameter_s=''): |
|
1188 | def pfile(self, parameter_s=''): | |
1189 | """Print (or run through pager) the file where an object is defined. |
|
1189 | """Print (or run through pager) the file where an object is defined. | |
1190 |
|
1190 | |||
1191 | The file opens at the line where the object definition begins. IPython |
|
1191 | The file opens at the line where the object definition begins. IPython | |
1192 | will honor the environment variable PAGER if set, and otherwise will |
|
1192 | will honor the environment variable PAGER if set, and otherwise will | |
1193 | do its best to print the file in a convenient form. |
|
1193 | do its best to print the file in a convenient form. | |
1194 |
|
1194 | |||
1195 | If the given argument is not an object currently defined, IPython will |
|
1195 | If the given argument is not an object currently defined, IPython will | |
1196 | try to interpret it as a filename (automatically adding a .py extension |
|
1196 | try to interpret it as a filename (automatically adding a .py extension | |
1197 | if needed). You can thus use %pfile as a syntax highlighting code |
|
1197 | if needed). You can thus use %pfile as a syntax highlighting code | |
1198 | viewer.""" |
|
1198 | viewer.""" | |
1199 |
|
1199 | |||
1200 | # first interpret argument as an object name |
|
1200 | # first interpret argument as an object name | |
1201 | out = self._inspect('pfile',parameter_s) |
|
1201 | out = self._inspect('pfile',parameter_s) | |
1202 | # if not, try the input as a filename |
|
1202 | # if not, try the input as a filename | |
1203 | if out == 'not found': |
|
1203 | if out == 'not found': | |
1204 | try: |
|
1204 | try: | |
1205 | filename = get_py_filename(parameter_s) |
|
1205 | filename = get_py_filename(parameter_s) | |
1206 | except IOError,msg: |
|
1206 | except IOError,msg: | |
1207 | print msg |
|
1207 | print msg | |
1208 | return |
|
1208 | return | |
1209 | page.page(self.shell.inspector.format(open(filename).read())) |
|
1209 | page.page(self.shell.inspector.format(open(filename).read())) | |
1210 |
|
1210 | |||
1211 | @line_magic |
|
1211 | @line_magic | |
1212 | def psearch(self, parameter_s=''): |
|
1212 | def psearch(self, parameter_s=''): | |
1213 | """Search for object in namespaces by wildcard. |
|
1213 | """Search for object in namespaces by wildcard. | |
1214 |
|
1214 | |||
1215 | %psearch [options] PATTERN [OBJECT TYPE] |
|
1215 | %psearch [options] PATTERN [OBJECT TYPE] | |
1216 |
|
1216 | |||
1217 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
1217 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
1218 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
1218 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
1219 | rest of the command line must be unchanged (options come first), so |
|
1219 | rest of the command line must be unchanged (options come first), so | |
1220 | for example the following forms are equivalent |
|
1220 | for example the following forms are equivalent | |
1221 |
|
1221 | |||
1222 | %psearch -i a* function |
|
1222 | %psearch -i a* function | |
1223 | -i a* function? |
|
1223 | -i a* function? | |
1224 | ?-i a* function |
|
1224 | ?-i a* function | |
1225 |
|
1225 | |||
1226 | Arguments: |
|
1226 | Arguments: | |
1227 |
|
1227 | |||
1228 | PATTERN |
|
1228 | PATTERN | |
1229 |
|
1229 | |||
1230 | where PATTERN is a string containing * as a wildcard similar to its |
|
1230 | where PATTERN is a string containing * as a wildcard similar to its | |
1231 | use in a shell. The pattern is matched in all namespaces on the |
|
1231 | use in a shell. The pattern is matched in all namespaces on the | |
1232 | search path. By default objects starting with a single _ are not |
|
1232 | search path. By default objects starting with a single _ are not | |
1233 | matched, many IPython generated objects have a single |
|
1233 | matched, many IPython generated objects have a single | |
1234 | underscore. The default is case insensitive matching. Matching is |
|
1234 | underscore. The default is case insensitive matching. Matching is | |
1235 | also done on the attributes of objects and not only on the objects |
|
1235 | also done on the attributes of objects and not only on the objects | |
1236 | in a module. |
|
1236 | in a module. | |
1237 |
|
1237 | |||
1238 | [OBJECT TYPE] |
|
1238 | [OBJECT TYPE] | |
1239 |
|
1239 | |||
1240 | Is the name of a python type from the types module. The name is |
|
1240 | Is the name of a python type from the types module. The name is | |
1241 | given in lowercase without the ending type, ex. StringType is |
|
1241 | given in lowercase without the ending type, ex. StringType is | |
1242 | written string. By adding a type here only objects matching the |
|
1242 | written string. By adding a type here only objects matching the | |
1243 | given type are matched. Using all here makes the pattern match all |
|
1243 | given type are matched. Using all here makes the pattern match all | |
1244 | types (this is the default). |
|
1244 | types (this is the default). | |
1245 |
|
1245 | |||
1246 | Options: |
|
1246 | Options: | |
1247 |
|
1247 | |||
1248 | -a: makes the pattern match even objects whose names start with a |
|
1248 | -a: makes the pattern match even objects whose names start with a | |
1249 | single underscore. These names are normally omitted from the |
|
1249 | single underscore. These names are normally omitted from the | |
1250 | search. |
|
1250 | search. | |
1251 |
|
1251 | |||
1252 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
1252 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
1253 | these options are given, the default is read from your configuration |
|
1253 | these options are given, the default is read from your configuration | |
1254 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. |
|
1254 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. | |
1255 | If this option is not specified in your configuration file, IPython's |
|
1255 | If this option is not specified in your configuration file, IPython's | |
1256 | internal default is to do a case sensitive search. |
|
1256 | internal default is to do a case sensitive search. | |
1257 |
|
1257 | |||
1258 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
1258 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
1259 | specify can be searched in any of the following namespaces: |
|
1259 | specify can be searched in any of the following namespaces: | |
1260 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
1260 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
1261 | 'builtin' and 'user' are the search defaults. Note that you should |
|
1261 | 'builtin' and 'user' are the search defaults. Note that you should | |
1262 | not use quotes when specifying namespaces. |
|
1262 | not use quotes when specifying namespaces. | |
1263 |
|
1263 | |||
1264 | 'Builtin' contains the python module builtin, 'user' contains all |
|
1264 | 'Builtin' contains the python module builtin, 'user' contains all | |
1265 | user data, 'alias' only contain the shell aliases and no python |
|
1265 | user data, 'alias' only contain the shell aliases and no python | |
1266 | objects, 'internal' contains objects used by IPython. The |
|
1266 | objects, 'internal' contains objects used by IPython. The | |
1267 | 'user_global' namespace is only used by embedded IPython instances, |
|
1267 | 'user_global' namespace is only used by embedded IPython instances, | |
1268 | and it contains module-level globals. You can add namespaces to the |
|
1268 | and it contains module-level globals. You can add namespaces to the | |
1269 | search with -s or exclude them with -e (these options can be given |
|
1269 | search with -s or exclude them with -e (these options can be given | |
1270 | more than once). |
|
1270 | more than once). | |
1271 |
|
1271 | |||
1272 | Examples |
|
1272 | Examples | |
1273 | -------- |
|
1273 | -------- | |
1274 | :: |
|
1274 | :: | |
1275 |
|
1275 | |||
1276 | %psearch a* -> objects beginning with an a |
|
1276 | %psearch a* -> objects beginning with an a | |
1277 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
1277 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
1278 | %psearch a* function -> all functions beginning with an a |
|
1278 | %psearch a* function -> all functions beginning with an a | |
1279 | %psearch re.e* -> objects beginning with an e in module re |
|
1279 | %psearch re.e* -> objects beginning with an e in module re | |
1280 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
1280 | %psearch r*.e* -> objects that start with e in modules starting in r | |
1281 | %psearch r*.* string -> all strings in modules beginning with r |
|
1281 | %psearch r*.* string -> all strings in modules beginning with r | |
1282 |
|
1282 | |||
1283 | Case sensitive search:: |
|
1283 | Case sensitive search:: | |
1284 |
|
1284 | |||
1285 | %psearch -c a* list all object beginning with lower case a |
|
1285 | %psearch -c a* list all object beginning with lower case a | |
1286 |
|
1286 | |||
1287 | Show objects beginning with a single _:: |
|
1287 | Show objects beginning with a single _:: | |
1288 |
|
1288 | |||
1289 | %psearch -a _* list objects beginning with a single underscore""" |
|
1289 | %psearch -a _* list objects beginning with a single underscore""" | |
1290 | try: |
|
1290 | try: | |
1291 | parameter_s.encode('ascii') |
|
1291 | parameter_s.encode('ascii') | |
1292 | except UnicodeEncodeError: |
|
1292 | except UnicodeEncodeError: | |
1293 | print 'Python identifiers can only contain ascii characters.' |
|
1293 | print 'Python identifiers can only contain ascii characters.' | |
1294 | return |
|
1294 | return | |
1295 |
|
1295 | |||
1296 | # default namespaces to be searched |
|
1296 | # default namespaces to be searched | |
1297 | def_search = ['user_local', 'user_global', 'builtin'] |
|
1297 | def_search = ['user_local', 'user_global', 'builtin'] | |
1298 |
|
1298 | |||
1299 | # Process options/args |
|
1299 | # Process options/args | |
1300 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
1300 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
1301 | opt = opts.get |
|
1301 | opt = opts.get | |
1302 | shell = self.shell |
|
1302 | shell = self.shell | |
1303 | psearch = shell.inspector.psearch |
|
1303 | psearch = shell.inspector.psearch | |
1304 |
|
1304 | |||
1305 | # select case options |
|
1305 | # select case options | |
1306 | if opts.has_key('i'): |
|
1306 | if opts.has_key('i'): | |
1307 | ignore_case = True |
|
1307 | ignore_case = True | |
1308 | elif opts.has_key('c'): |
|
1308 | elif opts.has_key('c'): | |
1309 | ignore_case = False |
|
1309 | ignore_case = False | |
1310 | else: |
|
1310 | else: | |
1311 | ignore_case = not shell.wildcards_case_sensitive |
|
1311 | ignore_case = not shell.wildcards_case_sensitive | |
1312 |
|
1312 | |||
1313 | # Build list of namespaces to search from user options |
|
1313 | # Build list of namespaces to search from user options | |
1314 | def_search.extend(opt('s',[])) |
|
1314 | def_search.extend(opt('s',[])) | |
1315 | ns_exclude = ns_exclude=opt('e',[]) |
|
1315 | ns_exclude = ns_exclude=opt('e',[]) | |
1316 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
1316 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
1317 |
|
1317 | |||
1318 | # Call the actual search |
|
1318 | # Call the actual search | |
1319 | try: |
|
1319 | try: | |
1320 | psearch(args,shell.ns_table,ns_search, |
|
1320 | psearch(args,shell.ns_table,ns_search, | |
1321 | show_all=opt('a'),ignore_case=ignore_case) |
|
1321 | show_all=opt('a'),ignore_case=ignore_case) | |
1322 | except: |
|
1322 | except: | |
1323 | shell.showtraceback() |
|
1323 | shell.showtraceback() | |
1324 |
|
1324 | |||
1325 | @skip_doctest |
|
1325 | @skip_doctest | |
1326 | @line_magic |
|
1326 | @line_magic | |
1327 | def who_ls(self, parameter_s=''): |
|
1327 | def who_ls(self, parameter_s=''): | |
1328 | """Return a sorted list of all interactive variables. |
|
1328 | """Return a sorted list of all interactive variables. | |
1329 |
|
1329 | |||
1330 | If arguments are given, only variables of types matching these |
|
1330 | If arguments are given, only variables of types matching these | |
1331 | arguments are returned. |
|
1331 | arguments are returned. | |
1332 |
|
1332 | |||
1333 | Examples |
|
1333 | Examples | |
1334 | -------- |
|
1334 | -------- | |
1335 |
|
1335 | |||
1336 | Define two variables and list them with who_ls:: |
|
1336 | Define two variables and list them with who_ls:: | |
1337 |
|
1337 | |||
1338 | In [1]: alpha = 123 |
|
1338 | In [1]: alpha = 123 | |
1339 |
|
1339 | |||
1340 | In [2]: beta = 'test' |
|
1340 | In [2]: beta = 'test' | |
1341 |
|
1341 | |||
1342 | In [3]: %who_ls |
|
1342 | In [3]: %who_ls | |
1343 | Out[3]: ['alpha', 'beta'] |
|
1343 | Out[3]: ['alpha', 'beta'] | |
1344 |
|
1344 | |||
1345 | In [4]: %who_ls int |
|
1345 | In [4]: %who_ls int | |
1346 | Out[4]: ['alpha'] |
|
1346 | Out[4]: ['alpha'] | |
1347 |
|
1347 | |||
1348 | In [5]: %who_ls str |
|
1348 | In [5]: %who_ls str | |
1349 | Out[5]: ['beta'] |
|
1349 | Out[5]: ['beta'] | |
1350 | """ |
|
1350 | """ | |
1351 |
|
1351 | |||
1352 | user_ns = self.shell.user_ns |
|
1352 | user_ns = self.shell.user_ns | |
1353 | user_ns_hidden = self.shell.user_ns_hidden |
|
1353 | user_ns_hidden = self.shell.user_ns_hidden | |
1354 | out = [ i for i in user_ns |
|
1354 | out = [ i for i in user_ns | |
1355 | if not i.startswith('_') \ |
|
1355 | if not i.startswith('_') \ | |
1356 | and not i in user_ns_hidden ] |
|
1356 | and not i in user_ns_hidden ] | |
1357 |
|
1357 | |||
1358 | typelist = parameter_s.split() |
|
1358 | typelist = parameter_s.split() | |
1359 | if typelist: |
|
1359 | if typelist: | |
1360 | typeset = set(typelist) |
|
1360 | typeset = set(typelist) | |
1361 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
1361 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] | |
1362 |
|
1362 | |||
1363 | out.sort() |
|
1363 | out.sort() | |
1364 | return out |
|
1364 | return out | |
1365 |
|
1365 | |||
1366 | @skip_doctest |
|
1366 | @skip_doctest | |
1367 | @line_magic |
|
1367 | @line_magic | |
1368 | def who(self, parameter_s=''): |
|
1368 | def who(self, parameter_s=''): | |
1369 | """Print all interactive variables, with some minimal formatting. |
|
1369 | """Print all interactive variables, with some minimal formatting. | |
1370 |
|
1370 | |||
1371 | If any arguments are given, only variables whose type matches one of |
|
1371 | If any arguments are given, only variables whose type matches one of | |
1372 | these are printed. For example:: |
|
1372 | these are printed. For example:: | |
1373 |
|
1373 | |||
1374 | %who function str |
|
1374 | %who function str | |
1375 |
|
1375 | |||
1376 | will only list functions and strings, excluding all other types of |
|
1376 | will only list functions and strings, excluding all other types of | |
1377 | variables. To find the proper type names, simply use type(var) at a |
|
1377 | variables. To find the proper type names, simply use type(var) at a | |
1378 | command line to see how python prints type names. For example: |
|
1378 | command line to see how python prints type names. For example: | |
1379 |
|
1379 | |||
1380 | :: |
|
1380 | :: | |
1381 |
|
1381 | |||
1382 | In [1]: type('hello')\\ |
|
1382 | In [1]: type('hello')\\ | |
1383 | Out[1]: <type 'str'> |
|
1383 | Out[1]: <type 'str'> | |
1384 |
|
1384 | |||
1385 | indicates that the type name for strings is 'str'. |
|
1385 | indicates that the type name for strings is 'str'. | |
1386 |
|
1386 | |||
1387 | ``%who`` always excludes executed names loaded through your configuration |
|
1387 | ``%who`` always excludes executed names loaded through your configuration | |
1388 | file and things which are internal to IPython. |
|
1388 | file and things which are internal to IPython. | |
1389 |
|
1389 | |||
1390 | This is deliberate, as typically you may load many modules and the |
|
1390 | This is deliberate, as typically you may load many modules and the | |
1391 | purpose of %who is to show you only what you've manually defined. |
|
1391 | purpose of %who is to show you only what you've manually defined. | |
1392 |
|
1392 | |||
1393 | Examples |
|
1393 | Examples | |
1394 | -------- |
|
1394 | -------- | |
1395 |
|
1395 | |||
1396 | Define two variables and list them with who:: |
|
1396 | Define two variables and list them with who:: | |
1397 |
|
1397 | |||
1398 | In [1]: alpha = 123 |
|
1398 | In [1]: alpha = 123 | |
1399 |
|
1399 | |||
1400 | In [2]: beta = 'test' |
|
1400 | In [2]: beta = 'test' | |
1401 |
|
1401 | |||
1402 | In [3]: %who |
|
1402 | In [3]: %who | |
1403 | alpha beta |
|
1403 | alpha beta | |
1404 |
|
1404 | |||
1405 | In [4]: %who int |
|
1405 | In [4]: %who int | |
1406 | alpha |
|
1406 | alpha | |
1407 |
|
1407 | |||
1408 | In [5]: %who str |
|
1408 | In [5]: %who str | |
1409 | beta |
|
1409 | beta | |
1410 | """ |
|
1410 | """ | |
1411 |
|
1411 | |||
1412 | varlist = self.magic_who_ls(parameter_s) |
|
1412 | varlist = self.magic_who_ls(parameter_s) | |
1413 | if not varlist: |
|
1413 | if not varlist: | |
1414 | if parameter_s: |
|
1414 | if parameter_s: | |
1415 | print 'No variables match your requested type.' |
|
1415 | print 'No variables match your requested type.' | |
1416 | else: |
|
1416 | else: | |
1417 | print 'Interactive namespace is empty.' |
|
1417 | print 'Interactive namespace is empty.' | |
1418 | return |
|
1418 | return | |
1419 |
|
1419 | |||
1420 | # if we have variables, move on... |
|
1420 | # if we have variables, move on... | |
1421 | count = 0 |
|
1421 | count = 0 | |
1422 | for i in varlist: |
|
1422 | for i in varlist: | |
1423 | print i+'\t', |
|
1423 | print i+'\t', | |
1424 | count += 1 |
|
1424 | count += 1 | |
1425 | if count > 8: |
|
1425 | if count > 8: | |
1426 | count = 0 |
|
1426 | count = 0 | |
1427 |
|
1427 | |||
1428 |
|
1428 | |||
1429 |
|
1429 | |||
1430 | @skip_doctest |
|
1430 | @skip_doctest | |
1431 | @line_magic |
|
1431 | @line_magic | |
1432 | def whos(self, parameter_s=''): |
|
1432 | def whos(self, parameter_s=''): | |
1433 | """Like %who, but gives some extra information about each variable. |
|
1433 | """Like %who, but gives some extra information about each variable. | |
1434 |
|
1434 | |||
1435 | The same type filtering of %who can be applied here. |
|
1435 | The same type filtering of %who can be applied here. | |
1436 |
|
1436 | |||
1437 | For all variables, the type is printed. Additionally it prints: |
|
1437 | For all variables, the type is printed. Additionally it prints: | |
1438 |
|
1438 | |||
1439 | - For {},[],(): their length. |
|
1439 | - For {},[],(): their length. | |
1440 |
|
1440 | |||
1441 | - For numpy arrays, a summary with shape, number of |
|
1441 | - For numpy arrays, a summary with shape, number of | |
1442 | elements, typecode and size in memory. |
|
1442 | elements, typecode and size in memory. | |
1443 |
|
1443 | |||
1444 | - Everything else: a string representation, snipping their middle if |
|
1444 | - Everything else: a string representation, snipping their middle if | |
1445 | too long. |
|
1445 | too long. | |
1446 |
|
1446 | |||
1447 | Examples |
|
1447 | Examples | |
1448 | -------- |
|
1448 | -------- | |
1449 |
|
1449 | |||
1450 | Define two variables and list them with whos:: |
|
1450 | Define two variables and list them with whos:: | |
1451 |
|
1451 | |||
1452 | In [1]: alpha = 123 |
|
1452 | In [1]: alpha = 123 | |
1453 |
|
1453 | |||
1454 | In [2]: beta = 'test' |
|
1454 | In [2]: beta = 'test' | |
1455 |
|
1455 | |||
1456 | In [3]: %whos |
|
1456 | In [3]: %whos | |
1457 | Variable Type Data/Info |
|
1457 | Variable Type Data/Info | |
1458 | -------------------------------- |
|
1458 | -------------------------------- | |
1459 | alpha int 123 |
|
1459 | alpha int 123 | |
1460 | beta str test |
|
1460 | beta str test | |
1461 | """ |
|
1461 | """ | |
1462 |
|
1462 | |||
1463 | varnames = self.magic_who_ls(parameter_s) |
|
1463 | varnames = self.magic_who_ls(parameter_s) | |
1464 | if not varnames: |
|
1464 | if not varnames: | |
1465 | if parameter_s: |
|
1465 | if parameter_s: | |
1466 | print 'No variables match your requested type.' |
|
1466 | print 'No variables match your requested type.' | |
1467 | else: |
|
1467 | else: | |
1468 | print 'Interactive namespace is empty.' |
|
1468 | print 'Interactive namespace is empty.' | |
1469 | return |
|
1469 | return | |
1470 |
|
1470 | |||
1471 | # if we have variables, move on... |
|
1471 | # if we have variables, move on... | |
1472 |
|
1472 | |||
1473 | # for these types, show len() instead of data: |
|
1473 | # for these types, show len() instead of data: | |
1474 | seq_types = ['dict', 'list', 'tuple'] |
|
1474 | seq_types = ['dict', 'list', 'tuple'] | |
1475 |
|
1475 | |||
1476 | # for numpy arrays, display summary info |
|
1476 | # for numpy arrays, display summary info | |
1477 | ndarray_type = None |
|
1477 | ndarray_type = None | |
1478 | if 'numpy' in sys.modules: |
|
1478 | if 'numpy' in sys.modules: | |
1479 | try: |
|
1479 | try: | |
1480 | from numpy import ndarray |
|
1480 | from numpy import ndarray | |
1481 | except ImportError: |
|
1481 | except ImportError: | |
1482 | pass |
|
1482 | pass | |
1483 | else: |
|
1483 | else: | |
1484 | ndarray_type = ndarray.__name__ |
|
1484 | ndarray_type = ndarray.__name__ | |
1485 |
|
1485 | |||
1486 | # Find all variable names and types so we can figure out column sizes |
|
1486 | # Find all variable names and types so we can figure out column sizes | |
1487 | def get_vars(i): |
|
1487 | def get_vars(i): | |
1488 | return self.shell.user_ns[i] |
|
1488 | return self.shell.user_ns[i] | |
1489 |
|
1489 | |||
1490 | # some types are well known and can be shorter |
|
1490 | # some types are well known and can be shorter | |
1491 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
1491 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
1492 | def type_name(v): |
|
1492 | def type_name(v): | |
1493 | tn = type(v).__name__ |
|
1493 | tn = type(v).__name__ | |
1494 | return abbrevs.get(tn,tn) |
|
1494 | return abbrevs.get(tn,tn) | |
1495 |
|
1495 | |||
1496 | varlist = map(get_vars,varnames) |
|
1496 | varlist = map(get_vars,varnames) | |
1497 |
|
1497 | |||
1498 | typelist = [] |
|
1498 | typelist = [] | |
1499 | for vv in varlist: |
|
1499 | for vv in varlist: | |
1500 | tt = type_name(vv) |
|
1500 | tt = type_name(vv) | |
1501 |
|
1501 | |||
1502 | if tt=='instance': |
|
1502 | if tt=='instance': | |
1503 | typelist.append( abbrevs.get(str(vv.__class__), |
|
1503 | typelist.append( abbrevs.get(str(vv.__class__), | |
1504 | str(vv.__class__))) |
|
1504 | str(vv.__class__))) | |
1505 | else: |
|
1505 | else: | |
1506 | typelist.append(tt) |
|
1506 | typelist.append(tt) | |
1507 |
|
1507 | |||
1508 | # column labels and # of spaces as separator |
|
1508 | # column labels and # of spaces as separator | |
1509 | varlabel = 'Variable' |
|
1509 | varlabel = 'Variable' | |
1510 | typelabel = 'Type' |
|
1510 | typelabel = 'Type' | |
1511 | datalabel = 'Data/Info' |
|
1511 | datalabel = 'Data/Info' | |
1512 | colsep = 3 |
|
1512 | colsep = 3 | |
1513 | # variable format strings |
|
1513 | # variable format strings | |
1514 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" |
|
1514 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" | |
1515 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
1515 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
1516 | # find the size of the columns to format the output nicely |
|
1516 | # find the size of the columns to format the output nicely | |
1517 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
1517 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
1518 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
1518 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
1519 | # table header |
|
1519 | # table header | |
1520 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
1520 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
1521 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
1521 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
1522 | # and the table itself |
|
1522 | # and the table itself | |
1523 | kb = 1024 |
|
1523 | kb = 1024 | |
1524 | Mb = 1048576 # kb**2 |
|
1524 | Mb = 1048576 # kb**2 | |
1525 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
1525 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
1526 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), |
|
1526 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), | |
1527 | if vtype in seq_types: |
|
1527 | if vtype in seq_types: | |
1528 | print "n="+str(len(var)) |
|
1528 | print "n="+str(len(var)) | |
1529 | elif vtype == ndarray_type: |
|
1529 | elif vtype == ndarray_type: | |
1530 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
1530 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
1531 | if vtype==ndarray_type: |
|
1531 | if vtype==ndarray_type: | |
1532 | # numpy |
|
1532 | # numpy | |
1533 | vsize = var.size |
|
1533 | vsize = var.size | |
1534 | vbytes = vsize*var.itemsize |
|
1534 | vbytes = vsize*var.itemsize | |
1535 | vdtype = var.dtype |
|
1535 | vdtype = var.dtype | |
1536 |
|
1536 | |||
1537 | if vbytes < 100000: |
|
1537 | if vbytes < 100000: | |
1538 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
1538 | print aformat % (vshape,vsize,vdtype,vbytes) | |
1539 | else: |
|
1539 | else: | |
1540 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
1540 | print aformat % (vshape,vsize,vdtype,vbytes), | |
1541 | if vbytes < Mb: |
|
1541 | if vbytes < Mb: | |
1542 | print '(%s kb)' % (vbytes/kb,) |
|
1542 | print '(%s kb)' % (vbytes/kb,) | |
1543 | else: |
|
1543 | else: | |
1544 | print '(%s Mb)' % (vbytes/Mb,) |
|
1544 | print '(%s Mb)' % (vbytes/Mb,) | |
1545 | else: |
|
1545 | else: | |
1546 | try: |
|
1546 | try: | |
1547 | vstr = str(var) |
|
1547 | vstr = str(var) | |
1548 | except UnicodeEncodeError: |
|
1548 | except UnicodeEncodeError: | |
1549 | vstr = unicode(var).encode(DEFAULT_ENCODING, |
|
1549 | vstr = unicode(var).encode(DEFAULT_ENCODING, | |
1550 | 'backslashreplace') |
|
1550 | 'backslashreplace') | |
1551 | except: |
|
1551 | except: | |
1552 | vstr = "<object with id %d (str() failed)>" % id(var) |
|
1552 | vstr = "<object with id %d (str() failed)>" % id(var) | |
1553 | vstr = vstr.replace('\n','\\n') |
|
1553 | vstr = vstr.replace('\n','\\n') | |
1554 | if len(vstr) < 50: |
|
1554 | if len(vstr) < 50: | |
1555 | print vstr |
|
1555 | print vstr | |
1556 | else: |
|
1556 | else: | |
1557 | print vstr[:25] + "<...>" + vstr[-25:] |
|
1557 | print vstr[:25] + "<...>" + vstr[-25:] | |
1558 |
|
1558 | |||
1559 | @line_magic |
|
1559 | @line_magic | |
1560 | def reset(self, parameter_s=''): |
|
1560 | def reset(self, parameter_s=''): | |
1561 | """Resets the namespace by removing all names defined by the user, if |
|
1561 | """Resets the namespace by removing all names defined by the user, if | |
1562 | called without arguments, or by removing some types of objects, such |
|
1562 | called without arguments, or by removing some types of objects, such | |
1563 | as everything currently in IPython's In[] and Out[] containers (see |
|
1563 | as everything currently in IPython's In[] and Out[] containers (see | |
1564 | the parameters for details). |
|
1564 | the parameters for details). | |
1565 |
|
1565 | |||
1566 | Parameters |
|
1566 | Parameters | |
1567 | ---------- |
|
1567 | ---------- | |
1568 | -f : force reset without asking for confirmation. |
|
1568 | -f : force reset without asking for confirmation. | |
1569 |
|
1569 | |||
1570 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. |
|
1570 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. | |
1571 | References to objects may be kept. By default (without this option), |
|
1571 | References to objects may be kept. By default (without this option), | |
1572 | we do a 'hard' reset, giving you a new session and removing all |
|
1572 | we do a 'hard' reset, giving you a new session and removing all | |
1573 | references to objects from the current session. |
|
1573 | references to objects from the current session. | |
1574 |
|
1574 | |||
1575 | in : reset input history |
|
1575 | in : reset input history | |
1576 |
|
1576 | |||
1577 | out : reset output history |
|
1577 | out : reset output history | |
1578 |
|
1578 | |||
1579 | dhist : reset directory history |
|
1579 | dhist : reset directory history | |
1580 |
|
1580 | |||
1581 | array : reset only variables that are NumPy arrays |
|
1581 | array : reset only variables that are NumPy arrays | |
1582 |
|
1582 | |||
1583 | See Also |
|
1583 | See Also | |
1584 | -------- |
|
1584 | -------- | |
1585 | magic_reset_selective : invoked as ``%reset_selective`` |
|
1585 | magic_reset_selective : invoked as ``%reset_selective`` | |
1586 |
|
1586 | |||
1587 | Examples |
|
1587 | Examples | |
1588 | -------- |
|
1588 | -------- | |
1589 | :: |
|
1589 | :: | |
1590 |
|
1590 | |||
1591 | In [6]: a = 1 |
|
1591 | In [6]: a = 1 | |
1592 |
|
1592 | |||
1593 | In [7]: a |
|
1593 | In [7]: a | |
1594 | Out[7]: 1 |
|
1594 | Out[7]: 1 | |
1595 |
|
1595 | |||
1596 | In [8]: 'a' in _ip.user_ns |
|
1596 | In [8]: 'a' in _ip.user_ns | |
1597 | Out[8]: True |
|
1597 | Out[8]: True | |
1598 |
|
1598 | |||
1599 | In [9]: %reset -f |
|
1599 | In [9]: %reset -f | |
1600 |
|
1600 | |||
1601 | In [1]: 'a' in _ip.user_ns |
|
1601 | In [1]: 'a' in _ip.user_ns | |
1602 | Out[1]: False |
|
1602 | Out[1]: False | |
1603 |
|
1603 | |||
1604 | In [2]: %reset -f in |
|
1604 | In [2]: %reset -f in | |
1605 | Flushing input history |
|
1605 | Flushing input history | |
1606 |
|
1606 | |||
1607 | In [3]: %reset -f dhist in |
|
1607 | In [3]: %reset -f dhist in | |
1608 | Flushing directory history |
|
1608 | Flushing directory history | |
1609 | Flushing input history |
|
1609 | Flushing input history | |
1610 |
|
1610 | |||
1611 | Notes |
|
1611 | Notes | |
1612 | ----- |
|
1612 | ----- | |
1613 | Calling this magic from clients that do not implement standard input, |
|
1613 | Calling this magic from clients that do not implement standard input, | |
1614 | such as the ipython notebook interface, will reset the namespace |
|
1614 | such as the ipython notebook interface, will reset the namespace | |
1615 | without confirmation. |
|
1615 | without confirmation. | |
1616 | """ |
|
1616 | """ | |
1617 | opts, args = self.parse_options(parameter_s,'sf', mode='list') |
|
1617 | opts, args = self.parse_options(parameter_s,'sf', mode='list') | |
1618 | if 'f' in opts: |
|
1618 | if 'f' in opts: | |
1619 | ans = True |
|
1619 | ans = True | |
1620 | else: |
|
1620 | else: | |
1621 | try: |
|
1621 | try: | |
1622 | ans = self.shell.ask_yes_no( |
|
1622 | ans = self.shell.ask_yes_no( | |
1623 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n') |
|
1623 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n') | |
1624 | except StdinNotImplementedError: |
|
1624 | except StdinNotImplementedError: | |
1625 | ans = True |
|
1625 | ans = True | |
1626 | if not ans: |
|
1626 | if not ans: | |
1627 | print 'Nothing done.' |
|
1627 | print 'Nothing done.' | |
1628 | return |
|
1628 | return | |
1629 |
|
1629 | |||
1630 | if 's' in opts: # Soft reset |
|
1630 | if 's' in opts: # Soft reset | |
1631 | user_ns = self.shell.user_ns |
|
1631 | user_ns = self.shell.user_ns | |
1632 | for i in self.magic_who_ls(): |
|
1632 | for i in self.magic_who_ls(): | |
1633 | del(user_ns[i]) |
|
1633 | del(user_ns[i]) | |
1634 | elif len(args) == 0: # Hard reset |
|
1634 | elif len(args) == 0: # Hard reset | |
1635 | self.shell.reset(new_session = False) |
|
1635 | self.shell.reset(new_session = False) | |
1636 |
|
1636 | |||
1637 | # reset in/out/dhist/array: previously extensinions/clearcmd.py |
|
1637 | # reset in/out/dhist/array: previously extensinions/clearcmd.py | |
1638 | ip = self.shell |
|
1638 | ip = self.shell | |
1639 | user_ns = self.shell.user_ns # local lookup, heavily used |
|
1639 | user_ns = self.shell.user_ns # local lookup, heavily used | |
1640 |
|
1640 | |||
1641 | for target in args: |
|
1641 | for target in args: | |
1642 | target = target.lower() # make matches case insensitive |
|
1642 | target = target.lower() # make matches case insensitive | |
1643 | if target == 'out': |
|
1643 | if target == 'out': | |
1644 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) |
|
1644 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) | |
1645 | self.shell.displayhook.flush() |
|
1645 | self.shell.displayhook.flush() | |
1646 |
|
1646 | |||
1647 | elif target == 'in': |
|
1647 | elif target == 'in': | |
1648 | print "Flushing input history" |
|
1648 | print "Flushing input history" | |
1649 | pc = self.shell.displayhook.prompt_count + 1 |
|
1649 | pc = self.shell.displayhook.prompt_count + 1 | |
1650 | for n in range(1, pc): |
|
1650 | for n in range(1, pc): | |
1651 | key = '_i'+repr(n) |
|
1651 | key = '_i'+repr(n) | |
1652 | user_ns.pop(key,None) |
|
1652 | user_ns.pop(key,None) | |
1653 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) |
|
1653 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) | |
1654 | hm = ip.history_manager |
|
1654 | hm = ip.history_manager | |
1655 | # don't delete these, as %save and %macro depending on the length |
|
1655 | # don't delete these, as %save and %macro depending on the length | |
1656 | # of these lists to be preserved |
|
1656 | # of these lists to be preserved | |
1657 | hm.input_hist_parsed[:] = [''] * pc |
|
1657 | hm.input_hist_parsed[:] = [''] * pc | |
1658 | hm.input_hist_raw[:] = [''] * pc |
|
1658 | hm.input_hist_raw[:] = [''] * pc | |
1659 | # hm has internal machinery for _i,_ii,_iii, clear it out |
|
1659 | # hm has internal machinery for _i,_ii,_iii, clear it out | |
1660 | hm._i = hm._ii = hm._iii = hm._i00 = u'' |
|
1660 | hm._i = hm._ii = hm._iii = hm._i00 = u'' | |
1661 |
|
1661 | |||
1662 | elif target == 'array': |
|
1662 | elif target == 'array': | |
1663 | # Support cleaning up numpy arrays |
|
1663 | # Support cleaning up numpy arrays | |
1664 | try: |
|
1664 | try: | |
1665 | from numpy import ndarray |
|
1665 | from numpy import ndarray | |
1666 | # This must be done with items and not iteritems because we're |
|
1666 | # This must be done with items and not iteritems because we're | |
1667 | # going to modify the dict in-place. |
|
1667 | # going to modify the dict in-place. | |
1668 | for x,val in user_ns.items(): |
|
1668 | for x,val in user_ns.items(): | |
1669 | if isinstance(val,ndarray): |
|
1669 | if isinstance(val,ndarray): | |
1670 | del user_ns[x] |
|
1670 | del user_ns[x] | |
1671 | except ImportError: |
|
1671 | except ImportError: | |
1672 | print "reset array only works if Numpy is available." |
|
1672 | print "reset array only works if Numpy is available." | |
1673 |
|
1673 | |||
1674 | elif target == 'dhist': |
|
1674 | elif target == 'dhist': | |
1675 | print "Flushing directory history" |
|
1675 | print "Flushing directory history" | |
1676 | del user_ns['_dh'][:] |
|
1676 | del user_ns['_dh'][:] | |
1677 |
|
1677 | |||
1678 | else: |
|
1678 | else: | |
1679 | print "Don't know how to reset ", |
|
1679 | print "Don't know how to reset ", | |
1680 | print target + ", please run `%reset?` for details" |
|
1680 | print target + ", please run `%reset?` for details" | |
1681 |
|
1681 | |||
1682 | gc.collect() |
|
1682 | gc.collect() | |
1683 |
|
1683 | |||
1684 | @line_magic |
|
1684 | @line_magic | |
1685 | def reset_selective(self, parameter_s=''): |
|
1685 | def reset_selective(self, parameter_s=''): | |
1686 | """Resets the namespace by removing names defined by the user. |
|
1686 | """Resets the namespace by removing names defined by the user. | |
1687 |
|
1687 | |||
1688 | Input/Output history are left around in case you need them. |
|
1688 | Input/Output history are left around in case you need them. | |
1689 |
|
1689 | |||
1690 | %reset_selective [-f] regex |
|
1690 | %reset_selective [-f] regex | |
1691 |
|
1691 | |||
1692 | No action is taken if regex is not included |
|
1692 | No action is taken if regex is not included | |
1693 |
|
1693 | |||
1694 | Options |
|
1694 | Options | |
1695 | -f : force reset without asking for confirmation. |
|
1695 | -f : force reset without asking for confirmation. | |
1696 |
|
1696 | |||
1697 | See Also |
|
1697 | See Also | |
1698 | -------- |
|
1698 | -------- | |
1699 | magic_reset : invoked as ``%reset`` |
|
1699 | magic_reset : invoked as ``%reset`` | |
1700 |
|
1700 | |||
1701 | Examples |
|
1701 | Examples | |
1702 | -------- |
|
1702 | -------- | |
1703 |
|
1703 | |||
1704 | We first fully reset the namespace so your output looks identical to |
|
1704 | We first fully reset the namespace so your output looks identical to | |
1705 | this example for pedagogical reasons; in practice you do not need a |
|
1705 | this example for pedagogical reasons; in practice you do not need a | |
1706 | full reset:: |
|
1706 | full reset:: | |
1707 |
|
1707 | |||
1708 | In [1]: %reset -f |
|
1708 | In [1]: %reset -f | |
1709 |
|
1709 | |||
1710 | Now, with a clean namespace we can make a few variables and use |
|
1710 | Now, with a clean namespace we can make a few variables and use | |
1711 | ``%reset_selective`` to only delete names that match our regexp:: |
|
1711 | ``%reset_selective`` to only delete names that match our regexp:: | |
1712 |
|
1712 | |||
1713 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
1713 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
1714 |
|
1714 | |||
1715 | In [3]: who_ls |
|
1715 | In [3]: who_ls | |
1716 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
1716 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
1717 |
|
1717 | |||
1718 | In [4]: %reset_selective -f b[2-3]m |
|
1718 | In [4]: %reset_selective -f b[2-3]m | |
1719 |
|
1719 | |||
1720 | In [5]: who_ls |
|
1720 | In [5]: who_ls | |
1721 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1721 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1722 |
|
1722 | |||
1723 | In [6]: %reset_selective -f d |
|
1723 | In [6]: %reset_selective -f d | |
1724 |
|
1724 | |||
1725 | In [7]: who_ls |
|
1725 | In [7]: who_ls | |
1726 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1726 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1727 |
|
1727 | |||
1728 | In [8]: %reset_selective -f c |
|
1728 | In [8]: %reset_selective -f c | |
1729 |
|
1729 | |||
1730 | In [9]: who_ls |
|
1730 | In [9]: who_ls | |
1731 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
1731 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
1732 |
|
1732 | |||
1733 | In [10]: %reset_selective -f b |
|
1733 | In [10]: %reset_selective -f b | |
1734 |
|
1734 | |||
1735 | In [11]: who_ls |
|
1735 | In [11]: who_ls | |
1736 | Out[11]: ['a'] |
|
1736 | Out[11]: ['a'] | |
1737 |
|
1737 | |||
1738 | Notes |
|
1738 | Notes | |
1739 | ----- |
|
1739 | ----- | |
1740 | Calling this magic from clients that do not implement standard input, |
|
1740 | Calling this magic from clients that do not implement standard input, | |
1741 | such as the ipython notebook interface, will reset the namespace |
|
1741 | such as the ipython notebook interface, will reset the namespace | |
1742 | without confirmation. |
|
1742 | without confirmation. | |
1743 | """ |
|
1743 | """ | |
1744 |
|
1744 | |||
1745 | opts, regex = self.parse_options(parameter_s,'f') |
|
1745 | opts, regex = self.parse_options(parameter_s,'f') | |
1746 |
|
1746 | |||
1747 | if opts.has_key('f'): |
|
1747 | if opts.has_key('f'): | |
1748 | ans = True |
|
1748 | ans = True | |
1749 | else: |
|
1749 | else: | |
1750 | try: |
|
1750 | try: | |
1751 | ans = self.shell.ask_yes_no( |
|
1751 | ans = self.shell.ask_yes_no( | |
1752 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", |
|
1752 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", | |
1753 | default='n') |
|
1753 | default='n') | |
1754 | except StdinNotImplementedError: |
|
1754 | except StdinNotImplementedError: | |
1755 | ans = True |
|
1755 | ans = True | |
1756 | if not ans: |
|
1756 | if not ans: | |
1757 | print 'Nothing done.' |
|
1757 | print 'Nothing done.' | |
1758 | return |
|
1758 | return | |
1759 | user_ns = self.shell.user_ns |
|
1759 | user_ns = self.shell.user_ns | |
1760 | if not regex: |
|
1760 | if not regex: | |
1761 | print 'No regex pattern specified. Nothing done.' |
|
1761 | print 'No regex pattern specified. Nothing done.' | |
1762 | return |
|
1762 | return | |
1763 | else: |
|
1763 | else: | |
1764 | try: |
|
1764 | try: | |
1765 | m = re.compile(regex) |
|
1765 | m = re.compile(regex) | |
1766 | except TypeError: |
|
1766 | except TypeError: | |
1767 | raise TypeError('regex must be a string or compiled pattern') |
|
1767 | raise TypeError('regex must be a string or compiled pattern') | |
1768 | for i in self.magic_who_ls(): |
|
1768 | for i in self.magic_who_ls(): | |
1769 | if m.search(i): |
|
1769 | if m.search(i): | |
1770 | del(user_ns[i]) |
|
1770 | del(user_ns[i]) | |
1771 |
|
1771 | |||
1772 | @line_magic |
|
1772 | @line_magic | |
1773 | def xdel(self, parameter_s=''): |
|
1773 | def xdel(self, parameter_s=''): | |
1774 | """Delete a variable, trying to clear it from anywhere that |
|
1774 | """Delete a variable, trying to clear it from anywhere that | |
1775 | IPython's machinery has references to it. By default, this uses |
|
1775 | IPython's machinery has references to it. By default, this uses | |
1776 | the identity of the named object in the user namespace to remove |
|
1776 | the identity of the named object in the user namespace to remove | |
1777 | references held under other names. The object is also removed |
|
1777 | references held under other names. The object is also removed | |
1778 | from the output history. |
|
1778 | from the output history. | |
1779 |
|
1779 | |||
1780 | Options |
|
1780 | Options | |
1781 | -n : Delete the specified name from all namespaces, without |
|
1781 | -n : Delete the specified name from all namespaces, without | |
1782 | checking their identity. |
|
1782 | checking their identity. | |
1783 | """ |
|
1783 | """ | |
1784 | opts, varname = self.parse_options(parameter_s,'n') |
|
1784 | opts, varname = self.parse_options(parameter_s,'n') | |
1785 | try: |
|
1785 | try: | |
1786 | self.shell.del_var(varname, ('n' in opts)) |
|
1786 | self.shell.del_var(varname, ('n' in opts)) | |
1787 | except (NameError, ValueError) as e: |
|
1787 | except (NameError, ValueError) as e: | |
1788 | print type(e).__name__ +": "+ str(e) |
|
1788 | print type(e).__name__ +": "+ str(e) | |
1789 |
|
1789 | |||
1790 |
|
1790 | |||
1791 | @register_magics |
|
1791 | @register_magics | |
1792 | class ExecutionMagics(Magics): |
|
1792 | class ExecutionMagics(Magics): | |
1793 | """Magics related to code execution, debugging, profiling, etc. |
|
1793 | """Magics related to code execution, debugging, profiling, etc. | |
1794 |
|
1794 | |||
1795 | """ |
|
1795 | """ | |
1796 |
|
1796 | |||
1797 | def __init__(self, shell): |
|
1797 | def __init__(self, shell): | |
1798 | super(ExecutionMagics, self).__init__(shell) |
|
1798 | super(ExecutionMagics, self).__init__(shell) | |
1799 | if profile is None: |
|
1799 | if profile is None: | |
1800 | self.magic_prun = self.profile_missing_notice |
|
1800 | self.magic_prun = self.profile_missing_notice | |
1801 | # Default execution function used to actually run user code. |
|
1801 | # Default execution function used to actually run user code. | |
1802 | self.default_runner = None |
|
1802 | self.default_runner = None | |
1803 |
|
1803 | |||
1804 | def profile_missing_notice(self, *args, **kwargs): |
|
1804 | def profile_missing_notice(self, *args, **kwargs): | |
1805 | error("""\ |
|
1805 | error("""\ | |
1806 | The profile module could not be found. It has been removed from the standard |
|
1806 | The profile module could not be found. It has been removed from the standard | |
1807 | python packages because of its non-free license. To use profiling, install the |
|
1807 | python packages because of its non-free license. To use profiling, install the | |
1808 | python-profiler package from non-free.""") |
|
1808 | python-profiler package from non-free.""") | |
1809 |
|
1809 | |||
1810 | @skip_doctest |
|
1810 | @skip_doctest | |
1811 | @line_magic |
|
1811 | @line_magic | |
1812 | def prun(self, parameter_s='',user_mode=1, |
|
1812 | def prun(self, parameter_s='',user_mode=1, | |
1813 | opts=None,arg_lst=None,prog_ns=None): |
|
1813 | opts=None,arg_lst=None,prog_ns=None): | |
1814 |
|
1814 | |||
1815 | """Run a statement through the python code profiler. |
|
1815 | """Run a statement through the python code profiler. | |
1816 |
|
1816 | |||
1817 | Usage: |
|
1817 | Usage: | |
1818 | %prun [options] statement |
|
1818 | %prun [options] statement | |
1819 |
|
1819 | |||
1820 | The given statement (which doesn't require quote marks) is run via the |
|
1820 | The given statement (which doesn't require quote marks) is run via the | |
1821 | python profiler in a manner similar to the profile.run() function. |
|
1821 | python profiler in a manner similar to the profile.run() function. | |
1822 | Namespaces are internally managed to work correctly; profile.run |
|
1822 | Namespaces are internally managed to work correctly; profile.run | |
1823 | cannot be used in IPython because it makes certain assumptions about |
|
1823 | cannot be used in IPython because it makes certain assumptions about | |
1824 | namespaces which do not hold under IPython. |
|
1824 | namespaces which do not hold under IPython. | |
1825 |
|
1825 | |||
1826 | Options: |
|
1826 | Options: | |
1827 |
|
1827 | |||
1828 | -l <limit>: you can place restrictions on what or how much of the |
|
1828 | -l <limit>: you can place restrictions on what or how much of the | |
1829 | profile gets printed. The limit value can be: |
|
1829 | profile gets printed. The limit value can be: | |
1830 |
|
1830 | |||
1831 | * A string: only information for function names containing this string |
|
1831 | * A string: only information for function names containing this string | |
1832 | is printed. |
|
1832 | is printed. | |
1833 |
|
1833 | |||
1834 | * An integer: only these many lines are printed. |
|
1834 | * An integer: only these many lines are printed. | |
1835 |
|
1835 | |||
1836 | * A float (between 0 and 1): this fraction of the report is printed |
|
1836 | * A float (between 0 and 1): this fraction of the report is printed | |
1837 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1837 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1838 |
|
1838 | |||
1839 | You can combine several limits with repeated use of the option. For |
|
1839 | You can combine several limits with repeated use of the option. For | |
1840 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1840 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1841 | information about class constructors. |
|
1841 | information about class constructors. | |
1842 |
|
1842 | |||
1843 | -r: return the pstats.Stats object generated by the profiling. This |
|
1843 | -r: return the pstats.Stats object generated by the profiling. This | |
1844 | object has all the information about the profile in it, and you can |
|
1844 | object has all the information about the profile in it, and you can | |
1845 | later use it for further analysis or in other functions. |
|
1845 | later use it for further analysis or in other functions. | |
1846 |
|
1846 | |||
1847 | -s <key>: sort profile by given key. You can provide more than one key |
|
1847 | -s <key>: sort profile by given key. You can provide more than one key | |
1848 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1848 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1849 | default sorting key is 'time'. |
|
1849 | default sorting key is 'time'. | |
1850 |
|
1850 | |||
1851 | The following is copied verbatim from the profile documentation |
|
1851 | The following is copied verbatim from the profile documentation | |
1852 | referenced below: |
|
1852 | referenced below: | |
1853 |
|
1853 | |||
1854 | When more than one key is provided, additional keys are used as |
|
1854 | When more than one key is provided, additional keys are used as | |
1855 | secondary criteria when the there is equality in all keys selected |
|
1855 | secondary criteria when the there is equality in all keys selected | |
1856 | before them. |
|
1856 | before them. | |
1857 |
|
1857 | |||
1858 | Abbreviations can be used for any key names, as long as the |
|
1858 | Abbreviations can be used for any key names, as long as the | |
1859 | abbreviation is unambiguous. The following are the keys currently |
|
1859 | abbreviation is unambiguous. The following are the keys currently | |
1860 | defined: |
|
1860 | defined: | |
1861 |
|
1861 | |||
1862 | Valid Arg Meaning |
|
1862 | Valid Arg Meaning | |
1863 | "calls" call count |
|
1863 | "calls" call count | |
1864 | "cumulative" cumulative time |
|
1864 | "cumulative" cumulative time | |
1865 | "file" file name |
|
1865 | "file" file name | |
1866 | "module" file name |
|
1866 | "module" file name | |
1867 | "pcalls" primitive call count |
|
1867 | "pcalls" primitive call count | |
1868 | "line" line number |
|
1868 | "line" line number | |
1869 | "name" function name |
|
1869 | "name" function name | |
1870 | "nfl" name/file/line |
|
1870 | "nfl" name/file/line | |
1871 | "stdname" standard name |
|
1871 | "stdname" standard name | |
1872 | "time" internal time |
|
1872 | "time" internal time | |
1873 |
|
1873 | |||
1874 | Note that all sorts on statistics are in descending order (placing |
|
1874 | Note that all sorts on statistics are in descending order (placing | |
1875 | most time consuming items first), where as name, file, and line number |
|
1875 | most time consuming items first), where as name, file, and line number | |
1876 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1876 | searches are in ascending order (i.e., alphabetical). The subtle | |
1877 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1877 | distinction between "nfl" and "stdname" is that the standard name is a | |
1878 | sort of the name as printed, which means that the embedded line |
|
1878 | sort of the name as printed, which means that the embedded line | |
1879 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1879 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1880 | would (if the file names were the same) appear in the string order |
|
1880 | would (if the file names were the same) appear in the string order | |
1881 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1881 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1882 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1882 | line numbers. In fact, sort_stats("nfl") is the same as | |
1883 | sort_stats("name", "file", "line"). |
|
1883 | sort_stats("name", "file", "line"). | |
1884 |
|
1884 | |||
1885 | -T <filename>: save profile results as shown on screen to a text |
|
1885 | -T <filename>: save profile results as shown on screen to a text | |
1886 | file. The profile is still shown on screen. |
|
1886 | file. The profile is still shown on screen. | |
1887 |
|
1887 | |||
1888 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1888 | -D <filename>: save (via dump_stats) profile statistics to given | |
1889 | filename. This data is in a format understood by the pstats module, and |
|
1889 | filename. This data is in a format understood by the pstats module, and | |
1890 | is generated by a call to the dump_stats() method of profile |
|
1890 | is generated by a call to the dump_stats() method of profile | |
1891 | objects. The profile is still shown on screen. |
|
1891 | objects. The profile is still shown on screen. | |
1892 |
|
1892 | |||
1893 | -q: suppress output to the pager. Best used with -T and/or -D above. |
|
1893 | -q: suppress output to the pager. Best used with -T and/or -D above. | |
1894 |
|
1894 | |||
1895 | If you want to run complete programs under the profiler's control, use |
|
1895 | If you want to run complete programs under the profiler's control, use | |
1896 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1896 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1897 | contains profiler specific options as described here. |
|
1897 | contains profiler specific options as described here. | |
1898 |
|
1898 | |||
1899 | You can read the complete documentation for the profile module with:: |
|
1899 | You can read the complete documentation for the profile module with:: | |
1900 |
|
1900 | |||
1901 | In [1]: import profile; profile.help() |
|
1901 | In [1]: import profile; profile.help() | |
1902 | """ |
|
1902 | """ | |
1903 |
|
1903 | |||
1904 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1904 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1905 |
|
1905 | |||
1906 | if user_mode: # regular user call |
|
1906 | if user_mode: # regular user call | |
1907 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q', |
|
1907 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q', | |
1908 | list_all=1, posix=False) |
|
1908 | list_all=1, posix=False) | |
1909 | namespace = self.shell.user_ns |
|
1909 | namespace = self.shell.user_ns | |
1910 | else: # called to run a program by %run -p |
|
1910 | else: # called to run a program by %run -p | |
1911 | try: |
|
1911 | try: | |
1912 | filename = get_py_filename(arg_lst[0]) |
|
1912 | filename = get_py_filename(arg_lst[0]) | |
1913 | except IOError as e: |
|
1913 | except IOError as e: | |
1914 | try: |
|
1914 | try: | |
1915 | msg = str(e) |
|
1915 | msg = str(e) | |
1916 | except UnicodeError: |
|
1916 | except UnicodeError: | |
1917 | msg = e.message |
|
1917 | msg = e.message | |
1918 | error(msg) |
|
1918 | error(msg) | |
1919 | return |
|
1919 | return | |
1920 |
|
1920 | |||
1921 | arg_str = 'execfile(filename,prog_ns)' |
|
1921 | arg_str = 'execfile(filename,prog_ns)' | |
1922 | namespace = { |
|
1922 | namespace = { | |
1923 | 'execfile': self.shell.safe_execfile, |
|
1923 | 'execfile': self.shell.safe_execfile, | |
1924 | 'prog_ns': prog_ns, |
|
1924 | 'prog_ns': prog_ns, | |
1925 | 'filename': filename |
|
1925 | 'filename': filename | |
1926 | } |
|
1926 | } | |
1927 |
|
1927 | |||
1928 | opts.merge(opts_def) |
|
1928 | opts.merge(opts_def) | |
1929 |
|
1929 | |||
1930 | prof = profile.Profile() |
|
1930 | prof = profile.Profile() | |
1931 | try: |
|
1931 | try: | |
1932 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1932 | prof = prof.runctx(arg_str,namespace,namespace) | |
1933 | sys_exit = '' |
|
1933 | sys_exit = '' | |
1934 | except SystemExit: |
|
1934 | except SystemExit: | |
1935 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1935 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1936 |
|
1936 | |||
1937 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1937 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1938 |
|
1938 | |||
1939 | lims = opts.l |
|
1939 | lims = opts.l | |
1940 | if lims: |
|
1940 | if lims: | |
1941 | lims = [] # rebuild lims with ints/floats/strings |
|
1941 | lims = [] # rebuild lims with ints/floats/strings | |
1942 | for lim in opts.l: |
|
1942 | for lim in opts.l: | |
1943 | try: |
|
1943 | try: | |
1944 | lims.append(int(lim)) |
|
1944 | lims.append(int(lim)) | |
1945 | except ValueError: |
|
1945 | except ValueError: | |
1946 | try: |
|
1946 | try: | |
1947 | lims.append(float(lim)) |
|
1947 | lims.append(float(lim)) | |
1948 | except ValueError: |
|
1948 | except ValueError: | |
1949 | lims.append(lim) |
|
1949 | lims.append(lim) | |
1950 |
|
1950 | |||
1951 | # Trap output. |
|
1951 | # Trap output. | |
1952 | stdout_trap = StringIO() |
|
1952 | stdout_trap = StringIO() | |
1953 |
|
1953 | |||
1954 | if hasattr(stats,'stream'): |
|
1954 | if hasattr(stats,'stream'): | |
1955 | # In newer versions of python, the stats object has a 'stream' |
|
1955 | # In newer versions of python, the stats object has a 'stream' | |
1956 | # attribute to write into. |
|
1956 | # attribute to write into. | |
1957 | stats.stream = stdout_trap |
|
1957 | stats.stream = stdout_trap | |
1958 | stats.print_stats(*lims) |
|
1958 | stats.print_stats(*lims) | |
1959 | else: |
|
1959 | else: | |
1960 | # For older versions, we manually redirect stdout during printing |
|
1960 | # For older versions, we manually redirect stdout during printing | |
1961 | sys_stdout = sys.stdout |
|
1961 | sys_stdout = sys.stdout | |
1962 | try: |
|
1962 | try: | |
1963 | sys.stdout = stdout_trap |
|
1963 | sys.stdout = stdout_trap | |
1964 | stats.print_stats(*lims) |
|
1964 | stats.print_stats(*lims) | |
1965 | finally: |
|
1965 | finally: | |
1966 | sys.stdout = sys_stdout |
|
1966 | sys.stdout = sys_stdout | |
1967 |
|
1967 | |||
1968 | output = stdout_trap.getvalue() |
|
1968 | output = stdout_trap.getvalue() | |
1969 | output = output.rstrip() |
|
1969 | output = output.rstrip() | |
1970 |
|
1970 | |||
1971 | if 'q' not in opts: |
|
1971 | if 'q' not in opts: | |
1972 | page.page(output) |
|
1972 | page.page(output) | |
1973 | print sys_exit, |
|
1973 | print sys_exit, | |
1974 |
|
1974 | |||
1975 | dump_file = opts.D[0] |
|
1975 | dump_file = opts.D[0] | |
1976 | text_file = opts.T[0] |
|
1976 | text_file = opts.T[0] | |
1977 | if dump_file: |
|
1977 | if dump_file: | |
1978 | dump_file = unquote_filename(dump_file) |
|
1978 | dump_file = unquote_filename(dump_file) | |
1979 | prof.dump_stats(dump_file) |
|
1979 | prof.dump_stats(dump_file) | |
1980 | print '\n*** Profile stats marshalled to file',\ |
|
1980 | print '\n*** Profile stats marshalled to file',\ | |
1981 | `dump_file`+'.',sys_exit |
|
1981 | `dump_file`+'.',sys_exit | |
1982 | if text_file: |
|
1982 | if text_file: | |
1983 | text_file = unquote_filename(text_file) |
|
1983 | text_file = unquote_filename(text_file) | |
1984 | pfile = open(text_file,'w') |
|
1984 | pfile = open(text_file,'w') | |
1985 | pfile.write(output) |
|
1985 | pfile.write(output) | |
1986 | pfile.close() |
|
1986 | pfile.close() | |
1987 | print '\n*** Profile printout saved to text file',\ |
|
1987 | print '\n*** Profile printout saved to text file',\ | |
1988 | `text_file`+'.',sys_exit |
|
1988 | `text_file`+'.',sys_exit | |
1989 |
|
1989 | |||
1990 | if opts.has_key('r'): |
|
1990 | if opts.has_key('r'): | |
1991 | return stats |
|
1991 | return stats | |
1992 | else: |
|
1992 | else: | |
1993 | return None |
|
1993 | return None | |
1994 |
|
1994 | |||
1995 | @line_magic |
|
1995 | @line_magic | |
1996 | def pdb(self, parameter_s=''): |
|
1996 | def pdb(self, parameter_s=''): | |
1997 | """Control the automatic calling of the pdb interactive debugger. |
|
1997 | """Control the automatic calling of the pdb interactive debugger. | |
1998 |
|
1998 | |||
1999 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1999 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
2000 | argument it works as a toggle. |
|
2000 | argument it works as a toggle. | |
2001 |
|
2001 | |||
2002 | When an exception is triggered, IPython can optionally call the |
|
2002 | When an exception is triggered, IPython can optionally call the | |
2003 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
2003 | interactive pdb debugger after the traceback printout. %pdb toggles | |
2004 | this feature on and off. |
|
2004 | this feature on and off. | |
2005 |
|
2005 | |||
2006 | The initial state of this feature is set in your configuration |
|
2006 | The initial state of this feature is set in your configuration | |
2007 | file (the option is ``InteractiveShell.pdb``). |
|
2007 | file (the option is ``InteractiveShell.pdb``). | |
2008 |
|
2008 | |||
2009 | If you want to just activate the debugger AFTER an exception has fired, |
|
2009 | If you want to just activate the debugger AFTER an exception has fired, | |
2010 | without having to type '%pdb on' and rerunning your code, you can use |
|
2010 | without having to type '%pdb on' and rerunning your code, you can use | |
2011 | the %debug magic.""" |
|
2011 | the %debug magic.""" | |
2012 |
|
2012 | |||
2013 | par = parameter_s.strip().lower() |
|
2013 | par = parameter_s.strip().lower() | |
2014 |
|
2014 | |||
2015 | if par: |
|
2015 | if par: | |
2016 | try: |
|
2016 | try: | |
2017 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
2017 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
2018 | except KeyError: |
|
2018 | except KeyError: | |
2019 | print ('Incorrect argument. Use on/1, off/0, ' |
|
2019 | print ('Incorrect argument. Use on/1, off/0, ' | |
2020 | 'or nothing for a toggle.') |
|
2020 | 'or nothing for a toggle.') | |
2021 | return |
|
2021 | return | |
2022 | else: |
|
2022 | else: | |
2023 | # toggle |
|
2023 | # toggle | |
2024 | new_pdb = not self.shell.call_pdb |
|
2024 | new_pdb = not self.shell.call_pdb | |
2025 |
|
2025 | |||
2026 | # set on the shell |
|
2026 | # set on the shell | |
2027 | self.shell.call_pdb = new_pdb |
|
2027 | self.shell.call_pdb = new_pdb | |
2028 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
2028 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
2029 |
|
2029 | |||
2030 | @line_magic |
|
2030 | @line_magic | |
2031 | def debug(self, parameter_s=''): |
|
2031 | def debug(self, parameter_s=''): | |
2032 | """Activate the interactive debugger in post-mortem mode. |
|
2032 | """Activate the interactive debugger in post-mortem mode. | |
2033 |
|
2033 | |||
2034 | If an exception has just occurred, this lets you inspect its stack |
|
2034 | If an exception has just occurred, this lets you inspect its stack | |
2035 | frames interactively. Note that this will always work only on the last |
|
2035 | frames interactively. Note that this will always work only on the last | |
2036 | traceback that occurred, so you must call this quickly after an |
|
2036 | traceback that occurred, so you must call this quickly after an | |
2037 | exception that you wish to inspect has fired, because if another one |
|
2037 | exception that you wish to inspect has fired, because if another one | |
2038 | occurs, it clobbers the previous one. |
|
2038 | occurs, it clobbers the previous one. | |
2039 |
|
2039 | |||
2040 | If you want IPython to automatically do this on every exception, see |
|
2040 | If you want IPython to automatically do this on every exception, see | |
2041 | the %pdb magic for more details. |
|
2041 | the %pdb magic for more details. | |
2042 | """ |
|
2042 | """ | |
2043 | self.shell.debugger(force=True) |
|
2043 | self.shell.debugger(force=True) | |
2044 |
|
2044 | |||
2045 | @line_magic |
|
2045 | @line_magic | |
2046 | def tb(self, s): |
|
2046 | def tb(self, s): | |
2047 | """Print the last traceback with the currently active exception mode. |
|
2047 | """Print the last traceback with the currently active exception mode. | |
2048 |
|
2048 | |||
2049 | See %xmode for changing exception reporting modes.""" |
|
2049 | See %xmode for changing exception reporting modes.""" | |
2050 | self.shell.showtraceback() |
|
2050 | self.shell.showtraceback() | |
2051 |
|
2051 | |||
2052 | @skip_doctest |
|
2052 | @skip_doctest | |
2053 | @line_magic |
|
2053 | @line_magic | |
2054 | def run(self, parameter_s='', runner=None, |
|
2054 | def run(self, parameter_s='', runner=None, | |
2055 | file_finder=get_py_filename): |
|
2055 | file_finder=get_py_filename): | |
2056 | """Run the named file inside IPython as a program. |
|
2056 | """Run the named file inside IPython as a program. | |
2057 |
|
2057 | |||
2058 | Usage:\\ |
|
2058 | Usage:\\ | |
2059 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
2059 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
2060 |
|
2060 | |||
2061 | Parameters after the filename are passed as command-line arguments to |
|
2061 | Parameters after the filename are passed as command-line arguments to | |
2062 | the program (put in sys.argv). Then, control returns to IPython's |
|
2062 | the program (put in sys.argv). Then, control returns to IPython's | |
2063 | prompt. |
|
2063 | prompt. | |
2064 |
|
2064 | |||
2065 | This is similar to running at a system prompt:\\ |
|
2065 | This is similar to running at a system prompt:\\ | |
2066 | $ python file args\\ |
|
2066 | $ python file args\\ | |
2067 | but with the advantage of giving you IPython's tracebacks, and of |
|
2067 | but with the advantage of giving you IPython's tracebacks, and of | |
2068 | loading all variables into your interactive namespace for further use |
|
2068 | loading all variables into your interactive namespace for further use | |
2069 | (unless -p is used, see below). |
|
2069 | (unless -p is used, see below). | |
2070 |
|
2070 | |||
2071 | The file is executed in a namespace initially consisting only of |
|
2071 | The file is executed in a namespace initially consisting only of | |
2072 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
2072 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
2073 | sees its environment as if it were being run as a stand-alone program |
|
2073 | sees its environment as if it were being run as a stand-alone program | |
2074 | (except for sharing global objects such as previously imported |
|
2074 | (except for sharing global objects such as previously imported | |
2075 | modules). But after execution, the IPython interactive namespace gets |
|
2075 | modules). But after execution, the IPython interactive namespace gets | |
2076 | updated with all variables defined in the program (except for __name__ |
|
2076 | updated with all variables defined in the program (except for __name__ | |
2077 | and sys.argv). This allows for very convenient loading of code for |
|
2077 | and sys.argv). This allows for very convenient loading of code for | |
2078 | interactive work, while giving each program a 'clean sheet' to run in. |
|
2078 | interactive work, while giving each program a 'clean sheet' to run in. | |
2079 |
|
2079 | |||
2080 | Options: |
|
2080 | Options: | |
2081 |
|
2081 | |||
2082 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
2082 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
2083 | without extension (as python does under import). This allows running |
|
2083 | without extension (as python does under import). This allows running | |
2084 | scripts and reloading the definitions in them without calling code |
|
2084 | scripts and reloading the definitions in them without calling code | |
2085 | protected by an ' if __name__ == "__main__" ' clause. |
|
2085 | protected by an ' if __name__ == "__main__" ' clause. | |
2086 |
|
2086 | |||
2087 | -i: run the file in IPython's namespace instead of an empty one. This |
|
2087 | -i: run the file in IPython's namespace instead of an empty one. This | |
2088 | is useful if you are experimenting with code written in a text editor |
|
2088 | is useful if you are experimenting with code written in a text editor | |
2089 | which depends on variables defined interactively. |
|
2089 | which depends on variables defined interactively. | |
2090 |
|
2090 | |||
2091 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
2091 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
2092 | being run. This is particularly useful if IPython is being used to |
|
2092 | being run. This is particularly useful if IPython is being used to | |
2093 | run unittests, which always exit with a sys.exit() call. In such |
|
2093 | run unittests, which always exit with a sys.exit() call. In such | |
2094 | cases you are interested in the output of the test results, not in |
|
2094 | cases you are interested in the output of the test results, not in | |
2095 | seeing a traceback of the unittest module. |
|
2095 | seeing a traceback of the unittest module. | |
2096 |
|
2096 | |||
2097 | -t: print timing information at the end of the run. IPython will give |
|
2097 | -t: print timing information at the end of the run. IPython will give | |
2098 | you an estimated CPU time consumption for your script, which under |
|
2098 | you an estimated CPU time consumption for your script, which under | |
2099 | Unix uses the resource module to avoid the wraparound problems of |
|
2099 | Unix uses the resource module to avoid the wraparound problems of | |
2100 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
2100 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
2101 | is also given (for Windows platforms this is reported as 0.0). |
|
2101 | is also given (for Windows platforms this is reported as 0.0). | |
2102 |
|
2102 | |||
2103 | If -t is given, an additional -N<N> option can be given, where <N> |
|
2103 | If -t is given, an additional -N<N> option can be given, where <N> | |
2104 | must be an integer indicating how many times you want the script to |
|
2104 | must be an integer indicating how many times you want the script to | |
2105 | run. The final timing report will include total and per run results. |
|
2105 | run. The final timing report will include total and per run results. | |
2106 |
|
2106 | |||
2107 | For example (testing the script uniq_stable.py):: |
|
2107 | For example (testing the script uniq_stable.py):: | |
2108 |
|
2108 | |||
2109 | In [1]: run -t uniq_stable |
|
2109 | In [1]: run -t uniq_stable | |
2110 |
|
2110 | |||
2111 | IPython CPU timings (estimated):\\ |
|
2111 | IPython CPU timings (estimated):\\ | |
2112 | User : 0.19597 s.\\ |
|
2112 | User : 0.19597 s.\\ | |
2113 | System: 0.0 s.\\ |
|
2113 | System: 0.0 s.\\ | |
2114 |
|
2114 | |||
2115 | In [2]: run -t -N5 uniq_stable |
|
2115 | In [2]: run -t -N5 uniq_stable | |
2116 |
|
2116 | |||
2117 | IPython CPU timings (estimated):\\ |
|
2117 | IPython CPU timings (estimated):\\ | |
2118 | Total runs performed: 5\\ |
|
2118 | Total runs performed: 5\\ | |
2119 | Times : Total Per run\\ |
|
2119 | Times : Total Per run\\ | |
2120 | User : 0.910862 s, 0.1821724 s.\\ |
|
2120 | User : 0.910862 s, 0.1821724 s.\\ | |
2121 | System: 0.0 s, 0.0 s. |
|
2121 | System: 0.0 s, 0.0 s. | |
2122 |
|
2122 | |||
2123 | -d: run your program under the control of pdb, the Python debugger. |
|
2123 | -d: run your program under the control of pdb, the Python debugger. | |
2124 | This allows you to execute your program step by step, watch variables, |
|
2124 | This allows you to execute your program step by step, watch variables, | |
2125 | etc. Internally, what IPython does is similar to calling: |
|
2125 | etc. Internally, what IPython does is similar to calling: | |
2126 |
|
2126 | |||
2127 | pdb.run('execfile("YOURFILENAME")') |
|
2127 | pdb.run('execfile("YOURFILENAME")') | |
2128 |
|
2128 | |||
2129 | with a breakpoint set on line 1 of your file. You can change the line |
|
2129 | with a breakpoint set on line 1 of your file. You can change the line | |
2130 | number for this automatic breakpoint to be <N> by using the -bN option |
|
2130 | number for this automatic breakpoint to be <N> by using the -bN option | |
2131 | (where N must be an integer). For example:: |
|
2131 | (where N must be an integer). For example:: | |
2132 |
|
2132 | |||
2133 | %run -d -b40 myscript |
|
2133 | %run -d -b40 myscript | |
2134 |
|
2134 | |||
2135 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
2135 | will set the first breakpoint at line 40 in myscript.py. Note that | |
2136 | the first breakpoint must be set on a line which actually does |
|
2136 | the first breakpoint must be set on a line which actually does | |
2137 | something (not a comment or docstring) for it to stop execution. |
|
2137 | something (not a comment or docstring) for it to stop execution. | |
2138 |
|
2138 | |||
2139 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
2139 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
2140 | first enter 'c' (without quotes) to start execution up to the first |
|
2140 | first enter 'c' (without quotes) to start execution up to the first | |
2141 | breakpoint. |
|
2141 | breakpoint. | |
2142 |
|
2142 | |||
2143 | Entering 'help' gives information about the use of the debugger. You |
|
2143 | Entering 'help' gives information about the use of the debugger. You | |
2144 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
2144 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
2145 | at a prompt. |
|
2145 | at a prompt. | |
2146 |
|
2146 | |||
2147 | -p: run program under the control of the Python profiler module (which |
|
2147 | -p: run program under the control of the Python profiler module (which | |
2148 | prints a detailed report of execution times, function calls, etc). |
|
2148 | prints a detailed report of execution times, function calls, etc). | |
2149 |
|
2149 | |||
2150 | You can pass other options after -p which affect the behavior of the |
|
2150 | You can pass other options after -p which affect the behavior of the | |
2151 | profiler itself. See the docs for %prun for details. |
|
2151 | profiler itself. See the docs for %prun for details. | |
2152 |
|
2152 | |||
2153 | In this mode, the program's variables do NOT propagate back to the |
|
2153 | In this mode, the program's variables do NOT propagate back to the | |
2154 | IPython interactive namespace (because they remain in the namespace |
|
2154 | IPython interactive namespace (because they remain in the namespace | |
2155 | where the profiler executes them). |
|
2155 | where the profiler executes them). | |
2156 |
|
2156 | |||
2157 | Internally this triggers a call to %prun, see its documentation for |
|
2157 | Internally this triggers a call to %prun, see its documentation for | |
2158 | details on the options available specifically for profiling. |
|
2158 | details on the options available specifically for profiling. | |
2159 |
|
2159 | |||
2160 | There is one special usage for which the text above doesn't apply: |
|
2160 | There is one special usage for which the text above doesn't apply: | |
2161 | if the filename ends with .ipy, the file is run as ipython script, |
|
2161 | if the filename ends with .ipy, the file is run as ipython script, | |
2162 | just as if the commands were written on IPython prompt. |
|
2162 | just as if the commands were written on IPython prompt. | |
2163 |
|
2163 | |||
2164 | -m: specify module name to load instead of script path. Similar to |
|
2164 | -m: specify module name to load instead of script path. Similar to | |
2165 | the -m option for the python interpreter. Use this option last if you |
|
2165 | the -m option for the python interpreter. Use this option last if you | |
2166 | want to combine with other %run options. Unlike the python interpreter |
|
2166 | want to combine with other %run options. Unlike the python interpreter | |
2167 | only source modules are allowed no .pyc or .pyo files. |
|
2167 | only source modules are allowed no .pyc or .pyo files. | |
2168 | For example:: |
|
2168 | For example:: | |
2169 |
|
2169 | |||
2170 | %run -m example |
|
2170 | %run -m example | |
2171 |
|
2171 | |||
2172 | will run the example module. |
|
2172 | will run the example module. | |
2173 |
|
2173 | |||
2174 | """ |
|
2174 | """ | |
2175 |
|
2175 | |||
2176 | # get arguments and set sys.argv for program to be run. |
|
2176 | # get arguments and set sys.argv for program to be run. | |
2177 | opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:', |
|
2177 | opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:', | |
2178 | mode='list', list_all=1) |
|
2178 | mode='list', list_all=1) | |
2179 | if "m" in opts: |
|
2179 | if "m" in opts: | |
2180 | modulename = opts["m"][0] |
|
2180 | modulename = opts["m"][0] | |
2181 | modpath = find_mod(modulename) |
|
2181 | modpath = find_mod(modulename) | |
2182 | if modpath is None: |
|
2182 | if modpath is None: | |
2183 | warn('%r is not a valid modulename on sys.path'%modulename) |
|
2183 | warn('%r is not a valid modulename on sys.path'%modulename) | |
2184 | return |
|
2184 | return | |
2185 | arg_lst = [modpath] + arg_lst |
|
2185 | arg_lst = [modpath] + arg_lst | |
2186 | try: |
|
2186 | try: | |
2187 | filename = file_finder(arg_lst[0]) |
|
2187 | filename = file_finder(arg_lst[0]) | |
2188 | except IndexError: |
|
2188 | except IndexError: | |
2189 | warn('you must provide at least a filename.') |
|
2189 | warn('you must provide at least a filename.') | |
2190 | print '\n%run:\n', oinspect.getdoc(self.magic_run) |
|
2190 | print '\n%run:\n', oinspect.getdoc(self.magic_run) | |
2191 | return |
|
2191 | return | |
2192 | except IOError as e: |
|
2192 | except IOError as e: | |
2193 | try: |
|
2193 | try: | |
2194 | msg = str(e) |
|
2194 | msg = str(e) | |
2195 | except UnicodeError: |
|
2195 | except UnicodeError: | |
2196 | msg = e.message |
|
2196 | msg = e.message | |
2197 | error(msg) |
|
2197 | error(msg) | |
2198 | return |
|
2198 | return | |
2199 |
|
2199 | |||
2200 | if filename.lower().endswith('.ipy'): |
|
2200 | if filename.lower().endswith('.ipy'): | |
2201 | self.shell.safe_execfile_ipy(filename) |
|
2201 | self.shell.safe_execfile_ipy(filename) | |
2202 | return |
|
2202 | return | |
2203 |
|
2203 | |||
2204 | # Control the response to exit() calls made by the script being run |
|
2204 | # Control the response to exit() calls made by the script being run | |
2205 | exit_ignore = 'e' in opts |
|
2205 | exit_ignore = 'e' in opts | |
2206 |
|
2206 | |||
2207 | # Make sure that the running script gets a proper sys.argv as if it |
|
2207 | # Make sure that the running script gets a proper sys.argv as if it | |
2208 | # were run from a system shell. |
|
2208 | # were run from a system shell. | |
2209 | save_argv = sys.argv # save it for later restoring |
|
2209 | save_argv = sys.argv # save it for later restoring | |
2210 |
|
2210 | |||
2211 | # simulate shell expansion on arguments, at least tilde expansion |
|
2211 | # simulate shell expansion on arguments, at least tilde expansion | |
2212 | args = [ os.path.expanduser(a) for a in arg_lst[1:] ] |
|
2212 | args = [ os.path.expanduser(a) for a in arg_lst[1:] ] | |
2213 |
|
2213 | |||
2214 | sys.argv = [filename] + args # put in the proper filename |
|
2214 | sys.argv = [filename] + args # put in the proper filename | |
2215 | # protect sys.argv from potential unicode strings on Python 2: |
|
2215 | # protect sys.argv from potential unicode strings on Python 2: | |
2216 | if not py3compat.PY3: |
|
2216 | if not py3compat.PY3: | |
2217 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] |
|
2217 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] | |
2218 |
|
2218 | |||
2219 | if 'i' in opts: |
|
2219 | if 'i' in opts: | |
2220 | # Run in user's interactive namespace |
|
2220 | # Run in user's interactive namespace | |
2221 | prog_ns = self.shell.user_ns |
|
2221 | prog_ns = self.shell.user_ns | |
2222 | __name__save = self.shell.user_ns['__name__'] |
|
2222 | __name__save = self.shell.user_ns['__name__'] | |
2223 | prog_ns['__name__'] = '__main__' |
|
2223 | prog_ns['__name__'] = '__main__' | |
2224 | main_mod = self.shell.new_main_mod(prog_ns) |
|
2224 | main_mod = self.shell.new_main_mod(prog_ns) | |
2225 | else: |
|
2225 | else: | |
2226 | # Run in a fresh, empty namespace |
|
2226 | # Run in a fresh, empty namespace | |
2227 | if 'n' in opts: |
|
2227 | if 'n' in opts: | |
2228 | name = os.path.splitext(os.path.basename(filename))[0] |
|
2228 | name = os.path.splitext(os.path.basename(filename))[0] | |
2229 | else: |
|
2229 | else: | |
2230 | name = '__main__' |
|
2230 | name = '__main__' | |
2231 |
|
2231 | |||
2232 | main_mod = self.shell.new_main_mod() |
|
2232 | main_mod = self.shell.new_main_mod() | |
2233 | prog_ns = main_mod.__dict__ |
|
2233 | prog_ns = main_mod.__dict__ | |
2234 | prog_ns['__name__'] = name |
|
2234 | prog_ns['__name__'] = name | |
2235 |
|
2235 | |||
2236 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
2236 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
2237 | # set the __file__ global in the script's namespace |
|
2237 | # set the __file__ global in the script's namespace | |
2238 | prog_ns['__file__'] = filename |
|
2238 | prog_ns['__file__'] = filename | |
2239 |
|
2239 | |||
2240 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
2240 | # pickle fix. See interactiveshell for an explanation. But we need to make sure | |
2241 | # that, if we overwrite __main__, we replace it at the end |
|
2241 | # that, if we overwrite __main__, we replace it at the end | |
2242 | main_mod_name = prog_ns['__name__'] |
|
2242 | main_mod_name = prog_ns['__name__'] | |
2243 |
|
2243 | |||
2244 | if main_mod_name == '__main__': |
|
2244 | if main_mod_name == '__main__': | |
2245 | restore_main = sys.modules['__main__'] |
|
2245 | restore_main = sys.modules['__main__'] | |
2246 | else: |
|
2246 | else: | |
2247 | restore_main = False |
|
2247 | restore_main = False | |
2248 |
|
2248 | |||
2249 | # This needs to be undone at the end to prevent holding references to |
|
2249 | # This needs to be undone at the end to prevent holding references to | |
2250 | # every single object ever created. |
|
2250 | # every single object ever created. | |
2251 | sys.modules[main_mod_name] = main_mod |
|
2251 | sys.modules[main_mod_name] = main_mod | |
2252 |
|
2252 | |||
2253 | try: |
|
2253 | try: | |
2254 | stats = None |
|
2254 | stats = None | |
2255 | with self.shell.readline_no_record: |
|
2255 | with self.shell.readline_no_record: | |
2256 | if 'p' in opts: |
|
2256 | if 'p' in opts: | |
2257 | stats = self.magic_prun('', 0, opts, arg_lst, prog_ns) |
|
2257 | stats = self.magic_prun('', 0, opts, arg_lst, prog_ns) | |
2258 | else: |
|
2258 | else: | |
2259 | if 'd' in opts: |
|
2259 | if 'd' in opts: | |
2260 | deb = debugger.Pdb(self.shell.colors) |
|
2260 | deb = debugger.Pdb(self.shell.colors) | |
2261 | # reset Breakpoint state, which is moronically kept |
|
2261 | # reset Breakpoint state, which is moronically kept | |
2262 | # in a class |
|
2262 | # in a class | |
2263 | bdb.Breakpoint.next = 1 |
|
2263 | bdb.Breakpoint.next = 1 | |
2264 | bdb.Breakpoint.bplist = {} |
|
2264 | bdb.Breakpoint.bplist = {} | |
2265 | bdb.Breakpoint.bpbynumber = [None] |
|
2265 | bdb.Breakpoint.bpbynumber = [None] | |
2266 | # Set an initial breakpoint to stop execution |
|
2266 | # Set an initial breakpoint to stop execution | |
2267 | maxtries = 10 |
|
2267 | maxtries = 10 | |
2268 | bp = int(opts.get('b', [1])[0]) |
|
2268 | bp = int(opts.get('b', [1])[0]) | |
2269 | checkline = deb.checkline(filename, bp) |
|
2269 | checkline = deb.checkline(filename, bp) | |
2270 | if not checkline: |
|
2270 | if not checkline: | |
2271 | for bp in range(bp + 1, bp + maxtries + 1): |
|
2271 | for bp in range(bp + 1, bp + maxtries + 1): | |
2272 | if deb.checkline(filename, bp): |
|
2272 | if deb.checkline(filename, bp): | |
2273 | break |
|
2273 | break | |
2274 | else: |
|
2274 | else: | |
2275 | msg = ("\nI failed to find a valid line to set " |
|
2275 | msg = ("\nI failed to find a valid line to set " | |
2276 | "a breakpoint\n" |
|
2276 | "a breakpoint\n" | |
2277 | "after trying up to line: %s.\n" |
|
2277 | "after trying up to line: %s.\n" | |
2278 | "Please set a valid breakpoint manually " |
|
2278 | "Please set a valid breakpoint manually " | |
2279 | "with the -b option." % bp) |
|
2279 | "with the -b option." % bp) | |
2280 | error(msg) |
|
2280 | error(msg) | |
2281 | return |
|
2281 | return | |
2282 | # if we find a good linenumber, set the breakpoint |
|
2282 | # if we find a good linenumber, set the breakpoint | |
2283 | deb.do_break('%s:%s' % (filename, bp)) |
|
2283 | deb.do_break('%s:%s' % (filename, bp)) | |
2284 | # Start file run |
|
2284 | # Start file run | |
2285 | print "NOTE: Enter 'c' at the", |
|
2285 | print "NOTE: Enter 'c' at the", | |
2286 | print "%s prompt to start your script." % deb.prompt |
|
2286 | print "%s prompt to start your script." % deb.prompt | |
2287 | ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns} |
|
2287 | ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns} | |
2288 | try: |
|
2288 | try: | |
2289 | deb.run('execfile("%s", prog_ns)' % filename, ns) |
|
2289 | deb.run('execfile("%s", prog_ns)' % filename, ns) | |
2290 |
|
2290 | |||
2291 | except: |
|
2291 | except: | |
2292 | etype, value, tb = sys.exc_info() |
|
2292 | etype, value, tb = sys.exc_info() | |
2293 | # Skip three frames in the traceback: the %run one, |
|
2293 | # Skip three frames in the traceback: the %run one, | |
2294 | # one inside bdb.py, and the command-line typed by the |
|
2294 | # one inside bdb.py, and the command-line typed by the | |
2295 | # user (run by exec in pdb itself). |
|
2295 | # user (run by exec in pdb itself). | |
2296 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) |
|
2296 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) | |
2297 | else: |
|
2297 | else: | |
2298 | if runner is None: |
|
2298 | if runner is None: | |
2299 | runner = self.default_runner |
|
2299 | runner = self.default_runner | |
2300 | if runner is None: |
|
2300 | if runner is None: | |
2301 | runner = self.shell.safe_execfile |
|
2301 | runner = self.shell.safe_execfile | |
2302 | if 't' in opts: |
|
2302 | if 't' in opts: | |
2303 | # timed execution |
|
2303 | # timed execution | |
2304 | try: |
|
2304 | try: | |
2305 | nruns = int(opts['N'][0]) |
|
2305 | nruns = int(opts['N'][0]) | |
2306 | if nruns < 1: |
|
2306 | if nruns < 1: | |
2307 | error('Number of runs must be >=1') |
|
2307 | error('Number of runs must be >=1') | |
2308 | return |
|
2308 | return | |
2309 | except (KeyError): |
|
2309 | except (KeyError): | |
2310 | nruns = 1 |
|
2310 | nruns = 1 | |
2311 | twall0 = time.time() |
|
2311 | twall0 = time.time() | |
2312 | if nruns == 1: |
|
2312 | if nruns == 1: | |
2313 | t0 = clock2() |
|
2313 | t0 = clock2() | |
2314 | runner(filename, prog_ns, prog_ns, |
|
2314 | runner(filename, prog_ns, prog_ns, | |
2315 | exit_ignore=exit_ignore) |
|
2315 | exit_ignore=exit_ignore) | |
2316 | t1 = clock2() |
|
2316 | t1 = clock2() | |
2317 | t_usr = t1[0] - t0[0] |
|
2317 | t_usr = t1[0] - t0[0] | |
2318 | t_sys = t1[1] - t0[1] |
|
2318 | t_sys = t1[1] - t0[1] | |
2319 | print "\nIPython CPU timings (estimated):" |
|
2319 | print "\nIPython CPU timings (estimated):" | |
2320 | print " User : %10.2f s." % t_usr |
|
2320 | print " User : %10.2f s." % t_usr | |
2321 | print " System : %10.2f s." % t_sys |
|
2321 | print " System : %10.2f s." % t_sys | |
2322 | else: |
|
2322 | else: | |
2323 | runs = range(nruns) |
|
2323 | runs = range(nruns) | |
2324 | t0 = clock2() |
|
2324 | t0 = clock2() | |
2325 | for nr in runs: |
|
2325 | for nr in runs: | |
2326 | runner(filename, prog_ns, prog_ns, |
|
2326 | runner(filename, prog_ns, prog_ns, | |
2327 | exit_ignore=exit_ignore) |
|
2327 | exit_ignore=exit_ignore) | |
2328 | t1 = clock2() |
|
2328 | t1 = clock2() | |
2329 | t_usr = t1[0] - t0[0] |
|
2329 | t_usr = t1[0] - t0[0] | |
2330 | t_sys = t1[1] - t0[1] |
|
2330 | t_sys = t1[1] - t0[1] | |
2331 | print "\nIPython CPU timings (estimated):" |
|
2331 | print "\nIPython CPU timings (estimated):" | |
2332 | print "Total runs performed:", nruns |
|
2332 | print "Total runs performed:", nruns | |
2333 | print " Times : %10.2f %10.2f" % ('Total', 'Per run') |
|
2333 | print " Times : %10.2f %10.2f" % ('Total', 'Per run') | |
2334 | print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns) |
|
2334 | print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns) | |
2335 | print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns) |
|
2335 | print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns) | |
2336 | twall1 = time.time() |
|
2336 | twall1 = time.time() | |
2337 | print "Wall time: %10.2f s." % (twall1 - twall0) |
|
2337 | print "Wall time: %10.2f s." % (twall1 - twall0) | |
2338 |
|
2338 | |||
2339 | else: |
|
2339 | else: | |
2340 | # regular execution |
|
2340 | # regular execution | |
2341 | runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore) |
|
2341 | runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore) | |
2342 |
|
2342 | |||
2343 | if 'i' in opts: |
|
2343 | if 'i' in opts: | |
2344 | self.shell.user_ns['__name__'] = __name__save |
|
2344 | self.shell.user_ns['__name__'] = __name__save | |
2345 | else: |
|
2345 | else: | |
2346 | # The shell MUST hold a reference to prog_ns so after %run |
|
2346 | # The shell MUST hold a reference to prog_ns so after %run | |
2347 | # exits, the python deletion mechanism doesn't zero it out |
|
2347 | # exits, the python deletion mechanism doesn't zero it out | |
2348 | # (leaving dangling references). |
|
2348 | # (leaving dangling references). | |
2349 | self.shell.cache_main_mod(prog_ns, filename) |
|
2349 | self.shell.cache_main_mod(prog_ns, filename) | |
2350 | # update IPython interactive namespace |
|
2350 | # update IPython interactive namespace | |
2351 |
|
2351 | |||
2352 | # Some forms of read errors on the file may mean the |
|
2352 | # Some forms of read errors on the file may mean the | |
2353 | # __name__ key was never set; using pop we don't have to |
|
2353 | # __name__ key was never set; using pop we don't have to | |
2354 | # worry about a possible KeyError. |
|
2354 | # worry about a possible KeyError. | |
2355 | prog_ns.pop('__name__', None) |
|
2355 | prog_ns.pop('__name__', None) | |
2356 |
|
2356 | |||
2357 | self.shell.user_ns.update(prog_ns) |
|
2357 | self.shell.user_ns.update(prog_ns) | |
2358 | finally: |
|
2358 | finally: | |
2359 | # It's a bit of a mystery why, but __builtins__ can change from |
|
2359 | # It's a bit of a mystery why, but __builtins__ can change from | |
2360 | # being a module to becoming a dict missing some key data after |
|
2360 | # being a module to becoming a dict missing some key data after | |
2361 | # %run. As best I can see, this is NOT something IPython is doing |
|
2361 | # %run. As best I can see, this is NOT something IPython is doing | |
2362 | # at all, and similar problems have been reported before: |
|
2362 | # at all, and similar problems have been reported before: | |
2363 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
2363 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
2364 | # Since this seems to be done by the interpreter itself, the best |
|
2364 | # Since this seems to be done by the interpreter itself, the best | |
2365 | # we can do is to at least restore __builtins__ for the user on |
|
2365 | # we can do is to at least restore __builtins__ for the user on | |
2366 | # exit. |
|
2366 | # exit. | |
2367 | self.shell.user_ns['__builtins__'] = builtin_mod |
|
2367 | self.shell.user_ns['__builtins__'] = builtin_mod | |
2368 |
|
2368 | |||
2369 | # Ensure key global structures are restored |
|
2369 | # Ensure key global structures are restored | |
2370 | sys.argv = save_argv |
|
2370 | sys.argv = save_argv | |
2371 | if restore_main: |
|
2371 | if restore_main: | |
2372 | sys.modules['__main__'] = restore_main |
|
2372 | sys.modules['__main__'] = restore_main | |
2373 | else: |
|
2373 | else: | |
2374 | # Remove from sys.modules the reference to main_mod we'd |
|
2374 | # Remove from sys.modules the reference to main_mod we'd | |
2375 | # added. Otherwise it will trap references to objects |
|
2375 | # added. Otherwise it will trap references to objects | |
2376 | # contained therein. |
|
2376 | # contained therein. | |
2377 | del sys.modules[main_mod_name] |
|
2377 | del sys.modules[main_mod_name] | |
2378 |
|
2378 | |||
2379 | return stats |
|
2379 | return stats | |
2380 |
|
2380 | |||
2381 | @skip_doctest |
|
2381 | @skip_doctest | |
2382 | @line_magic |
|
2382 | @line_magic | |
2383 | def timeit(self, parameter_s=''): |
|
2383 | def timeit(self, parameter_s=''): | |
2384 | """Time execution of a Python statement or expression |
|
2384 | """Time execution of a Python statement or expression | |
2385 |
|
2385 | |||
2386 | Usage:\\ |
|
2386 | Usage:\\ | |
2387 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
2387 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
2388 |
|
2388 | |||
2389 | Time execution of a Python statement or expression using the timeit |
|
2389 | Time execution of a Python statement or expression using the timeit | |
2390 | module. |
|
2390 | module. | |
2391 |
|
2391 | |||
2392 | Options: |
|
2392 | Options: | |
2393 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
2393 | -n<N>: execute the given statement <N> times in a loop. If this value | |
2394 | is not given, a fitting value is chosen. |
|
2394 | is not given, a fitting value is chosen. | |
2395 |
|
2395 | |||
2396 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
2396 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
2397 | Default: 3 |
|
2397 | Default: 3 | |
2398 |
|
2398 | |||
2399 | -t: use time.time to measure the time, which is the default on Unix. |
|
2399 | -t: use time.time to measure the time, which is the default on Unix. | |
2400 | This function measures wall time. |
|
2400 | This function measures wall time. | |
2401 |
|
2401 | |||
2402 | -c: use time.clock to measure the time, which is the default on |
|
2402 | -c: use time.clock to measure the time, which is the default on | |
2403 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
2403 | Windows and measures wall time. On Unix, resource.getrusage is used | |
2404 | instead and returns the CPU user time. |
|
2404 | instead and returns the CPU user time. | |
2405 |
|
2405 | |||
2406 | -p<P>: use a precision of <P> digits to display the timing result. |
|
2406 | -p<P>: use a precision of <P> digits to display the timing result. | |
2407 | Default: 3 |
|
2407 | Default: 3 | |
2408 |
|
2408 | |||
2409 |
|
2409 | |||
2410 | Examples |
|
2410 | Examples | |
2411 | -------- |
|
2411 | -------- | |
2412 | :: |
|
2412 | :: | |
2413 |
|
2413 | |||
2414 | In [1]: %timeit pass |
|
2414 | In [1]: %timeit pass | |
2415 | 10000000 loops, best of 3: 53.3 ns per loop |
|
2415 | 10000000 loops, best of 3: 53.3 ns per loop | |
2416 |
|
2416 | |||
2417 | In [2]: u = None |
|
2417 | In [2]: u = None | |
2418 |
|
2418 | |||
2419 | In [3]: %timeit u is None |
|
2419 | In [3]: %timeit u is None | |
2420 | 10000000 loops, best of 3: 184 ns per loop |
|
2420 | 10000000 loops, best of 3: 184 ns per loop | |
2421 |
|
2421 | |||
2422 | In [4]: %timeit -r 4 u == None |
|
2422 | In [4]: %timeit -r 4 u == None | |
2423 | 1000000 loops, best of 4: 242 ns per loop |
|
2423 | 1000000 loops, best of 4: 242 ns per loop | |
2424 |
|
2424 | |||
2425 | In [5]: import time |
|
2425 | In [5]: import time | |
2426 |
|
2426 | |||
2427 | In [6]: %timeit -n1 time.sleep(2) |
|
2427 | In [6]: %timeit -n1 time.sleep(2) | |
2428 | 1 loops, best of 3: 2 s per loop |
|
2428 | 1 loops, best of 3: 2 s per loop | |
2429 |
|
2429 | |||
2430 |
|
2430 | |||
2431 | The times reported by %timeit will be slightly higher than those |
|
2431 | The times reported by %timeit will be slightly higher than those | |
2432 | reported by the timeit.py script when variables are accessed. This is |
|
2432 | reported by the timeit.py script when variables are accessed. This is | |
2433 | due to the fact that %timeit executes the statement in the namespace |
|
2433 | due to the fact that %timeit executes the statement in the namespace | |
2434 | of the shell, compared with timeit.py, which uses a single setup |
|
2434 | of the shell, compared with timeit.py, which uses a single setup | |
2435 | statement to import function or create variables. Generally, the bias |
|
2435 | statement to import function or create variables. Generally, the bias | |
2436 | does not matter as long as results from timeit.py are not mixed with |
|
2436 | does not matter as long as results from timeit.py are not mixed with | |
2437 | those from %timeit.""" |
|
2437 | those from %timeit.""" | |
2438 |
|
2438 | |||
2439 | import timeit |
|
2439 | import timeit | |
2440 | import math |
|
2440 | import math | |
2441 |
|
2441 | |||
2442 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
2442 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
2443 | # certain terminals. Until we figure out a robust way of |
|
2443 | # certain terminals. Until we figure out a robust way of | |
2444 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
2444 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
2445 | # microseconds. I am really NOT happy about disabling the proper |
|
2445 | # microseconds. I am really NOT happy about disabling the proper | |
2446 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
2446 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
2447 | # right solution for this is, I'm all ears... |
|
2447 | # right solution for this is, I'm all ears... | |
2448 | # |
|
2448 | # | |
2449 | # Note: using |
|
2449 | # Note: using | |
2450 | # |
|
2450 | # | |
2451 | # s = u'\xb5' |
|
2451 | # s = u'\xb5' | |
2452 | # s.encode(sys.getdefaultencoding()) |
|
2452 | # s.encode(sys.getdefaultencoding()) | |
2453 | # |
|
2453 | # | |
2454 | # is not sufficient, as I've seen terminals where that fails but |
|
2454 | # is not sufficient, as I've seen terminals where that fails but | |
2455 | # print s |
|
2455 | # print s | |
2456 | # |
|
2456 | # | |
2457 | # succeeds |
|
2457 | # succeeds | |
2458 | # |
|
2458 | # | |
2459 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
2459 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
2460 |
|
2460 | |||
2461 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
2461 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
2462 | units = [u"s", u"ms",u'us',"ns"] |
|
2462 | units = [u"s", u"ms",u'us',"ns"] | |
2463 |
|
2463 | |||
2464 | scaling = [1, 1e3, 1e6, 1e9] |
|
2464 | scaling = [1, 1e3, 1e6, 1e9] | |
2465 |
|
2465 | |||
2466 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
2466 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
2467 | posix=False, strict=False) |
|
2467 | posix=False, strict=False) | |
2468 | if stmt == "": |
|
2468 | if stmt == "": | |
2469 | return |
|
2469 | return | |
2470 | timefunc = timeit.default_timer |
|
2470 | timefunc = timeit.default_timer | |
2471 | number = int(getattr(opts, "n", 0)) |
|
2471 | number = int(getattr(opts, "n", 0)) | |
2472 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
2472 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
2473 | precision = int(getattr(opts, "p", 3)) |
|
2473 | precision = int(getattr(opts, "p", 3)) | |
2474 | if hasattr(opts, "t"): |
|
2474 | if hasattr(opts, "t"): | |
2475 | timefunc = time.time |
|
2475 | timefunc = time.time | |
2476 | if hasattr(opts, "c"): |
|
2476 | if hasattr(opts, "c"): | |
2477 | timefunc = clock |
|
2477 | timefunc = clock | |
2478 |
|
2478 | |||
2479 | timer = timeit.Timer(timer=timefunc) |
|
2479 | timer = timeit.Timer(timer=timefunc) | |
2480 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
2480 | # this code has tight coupling to the inner workings of timeit.Timer, | |
2481 | # but is there a better way to achieve that the code stmt has access |
|
2481 | # but is there a better way to achieve that the code stmt has access | |
2482 | # to the shell namespace? |
|
2482 | # to the shell namespace? | |
2483 |
|
2483 | |||
2484 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
2484 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
2485 | 'setup': "pass"} |
|
2485 | 'setup': "pass"} | |
2486 | # Track compilation time so it can be reported if too long |
|
2486 | # Track compilation time so it can be reported if too long | |
2487 | # Minimum time above which compilation time will be reported |
|
2487 | # Minimum time above which compilation time will be reported | |
2488 | tc_min = 0.1 |
|
2488 | tc_min = 0.1 | |
2489 |
|
2489 | |||
2490 | t0 = clock() |
|
2490 | t0 = clock() | |
2491 | code = compile(src, "<magic-timeit>", "exec") |
|
2491 | code = compile(src, "<magic-timeit>", "exec") | |
2492 | tc = clock()-t0 |
|
2492 | tc = clock()-t0 | |
2493 |
|
2493 | |||
2494 | ns = {} |
|
2494 | ns = {} | |
2495 | exec code in self.shell.user_ns, ns |
|
2495 | exec code in self.shell.user_ns, ns | |
2496 | timer.inner = ns["inner"] |
|
2496 | timer.inner = ns["inner"] | |
2497 |
|
2497 | |||
2498 | if number == 0: |
|
2498 | if number == 0: | |
2499 | # determine number so that 0.2 <= total time < 2.0 |
|
2499 | # determine number so that 0.2 <= total time < 2.0 | |
2500 | number = 1 |
|
2500 | number = 1 | |
2501 | for i in range(1, 10): |
|
2501 | for i in range(1, 10): | |
2502 | if timer.timeit(number) >= 0.2: |
|
2502 | if timer.timeit(number) >= 0.2: | |
2503 | break |
|
2503 | break | |
2504 | number *= 10 |
|
2504 | number *= 10 | |
2505 |
|
2505 | |||
2506 | best = min(timer.repeat(repeat, number)) / number |
|
2506 | best = min(timer.repeat(repeat, number)) / number | |
2507 |
|
2507 | |||
2508 | if best > 0.0 and best < 1000.0: |
|
2508 | if best > 0.0 and best < 1000.0: | |
2509 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
2509 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
2510 | elif best >= 1000.0: |
|
2510 | elif best >= 1000.0: | |
2511 | order = 0 |
|
2511 | order = 0 | |
2512 | else: |
|
2512 | else: | |
2513 | order = 3 |
|
2513 | order = 3 | |
2514 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
2514 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
2515 | precision, |
|
2515 | precision, | |
2516 | best * scaling[order], |
|
2516 | best * scaling[order], | |
2517 | units[order]) |
|
2517 | units[order]) | |
2518 | if tc > tc_min: |
|
2518 | if tc > tc_min: | |
2519 | print "Compiler time: %.2f s" % tc |
|
2519 | print "Compiler time: %.2f s" % tc | |
2520 |
|
2520 | |||
2521 | @cell_magic('timeit') |
|
2521 | @cell_magic('timeit') | |
2522 | def cell_timeit(self, line, cell): |
|
2522 | def cell_timeit(self, line, cell): | |
2523 | """Time execution of a Python cell.""" |
|
2523 | """Time execution of a Python cell.""" | |
2524 | raise NotImplementedError |
|
2524 | raise NotImplementedError | |
2525 |
|
2525 | |||
2526 | @skip_doctest |
|
2526 | @skip_doctest | |
2527 | @needs_local_scope |
|
2527 | @needs_local_scope | |
2528 | @line_magic |
|
2528 | @line_magic | |
2529 | def time(self,parameter_s, user_locals): |
|
2529 | def time(self,parameter_s, user_locals): | |
2530 | """Time execution of a Python statement or expression. |
|
2530 | """Time execution of a Python statement or expression. | |
2531 |
|
2531 | |||
2532 | The CPU and wall clock times are printed, and the value of the |
|
2532 | The CPU and wall clock times are printed, and the value of the | |
2533 | expression (if any) is returned. Note that under Win32, system time |
|
2533 | expression (if any) is returned. Note that under Win32, system time | |
2534 | is always reported as 0, since it can not be measured. |
|
2534 | is always reported as 0, since it can not be measured. | |
2535 |
|
2535 | |||
2536 | This function provides very basic timing functionality. In Python |
|
2536 | This function provides very basic timing functionality. In Python | |
2537 | 2.3, the timeit module offers more control and sophistication, so this |
|
2537 | 2.3, the timeit module offers more control and sophistication, so this | |
2538 | could be rewritten to use it (patches welcome). |
|
2538 | could be rewritten to use it (patches welcome). | |
2539 |
|
2539 | |||
2540 | Examples |
|
2540 | Examples | |
2541 | -------- |
|
2541 | -------- | |
2542 | :: |
|
2542 | :: | |
2543 |
|
2543 | |||
2544 | In [1]: time 2**128 |
|
2544 | In [1]: time 2**128 | |
2545 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2545 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
2546 | Wall time: 0.00 |
|
2546 | Wall time: 0.00 | |
2547 | Out[1]: 340282366920938463463374607431768211456L |
|
2547 | Out[1]: 340282366920938463463374607431768211456L | |
2548 |
|
2548 | |||
2549 | In [2]: n = 1000000 |
|
2549 | In [2]: n = 1000000 | |
2550 |
|
2550 | |||
2551 | In [3]: time sum(range(n)) |
|
2551 | In [3]: time sum(range(n)) | |
2552 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
2552 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
2553 | Wall time: 1.37 |
|
2553 | Wall time: 1.37 | |
2554 | Out[3]: 499999500000L |
|
2554 | Out[3]: 499999500000L | |
2555 |
|
2555 | |||
2556 | In [4]: time print 'hello world' |
|
2556 | In [4]: time print 'hello world' | |
2557 | hello world |
|
2557 | hello world | |
2558 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2558 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
2559 | Wall time: 0.00 |
|
2559 | Wall time: 0.00 | |
2560 |
|
2560 | |||
2561 | Note that the time needed by Python to compile the given expression |
|
2561 | Note that the time needed by Python to compile the given expression | |
2562 | will be reported if it is more than 0.1s. In this example, the |
|
2562 | will be reported if it is more than 0.1s. In this example, the | |
2563 | actual exponentiation is done by Python at compilation time, so while |
|
2563 | actual exponentiation is done by Python at compilation time, so while | |
2564 | the expression can take a noticeable amount of time to compute, that |
|
2564 | the expression can take a noticeable amount of time to compute, that | |
2565 | time is purely due to the compilation: |
|
2565 | time is purely due to the compilation: | |
2566 |
|
2566 | |||
2567 | In [5]: time 3**9999; |
|
2567 | In [5]: time 3**9999; | |
2568 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2568 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
2569 | Wall time: 0.00 s |
|
2569 | Wall time: 0.00 s | |
2570 |
|
2570 | |||
2571 | In [6]: time 3**999999; |
|
2571 | In [6]: time 3**999999; | |
2572 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2572 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
2573 | Wall time: 0.00 s |
|
2573 | Wall time: 0.00 s | |
2574 | Compiler : 0.78 s |
|
2574 | Compiler : 0.78 s | |
2575 | """ |
|
2575 | """ | |
2576 |
|
2576 | |||
2577 | # fail immediately if the given expression can't be compiled |
|
2577 | # fail immediately if the given expression can't be compiled | |
2578 |
|
2578 | |||
2579 | expr = self.shell.prefilter(parameter_s,False) |
|
2579 | expr = self.shell.prefilter(parameter_s,False) | |
2580 |
|
2580 | |||
2581 | # Minimum time above which compilation time will be reported |
|
2581 | # Minimum time above which compilation time will be reported | |
2582 | tc_min = 0.1 |
|
2582 | tc_min = 0.1 | |
2583 |
|
2583 | |||
2584 | try: |
|
2584 | try: | |
2585 | mode = 'eval' |
|
2585 | mode = 'eval' | |
2586 | t0 = clock() |
|
2586 | t0 = clock() | |
2587 | code = compile(expr,'<timed eval>',mode) |
|
2587 | code = compile(expr,'<timed eval>',mode) | |
2588 | tc = clock()-t0 |
|
2588 | tc = clock()-t0 | |
2589 | except SyntaxError: |
|
2589 | except SyntaxError: | |
2590 | mode = 'exec' |
|
2590 | mode = 'exec' | |
2591 | t0 = clock() |
|
2591 | t0 = clock() | |
2592 | code = compile(expr,'<timed exec>',mode) |
|
2592 | code = compile(expr,'<timed exec>',mode) | |
2593 | tc = clock()-t0 |
|
2593 | tc = clock()-t0 | |
2594 | # skew measurement as little as possible |
|
2594 | # skew measurement as little as possible | |
2595 | glob = self.shell.user_ns |
|
2595 | glob = self.shell.user_ns | |
2596 | wtime = time.time |
|
2596 | wtime = time.time | |
2597 | # time execution |
|
2597 | # time execution | |
2598 | wall_st = wtime() |
|
2598 | wall_st = wtime() | |
2599 | if mode=='eval': |
|
2599 | if mode=='eval': | |
2600 | st = clock2() |
|
2600 | st = clock2() | |
2601 | out = eval(code, glob, user_locals) |
|
2601 | out = eval(code, glob, user_locals) | |
2602 | end = clock2() |
|
2602 | end = clock2() | |
2603 | else: |
|
2603 | else: | |
2604 | st = clock2() |
|
2604 | st = clock2() | |
2605 | exec code in glob, user_locals |
|
2605 | exec code in glob, user_locals | |
2606 | end = clock2() |
|
2606 | end = clock2() | |
2607 | out = None |
|
2607 | out = None | |
2608 | wall_end = wtime() |
|
2608 | wall_end = wtime() | |
2609 | # Compute actual times and report |
|
2609 | # Compute actual times and report | |
2610 | wall_time = wall_end-wall_st |
|
2610 | wall_time = wall_end-wall_st | |
2611 | cpu_user = end[0]-st[0] |
|
2611 | cpu_user = end[0]-st[0] | |
2612 | cpu_sys = end[1]-st[1] |
|
2612 | cpu_sys = end[1]-st[1] | |
2613 | cpu_tot = cpu_user+cpu_sys |
|
2613 | cpu_tot = cpu_user+cpu_sys | |
2614 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
2614 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
2615 | (cpu_user,cpu_sys,cpu_tot) |
|
2615 | (cpu_user,cpu_sys,cpu_tot) | |
2616 | print "Wall time: %.2f s" % wall_time |
|
2616 | print "Wall time: %.2f s" % wall_time | |
2617 | if tc > tc_min: |
|
2617 | if tc > tc_min: | |
2618 | print "Compiler : %.2f s" % tc |
|
2618 | print "Compiler : %.2f s" % tc | |
2619 | return out |
|
2619 | return out | |
2620 |
|
2620 | |||
2621 | @skip_doctest |
|
2621 | @skip_doctest | |
2622 | @line_magic |
|
2622 | @line_magic | |
2623 | def macro(self, parameter_s=''): |
|
2623 | def macro(self, parameter_s=''): | |
2624 | """Define a macro for future re-execution. It accepts ranges of history, |
|
2624 | """Define a macro for future re-execution. It accepts ranges of history, | |
2625 | filenames or string objects. |
|
2625 | filenames or string objects. | |
2626 |
|
2626 | |||
2627 | Usage:\\ |
|
2627 | Usage:\\ | |
2628 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
2628 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
2629 |
|
2629 | |||
2630 | Options: |
|
2630 | Options: | |
2631 |
|
2631 | |||
2632 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2632 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2633 | so that magics are loaded in their transformed version to valid |
|
2633 | so that magics are loaded in their transformed version to valid | |
2634 | Python. If this option is given, the raw input as typed as the |
|
2634 | Python. If this option is given, the raw input as typed as the | |
2635 | command line is used instead. |
|
2635 | command line is used instead. | |
2636 |
|
2636 | |||
2637 | This will define a global variable called `name` which is a string |
|
2637 | This will define a global variable called `name` which is a string | |
2638 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
2638 | made of joining the slices and lines you specify (n1,n2,... numbers | |
2639 | above) from your input history into a single string. This variable |
|
2639 | above) from your input history into a single string. This variable | |
2640 | acts like an automatic function which re-executes those lines as if |
|
2640 | acts like an automatic function which re-executes those lines as if | |
2641 | you had typed them. You just type 'name' at the prompt and the code |
|
2641 | you had typed them. You just type 'name' at the prompt and the code | |
2642 | executes. |
|
2642 | executes. | |
2643 |
|
2643 | |||
2644 | The syntax for indicating input ranges is described in %history. |
|
2644 | The syntax for indicating input ranges is described in %history. | |
2645 |
|
2645 | |||
2646 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
2646 | Note: as a 'hidden' feature, you can also use traditional python slice | |
2647 | notation, where N:M means numbers N through M-1. |
|
2647 | notation, where N:M means numbers N through M-1. | |
2648 |
|
2648 | |||
2649 | For example, if your history contains (%hist prints it):: |
|
2649 | For example, if your history contains (%hist prints it):: | |
2650 |
|
2650 | |||
2651 | 44: x=1 |
|
2651 | 44: x=1 | |
2652 | 45: y=3 |
|
2652 | 45: y=3 | |
2653 | 46: z=x+y |
|
2653 | 46: z=x+y | |
2654 | 47: print x |
|
2654 | 47: print x | |
2655 | 48: a=5 |
|
2655 | 48: a=5 | |
2656 | 49: print 'x',x,'y',y |
|
2656 | 49: print 'x',x,'y',y | |
2657 |
|
2657 | |||
2658 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2658 | you can create a macro with lines 44 through 47 (included) and line 49 | |
2659 | called my_macro with:: |
|
2659 | called my_macro with:: | |
2660 |
|
2660 | |||
2661 | In [55]: %macro my_macro 44-47 49 |
|
2661 | In [55]: %macro my_macro 44-47 49 | |
2662 |
|
2662 | |||
2663 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2663 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
2664 | in one pass. |
|
2664 | in one pass. | |
2665 |
|
2665 | |||
2666 | You don't need to give the line-numbers in order, and any given line |
|
2666 | You don't need to give the line-numbers in order, and any given line | |
2667 | number can appear multiple times. You can assemble macros with any |
|
2667 | number can appear multiple times. You can assemble macros with any | |
2668 | lines from your input history in any order. |
|
2668 | lines from your input history in any order. | |
2669 |
|
2669 | |||
2670 | The macro is a simple object which holds its value in an attribute, |
|
2670 | The macro is a simple object which holds its value in an attribute, | |
2671 | but IPython's display system checks for macros and executes them as |
|
2671 | but IPython's display system checks for macros and executes them as | |
2672 | code instead of printing them when you type their name. |
|
2672 | code instead of printing them when you type their name. | |
2673 |
|
2673 | |||
2674 | You can view a macro's contents by explicitly printing it with:: |
|
2674 | You can view a macro's contents by explicitly printing it with:: | |
2675 |
|
2675 | |||
2676 | print macro_name |
|
2676 | print macro_name | |
2677 |
|
2677 | |||
2678 | """ |
|
2678 | """ | |
2679 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2679 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2680 | if not args: # List existing macros |
|
2680 | if not args: # List existing macros | |
2681 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ |
|
2681 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ | |
2682 | isinstance(v, Macro)) |
|
2682 | isinstance(v, Macro)) | |
2683 | if len(args) == 1: |
|
2683 | if len(args) == 1: | |
2684 | raise UsageError( |
|
2684 | raise UsageError( | |
2685 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2685 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
2686 | name, codefrom = args[0], " ".join(args[1:]) |
|
2686 | name, codefrom = args[0], " ".join(args[1:]) | |
2687 |
|
2687 | |||
2688 | #print 'rng',ranges # dbg |
|
2688 | #print 'rng',ranges # dbg | |
2689 | try: |
|
2689 | try: | |
2690 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2690 | lines = self.shell.find_user_code(codefrom, 'r' in opts) | |
2691 | except (ValueError, TypeError) as e: |
|
2691 | except (ValueError, TypeError) as e: | |
2692 | print e.args[0] |
|
2692 | print e.args[0] | |
2693 | return |
|
2693 | return | |
2694 | macro = Macro(lines) |
|
2694 | macro = Macro(lines) | |
2695 | self.shell.define_macro(name, macro) |
|
2695 | self.shell.define_macro(name, macro) | |
2696 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2696 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
2697 | print '=== Macro contents: ===' |
|
2697 | print '=== Macro contents: ===' | |
2698 | print macro, |
|
2698 | print macro, | |
2699 |
|
2699 | |||
2700 |
|
2700 | |||
2701 | @register_magics |
|
2701 | @register_magics | |
2702 | class AutoMagics(Magics): |
|
2702 | class AutoMagics(Magics): | |
2703 | """Magics that control various autoX behaviors.""" |
|
2703 | """Magics that control various autoX behaviors.""" | |
2704 |
|
2704 | |||
2705 | def __init__(self, shell): |
|
2705 | def __init__(self, shell): | |
2706 | super(AutoMagics, self).__init__(shell) |
|
2706 | super(AutoMagics, self).__init__(shell) | |
2707 | # namespace for holding state we may need |
|
2707 | # namespace for holding state we may need | |
2708 | self._magic_state = Bunch() |
|
2708 | self._magic_state = Bunch() | |
2709 |
|
2709 | |||
2710 | @line_magic |
|
2710 | @line_magic | |
2711 | def automagic(self, parameter_s=''): |
|
2711 | def automagic(self, parameter_s=''): | |
2712 | """Make magic functions callable without having to type the initial %. |
|
2712 | """Make magic functions callable without having to type the initial %. | |
2713 |
|
2713 | |||
2714 | Without argumentsl toggles on/off (when off, you must call it as |
|
2714 | Without argumentsl toggles on/off (when off, you must call it as | |
2715 | %automagic, of course). With arguments it sets the value, and you can |
|
2715 | %automagic, of course). With arguments it sets the value, and you can | |
2716 | use any of (case insensitive): |
|
2716 | use any of (case insensitive): | |
2717 |
|
2717 | |||
2718 | - on, 1, True: to activate |
|
2718 | - on, 1, True: to activate | |
2719 |
|
2719 | |||
2720 | - off, 0, False: to deactivate. |
|
2720 | - off, 0, False: to deactivate. | |
2721 |
|
2721 | |||
2722 | Note that magic functions have lowest priority, so if there's a |
|
2722 | Note that magic functions have lowest priority, so if there's a | |
2723 | variable whose name collides with that of a magic fn, automagic won't |
|
2723 | variable whose name collides with that of a magic fn, automagic won't | |
2724 | work for that function (you get the variable instead). However, if you |
|
2724 | work for that function (you get the variable instead). However, if you | |
2725 | delete the variable (del var), the previously shadowed magic function |
|
2725 | delete the variable (del var), the previously shadowed magic function | |
2726 | becomes visible to automagic again.""" |
|
2726 | becomes visible to automagic again.""" | |
2727 |
|
2727 | |||
2728 | arg = parameter_s.lower() |
|
2728 | arg = parameter_s.lower() | |
2729 | mman = self.shell.magics_manager |
|
2729 | mman = self.shell.magics_manager | |
2730 | if arg in ('on', '1', 'true'): |
|
2730 | if arg in ('on', '1', 'true'): | |
2731 | val = True |
|
2731 | val = True | |
2732 | elif arg in ('off', '0', 'false'): |
|
2732 | elif arg in ('off', '0', 'false'): | |
2733 | val = False |
|
2733 | val = False | |
2734 | else: |
|
2734 | else: | |
2735 | val = not mman.auto_magic |
|
2735 | val = not mman.auto_magic | |
2736 | mman.auto_magic = val |
|
2736 | mman.auto_magic = val | |
2737 | print '\n' + self.shell.magics_manager.auto_status() |
|
2737 | print '\n' + self.shell.magics_manager.auto_status() | |
2738 |
|
2738 | |||
2739 | @skip_doctest |
|
2739 | @skip_doctest | |
2740 | @line_magic |
|
2740 | @line_magic | |
2741 | def autocall(self, parameter_s=''): |
|
2741 | def autocall(self, parameter_s=''): | |
2742 | """Make functions callable without having to type parentheses. |
|
2742 | """Make functions callable without having to type parentheses. | |
2743 |
|
2743 | |||
2744 | Usage: |
|
2744 | Usage: | |
2745 |
|
2745 | |||
2746 | %autocall [mode] |
|
2746 | %autocall [mode] | |
2747 |
|
2747 | |||
2748 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
2748 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
2749 | value is toggled on and off (remembering the previous state). |
|
2749 | value is toggled on and off (remembering the previous state). | |
2750 |
|
2750 | |||
2751 | In more detail, these values mean: |
|
2751 | In more detail, these values mean: | |
2752 |
|
2752 | |||
2753 | 0 -> fully disabled |
|
2753 | 0 -> fully disabled | |
2754 |
|
2754 | |||
2755 | 1 -> active, but do not apply if there are no arguments on the line. |
|
2755 | 1 -> active, but do not apply if there are no arguments on the line. | |
2756 |
|
2756 | |||
2757 | In this mode, you get:: |
|
2757 | In this mode, you get:: | |
2758 |
|
2758 | |||
2759 | In [1]: callable |
|
2759 | In [1]: callable | |
2760 | Out[1]: <built-in function callable> |
|
2760 | Out[1]: <built-in function callable> | |
2761 |
|
2761 | |||
2762 | In [2]: callable 'hello' |
|
2762 | In [2]: callable 'hello' | |
2763 | ------> callable('hello') |
|
2763 | ------> callable('hello') | |
2764 | Out[2]: False |
|
2764 | Out[2]: False | |
2765 |
|
2765 | |||
2766 | 2 -> Active always. Even if no arguments are present, the callable |
|
2766 | 2 -> Active always. Even if no arguments are present, the callable | |
2767 | object is called:: |
|
2767 | object is called:: | |
2768 |
|
2768 | |||
2769 | In [2]: float |
|
2769 | In [2]: float | |
2770 | ------> float() |
|
2770 | ------> float() | |
2771 | Out[2]: 0.0 |
|
2771 | Out[2]: 0.0 | |
2772 |
|
2772 | |||
2773 | Note that even with autocall off, you can still use '/' at the start of |
|
2773 | Note that even with autocall off, you can still use '/' at the start of | |
2774 | a line to treat the first argument on the command line as a function |
|
2774 | a line to treat the first argument on the command line as a function | |
2775 | and add parentheses to it:: |
|
2775 | and add parentheses to it:: | |
2776 |
|
2776 | |||
2777 | In [8]: /str 43 |
|
2777 | In [8]: /str 43 | |
2778 | ------> str(43) |
|
2778 | ------> str(43) | |
2779 | Out[8]: '43' |
|
2779 | Out[8]: '43' | |
2780 |
|
2780 | |||
2781 | # all-random (note for auto-testing) |
|
2781 | # all-random (note for auto-testing) | |
2782 | """ |
|
2782 | """ | |
2783 |
|
2783 | |||
2784 | if parameter_s: |
|
2784 | if parameter_s: | |
2785 | arg = int(parameter_s) |
|
2785 | arg = int(parameter_s) | |
2786 | else: |
|
2786 | else: | |
2787 | arg = 'toggle' |
|
2787 | arg = 'toggle' | |
2788 |
|
2788 | |||
2789 | if not arg in (0, 1, 2,'toggle'): |
|
2789 | if not arg in (0, 1, 2,'toggle'): | |
2790 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
2790 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
2791 | return |
|
2791 | return | |
2792 |
|
2792 | |||
2793 | if arg in (0, 1, 2): |
|
2793 | if arg in (0, 1, 2): | |
2794 | self.shell.autocall = arg |
|
2794 | self.shell.autocall = arg | |
2795 | else: # toggle |
|
2795 | else: # toggle | |
2796 | if self.shell.autocall: |
|
2796 | if self.shell.autocall: | |
2797 | self._magic_state.autocall_save = self.shell.autocall |
|
2797 | self._magic_state.autocall_save = self.shell.autocall | |
2798 | self.shell.autocall = 0 |
|
2798 | self.shell.autocall = 0 | |
2799 | else: |
|
2799 | else: | |
2800 | try: |
|
2800 | try: | |
2801 | self.shell.autocall = self._magic_state.autocall_save |
|
2801 | self.shell.autocall = self._magic_state.autocall_save | |
2802 | except AttributeError: |
|
2802 | except AttributeError: | |
2803 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
2803 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
2804 |
|
2804 | |||
2805 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
2805 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
2806 |
|
2806 | |||
2807 |
|
2807 | |||
2808 | @register_magics |
|
2808 | @register_magics | |
2809 | class OSMagics(Magics): |
|
2809 | class OSMagics(Magics): | |
2810 | """Magics to interact with the underlying OS (shell-type functionality). |
|
2810 | """Magics to interact with the underlying OS (shell-type functionality). | |
2811 | """ |
|
2811 | """ | |
2812 |
|
2812 | |||
2813 | @skip_doctest |
|
2813 | @skip_doctest | |
2814 | @line_magic |
|
2814 | @line_magic | |
2815 | def alias(self, parameter_s=''): |
|
2815 | def alias(self, parameter_s=''): | |
2816 | """Define an alias for a system command. |
|
2816 | """Define an alias for a system command. | |
2817 |
|
2817 | |||
2818 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2818 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2819 |
|
2819 | |||
2820 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2820 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2821 | params' (from your underlying operating system). |
|
2821 | params' (from your underlying operating system). | |
2822 |
|
2822 | |||
2823 | Aliases have lower precedence than magic functions and Python normal |
|
2823 | Aliases have lower precedence than magic functions and Python normal | |
2824 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2824 | variables, so if 'foo' is both a Python variable and an alias, the | |
2825 | alias can not be executed until 'del foo' removes the Python variable. |
|
2825 | alias can not be executed until 'del foo' removes the Python variable. | |
2826 |
|
2826 | |||
2827 | You can use the %l specifier in an alias definition to represent the |
|
2827 | You can use the %l specifier in an alias definition to represent the | |
2828 | whole line when the alias is called. For example:: |
|
2828 | whole line when the alias is called. For example:: | |
2829 |
|
2829 | |||
2830 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2830 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
2831 | In [3]: bracket hello world |
|
2831 | In [3]: bracket hello world | |
2832 | Input in brackets: <hello world> |
|
2832 | Input in brackets: <hello world> | |
2833 |
|
2833 | |||
2834 | You can also define aliases with parameters using %s specifiers (one |
|
2834 | You can also define aliases with parameters using %s specifiers (one | |
2835 | per parameter):: |
|
2835 | per parameter):: | |
2836 |
|
2836 | |||
2837 | In [1]: alias parts echo first %s second %s |
|
2837 | In [1]: alias parts echo first %s second %s | |
2838 | In [2]: %parts A B |
|
2838 | In [2]: %parts A B | |
2839 | first A second B |
|
2839 | first A second B | |
2840 | In [3]: %parts A |
|
2840 | In [3]: %parts A | |
2841 | Incorrect number of arguments: 2 expected. |
|
2841 | Incorrect number of arguments: 2 expected. | |
2842 | parts is an alias to: 'echo first %s second %s' |
|
2842 | parts is an alias to: 'echo first %s second %s' | |
2843 |
|
2843 | |||
2844 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2844 | Note that %l and %s are mutually exclusive. You can only use one or | |
2845 | the other in your aliases. |
|
2845 | the other in your aliases. | |
2846 |
|
2846 | |||
2847 | Aliases expand Python variables just like system calls using ! or !! |
|
2847 | Aliases expand Python variables just like system calls using ! or !! | |
2848 | do: all expressions prefixed with '$' get expanded. For details of |
|
2848 | do: all expressions prefixed with '$' get expanded. For details of | |
2849 | the semantic rules, see PEP-215: |
|
2849 | the semantic rules, see PEP-215: | |
2850 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2850 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2851 | IPython for variable expansion. If you want to access a true shell |
|
2851 | IPython for variable expansion. If you want to access a true shell | |
2852 | variable, an extra $ is necessary to prevent its expansion by |
|
2852 | variable, an extra $ is necessary to prevent its expansion by | |
2853 | IPython:: |
|
2853 | IPython:: | |
2854 |
|
2854 | |||
2855 | In [6]: alias show echo |
|
2855 | In [6]: alias show echo | |
2856 | In [7]: PATH='A Python string' |
|
2856 | In [7]: PATH='A Python string' | |
2857 | In [8]: show $PATH |
|
2857 | In [8]: show $PATH | |
2858 | A Python string |
|
2858 | A Python string | |
2859 | In [9]: show $$PATH |
|
2859 | In [9]: show $$PATH | |
2860 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2860 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2861 |
|
2861 | |||
2862 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2862 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2863 | and %rehashx functions, which automatically create aliases for the |
|
2863 | and %rehashx functions, which automatically create aliases for the | |
2864 | contents of your $PATH. |
|
2864 | contents of your $PATH. | |
2865 |
|
2865 | |||
2866 | If called with no parameters, %alias prints the current alias table.""" |
|
2866 | If called with no parameters, %alias prints the current alias table.""" | |
2867 |
|
2867 | |||
2868 | par = parameter_s.strip() |
|
2868 | par = parameter_s.strip() | |
2869 | if not par: |
|
2869 | if not par: | |
2870 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2870 | aliases = sorted(self.shell.alias_manager.aliases) | |
2871 | # stored = self.shell.db.get('stored_aliases', {} ) |
|
2871 | # stored = self.shell.db.get('stored_aliases', {} ) | |
2872 | # for k, v in stored: |
|
2872 | # for k, v in stored: | |
2873 | # atab.append(k, v[0]) |
|
2873 | # atab.append(k, v[0]) | |
2874 |
|
2874 | |||
2875 | print "Total number of aliases:", len(aliases) |
|
2875 | print "Total number of aliases:", len(aliases) | |
2876 | sys.stdout.flush() |
|
2876 | sys.stdout.flush() | |
2877 | return aliases |
|
2877 | return aliases | |
2878 |
|
2878 | |||
2879 | # Now try to define a new one |
|
2879 | # Now try to define a new one | |
2880 | try: |
|
2880 | try: | |
2881 | alias,cmd = par.split(None, 1) |
|
2881 | alias,cmd = par.split(None, 1) | |
2882 | except: |
|
2882 | except: | |
2883 | print oinspect.getdoc(self.magic_alias) |
|
2883 | print oinspect.getdoc(self.magic_alias) | |
2884 | else: |
|
2884 | else: | |
2885 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2885 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2886 | # end magic_alias |
|
2886 | # end magic_alias | |
2887 |
|
2887 | |||
2888 | @line_magic |
|
2888 | @line_magic | |
2889 | def unalias(self, parameter_s=''): |
|
2889 | def unalias(self, parameter_s=''): | |
2890 | """Remove an alias""" |
|
2890 | """Remove an alias""" | |
2891 |
|
2891 | |||
2892 | aname = parameter_s.strip() |
|
2892 | aname = parameter_s.strip() | |
2893 | self.shell.alias_manager.undefine_alias(aname) |
|
2893 | self.shell.alias_manager.undefine_alias(aname) | |
2894 | stored = self.shell.db.get('stored_aliases', {} ) |
|
2894 | stored = self.shell.db.get('stored_aliases', {} ) | |
2895 | if aname in stored: |
|
2895 | if aname in stored: | |
2896 | print "Removing %stored alias",aname |
|
2896 | print "Removing %stored alias",aname | |
2897 | del stored[aname] |
|
2897 | del stored[aname] | |
2898 | self.shell.db['stored_aliases'] = stored |
|
2898 | self.shell.db['stored_aliases'] = stored | |
2899 |
|
2899 | |||
2900 | @line_magic |
|
2900 | @line_magic | |
2901 | def rehashx(self, parameter_s=''): |
|
2901 | def rehashx(self, parameter_s=''): | |
2902 | """Update the alias table with all executable files in $PATH. |
|
2902 | """Update the alias table with all executable files in $PATH. | |
2903 |
|
2903 | |||
2904 | This version explicitly checks that every entry in $PATH is a file |
|
2904 | This version explicitly checks that every entry in $PATH is a file | |
2905 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2905 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2906 |
|
2906 | |||
2907 | Under Windows, it checks executability as a match against a |
|
2907 | Under Windows, it checks executability as a match against a | |
2908 | '|'-separated string of extensions, stored in the IPython config |
|
2908 | '|'-separated string of extensions, stored in the IPython config | |
2909 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2909 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2910 |
|
2910 | |||
2911 | This function also resets the root module cache of module completer, |
|
2911 | This function also resets the root module cache of module completer, | |
2912 | used on slow filesystems. |
|
2912 | used on slow filesystems. | |
2913 | """ |
|
2913 | """ | |
2914 | from IPython.core.alias import InvalidAliasError |
|
2914 | from IPython.core.alias import InvalidAliasError | |
2915 |
|
2915 | |||
2916 | # for the benefit of module completer in ipy_completers.py |
|
2916 | # for the benefit of module completer in ipy_completers.py | |
2917 | del self.shell.db['rootmodules'] |
|
2917 | del self.shell.db['rootmodules'] | |
2918 |
|
2918 | |||
2919 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2919 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2920 | os.environ.get('PATH','').split(os.pathsep)] |
|
2920 | os.environ.get('PATH','').split(os.pathsep)] | |
2921 | path = filter(os.path.isdir,path) |
|
2921 | path = filter(os.path.isdir,path) | |
2922 |
|
2922 | |||
2923 | syscmdlist = [] |
|
2923 | syscmdlist = [] | |
2924 | # Now define isexec in a cross platform manner. |
|
2924 | # Now define isexec in a cross platform manner. | |
2925 | if os.name == 'posix': |
|
2925 | if os.name == 'posix': | |
2926 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2926 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2927 | os.access(fname,os.X_OK) |
|
2927 | os.access(fname,os.X_OK) | |
2928 | else: |
|
2928 | else: | |
2929 | try: |
|
2929 | try: | |
2930 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2930 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2931 | except KeyError: |
|
2931 | except KeyError: | |
2932 | winext = 'exe|com|bat|py' |
|
2932 | winext = 'exe|com|bat|py' | |
2933 | if 'py' not in winext: |
|
2933 | if 'py' not in winext: | |
2934 | winext += '|py' |
|
2934 | winext += '|py' | |
2935 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2935 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2936 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2936 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2937 | savedir = os.getcwdu() |
|
2937 | savedir = os.getcwdu() | |
2938 |
|
2938 | |||
2939 | # Now walk the paths looking for executables to alias. |
|
2939 | # Now walk the paths looking for executables to alias. | |
2940 | try: |
|
2940 | try: | |
2941 | # write the whole loop for posix/Windows so we don't have an if in |
|
2941 | # write the whole loop for posix/Windows so we don't have an if in | |
2942 | # the innermost part |
|
2942 | # the innermost part | |
2943 | if os.name == 'posix': |
|
2943 | if os.name == 'posix': | |
2944 | for pdir in path: |
|
2944 | for pdir in path: | |
2945 | os.chdir(pdir) |
|
2945 | os.chdir(pdir) | |
2946 | for ff in os.listdir(pdir): |
|
2946 | for ff in os.listdir(pdir): | |
2947 | if isexec(ff): |
|
2947 | if isexec(ff): | |
2948 | try: |
|
2948 | try: | |
2949 | # Removes dots from the name since ipython |
|
2949 | # Removes dots from the name since ipython | |
2950 | # will assume names with dots to be python. |
|
2950 | # will assume names with dots to be python. | |
2951 | self.shell.alias_manager.define_alias( |
|
2951 | self.shell.alias_manager.define_alias( | |
2952 | ff.replace('.',''), ff) |
|
2952 | ff.replace('.',''), ff) | |
2953 | except InvalidAliasError: |
|
2953 | except InvalidAliasError: | |
2954 | pass |
|
2954 | pass | |
2955 | else: |
|
2955 | else: | |
2956 | syscmdlist.append(ff) |
|
2956 | syscmdlist.append(ff) | |
2957 | else: |
|
2957 | else: | |
2958 | no_alias = self.shell.alias_manager.no_alias |
|
2958 | no_alias = self.shell.alias_manager.no_alias | |
2959 | for pdir in path: |
|
2959 | for pdir in path: | |
2960 | os.chdir(pdir) |
|
2960 | os.chdir(pdir) | |
2961 | for ff in os.listdir(pdir): |
|
2961 | for ff in os.listdir(pdir): | |
2962 | base, ext = os.path.splitext(ff) |
|
2962 | base, ext = os.path.splitext(ff) | |
2963 | if isexec(ff) and base.lower() not in no_alias: |
|
2963 | if isexec(ff) and base.lower() not in no_alias: | |
2964 | if ext.lower() == '.exe': |
|
2964 | if ext.lower() == '.exe': | |
2965 | ff = base |
|
2965 | ff = base | |
2966 | try: |
|
2966 | try: | |
2967 | # Removes dots from the name since ipython |
|
2967 | # Removes dots from the name since ipython | |
2968 | # will assume names with dots to be python. |
|
2968 | # will assume names with dots to be python. | |
2969 | self.shell.alias_manager.define_alias( |
|
2969 | self.shell.alias_manager.define_alias( | |
2970 | base.lower().replace('.',''), ff) |
|
2970 | base.lower().replace('.',''), ff) | |
2971 | except InvalidAliasError: |
|
2971 | except InvalidAliasError: | |
2972 | pass |
|
2972 | pass | |
2973 | syscmdlist.append(ff) |
|
2973 | syscmdlist.append(ff) | |
2974 | self.shell.db['syscmdlist'] = syscmdlist |
|
2974 | self.shell.db['syscmdlist'] = syscmdlist | |
2975 | finally: |
|
2975 | finally: | |
2976 | os.chdir(savedir) |
|
2976 | os.chdir(savedir) | |
2977 |
|
2977 | |||
2978 | @skip_doctest |
|
2978 | @skip_doctest | |
2979 | @line_magic |
|
2979 | @line_magic | |
2980 | def pwd(self, parameter_s=''): |
|
2980 | def pwd(self, parameter_s=''): | |
2981 | """Return the current working directory path. |
|
2981 | """Return the current working directory path. | |
2982 |
|
2982 | |||
2983 | Examples |
|
2983 | Examples | |
2984 | -------- |
|
2984 | -------- | |
2985 | :: |
|
2985 | :: | |
2986 |
|
2986 | |||
2987 | In [9]: pwd |
|
2987 | In [9]: pwd | |
2988 | Out[9]: '/home/tsuser/sprint/ipython' |
|
2988 | Out[9]: '/home/tsuser/sprint/ipython' | |
2989 | """ |
|
2989 | """ | |
2990 | return os.getcwdu() |
|
2990 | return os.getcwdu() | |
2991 |
|
2991 | |||
2992 | @skip_doctest |
|
2992 | @skip_doctest | |
2993 | @line_magic |
|
2993 | @line_magic | |
2994 | def cd(self, parameter_s=''): |
|
2994 | def cd(self, parameter_s=''): | |
2995 | """Change the current working directory. |
|
2995 | """Change the current working directory. | |
2996 |
|
2996 | |||
2997 | This command automatically maintains an internal list of directories |
|
2997 | This command automatically maintains an internal list of directories | |
2998 | you visit during your IPython session, in the variable _dh. The |
|
2998 | you visit during your IPython session, in the variable _dh. The | |
2999 | command %dhist shows this history nicely formatted. You can also |
|
2999 | command %dhist shows this history nicely formatted. You can also | |
3000 | do 'cd -<tab>' to see directory history conveniently. |
|
3000 | do 'cd -<tab>' to see directory history conveniently. | |
3001 |
|
3001 | |||
3002 | Usage: |
|
3002 | Usage: | |
3003 |
|
3003 | |||
3004 | cd 'dir': changes to directory 'dir'. |
|
3004 | cd 'dir': changes to directory 'dir'. | |
3005 |
|
3005 | |||
3006 | cd -: changes to the last visited directory. |
|
3006 | cd -: changes to the last visited directory. | |
3007 |
|
3007 | |||
3008 | cd -<n>: changes to the n-th directory in the directory history. |
|
3008 | cd -<n>: changes to the n-th directory in the directory history. | |
3009 |
|
3009 | |||
3010 | cd --foo: change to directory that matches 'foo' in history |
|
3010 | cd --foo: change to directory that matches 'foo' in history | |
3011 |
|
3011 | |||
3012 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
3012 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
3013 | (note: cd <bookmark_name> is enough if there is no |
|
3013 | (note: cd <bookmark_name> is enough if there is no | |
3014 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
3014 | directory <bookmark_name>, but a bookmark with the name exists.) | |
3015 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
3015 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
3016 |
|
3016 | |||
3017 | Options: |
|
3017 | Options: | |
3018 |
|
3018 | |||
3019 | -q: quiet. Do not print the working directory after the cd command is |
|
3019 | -q: quiet. Do not print the working directory after the cd command is | |
3020 | executed. By default IPython's cd command does print this directory, |
|
3020 | executed. By default IPython's cd command does print this directory, | |
3021 | since the default prompts do not display path information. |
|
3021 | since the default prompts do not display path information. | |
3022 |
|
3022 | |||
3023 | Note that !cd doesn't work for this purpose because the shell where |
|
3023 | Note that !cd doesn't work for this purpose because the shell where | |
3024 | !command runs is immediately discarded after executing 'command'. |
|
3024 | !command runs is immediately discarded after executing 'command'. | |
3025 |
|
3025 | |||
3026 | Examples |
|
3026 | Examples | |
3027 | -------- |
|
3027 | -------- | |
3028 | :: |
|
3028 | :: | |
3029 |
|
3029 | |||
3030 | In [10]: cd parent/child |
|
3030 | In [10]: cd parent/child | |
3031 | /home/tsuser/parent/child |
|
3031 | /home/tsuser/parent/child | |
3032 | """ |
|
3032 | """ | |
3033 |
|
3033 | |||
3034 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
3034 | #bkms = self.shell.persist.get("bookmarks",{}) | |
3035 |
|
3035 | |||
3036 | oldcwd = os.getcwdu() |
|
3036 | oldcwd = os.getcwdu() | |
3037 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
3037 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
3038 | # jump in directory history by number |
|
3038 | # jump in directory history by number | |
3039 | if numcd: |
|
3039 | if numcd: | |
3040 | nn = int(numcd.group(2)) |
|
3040 | nn = int(numcd.group(2)) | |
3041 | try: |
|
3041 | try: | |
3042 | ps = self.shell.user_ns['_dh'][nn] |
|
3042 | ps = self.shell.user_ns['_dh'][nn] | |
3043 | except IndexError: |
|
3043 | except IndexError: | |
3044 | print 'The requested directory does not exist in history.' |
|
3044 | print 'The requested directory does not exist in history.' | |
3045 | return |
|
3045 | return | |
3046 | else: |
|
3046 | else: | |
3047 | opts = {} |
|
3047 | opts = {} | |
3048 | elif parameter_s.startswith('--'): |
|
3048 | elif parameter_s.startswith('--'): | |
3049 | ps = None |
|
3049 | ps = None | |
3050 | fallback = None |
|
3050 | fallback = None | |
3051 | pat = parameter_s[2:] |
|
3051 | pat = parameter_s[2:] | |
3052 | dh = self.shell.user_ns['_dh'] |
|
3052 | dh = self.shell.user_ns['_dh'] | |
3053 | # first search only by basename (last component) |
|
3053 | # first search only by basename (last component) | |
3054 | for ent in reversed(dh): |
|
3054 | for ent in reversed(dh): | |
3055 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
3055 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
3056 | ps = ent |
|
3056 | ps = ent | |
3057 | break |
|
3057 | break | |
3058 |
|
3058 | |||
3059 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
3059 | if fallback is None and pat in ent and os.path.isdir(ent): | |
3060 | fallback = ent |
|
3060 | fallback = ent | |
3061 |
|
3061 | |||
3062 | # if we have no last part match, pick the first full path match |
|
3062 | # if we have no last part match, pick the first full path match | |
3063 | if ps is None: |
|
3063 | if ps is None: | |
3064 | ps = fallback |
|
3064 | ps = fallback | |
3065 |
|
3065 | |||
3066 | if ps is None: |
|
3066 | if ps is None: | |
3067 | print "No matching entry in directory history" |
|
3067 | print "No matching entry in directory history" | |
3068 | return |
|
3068 | return | |
3069 | else: |
|
3069 | else: | |
3070 | opts = {} |
|
3070 | opts = {} | |
3071 |
|
3071 | |||
3072 |
|
3072 | |||
3073 | else: |
|
3073 | else: | |
3074 | #turn all non-space-escaping backslashes to slashes, |
|
3074 | #turn all non-space-escaping backslashes to slashes, | |
3075 | # for c:\windows\directory\names\ |
|
3075 | # for c:\windows\directory\names\ | |
3076 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
3076 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
3077 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
3077 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
3078 | # jump to previous |
|
3078 | # jump to previous | |
3079 | if ps == '-': |
|
3079 | if ps == '-': | |
3080 | try: |
|
3080 | try: | |
3081 | ps = self.shell.user_ns['_dh'][-2] |
|
3081 | ps = self.shell.user_ns['_dh'][-2] | |
3082 | except IndexError: |
|
3082 | except IndexError: | |
3083 | raise UsageError('%cd -: No previous directory to change to.') |
|
3083 | raise UsageError('%cd -: No previous directory to change to.') | |
3084 | # jump to bookmark if needed |
|
3084 | # jump to bookmark if needed | |
3085 | else: |
|
3085 | else: | |
3086 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
3086 | if not os.path.isdir(ps) or opts.has_key('b'): | |
3087 | bkms = self.shell.db.get('bookmarks', {}) |
|
3087 | bkms = self.shell.db.get('bookmarks', {}) | |
3088 |
|
3088 | |||
3089 | if bkms.has_key(ps): |
|
3089 | if bkms.has_key(ps): | |
3090 | target = bkms[ps] |
|
3090 | target = bkms[ps] | |
3091 | print '(bookmark:%s) -> %s' % (ps,target) |
|
3091 | print '(bookmark:%s) -> %s' % (ps,target) | |
3092 | ps = target |
|
3092 | ps = target | |
3093 | else: |
|
3093 | else: | |
3094 | if opts.has_key('b'): |
|
3094 | if opts.has_key('b'): | |
3095 | raise UsageError("Bookmark '%s' not found. " |
|
3095 | raise UsageError("Bookmark '%s' not found. " | |
3096 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
3096 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
3097 |
|
3097 | |||
3098 | # strip extra quotes on Windows, because os.chdir doesn't like them |
|
3098 | # strip extra quotes on Windows, because os.chdir doesn't like them | |
3099 | ps = unquote_filename(ps) |
|
3099 | ps = unquote_filename(ps) | |
3100 | # at this point ps should point to the target dir |
|
3100 | # at this point ps should point to the target dir | |
3101 | if ps: |
|
3101 | if ps: | |
3102 | try: |
|
3102 | try: | |
3103 | os.chdir(os.path.expanduser(ps)) |
|
3103 | os.chdir(os.path.expanduser(ps)) | |
3104 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
3104 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
3105 | set_term_title('IPython: ' + abbrev_cwd()) |
|
3105 | set_term_title('IPython: ' + abbrev_cwd()) | |
3106 | except OSError: |
|
3106 | except OSError: | |
3107 | print sys.exc_info()[1] |
|
3107 | print sys.exc_info()[1] | |
3108 | else: |
|
3108 | else: | |
3109 | cwd = os.getcwdu() |
|
3109 | cwd = os.getcwdu() | |
3110 | dhist = self.shell.user_ns['_dh'] |
|
3110 | dhist = self.shell.user_ns['_dh'] | |
3111 | if oldcwd != cwd: |
|
3111 | if oldcwd != cwd: | |
3112 | dhist.append(cwd) |
|
3112 | dhist.append(cwd) | |
3113 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] |
|
3113 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] | |
3114 |
|
3114 | |||
3115 | else: |
|
3115 | else: | |
3116 | os.chdir(self.shell.home_dir) |
|
3116 | os.chdir(self.shell.home_dir) | |
3117 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
3117 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
3118 | set_term_title('IPython: ' + '~') |
|
3118 | set_term_title('IPython: ' + '~') | |
3119 | cwd = os.getcwdu() |
|
3119 | cwd = os.getcwdu() | |
3120 | dhist = self.shell.user_ns['_dh'] |
|
3120 | dhist = self.shell.user_ns['_dh'] | |
3121 |
|
3121 | |||
3122 | if oldcwd != cwd: |
|
3122 | if oldcwd != cwd: | |
3123 | dhist.append(cwd) |
|
3123 | dhist.append(cwd) | |
3124 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] |
|
3124 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] | |
3125 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
3125 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
3126 | print self.shell.user_ns['_dh'][-1] |
|
3126 | print self.shell.user_ns['_dh'][-1] | |
3127 |
|
3127 | |||
3128 |
|
3128 | |||
3129 | @line_magic |
|
3129 | @line_magic | |
3130 | def env(self, parameter_s=''): |
|
3130 | def env(self, parameter_s=''): | |
3131 | """List environment variables.""" |
|
3131 | """List environment variables.""" | |
3132 |
|
3132 | |||
3133 | return dict(os.environ) |
|
3133 | return dict(os.environ) | |
3134 |
|
3134 | |||
3135 | @line_magic |
|
3135 | @line_magic | |
3136 | def pushd(self, parameter_s=''): |
|
3136 | def pushd(self, parameter_s=''): | |
3137 | """Place the current dir on stack and change directory. |
|
3137 | """Place the current dir on stack and change directory. | |
3138 |
|
3138 | |||
3139 | Usage:\\ |
|
3139 | Usage:\\ | |
3140 | %pushd ['dirname'] |
|
3140 | %pushd ['dirname'] | |
3141 | """ |
|
3141 | """ | |
3142 |
|
3142 | |||
3143 | dir_s = self.shell.dir_stack |
|
3143 | dir_s = self.shell.dir_stack | |
3144 | tgt = os.path.expanduser(unquote_filename(parameter_s)) |
|
3144 | tgt = os.path.expanduser(unquote_filename(parameter_s)) | |
3145 | cwd = os.getcwdu().replace(self.shell.home_dir,'~') |
|
3145 | cwd = os.getcwdu().replace(self.shell.home_dir,'~') | |
3146 | if tgt: |
|
3146 | if tgt: | |
3147 | self.magic_cd(parameter_s) |
|
3147 | self.magic_cd(parameter_s) | |
3148 | dir_s.insert(0,cwd) |
|
3148 | dir_s.insert(0,cwd) | |
3149 | return self.shell.magic('dirs') |
|
3149 | return self.shell.magic('dirs') | |
3150 |
|
3150 | |||
3151 | @line_magic |
|
3151 | @line_magic | |
3152 | def popd(self, parameter_s=''): |
|
3152 | def popd(self, parameter_s=''): | |
3153 | """Change to directory popped off the top of the stack. |
|
3153 | """Change to directory popped off the top of the stack. | |
3154 | """ |
|
3154 | """ | |
3155 | if not self.shell.dir_stack: |
|
3155 | if not self.shell.dir_stack: | |
3156 | raise UsageError("%popd on empty stack") |
|
3156 | raise UsageError("%popd on empty stack") | |
3157 | top = self.shell.dir_stack.pop(0) |
|
3157 | top = self.shell.dir_stack.pop(0) | |
3158 | self.magic_cd(top) |
|
3158 | self.magic_cd(top) | |
3159 | print "popd ->",top |
|
3159 | print "popd ->",top | |
3160 |
|
3160 | |||
3161 | @line_magic |
|
3161 | @line_magic | |
3162 | def dirs(self, parameter_s=''): |
|
3162 | def dirs(self, parameter_s=''): | |
3163 | """Return the current directory stack.""" |
|
3163 | """Return the current directory stack.""" | |
3164 |
|
3164 | |||
3165 | return self.shell.dir_stack |
|
3165 | return self.shell.dir_stack | |
3166 |
|
3166 | |||
3167 | @line_magic |
|
3167 | @line_magic | |
3168 | def dhist(self, parameter_s=''): |
|
3168 | def dhist(self, parameter_s=''): | |
3169 | """Print your history of visited directories. |
|
3169 | """Print your history of visited directories. | |
3170 |
|
3170 | |||
3171 | %dhist -> print full history\\ |
|
3171 | %dhist -> print full history\\ | |
3172 | %dhist n -> print last n entries only\\ |
|
3172 | %dhist n -> print last n entries only\\ | |
3173 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
3173 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
3174 |
|
3174 | |||
3175 | This history is automatically maintained by the %cd command, and |
|
3175 | This history is automatically maintained by the %cd command, and | |
3176 | always available as the global list variable _dh. You can use %cd -<n> |
|
3176 | always available as the global list variable _dh. You can use %cd -<n> | |
3177 | to go to directory number <n>. |
|
3177 | to go to directory number <n>. | |
3178 |
|
3178 | |||
3179 | Note that most of time, you should view directory history by entering |
|
3179 | Note that most of time, you should view directory history by entering | |
3180 | cd -<TAB>. |
|
3180 | cd -<TAB>. | |
3181 |
|
3181 | |||
3182 | """ |
|
3182 | """ | |
3183 |
|
3183 | |||
3184 | dh = self.shell.user_ns['_dh'] |
|
3184 | dh = self.shell.user_ns['_dh'] | |
3185 | if parameter_s: |
|
3185 | if parameter_s: | |
3186 | try: |
|
3186 | try: | |
3187 | args = map(int,parameter_s.split()) |
|
3187 | args = map(int,parameter_s.split()) | |
3188 | except: |
|
3188 | except: | |
3189 | self.arg_err(self.dhist) |
|
3189 | self.arg_err(self.dhist) | |
3190 | return |
|
3190 | return | |
3191 | if len(args) == 1: |
|
3191 | if len(args) == 1: | |
3192 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
3192 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
3193 | elif len(args) == 2: |
|
3193 | elif len(args) == 2: | |
3194 | ini,fin = args |
|
3194 | ini,fin = args | |
3195 | else: |
|
3195 | else: | |
3196 | self.arg_err(self.dhist) |
|
3196 | self.arg_err(self.dhist) | |
3197 | return |
|
3197 | return | |
3198 | else: |
|
3198 | else: | |
3199 | ini,fin = 0,len(dh) |
|
3199 | ini,fin = 0,len(dh) | |
3200 | nlprint(dh, |
|
3200 | nlprint(dh, | |
3201 | header = 'Directory history (kept in _dh)', |
|
3201 | header = 'Directory history (kept in _dh)', | |
3202 | start=ini,stop=fin) |
|
3202 | start=ini,stop=fin) | |
3203 |
|
3203 | |||
3204 | @skip_doctest |
|
3204 | @skip_doctest | |
3205 | @line_magic |
|
3205 | @line_magic | |
3206 | def sc(self, parameter_s=''): |
|
3206 | def sc(self, parameter_s=''): | |
3207 | """Shell capture - execute a shell command and capture its output. |
|
3207 | """Shell capture - execute a shell command and capture its output. | |
3208 |
|
3208 | |||
3209 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
3209 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
3210 |
|
3210 | |||
3211 | You should use the form 'var = !command' instead. Example: |
|
3211 | You should use the form 'var = !command' instead. Example: | |
3212 |
|
3212 | |||
3213 | "%sc -l myfiles = ls ~" should now be written as |
|
3213 | "%sc -l myfiles = ls ~" should now be written as | |
3214 |
|
3214 | |||
3215 | "myfiles = !ls ~" |
|
3215 | "myfiles = !ls ~" | |
3216 |
|
3216 | |||
3217 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
3217 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
3218 | below. |
|
3218 | below. | |
3219 |
|
3219 | |||
3220 | -- |
|
3220 | -- | |
3221 | %sc [options] varname=command |
|
3221 | %sc [options] varname=command | |
3222 |
|
3222 | |||
3223 | IPython will run the given command using commands.getoutput(), and |
|
3223 | IPython will run the given command using commands.getoutput(), and | |
3224 | will then update the user's interactive namespace with a variable |
|
3224 | will then update the user's interactive namespace with a variable | |
3225 | called varname, containing the value of the call. Your command can |
|
3225 | called varname, containing the value of the call. Your command can | |
3226 | contain shell wildcards, pipes, etc. |
|
3226 | contain shell wildcards, pipes, etc. | |
3227 |
|
3227 | |||
3228 | The '=' sign in the syntax is mandatory, and the variable name you |
|
3228 | The '=' sign in the syntax is mandatory, and the variable name you | |
3229 | supply must follow Python's standard conventions for valid names. |
|
3229 | supply must follow Python's standard conventions for valid names. | |
3230 |
|
3230 | |||
3231 | (A special format without variable name exists for internal use) |
|
3231 | (A special format without variable name exists for internal use) | |
3232 |
|
3232 | |||
3233 | Options: |
|
3233 | Options: | |
3234 |
|
3234 | |||
3235 | -l: list output. Split the output on newlines into a list before |
|
3235 | -l: list output. Split the output on newlines into a list before | |
3236 | assigning it to the given variable. By default the output is stored |
|
3236 | assigning it to the given variable. By default the output is stored | |
3237 | as a single string. |
|
3237 | as a single string. | |
3238 |
|
3238 | |||
3239 | -v: verbose. Print the contents of the variable. |
|
3239 | -v: verbose. Print the contents of the variable. | |
3240 |
|
3240 | |||
3241 | In most cases you should not need to split as a list, because the |
|
3241 | In most cases you should not need to split as a list, because the | |
3242 | returned value is a special type of string which can automatically |
|
3242 | returned value is a special type of string which can automatically | |
3243 | provide its contents either as a list (split on newlines) or as a |
|
3243 | provide its contents either as a list (split on newlines) or as a | |
3244 | space-separated string. These are convenient, respectively, either |
|
3244 | space-separated string. These are convenient, respectively, either | |
3245 | for sequential processing or to be passed to a shell command. |
|
3245 | for sequential processing or to be passed to a shell command. | |
3246 |
|
3246 | |||
3247 | For example:: |
|
3247 | For example:: | |
3248 |
|
3248 | |||
3249 | # Capture into variable a |
|
3249 | # Capture into variable a | |
3250 | In [1]: sc a=ls *py |
|
3250 | In [1]: sc a=ls *py | |
3251 |
|
3251 | |||
3252 | # a is a string with embedded newlines |
|
3252 | # a is a string with embedded newlines | |
3253 | In [2]: a |
|
3253 | In [2]: a | |
3254 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
3254 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
3255 |
|
3255 | |||
3256 | # which can be seen as a list: |
|
3256 | # which can be seen as a list: | |
3257 | In [3]: a.l |
|
3257 | In [3]: a.l | |
3258 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
3258 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
3259 |
|
3259 | |||
3260 | # or as a whitespace-separated string: |
|
3260 | # or as a whitespace-separated string: | |
3261 | In [4]: a.s |
|
3261 | In [4]: a.s | |
3262 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
3262 | Out[4]: 'setup.py win32_manual_post_install.py' | |
3263 |
|
3263 | |||
3264 | # a.s is useful to pass as a single command line: |
|
3264 | # a.s is useful to pass as a single command line: | |
3265 | In [5]: !wc -l $a.s |
|
3265 | In [5]: !wc -l $a.s | |
3266 | 146 setup.py |
|
3266 | 146 setup.py | |
3267 | 130 win32_manual_post_install.py |
|
3267 | 130 win32_manual_post_install.py | |
3268 | 276 total |
|
3268 | 276 total | |
3269 |
|
3269 | |||
3270 | # while the list form is useful to loop over: |
|
3270 | # while the list form is useful to loop over: | |
3271 | In [6]: for f in a.l: |
|
3271 | In [6]: for f in a.l: | |
3272 | ...: !wc -l $f |
|
3272 | ...: !wc -l $f | |
3273 | ...: |
|
3273 | ...: | |
3274 | 146 setup.py |
|
3274 | 146 setup.py | |
3275 | 130 win32_manual_post_install.py |
|
3275 | 130 win32_manual_post_install.py | |
3276 |
|
3276 | |||
3277 | Similarly, the lists returned by the -l option are also special, in |
|
3277 | Similarly, the lists returned by the -l option are also special, in | |
3278 | the sense that you can equally invoke the .s attribute on them to |
|
3278 | the sense that you can equally invoke the .s attribute on them to | |
3279 | automatically get a whitespace-separated string from their contents:: |
|
3279 | automatically get a whitespace-separated string from their contents:: | |
3280 |
|
3280 | |||
3281 | In [7]: sc -l b=ls *py |
|
3281 | In [7]: sc -l b=ls *py | |
3282 |
|
3282 | |||
3283 | In [8]: b |
|
3283 | In [8]: b | |
3284 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
3284 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
3285 |
|
3285 | |||
3286 | In [9]: b.s |
|
3286 | In [9]: b.s | |
3287 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
3287 | Out[9]: 'setup.py win32_manual_post_install.py' | |
3288 |
|
3288 | |||
3289 | In summary, both the lists and strings used for output capture have |
|
3289 | In summary, both the lists and strings used for output capture have | |
3290 | the following special attributes:: |
|
3290 | the following special attributes:: | |
3291 |
|
3291 | |||
3292 | .l (or .list) : value as list. |
|
3292 | .l (or .list) : value as list. | |
3293 | .n (or .nlstr): value as newline-separated string. |
|
3293 | .n (or .nlstr): value as newline-separated string. | |
3294 | .s (or .spstr): value as space-separated string. |
|
3294 | .s (or .spstr): value as space-separated string. | |
3295 | """ |
|
3295 | """ | |
3296 |
|
3296 | |||
3297 | opts,args = self.parse_options(parameter_s,'lv') |
|
3297 | opts,args = self.parse_options(parameter_s,'lv') | |
3298 | # Try to get a variable name and command to run |
|
3298 | # Try to get a variable name and command to run | |
3299 | try: |
|
3299 | try: | |
3300 | # the variable name must be obtained from the parse_options |
|
3300 | # the variable name must be obtained from the parse_options | |
3301 | # output, which uses shlex.split to strip options out. |
|
3301 | # output, which uses shlex.split to strip options out. | |
3302 | var,_ = args.split('=',1) |
|
3302 | var,_ = args.split('=',1) | |
3303 | var = var.strip() |
|
3303 | var = var.strip() | |
3304 | # But the command has to be extracted from the original input |
|
3304 | # But the command has to be extracted from the original input | |
3305 | # parameter_s, not on what parse_options returns, to avoid the |
|
3305 | # parameter_s, not on what parse_options returns, to avoid the | |
3306 | # quote stripping which shlex.split performs on it. |
|
3306 | # quote stripping which shlex.split performs on it. | |
3307 | _,cmd = parameter_s.split('=',1) |
|
3307 | _,cmd = parameter_s.split('=',1) | |
3308 | except ValueError: |
|
3308 | except ValueError: | |
3309 | var,cmd = '','' |
|
3309 | var,cmd = '','' | |
3310 | # If all looks ok, proceed |
|
3310 | # If all looks ok, proceed | |
3311 | split = 'l' in opts |
|
3311 | split = 'l' in opts | |
3312 | out = self.shell.getoutput(cmd, split=split) |
|
3312 | out = self.shell.getoutput(cmd, split=split) | |
3313 | if opts.has_key('v'): |
|
3313 | if opts.has_key('v'): | |
3314 | print '%s ==\n%s' % (var,pformat(out)) |
|
3314 | print '%s ==\n%s' % (var,pformat(out)) | |
3315 | if var: |
|
3315 | if var: | |
3316 | self.shell.user_ns.update({var:out}) |
|
3316 | self.shell.user_ns.update({var:out}) | |
3317 | else: |
|
3317 | else: | |
3318 | return out |
|
3318 | return out | |
3319 |
|
3319 | |||
3320 | @line_magic |
|
3320 | @line_magic | |
3321 | def sx(self, parameter_s=''): |
|
3321 | def sx(self, parameter_s=''): | |
3322 | """Shell execute - run a shell command and capture its output. |
|
3322 | """Shell execute - run a shell command and capture its output. | |
3323 |
|
3323 | |||
3324 | %sx command |
|
3324 | %sx command | |
3325 |
|
3325 | |||
3326 | IPython will run the given command using commands.getoutput(), and |
|
3326 | IPython will run the given command using commands.getoutput(), and | |
3327 | return the result formatted as a list (split on '\\n'). Since the |
|
3327 | return the result formatted as a list (split on '\\n'). Since the | |
3328 | output is _returned_, it will be stored in ipython's regular output |
|
3328 | output is _returned_, it will be stored in ipython's regular output | |
3329 | cache Out[N] and in the '_N' automatic variables. |
|
3329 | cache Out[N] and in the '_N' automatic variables. | |
3330 |
|
3330 | |||
3331 | Notes: |
|
3331 | Notes: | |
3332 |
|
3332 | |||
3333 | 1) If an input line begins with '!!', then %sx is automatically |
|
3333 | 1) If an input line begins with '!!', then %sx is automatically | |
3334 | invoked. That is, while:: |
|
3334 | invoked. That is, while:: | |
3335 |
|
3335 | |||
3336 | !ls |
|
3336 | !ls | |
3337 |
|
3337 | |||
3338 | causes ipython to simply issue system('ls'), typing:: |
|
3338 | causes ipython to simply issue system('ls'), typing:: | |
3339 |
|
3339 | |||
3340 | !!ls |
|
3340 | !!ls | |
3341 |
|
3341 | |||
3342 | is a shorthand equivalent to:: |
|
3342 | is a shorthand equivalent to:: | |
3343 |
|
3343 | |||
3344 | %sx ls |
|
3344 | %sx ls | |
3345 |
|
3345 | |||
3346 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3346 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
3347 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3347 | like '%sc -l'. The reason for this is to make it as easy as possible | |
3348 | to process line-oriented shell output via further python commands. |
|
3348 | to process line-oriented shell output via further python commands. | |
3349 | %sc is meant to provide much finer control, but requires more |
|
3349 | %sc is meant to provide much finer control, but requires more | |
3350 | typing. |
|
3350 | typing. | |
3351 |
|
3351 | |||
3352 | 3) Just like %sc -l, this is a list with special attributes: |
|
3352 | 3) Just like %sc -l, this is a list with special attributes: | |
3353 | :: |
|
3353 | :: | |
3354 |
|
3354 | |||
3355 | .l (or .list) : value as list. |
|
3355 | .l (or .list) : value as list. | |
3356 | .n (or .nlstr): value as newline-separated string. |
|
3356 | .n (or .nlstr): value as newline-separated string. | |
3357 | .s (or .spstr): value as whitespace-separated string. |
|
3357 | .s (or .spstr): value as whitespace-separated string. | |
3358 |
|
3358 | |||
3359 | This is very useful when trying to use such lists as arguments to |
|
3359 | This is very useful when trying to use such lists as arguments to | |
3360 | system commands.""" |
|
3360 | system commands.""" | |
3361 |
|
3361 | |||
3362 | if parameter_s: |
|
3362 | if parameter_s: | |
3363 | return self.shell.getoutput(parameter_s) |
|
3363 | return self.shell.getoutput(parameter_s) | |
3364 |
|
3364 | |||
3365 |
|
3365 | |||
3366 | @line_magic |
|
3366 | @line_magic | |
3367 | def bookmark(self, parameter_s=''): |
|
3367 | def bookmark(self, parameter_s=''): | |
3368 | """Manage IPython's bookmark system. |
|
3368 | """Manage IPython's bookmark system. | |
3369 |
|
3369 | |||
3370 | %bookmark <name> - set bookmark to current dir |
|
3370 | %bookmark <name> - set bookmark to current dir | |
3371 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3371 | %bookmark <name> <dir> - set bookmark to <dir> | |
3372 | %bookmark -l - list all bookmarks |
|
3372 | %bookmark -l - list all bookmarks | |
3373 | %bookmark -d <name> - remove bookmark |
|
3373 | %bookmark -d <name> - remove bookmark | |
3374 | %bookmark -r - remove all bookmarks |
|
3374 | %bookmark -r - remove all bookmarks | |
3375 |
|
3375 | |||
3376 | You can later on access a bookmarked folder with:: |
|
3376 | You can later on access a bookmarked folder with:: | |
3377 |
|
3377 | |||
3378 | %cd -b <name> |
|
3378 | %cd -b <name> | |
3379 |
|
3379 | |||
3380 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3380 | or simply '%cd <name>' if there is no directory called <name> AND | |
3381 | there is such a bookmark defined. |
|
3381 | there is such a bookmark defined. | |
3382 |
|
3382 | |||
3383 | Your bookmarks persist through IPython sessions, but they are |
|
3383 | Your bookmarks persist through IPython sessions, but they are | |
3384 | associated with each profile.""" |
|
3384 | associated with each profile.""" | |
3385 |
|
3385 | |||
3386 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3386 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3387 | if len(args) > 2: |
|
3387 | if len(args) > 2: | |
3388 | raise UsageError("%bookmark: too many arguments") |
|
3388 | raise UsageError("%bookmark: too many arguments") | |
3389 |
|
3389 | |||
3390 | bkms = self.shell.db.get('bookmarks',{}) |
|
3390 | bkms = self.shell.db.get('bookmarks',{}) | |
3391 |
|
3391 | |||
3392 | if opts.has_key('d'): |
|
3392 | if opts.has_key('d'): | |
3393 | try: |
|
3393 | try: | |
3394 | todel = args[0] |
|
3394 | todel = args[0] | |
3395 | except IndexError: |
|
3395 | except IndexError: | |
3396 | raise UsageError( |
|
3396 | raise UsageError( | |
3397 | "%bookmark -d: must provide a bookmark to delete") |
|
3397 | "%bookmark -d: must provide a bookmark to delete") | |
3398 | else: |
|
3398 | else: | |
3399 | try: |
|
3399 | try: | |
3400 | del bkms[todel] |
|
3400 | del bkms[todel] | |
3401 | except KeyError: |
|
3401 | except KeyError: | |
3402 | raise UsageError( |
|
3402 | raise UsageError( | |
3403 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3403 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3404 |
|
3404 | |||
3405 | elif opts.has_key('r'): |
|
3405 | elif opts.has_key('r'): | |
3406 | bkms = {} |
|
3406 | bkms = {} | |
3407 | elif opts.has_key('l'): |
|
3407 | elif opts.has_key('l'): | |
3408 | bks = bkms.keys() |
|
3408 | bks = bkms.keys() | |
3409 | bks.sort() |
|
3409 | bks.sort() | |
3410 | if bks: |
|
3410 | if bks: | |
3411 | size = max(map(len,bks)) |
|
3411 | size = max(map(len,bks)) | |
3412 | else: |
|
3412 | else: | |
3413 | size = 0 |
|
3413 | size = 0 | |
3414 | fmt = '%-'+str(size)+'s -> %s' |
|
3414 | fmt = '%-'+str(size)+'s -> %s' | |
3415 | print 'Current bookmarks:' |
|
3415 | print 'Current bookmarks:' | |
3416 | for bk in bks: |
|
3416 | for bk in bks: | |
3417 | print fmt % (bk,bkms[bk]) |
|
3417 | print fmt % (bk,bkms[bk]) | |
3418 | else: |
|
3418 | else: | |
3419 | if not args: |
|
3419 | if not args: | |
3420 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3420 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3421 | elif len(args)==1: |
|
3421 | elif len(args)==1: | |
3422 | bkms[args[0]] = os.getcwdu() |
|
3422 | bkms[args[0]] = os.getcwdu() | |
3423 | elif len(args)==2: |
|
3423 | elif len(args)==2: | |
3424 | bkms[args[0]] = args[1] |
|
3424 | bkms[args[0]] = args[1] | |
3425 | self.shell.db['bookmarks'] = bkms |
|
3425 | self.shell.db['bookmarks'] = bkms | |
3426 |
|
3426 | |||
3427 | @line_magic |
|
3427 | @line_magic | |
3428 | def pycat(self, parameter_s=''): |
|
3428 | def pycat(self, parameter_s=''): | |
3429 | """Show a syntax-highlighted file through a pager. |
|
3429 | """Show a syntax-highlighted file through a pager. | |
3430 |
|
3430 | |||
3431 | This magic is similar to the cat utility, but it will assume the file |
|
3431 | This magic is similar to the cat utility, but it will assume the file | |
3432 | to be Python source and will show it with syntax highlighting. """ |
|
3432 | to be Python source and will show it with syntax highlighting. """ | |
3433 |
|
3433 | |||
3434 | try: |
|
3434 | try: | |
3435 | filename = get_py_filename(parameter_s) |
|
3435 | filename = get_py_filename(parameter_s) | |
3436 | cont = file_read(filename) |
|
3436 | cont = file_read(filename) | |
3437 | except IOError: |
|
3437 | except IOError: | |
3438 | try: |
|
3438 | try: | |
3439 | cont = eval(parameter_s, self.shell.user_ns) |
|
3439 | cont = eval(parameter_s, self.shell.user_ns) | |
3440 | except NameError: |
|
3440 | except NameError: | |
3441 | cont = None |
|
3441 | cont = None | |
3442 | if cont is None: |
|
3442 | if cont is None: | |
3443 | print "Error: no such file or variable" |
|
3443 | print "Error: no such file or variable" | |
3444 | return |
|
3444 | return | |
3445 |
|
3445 | |||
3446 | page.page(self.shell.pycolorize(cont)) |
|
3446 | page.page(self.shell.pycolorize(cont)) | |
3447 |
|
3447 | |||
3448 |
|
3448 | |||
3449 | @register_magics |
|
3449 | @register_magics | |
3450 | class LoggingMagics(Magics): |
|
3450 | class LoggingMagics(Magics): | |
3451 | """Magics related to all logging machinery.""" |
|
3451 | """Magics related to all logging machinery.""" | |
3452 |
|
3452 | |||
3453 | @line_magic |
|
3453 | @line_magic | |
3454 | def logstart(self, parameter_s=''): |
|
3454 | def logstart(self, parameter_s=''): | |
3455 | """Start logging anywhere in a session. |
|
3455 | """Start logging anywhere in a session. | |
3456 |
|
3456 | |||
3457 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
3457 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
3458 |
|
3458 | |||
3459 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
3459 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
3460 | current directory, in 'rotate' mode (see below). |
|
3460 | current directory, in 'rotate' mode (see below). | |
3461 |
|
3461 | |||
3462 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
3462 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
3463 | history up to that point and then continues logging. |
|
3463 | history up to that point and then continues logging. | |
3464 |
|
3464 | |||
3465 | %logstart takes a second optional parameter: logging mode. This can be one |
|
3465 | %logstart takes a second optional parameter: logging mode. This can be one | |
3466 | of (note that the modes are given unquoted):\\ |
|
3466 | of (note that the modes are given unquoted):\\ | |
3467 | append: well, that says it.\\ |
|
3467 | append: well, that says it.\\ | |
3468 | backup: rename (if exists) to name~ and start name.\\ |
|
3468 | backup: rename (if exists) to name~ and start name.\\ | |
3469 | global: single logfile in your home dir, appended to.\\ |
|
3469 | global: single logfile in your home dir, appended to.\\ | |
3470 | over : overwrite existing log.\\ |
|
3470 | over : overwrite existing log.\\ | |
3471 | rotate: create rotating logs name.1~, name.2~, etc. |
|
3471 | rotate: create rotating logs name.1~, name.2~, etc. | |
3472 |
|
3472 | |||
3473 | Options: |
|
3473 | Options: | |
3474 |
|
3474 | |||
3475 | -o: log also IPython's output. In this mode, all commands which |
|
3475 | -o: log also IPython's output. In this mode, all commands which | |
3476 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
3476 | generate an Out[NN] prompt are recorded to the logfile, right after | |
3477 | their corresponding input line. The output lines are always |
|
3477 | their corresponding input line. The output lines are always | |
3478 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
3478 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
3479 | Python code. |
|
3479 | Python code. | |
3480 |
|
3480 | |||
3481 | Since this marker is always the same, filtering only the output from |
|
3481 | Since this marker is always the same, filtering only the output from | |
3482 | a log is very easy, using for example a simple awk call:: |
|
3482 | a log is very easy, using for example a simple awk call:: | |
3483 |
|
3483 | |||
3484 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
3484 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
3485 |
|
3485 | |||
3486 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
3486 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
3487 | input, so that user lines are logged in their final form, converted |
|
3487 | input, so that user lines are logged in their final form, converted | |
3488 | into valid Python. For example, %Exit is logged as |
|
3488 | into valid Python. For example, %Exit is logged as | |
3489 | _ip.magic("Exit"). If the -r flag is given, all input is logged |
|
3489 | _ip.magic("Exit"). If the -r flag is given, all input is logged | |
3490 | exactly as typed, with no transformations applied. |
|
3490 | exactly as typed, with no transformations applied. | |
3491 |
|
3491 | |||
3492 | -t: put timestamps before each input line logged (these are put in |
|
3492 | -t: put timestamps before each input line logged (these are put in | |
3493 | comments).""" |
|
3493 | comments).""" | |
3494 |
|
3494 | |||
3495 | opts,par = self.parse_options(parameter_s,'ort') |
|
3495 | opts,par = self.parse_options(parameter_s,'ort') | |
3496 | log_output = 'o' in opts |
|
3496 | log_output = 'o' in opts | |
3497 | log_raw_input = 'r' in opts |
|
3497 | log_raw_input = 'r' in opts | |
3498 | timestamp = 't' in opts |
|
3498 | timestamp = 't' in opts | |
3499 |
|
3499 | |||
3500 | logger = self.shell.logger |
|
3500 | logger = self.shell.logger | |
3501 |
|
3501 | |||
3502 | # if no args are given, the defaults set in the logger constructor by |
|
3502 | # if no args are given, the defaults set in the logger constructor by | |
3503 | # ipython remain valid |
|
3503 | # ipython remain valid | |
3504 | if par: |
|
3504 | if par: | |
3505 | try: |
|
3505 | try: | |
3506 | logfname,logmode = par.split() |
|
3506 | logfname,logmode = par.split() | |
3507 | except: |
|
3507 | except: | |
3508 | logfname = par |
|
3508 | logfname = par | |
3509 | logmode = 'backup' |
|
3509 | logmode = 'backup' | |
3510 | else: |
|
3510 | else: | |
3511 | logfname = logger.logfname |
|
3511 | logfname = logger.logfname | |
3512 | logmode = logger.logmode |
|
3512 | logmode = logger.logmode | |
3513 | # put logfname into rc struct as if it had been called on the command |
|
3513 | # put logfname into rc struct as if it had been called on the command | |
3514 | # line, so it ends up saved in the log header Save it in case we need |
|
3514 | # line, so it ends up saved in the log header Save it in case we need | |
3515 | # to restore it... |
|
3515 | # to restore it... | |
3516 | old_logfile = self.shell.logfile |
|
3516 | old_logfile = self.shell.logfile | |
3517 | if logfname: |
|
3517 | if logfname: | |
3518 | logfname = os.path.expanduser(logfname) |
|
3518 | logfname = os.path.expanduser(logfname) | |
3519 | self.shell.logfile = logfname |
|
3519 | self.shell.logfile = logfname | |
3520 |
|
3520 | |||
3521 | loghead = '# IPython log file\n\n' |
|
3521 | loghead = '# IPython log file\n\n' | |
3522 | try: |
|
3522 | try: | |
3523 | logger.logstart(logfname, loghead, logmode, log_output, timestamp, |
|
3523 | logger.logstart(logfname, loghead, logmode, log_output, timestamp, | |
3524 | log_raw_input) |
|
3524 | log_raw_input) | |
3525 | except: |
|
3525 | except: | |
3526 | self.shell.logfile = old_logfile |
|
3526 | self.shell.logfile = old_logfile | |
3527 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
3527 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
3528 | else: |
|
3528 | else: | |
3529 | # log input history up to this point, optionally interleaving |
|
3529 | # log input history up to this point, optionally interleaving | |
3530 | # output if requested |
|
3530 | # output if requested | |
3531 |
|
3531 | |||
3532 | if timestamp: |
|
3532 | if timestamp: | |
3533 | # disable timestamping for the previous history, since we've |
|
3533 | # disable timestamping for the previous history, since we've | |
3534 | # lost those already (no time machine here). |
|
3534 | # lost those already (no time machine here). | |
3535 | logger.timestamp = False |
|
3535 | logger.timestamp = False | |
3536 |
|
3536 | |||
3537 | if log_raw_input: |
|
3537 | if log_raw_input: | |
3538 | input_hist = self.shell.history_manager.input_hist_raw |
|
3538 | input_hist = self.shell.history_manager.input_hist_raw | |
3539 | else: |
|
3539 | else: | |
3540 | input_hist = self.shell.history_manager.input_hist_parsed |
|
3540 | input_hist = self.shell.history_manager.input_hist_parsed | |
3541 |
|
3541 | |||
3542 | if log_output: |
|
3542 | if log_output: | |
3543 | log_write = logger.log_write |
|
3543 | log_write = logger.log_write | |
3544 | output_hist = self.shell.history_manager.output_hist |
|
3544 | output_hist = self.shell.history_manager.output_hist | |
3545 | for n in range(1,len(input_hist)-1): |
|
3545 | for n in range(1,len(input_hist)-1): | |
3546 | log_write(input_hist[n].rstrip() + '\n') |
|
3546 | log_write(input_hist[n].rstrip() + '\n') | |
3547 | if n in output_hist: |
|
3547 | if n in output_hist: | |
3548 | log_write(repr(output_hist[n]),'output') |
|
3548 | log_write(repr(output_hist[n]),'output') | |
3549 | else: |
|
3549 | else: | |
3550 | logger.log_write('\n'.join(input_hist[1:])) |
|
3550 | logger.log_write('\n'.join(input_hist[1:])) | |
3551 | logger.log_write('\n') |
|
3551 | logger.log_write('\n') | |
3552 | if timestamp: |
|
3552 | if timestamp: | |
3553 | # re-enable timestamping |
|
3553 | # re-enable timestamping | |
3554 | logger.timestamp = True |
|
3554 | logger.timestamp = True | |
3555 |
|
3555 | |||
3556 | print ('Activating auto-logging. ' |
|
3556 | print ('Activating auto-logging. ' | |
3557 | 'Current session state plus future input saved.') |
|
3557 | 'Current session state plus future input saved.') | |
3558 | logger.logstate() |
|
3558 | logger.logstate() | |
3559 |
|
3559 | |||
3560 | @line_magic |
|
3560 | @line_magic | |
3561 | def logstop(self, parameter_s=''): |
|
3561 | def logstop(self, parameter_s=''): | |
3562 | """Fully stop logging and close log file. |
|
3562 | """Fully stop logging and close log file. | |
3563 |
|
3563 | |||
3564 | In order to start logging again, a new %logstart call needs to be made, |
|
3564 | In order to start logging again, a new %logstart call needs to be made, | |
3565 | possibly (though not necessarily) with a new filename, mode and other |
|
3565 | possibly (though not necessarily) with a new filename, mode and other | |
3566 | options.""" |
|
3566 | options.""" | |
3567 | self.logger.logstop() |
|
3567 | self.logger.logstop() | |
3568 |
|
3568 | |||
3569 | @line_magic |
|
3569 | @line_magic | |
3570 | def logoff(self, parameter_s=''): |
|
3570 | def logoff(self, parameter_s=''): | |
3571 | """Temporarily stop logging. |
|
3571 | """Temporarily stop logging. | |
3572 |
|
3572 | |||
3573 | You must have previously started logging.""" |
|
3573 | You must have previously started logging.""" | |
3574 | self.shell.logger.switch_log(0) |
|
3574 | self.shell.logger.switch_log(0) | |
3575 |
|
3575 | |||
3576 | @line_magic |
|
3576 | @line_magic | |
3577 | def logon(self, parameter_s=''): |
|
3577 | def logon(self, parameter_s=''): | |
3578 | """Restart logging. |
|
3578 | """Restart logging. | |
3579 |
|
3579 | |||
3580 | This function is for restarting logging which you've temporarily |
|
3580 | This function is for restarting logging which you've temporarily | |
3581 | stopped with %logoff. For starting logging for the first time, you |
|
3581 | stopped with %logoff. For starting logging for the first time, you | |
3582 | must use the %logstart function, which allows you to specify an |
|
3582 | must use the %logstart function, which allows you to specify an | |
3583 | optional log filename.""" |
|
3583 | optional log filename.""" | |
3584 |
|
3584 | |||
3585 | self.shell.logger.switch_log(1) |
|
3585 | self.shell.logger.switch_log(1) | |
3586 |
|
3586 | |||
3587 | @line_magic |
|
3587 | @line_magic | |
3588 | def logstate(self, parameter_s=''): |
|
3588 | def logstate(self, parameter_s=''): | |
3589 | """Print the status of the logging system.""" |
|
3589 | """Print the status of the logging system.""" | |
3590 |
|
3590 | |||
3591 | self.shell.logger.logstate() |
|
3591 | self.shell.logger.logstate() | |
3592 |
|
3592 | |||
3593 |
|
3593 | |||
3594 | @register_magics |
|
3594 | @register_magics | |
3595 | class ExtensionsMagics(Magics): |
|
3595 | class ExtensionsMagics(Magics): | |
3596 | """Magics to manage the IPython extensions system.""" |
|
3596 | """Magics to manage the IPython extensions system.""" | |
3597 |
|
3597 | |||
3598 | @line_magic |
|
3598 | @line_magic | |
3599 | def install_ext(self, parameter_s=''): |
|
3599 | def install_ext(self, parameter_s=''): | |
3600 | """Download and install an extension from a URL, e.g.:: |
|
3600 | """Download and install an extension from a URL, e.g.:: | |
3601 |
|
3601 | |||
3602 | %install_ext https://bitbucket.org/birkenfeld/ipython-physics/raw/d1310a2ab15d/physics.py |
|
3602 | %install_ext https://bitbucket.org/birkenfeld/ipython-physics/raw/d1310a2ab15d/physics.py | |
3603 |
|
3603 | |||
3604 | The URL should point to an importable Python module - either a .py file |
|
3604 | The URL should point to an importable Python module - either a .py file | |
3605 | or a .zip file. |
|
3605 | or a .zip file. | |
3606 |
|
3606 | |||
3607 | Parameters: |
|
3607 | Parameters: | |
3608 |
|
3608 | |||
3609 | -n filename : Specify a name for the file, rather than taking it from |
|
3609 | -n filename : Specify a name for the file, rather than taking it from | |
3610 | the URL. |
|
3610 | the URL. | |
3611 | """ |
|
3611 | """ | |
3612 | opts, args = self.parse_options(parameter_s, 'n:') |
|
3612 | opts, args = self.parse_options(parameter_s, 'n:') | |
3613 | try: |
|
3613 | try: | |
3614 | filename = self.shell.extension_manager.install_extension(args, |
|
3614 | filename = self.shell.extension_manager.install_extension(args, | |
3615 | opts.get('n')) |
|
3615 | opts.get('n')) | |
3616 | except ValueError as e: |
|
3616 | except ValueError as e: | |
3617 | print e |
|
3617 | print e | |
3618 | return |
|
3618 | return | |
3619 |
|
3619 | |||
3620 | filename = os.path.basename(filename) |
|
3620 | filename = os.path.basename(filename) | |
3621 | print "Installed %s. To use it, type:" % filename |
|
3621 | print "Installed %s. To use it, type:" % filename | |
3622 | print " %%load_ext %s" % os.path.splitext(filename)[0] |
|
3622 | print " %%load_ext %s" % os.path.splitext(filename)[0] | |
3623 |
|
3623 | |||
3624 |
|
3624 | |||
3625 | @line_magic |
|
3625 | @line_magic | |
3626 | def load_ext(self, module_str): |
|
3626 | def load_ext(self, module_str): | |
3627 | """Load an IPython extension by its module name.""" |
|
3627 | """Load an IPython extension by its module name.""" | |
3628 | return self.shell.extension_manager.load_extension(module_str) |
|
3628 | return self.shell.extension_manager.load_extension(module_str) | |
3629 |
|
3629 | |||
3630 | @line_magic |
|
3630 | @line_magic | |
3631 | def unload_ext(self, module_str): |
|
3631 | def unload_ext(self, module_str): | |
3632 | """Unload an IPython extension by its module name.""" |
|
3632 | """Unload an IPython extension by its module name.""" | |
3633 | self.shell.extension_manager.unload_extension(module_str) |
|
3633 | self.shell.extension_manager.unload_extension(module_str) | |
3634 |
|
3634 | |||
3635 | @line_magic |
|
3635 | @line_magic | |
3636 | def reload_ext(self, module_str): |
|
3636 | def reload_ext(self, module_str): | |
3637 | """Reload an IPython extension by its module name.""" |
|
3637 | """Reload an IPython extension by its module name.""" | |
3638 | self.shell.extension_manager.reload_extension(module_str) |
|
3638 | self.shell.extension_manager.reload_extension(module_str) | |
3639 |
|
3639 | |||
3640 |
|
3640 | |||
3641 | @register_magics |
|
3641 | @register_magics | |
3642 | class PylabMagics(Magics): |
|
3642 | class PylabMagics(Magics): | |
3643 | """Magics related to matplotlib's pylab support""" |
|
3643 | """Magics related to matplotlib's pylab support""" | |
3644 |
|
3644 | |||
3645 | @skip_doctest |
|
3645 | @skip_doctest | |
3646 | @line_magic |
|
3646 | @line_magic | |
3647 | def pylab(self, parameter_s=''): |
|
3647 | def pylab(self, parameter_s=''): | |
3648 | """Load numpy and matplotlib to work interactively. |
|
3648 | """Load numpy and matplotlib to work interactively. | |
3649 |
|
3649 | |||
3650 | %pylab [GUINAME] |
|
3650 | %pylab [GUINAME] | |
3651 |
|
3651 | |||
3652 | This function lets you activate pylab (matplotlib, numpy and |
|
3652 | This function lets you activate pylab (matplotlib, numpy and | |
3653 | interactive support) at any point during an IPython session. |
|
3653 | interactive support) at any point during an IPython session. | |
3654 |
|
3654 | |||
3655 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3655 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3656 | pylab and mlab, as well as all names from numpy and pylab. |
|
3656 | pylab and mlab, as well as all names from numpy and pylab. | |
3657 |
|
3657 | |||
3658 | If you are using the inline matplotlib backend for embedded figures, |
|
3658 | If you are using the inline matplotlib backend for embedded figures, | |
3659 | you can adjust its behavior via the %config magic:: |
|
3659 | you can adjust its behavior via the %config magic:: | |
3660 |
|
3660 | |||
3661 | # enable SVG figures, necessary for SVG+XHTML export in the qtconsole |
|
3661 | # enable SVG figures, necessary for SVG+XHTML export in the qtconsole | |
3662 | In [1]: %config InlineBackend.figure_format = 'svg' |
|
3662 | In [1]: %config InlineBackend.figure_format = 'svg' | |
3663 |
|
3663 | |||
3664 | # change the behavior of closing all figures at the end of each |
|
3664 | # change the behavior of closing all figures at the end of each | |
3665 | # execution (cell), or allowing reuse of active figures across |
|
3665 | # execution (cell), or allowing reuse of active figures across | |
3666 | # cells: |
|
3666 | # cells: | |
3667 | In [2]: %config InlineBackend.close_figures = False |
|
3667 | In [2]: %config InlineBackend.close_figures = False | |
3668 |
|
3668 | |||
3669 | Parameters |
|
3669 | Parameters | |
3670 | ---------- |
|
3670 | ---------- | |
3671 | guiname : optional |
|
3671 | guiname : optional | |
3672 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', |
|
3672 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', | |
3673 | 'osx' or 'tk'). If given, the corresponding Matplotlib backend is |
|
3673 | 'osx' or 'tk'). If given, the corresponding Matplotlib backend is | |
3674 | used, otherwise matplotlib's default (which you can override in your |
|
3674 | used, otherwise matplotlib's default (which you can override in your | |
3675 | matplotlib config file) is used. |
|
3675 | matplotlib config file) is used. | |
3676 |
|
3676 | |||
3677 | Examples |
|
3677 | Examples | |
3678 | -------- |
|
3678 | -------- | |
3679 | In this case, where the MPL default is TkAgg:: |
|
3679 | In this case, where the MPL default is TkAgg:: | |
3680 |
|
3680 | |||
3681 | In [2]: %pylab |
|
3681 | In [2]: %pylab | |
3682 |
|
3682 | |||
3683 | Welcome to pylab, a matplotlib-based Python environment. |
|
3683 | Welcome to pylab, a matplotlib-based Python environment. | |
3684 | Backend in use: TkAgg |
|
3684 | Backend in use: TkAgg | |
3685 | For more information, type 'help(pylab)'. |
|
3685 | For more information, type 'help(pylab)'. | |
3686 |
|
3686 | |||
3687 | But you can explicitly request a different backend:: |
|
3687 | But you can explicitly request a different backend:: | |
3688 |
|
3688 | |||
3689 | In [3]: %pylab qt |
|
3689 | In [3]: %pylab qt | |
3690 |
|
3690 | |||
3691 | Welcome to pylab, a matplotlib-based Python environment. |
|
3691 | Welcome to pylab, a matplotlib-based Python environment. | |
3692 | Backend in use: Qt4Agg |
|
3692 | Backend in use: Qt4Agg | |
3693 | For more information, type 'help(pylab)'. |
|
3693 | For more information, type 'help(pylab)'. | |
3694 | """ |
|
3694 | """ | |
3695 |
|
3695 | |||
3696 | if Application.initialized(): |
|
3696 | if Application.initialized(): | |
3697 | app = Application.instance() |
|
3697 | app = Application.instance() | |
3698 | try: |
|
3698 | try: | |
3699 | import_all_status = app.pylab_import_all |
|
3699 | import_all_status = app.pylab_import_all | |
3700 | except AttributeError: |
|
3700 | except AttributeError: | |
3701 | import_all_status = True |
|
3701 | import_all_status = True | |
3702 | else: |
|
3702 | else: | |
3703 | import_all_status = True |
|
3703 | import_all_status = True | |
3704 |
|
3704 | |||
3705 | self.shell.enable_pylab(parameter_s, import_all=import_all_status) |
|
3705 | self.shell.enable_pylab(parameter_s, import_all=import_all_status) | |
3706 |
|
3706 | |||
3707 |
|
3707 | |||
3708 | @register_magics |
|
3708 | @register_magics | |
3709 | class DeprecatedMagics(Magics): |
|
3709 | class DeprecatedMagics(Magics): | |
3710 | """Magics slated for later removal.""" |
|
3710 | """Magics slated for later removal.""" | |
3711 |
|
3711 | |||
3712 | @line_magic |
|
3712 | @line_magic | |
3713 | def install_profiles(self, parameter_s=''): |
|
3713 | def install_profiles(self, parameter_s=''): | |
3714 | """%install_profiles has been deprecated.""" |
|
3714 | """%install_profiles has been deprecated.""" | |
3715 | print '\n'.join([ |
|
3715 | print '\n'.join([ | |
3716 | "%install_profiles has been deprecated.", |
|
3716 | "%install_profiles has been deprecated.", | |
3717 | "Use `ipython profile list` to view available profiles.", |
|
3717 | "Use `ipython profile list` to view available profiles.", | |
3718 | "Requesting a profile with `ipython profile create <name>`", |
|
3718 | "Requesting a profile with `ipython profile create <name>`", | |
3719 | "or `ipython --profile=<name>` will start with the bundled", |
|
3719 | "or `ipython --profile=<name>` will start with the bundled", | |
3720 | "profile of that name if it exists." |
|
3720 | "profile of that name if it exists." | |
3721 | ]) |
|
3721 | ]) | |
3722 |
|
3722 | |||
3723 | @line_magic |
|
3723 | @line_magic | |
3724 | def install_default_config(self, parameter_s=''): |
|
3724 | def install_default_config(self, parameter_s=''): | |
3725 | """%install_default_config has been deprecated.""" |
|
3725 | """%install_default_config has been deprecated.""" | |
3726 | print '\n'.join([ |
|
3726 | print '\n'.join([ | |
3727 | "%install_default_config has been deprecated.", |
|
3727 | "%install_default_config has been deprecated.", | |
3728 | "Use `ipython profile create <name>` to initialize a profile", |
|
3728 | "Use `ipython profile create <name>` to initialize a profile", | |
3729 | "with the default config files.", |
|
3729 | "with the default config files.", | |
3730 | "Add `--reset` to overwrite already existing config files with defaults." |
|
3730 | "Add `--reset` to overwrite already existing config files with defaults." | |
3731 | ]) |
|
3731 | ]) |
General Comments 0
You need to be logged in to leave comments.
Login now