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