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