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