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