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