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