##// END OF EJS Templates
minor docstring fixes
fperez -
Show More
@@ -1,2669 +1,2669 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3
3
4 $Id: Magic.py 968 2005-12-29 17:15:38Z fperez $"""
4 $Id: Magic.py 969 2005-12-29 17:18:31Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
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 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import sys
29 import sys
30 import re
30 import re
31 import tempfile
31 import tempfile
32 import time
32 import time
33 import cPickle as pickle
33 import cPickle as pickle
34 from cStringIO import StringIO
34 from cStringIO import StringIO
35 from getopt import getopt
35 from getopt import getopt
36 from pprint import pprint, pformat
36 from pprint import pprint, pformat
37
37
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 # Homebrewed
44 # Homebrewed
45 from IPython import Debugger, OInspect, wildcard
45 from IPython import Debugger, OInspect, wildcard
46 from IPython.FakeModule import FakeModule
46 from IPython.FakeModule import FakeModule
47 from IPython.Itpl import Itpl, itpl, printpl,itplns
47 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 from IPython.PyColorize import Parser
48 from IPython.PyColorize import Parser
49 from IPython.Struct import Struct
49 from IPython.Struct import Struct
50 from IPython.genutils import *
50 from IPython.genutils import *
51
51
52 #***************************************************************************
52 #***************************************************************************
53 # Utility functions
53 # Utility functions
54 def on_off(tag):
54 def on_off(tag):
55 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
55 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
56 return ['OFF','ON'][tag]
56 return ['OFF','ON'][tag]
57
57
58
58
59 #****************************************************************************
59 #****************************************************************************
60 # Utility classes
60 # Utility classes
61 class Macro(list):
61 class Macro(list):
62 """Simple class to store the value of macros as strings.
62 """Simple class to store the value of macros as strings.
63
63
64 This allows us to later exec them by checking when something is an
64 This allows us to later exec them by checking when something is an
65 instance of this class."""
65 instance of this class."""
66
66
67 def __init__(self,data):
67 def __init__(self,data):
68 list.__init__(self,data)
68 list.__init__(self,data)
69 self.value = ''.join(data)
69 self.value = ''.join(data)
70
70
71 #***************************************************************************
71 #***************************************************************************
72 # Main class implementing Magic functionality
72 # Main class implementing Magic functionality
73 class Magic:
73 class Magic:
74 """Magic functions for InteractiveShell.
74 """Magic functions for InteractiveShell.
75
75
76 Shell functions which can be reached as %function_name. All magic
76 Shell functions which can be reached as %function_name. All magic
77 functions should accept a string, which they can parse for their own
77 functions should accept a string, which they can parse for their own
78 needs. This can make some functions easier to type, eg `%cd ../`
78 needs. This can make some functions easier to type, eg `%cd ../`
79 vs. `%cd("../")`
79 vs. `%cd("../")`
80
80
81 ALL definitions MUST begin with the prefix magic_. The user won't need it
81 ALL definitions MUST begin with the prefix magic_. The user won't need it
82 at the command line, but it is is needed in the definition. """
82 at the command line, but it is is needed in the definition. """
83
83
84 # class globals
84 # class globals
85 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
85 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
86 'Automagic is ON, % prefix NOT needed for magic functions.']
86 'Automagic is ON, % prefix NOT needed for magic functions.']
87
87
88 #......................................................................
88 #......................................................................
89 # some utility functions
89 # some utility functions
90
90
91 def __init__(self,shell):
91 def __init__(self,shell):
92
92
93 self.options_table = {}
93 self.options_table = {}
94 if profile is None:
94 if profile is None:
95 self.magic_prun = self.profile_missing_notice
95 self.magic_prun = self.profile_missing_notice
96 self.shell = shell
96 self.shell = shell
97
97
98 def profile_missing_notice(self, *args, **kwargs):
98 def profile_missing_notice(self, *args, **kwargs):
99 error("""\
99 error("""\
100 The profile module could not be found. If you are a Debian user,
100 The profile module could not be found. If you are a Debian user,
101 it has been removed from the standard Debian package because of its non-free
101 it has been removed from the standard Debian package because of its non-free
102 license. To use profiling, please install"python2.3-profiler" from non-free.""")
102 license. To use profiling, please install"python2.3-profiler" from non-free.""")
103
103
104 def default_option(self,fn,optstr):
104 def default_option(self,fn,optstr):
105 """Make an entry in the options_table for fn, with value optstr"""
105 """Make an entry in the options_table for fn, with value optstr"""
106
106
107 if fn not in self.lsmagic():
107 if fn not in self.lsmagic():
108 error("%s is not a magic function" % fn)
108 error("%s is not a magic function" % fn)
109 self.options_table[fn] = optstr
109 self.options_table[fn] = optstr
110
110
111 def lsmagic(self):
111 def lsmagic(self):
112 """Return a list of currently available magic functions.
112 """Return a list of currently available magic functions.
113
113
114 Gives a list of the bare names after mangling (['ls','cd', ...], not
114 Gives a list of the bare names after mangling (['ls','cd', ...], not
115 ['magic_ls','magic_cd',...]"""
115 ['magic_ls','magic_cd',...]"""
116
116
117 # FIXME. This needs a cleanup, in the way the magics list is built.
117 # FIXME. This needs a cleanup, in the way the magics list is built.
118
118
119 # magics in class definition
119 # magics in class definition
120 class_magic = lambda fn: fn.startswith('magic_') and \
120 class_magic = lambda fn: fn.startswith('magic_') and \
121 callable(Magic.__dict__[fn])
121 callable(Magic.__dict__[fn])
122 # in instance namespace (run-time user additions)
122 # in instance namespace (run-time user additions)
123 inst_magic = lambda fn: fn.startswith('magic_') and \
123 inst_magic = lambda fn: fn.startswith('magic_') and \
124 callable(self.__dict__[fn])
124 callable(self.__dict__[fn])
125 # and bound magics by user (so they can access self):
125 # and bound magics by user (so they can access self):
126 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
126 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
127 callable(self.__class__.__dict__[fn])
127 callable(self.__class__.__dict__[fn])
128 magics = filter(class_magic,Magic.__dict__.keys()) + \
128 magics = filter(class_magic,Magic.__dict__.keys()) + \
129 filter(inst_magic,self.__dict__.keys()) + \
129 filter(inst_magic,self.__dict__.keys()) + \
130 filter(inst_bound_magic,self.__class__.__dict__.keys())
130 filter(inst_bound_magic,self.__class__.__dict__.keys())
131 out = []
131 out = []
132 for fn in magics:
132 for fn in magics:
133 out.append(fn.replace('magic_','',1))
133 out.append(fn.replace('magic_','',1))
134 out.sort()
134 out.sort()
135 return out
135 return out
136
136
137 def extract_input_slices(self,slices):
137 def extract_input_slices(self,slices):
138 """Return as a string a set of input history slices.
138 """Return as a string a set of input history slices.
139
139
140 The set of slices is given as a list of strings (like ['1','4:8','9'],
140 The set of slices is given as a list of strings (like ['1','4:8','9'],
141 since this function is for use by magic functions which get their
141 since this function is for use by magic functions which get their
142 arguments as strings."""
142 arguments as strings."""
143
143
144 cmds = []
144 cmds = []
145 for chunk in slices:
145 for chunk in slices:
146 if ':' in chunk:
146 if ':' in chunk:
147 ini,fin = map(int,chunk.split(':'))
147 ini,fin = map(int,chunk.split(':'))
148 else:
148 else:
149 ini = int(chunk)
149 ini = int(chunk)
150 fin = ini+1
150 fin = ini+1
151 cmds.append(self.shell.input_hist[ini:fin])
151 cmds.append(self.shell.input_hist[ini:fin])
152 return cmds
152 return cmds
153
153
154 def _ofind(self,oname):
154 def _ofind(self,oname):
155 """Find an object in the available namespaces.
155 """Find an object in the available namespaces.
156
156
157 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
157 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
158
158
159 Has special code to detect magic functions.
159 Has special code to detect magic functions.
160 """
160 """
161
161
162 oname = oname.strip()
162 oname = oname.strip()
163
163
164 # Namespaces to search in:
164 # Namespaces to search in:
165 user_ns = self.shell.user_ns
165 user_ns = self.shell.user_ns
166 internal_ns = self.shell.internal_ns
166 internal_ns = self.shell.internal_ns
167 builtin_ns = __builtin__.__dict__
167 builtin_ns = __builtin__.__dict__
168 alias_ns = self.shell.alias_table
168 alias_ns = self.shell.alias_table
169
169
170 # Put them in a list. The order is important so that we find things in
170 # Put them in a list. The order is important so that we find things in
171 # the same order that Python finds them.
171 # the same order that Python finds them.
172 namespaces = [ ('Interactive',user_ns),
172 namespaces = [ ('Interactive',user_ns),
173 ('IPython internal',internal_ns),
173 ('IPython internal',internal_ns),
174 ('Python builtin',builtin_ns),
174 ('Python builtin',builtin_ns),
175 ('Alias',alias_ns),
175 ('Alias',alias_ns),
176 ]
176 ]
177
177
178 # initialize results to 'null'
178 # initialize results to 'null'
179 found = 0; obj = None; ospace = None; ds = None;
179 found = 0; obj = None; ospace = None; ds = None;
180 ismagic = 0; isalias = 0
180 ismagic = 0; isalias = 0
181
181
182 # Look for the given name by splitting it in parts. If the head is
182 # Look for the given name by splitting it in parts. If the head is
183 # found, then we look for all the remaining parts as members, and only
183 # found, then we look for all the remaining parts as members, and only
184 # declare success if we can find them all.
184 # declare success if we can find them all.
185 oname_parts = oname.split('.')
185 oname_parts = oname.split('.')
186 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
186 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
187 for nsname,ns in namespaces:
187 for nsname,ns in namespaces:
188 try:
188 try:
189 obj = ns[oname_head]
189 obj = ns[oname_head]
190 except KeyError:
190 except KeyError:
191 continue
191 continue
192 else:
192 else:
193 for part in oname_rest:
193 for part in oname_rest:
194 try:
194 try:
195 obj = getattr(obj,part)
195 obj = getattr(obj,part)
196 except:
196 except:
197 # Blanket except b/c some badly implemented objects
197 # Blanket except b/c some badly implemented objects
198 # allow __getattr__ to raise exceptions other than
198 # allow __getattr__ to raise exceptions other than
199 # AttributeError, which then crashes IPython.
199 # AttributeError, which then crashes IPython.
200 break
200 break
201 else:
201 else:
202 # If we finish the for loop (no break), we got all members
202 # If we finish the for loop (no break), we got all members
203 found = 1
203 found = 1
204 ospace = nsname
204 ospace = nsname
205 if ns == alias_ns:
205 if ns == alias_ns:
206 isalias = 1
206 isalias = 1
207 break # namespace loop
207 break # namespace loop
208
208
209 # Try to see if it's magic
209 # Try to see if it's magic
210 if not found:
210 if not found:
211 if oname.startswith(self.shell.ESC_MAGIC):
211 if oname.startswith(self.shell.ESC_MAGIC):
212 oname = oname[1:]
212 oname = oname[1:]
213 obj = getattr(self,'magic_'+oname,None)
213 obj = getattr(self,'magic_'+oname,None)
214 if obj is not None:
214 if obj is not None:
215 found = 1
215 found = 1
216 ospace = 'IPython internal'
216 ospace = 'IPython internal'
217 ismagic = 1
217 ismagic = 1
218
218
219 # Last try: special-case some literals like '', [], {}, etc:
219 # Last try: special-case some literals like '', [], {}, etc:
220 if not found and oname_head in ["''",'""','[]','{}','()']:
220 if not found and oname_head in ["''",'""','[]','{}','()']:
221 obj = eval(oname_head)
221 obj = eval(oname_head)
222 found = 1
222 found = 1
223 ospace = 'Interactive'
223 ospace = 'Interactive'
224
224
225 return {'found':found, 'obj':obj, 'namespace':ospace,
225 return {'found':found, 'obj':obj, 'namespace':ospace,
226 'ismagic':ismagic, 'isalias':isalias}
226 'ismagic':ismagic, 'isalias':isalias}
227
227
228 def arg_err(self,func):
228 def arg_err(self,func):
229 """Print docstring if incorrect arguments were passed"""
229 """Print docstring if incorrect arguments were passed"""
230 print 'Error in arguments:'
230 print 'Error in arguments:'
231 print OInspect.getdoc(func)
231 print OInspect.getdoc(func)
232
232
233
233
234 def format_latex(self,str):
234 def format_latex(self,str):
235 """Format a string for latex inclusion."""
235 """Format a string for latex inclusion."""
236
236
237 # Characters that need to be escaped for latex:
237 # Characters that need to be escaped for latex:
238 escape_re = re.compile(r'(%|_|\$)',re.MULTILINE)
238 escape_re = re.compile(r'(%|_|\$)',re.MULTILINE)
239 # Magic command names as headers:
239 # Magic command names as headers:
240 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
240 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
241 re.MULTILINE)
241 re.MULTILINE)
242 # Magic commands
242 # Magic commands
243 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
243 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
244 re.MULTILINE)
244 re.MULTILINE)
245 # Paragraph continue
245 # Paragraph continue
246 par_re = re.compile(r'\\$',re.MULTILINE)
246 par_re = re.compile(r'\\$',re.MULTILINE)
247
247
248 str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str)
248 str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str)
249 str = cmd_re.sub(r'\\texttt{\g<cmd>}',str)
249 str = cmd_re.sub(r'\\texttt{\g<cmd>}',str)
250 str = par_re.sub(r'\\\\',str)
250 str = par_re.sub(r'\\\\',str)
251 str = escape_re.sub(r'\\\1',str)
251 str = escape_re.sub(r'\\\1',str)
252 return str
252 return str
253
253
254 def format_screen(self,str):
254 def format_screen(self,str):
255 """Format a string for screen printing.
255 """Format a string for screen printing.
256
256
257 This removes some latex-type format codes."""
257 This removes some latex-type format codes."""
258 # Paragraph continue
258 # Paragraph continue
259 par_re = re.compile(r'\\$',re.MULTILINE)
259 par_re = re.compile(r'\\$',re.MULTILINE)
260 str = par_re.sub('',str)
260 str = par_re.sub('',str)
261 return str
261 return str
262
262
263 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
263 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
264 """Parse options passed to an argument string.
264 """Parse options passed to an argument string.
265
265
266 The interface is similar to that of getopt(), but it returns back a
266 The interface is similar to that of getopt(), but it returns back a
267 Struct with the options as keys and the stripped argument string still
267 Struct with the options as keys and the stripped argument string still
268 as a string.
268 as a string.
269
269
270 arg_str is quoted as a true sys.argv vector by using shlex.split.
270 arg_str is quoted as a true sys.argv vector by using shlex.split.
271 This allows us to easily expand variables, glob files, quote
271 This allows us to easily expand variables, glob files, quote
272 arguments, etc.
272 arguments, etc.
273
273
274 Options:
274 Options:
275 -mode: default 'string'. If given as 'list', the argument string is
275 -mode: default 'string'. If given as 'list', the argument string is
276 returned as a list (split on whitespace) instead of a string.
276 returned as a list (split on whitespace) instead of a string.
277
277
278 -list_all: put all option values in lists. Normally only options
278 -list_all: put all option values in lists. Normally only options
279 appearing more than once are put in a list."""
279 appearing more than once are put in a list."""
280
280
281 # inject default options at the beginning of the input line
281 # inject default options at the beginning of the input line
282 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
282 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
283 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
283 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
284
284
285 mode = kw.get('mode','string')
285 mode = kw.get('mode','string')
286 if mode not in ['string','list']:
286 if mode not in ['string','list']:
287 raise ValueError,'incorrect mode given: %s' % mode
287 raise ValueError,'incorrect mode given: %s' % mode
288 # Get options
288 # Get options
289 list_all = kw.get('list_all',0)
289 list_all = kw.get('list_all',0)
290
290
291 # Check if we have more than one argument to warrant extra processing:
291 # Check if we have more than one argument to warrant extra processing:
292 odict = {} # Dictionary with options
292 odict = {} # Dictionary with options
293 args = arg_str.split()
293 args = arg_str.split()
294 if len(args) >= 1:
294 if len(args) >= 1:
295 # If the list of inputs only has 0 or 1 thing in it, there's no
295 # If the list of inputs only has 0 or 1 thing in it, there's no
296 # need to look for options
296 # need to look for options
297 argv = shlex_split(arg_str)
297 argv = shlex_split(arg_str)
298 # Do regular option processing
298 # Do regular option processing
299 opts,args = getopt(argv,opt_str,*long_opts)
299 opts,args = getopt(argv,opt_str,*long_opts)
300 for o,a in opts:
300 for o,a in opts:
301 if o.startswith('--'):
301 if o.startswith('--'):
302 o = o[2:]
302 o = o[2:]
303 else:
303 else:
304 o = o[1:]
304 o = o[1:]
305 try:
305 try:
306 odict[o].append(a)
306 odict[o].append(a)
307 except AttributeError:
307 except AttributeError:
308 odict[o] = [odict[o],a]
308 odict[o] = [odict[o],a]
309 except KeyError:
309 except KeyError:
310 if list_all:
310 if list_all:
311 odict[o] = [a]
311 odict[o] = [a]
312 else:
312 else:
313 odict[o] = a
313 odict[o] = a
314
314
315 # Prepare opts,args for return
315 # Prepare opts,args for return
316 opts = Struct(odict)
316 opts = Struct(odict)
317 if mode == 'string':
317 if mode == 'string':
318 args = ' '.join(args)
318 args = ' '.join(args)
319
319
320 return opts,args
320 return opts,args
321
321
322 #......................................................................
322 #......................................................................
323 # And now the actual magic functions
323 # And now the actual magic functions
324
324
325 # Functions for IPython shell work (vars,funcs, config, etc)
325 # Functions for IPython shell work (vars,funcs, config, etc)
326 def magic_lsmagic(self, parameter_s = ''):
326 def magic_lsmagic(self, parameter_s = ''):
327 """List currently available magic functions."""
327 """List currently available magic functions."""
328 mesc = self.shell.ESC_MAGIC
328 mesc = self.shell.ESC_MAGIC
329 print 'Available magic functions:\n'+mesc+\
329 print 'Available magic functions:\n'+mesc+\
330 (' '+mesc).join(self.lsmagic())
330 (' '+mesc).join(self.lsmagic())
331 print '\n' + Magic.auto_status[self.shell.rc.automagic]
331 print '\n' + Magic.auto_status[self.shell.rc.automagic]
332 return None
332 return None
333
333
334 def magic_magic(self, parameter_s = ''):
334 def magic_magic(self, parameter_s = ''):
335 """Print information about the magic function system."""
335 """Print information about the magic function system."""
336
336
337 mode = ''
337 mode = ''
338 try:
338 try:
339 if parameter_s.split()[0] == '-latex':
339 if parameter_s.split()[0] == '-latex':
340 mode = 'latex'
340 mode = 'latex'
341 except:
341 except:
342 pass
342 pass
343
343
344 magic_docs = []
344 magic_docs = []
345 for fname in self.lsmagic():
345 for fname in self.lsmagic():
346 mname = 'magic_' + fname
346 mname = 'magic_' + fname
347 for space in (Magic,self,self.__class__):
347 for space in (Magic,self,self.__class__):
348 try:
348 try:
349 fn = space.__dict__[mname]
349 fn = space.__dict__[mname]
350 except KeyError:
350 except KeyError:
351 pass
351 pass
352 else:
352 else:
353 break
353 break
354 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
354 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
355 fname,fn.__doc__))
355 fname,fn.__doc__))
356 magic_docs = ''.join(magic_docs)
356 magic_docs = ''.join(magic_docs)
357
357
358 if mode == 'latex':
358 if mode == 'latex':
359 print self.format_latex(magic_docs)
359 print self.format_latex(magic_docs)
360 return
360 return
361 else:
361 else:
362 magic_docs = self.format_screen(magic_docs)
362 magic_docs = self.format_screen(magic_docs)
363
363
364 outmsg = """
364 outmsg = """
365 IPython's 'magic' functions
365 IPython's 'magic' functions
366 ===========================
366 ===========================
367
367
368 The magic function system provides a series of functions which allow you to
368 The magic function system provides a series of functions which allow you to
369 control the behavior of IPython itself, plus a lot of system-type
369 control the behavior of IPython itself, plus a lot of system-type
370 features. All these functions are prefixed with a % character, but parameters
370 features. All these functions are prefixed with a % character, but parameters
371 are given without parentheses or quotes.
371 are given without parentheses or quotes.
372
372
373 NOTE: If you have 'automagic' enabled (via the command line option or with the
373 NOTE: If you have 'automagic' enabled (via the command line option or with the
374 %automagic function), you don't need to type in the % explicitly. By default,
374 %automagic function), you don't need to type in the % explicitly. By default,
375 IPython ships with automagic on, so you should only rarely need the % escape.
375 IPython ships with automagic on, so you should only rarely need the % escape.
376
376
377 Example: typing '%cd mydir' (without the quotes) changes you working directory
377 Example: typing '%cd mydir' (without the quotes) changes you working directory
378 to 'mydir', if it exists.
378 to 'mydir', if it exists.
379
379
380 You can define your own magic functions to extend the system. See the supplied
380 You can define your own magic functions to extend the system. See the supplied
381 ipythonrc and example-magic.py files for details (in your ipython
381 ipythonrc and example-magic.py files for details (in your ipython
382 configuration directory, typically $HOME/.ipython/).
382 configuration directory, typically $HOME/.ipython/).
383
383
384 You can also define your own aliased names for magic functions. In your
384 You can also define your own aliased names for magic functions. In your
385 ipythonrc file, placing a line like:
385 ipythonrc file, placing a line like:
386
386
387 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
387 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
388
388
389 will define %pf as a new name for %profile.
389 will define %pf as a new name for %profile.
390
390
391 You can also call magics in code using the ipmagic() function, which IPython
391 You can also call magics in code using the ipmagic() function, which IPython
392 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
392 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
393
393
394 For a list of the available magic functions, use %lsmagic. For a description
394 For a list of the available magic functions, use %lsmagic. For a description
395 of any of them, type %magic_name?, e.g. '%cd?'.
395 of any of them, type %magic_name?, e.g. '%cd?'.
396
396
397 Currently the magic system has the following functions:\n"""
397 Currently the magic system has the following functions:\n"""
398
398
399 mesc = self.shell.ESC_MAGIC
399 mesc = self.shell.ESC_MAGIC
400 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
400 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
401 "\n\n%s%s\n\n%s" % (outmsg,
401 "\n\n%s%s\n\n%s" % (outmsg,
402 magic_docs,mesc,mesc,
402 magic_docs,mesc,mesc,
403 (' '+mesc).join(self.lsmagic()),
403 (' '+mesc).join(self.lsmagic()),
404 Magic.auto_status[self.shell.rc.automagic] ) )
404 Magic.auto_status[self.shell.rc.automagic] ) )
405
405
406 page(outmsg,screen_lines=self.shell.rc.screen_length)
406 page(outmsg,screen_lines=self.shell.rc.screen_length)
407
407
408 def magic_automagic(self, parameter_s = ''):
408 def magic_automagic(self, parameter_s = ''):
409 """Make magic functions callable without having to type the initial %.
409 """Make magic functions callable without having to type the initial %.
410
410
411 Toggles on/off (when off, you must call it as %automagic, of
411 Toggles on/off (when off, you must call it as %automagic, of
412 course). Note that magic functions have lowest priority, so if there's
412 course). Note that magic functions have lowest priority, so if there's
413 a variable whose name collides with that of a magic fn, automagic
413 a variable whose name collides with that of a magic fn, automagic
414 won't work for that function (you get the variable instead). However,
414 won't work for that function (you get the variable instead). However,
415 if you delete the variable (del var), the previously shadowed magic
415 if you delete the variable (del var), the previously shadowed magic
416 function becomes visible to automagic again."""
416 function becomes visible to automagic again."""
417
417
418 rc = self.shell.rc
418 rc = self.shell.rc
419 rc.automagic = not rc.automagic
419 rc.automagic = not rc.automagic
420 print '\n' + Magic.auto_status[rc.automagic]
420 print '\n' + Magic.auto_status[rc.automagic]
421
421
422 def magic_autocall(self, parameter_s = ''):
422 def magic_autocall(self, parameter_s = ''):
423 """Make functions callable without having to type parentheses.
423 """Make functions callable without having to type parentheses.
424
424
425 This toggles the autocall command line option on and off."""
425 This toggles the autocall command line option on and off."""
426
426
427 rc = self.shell.rc
427 rc = self.shell.rc
428 rc.autocall = not rc.autocall
428 rc.autocall = not rc.autocall
429 print "Automatic calling is:",['OFF','ON'][rc.autocall]
429 print "Automatic calling is:",['OFF','ON'][rc.autocall]
430
430
431 def magic_autoindent(self, parameter_s = ''):
431 def magic_autoindent(self, parameter_s = ''):
432 """Toggle autoindent on/off (if available)."""
432 """Toggle autoindent on/off (if available)."""
433
433
434 self.shell.set_autoindent()
434 self.shell.set_autoindent()
435 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
435 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
436
436
437 def magic_system_verbose(self, parameter_s = ''):
437 def magic_system_verbose(self, parameter_s = ''):
438 """Toggle verbose printing of system calls on/off."""
438 """Toggle verbose printing of system calls on/off."""
439
439
440 self.shell.rc_set_toggle('system_verbose')
440 self.shell.rc_set_toggle('system_verbose')
441 print "System verbose printing is:",\
441 print "System verbose printing is:",\
442 ['OFF','ON'][self.shell.rc.system_verbose]
442 ['OFF','ON'][self.shell.rc.system_verbose]
443
443
444 def magic_history(self, parameter_s = ''):
444 def magic_history(self, parameter_s = ''):
445 """Print input history (_i<n> variables), with most recent last.
445 """Print input history (_i<n> variables), with most recent last.
446
446
447 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
447 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
448 %history [-n] n -> print at most n inputs\\
448 %history [-n] n -> print at most n inputs\\
449 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
449 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
450
450
451 Each input's number <n> is shown, and is accessible as the
451 Each input's number <n> is shown, and is accessible as the
452 automatically generated variable _i<n>. Multi-line statements are
452 automatically generated variable _i<n>. Multi-line statements are
453 printed starting at a new line for easy copy/paste.
453 printed starting at a new line for easy copy/paste.
454
454
455 If option -n is used, input numbers are not printed. This is useful if
455 If option -n is used, input numbers are not printed. This is useful if
456 you want to get a printout of many lines which can be directly pasted
456 you want to get a printout of many lines which can be directly pasted
457 into a text editor.
457 into a text editor.
458
458
459 This feature is only available if numbered prompts are in use."""
459 This feature is only available if numbered prompts are in use."""
460
460
461 if not self.shell.outputcache.do_full_cache:
461 if not self.shell.outputcache.do_full_cache:
462 print 'This feature is only available if numbered prompts are in use.'
462 print 'This feature is only available if numbered prompts are in use.'
463 return
463 return
464 opts,args = self.parse_options(parameter_s,'n',mode='list')
464 opts,args = self.parse_options(parameter_s,'n',mode='list')
465
465
466 default_length = 40
466 default_length = 40
467 if len(args) == 0:
467 if len(args) == 0:
468 final = self.shell.outputcache.prompt_count
468 final = self.shell.outputcache.prompt_count
469 init = max(1,final-default_length)
469 init = max(1,final-default_length)
470 elif len(args) == 1:
470 elif len(args) == 1:
471 final = self.shell.outputcache.prompt_count
471 final = self.shell.outputcache.prompt_count
472 init = max(1,final-int(args[0]))
472 init = max(1,final-int(args[0]))
473 elif len(args) == 2:
473 elif len(args) == 2:
474 init,final = map(int,args)
474 init,final = map(int,args)
475 else:
475 else:
476 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
476 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
477 print self.magic_hist.__doc__
477 print self.magic_hist.__doc__
478 return
478 return
479 width = len(str(final))
479 width = len(str(final))
480 line_sep = ['','\n']
480 line_sep = ['','\n']
481 input_hist = self.shell.input_hist
481 input_hist = self.shell.input_hist
482 print_nums = not opts.has_key('n')
482 print_nums = not opts.has_key('n')
483 for in_num in range(init,final):
483 for in_num in range(init,final):
484 inline = input_hist[in_num]
484 inline = input_hist[in_num]
485 multiline = inline.count('\n') > 1
485 multiline = inline.count('\n') > 1
486 if print_nums:
486 if print_nums:
487 print str(in_num).ljust(width)+':'+ line_sep[multiline],
487 print str(in_num).ljust(width)+':'+ line_sep[multiline],
488 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
488 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
489 inline.startswith('#!'):
489 inline.startswith('#!'):
490 print inline[1:],
490 print inline[1:],
491 else:
491 else:
492 print inline,
492 print inline,
493
493
494 def magic_hist(self, parameter_s=''):
494 def magic_hist(self, parameter_s=''):
495 """Alternate name for %history."""
495 """Alternate name for %history."""
496 return self.magic_history(parameter_s)
496 return self.magic_history(parameter_s)
497
497
498 def magic_p(self, parameter_s=''):
498 def magic_p(self, parameter_s=''):
499 """Just a short alias for Python's 'print'."""
499 """Just a short alias for Python's 'print'."""
500 exec 'print ' + parameter_s in self.shell.user_ns
500 exec 'print ' + parameter_s in self.shell.user_ns
501
501
502 def magic_r(self, parameter_s=''):
502 def magic_r(self, parameter_s=''):
503 """Repeat previous input.
503 """Repeat previous input.
504
504
505 If given an argument, repeats the previous command which starts with
505 If given an argument, repeats the previous command which starts with
506 the same string, otherwise it just repeats the previous input.
506 the same string, otherwise it just repeats the previous input.
507
507
508 Shell escaped commands (with ! as first character) are not recognized
508 Shell escaped commands (with ! as first character) are not recognized
509 by this system, only pure python code and magic commands.
509 by this system, only pure python code and magic commands.
510 """
510 """
511
511
512 start = parameter_s.strip()
512 start = parameter_s.strip()
513 esc_magic = self.shell.ESC_MAGIC
513 esc_magic = self.shell.ESC_MAGIC
514 # Identify magic commands even if automagic is on (which means
514 # Identify magic commands even if automagic is on (which means
515 # the in-memory version is different from that typed by the user).
515 # the in-memory version is different from that typed by the user).
516 if self.shell.rc.automagic:
516 if self.shell.rc.automagic:
517 start_magic = esc_magic+start
517 start_magic = esc_magic+start
518 else:
518 else:
519 start_magic = start
519 start_magic = start
520 # Look through the input history in reverse
520 # Look through the input history in reverse
521 for n in range(len(self.shell.input_hist)-2,0,-1):
521 for n in range(len(self.shell.input_hist)-2,0,-1):
522 input = self.shell.input_hist[n]
522 input = self.shell.input_hist[n]
523 # skip plain 'r' lines so we don't recurse to infinity
523 # skip plain 'r' lines so we don't recurse to infinity
524 if input != 'ipmagic("r")\n' and \
524 if input != 'ipmagic("r")\n' and \
525 (input.startswith(start) or input.startswith(start_magic)):
525 (input.startswith(start) or input.startswith(start_magic)):
526 #print 'match',`input` # dbg
526 #print 'match',`input` # dbg
527 print 'Executing:',input,
527 print 'Executing:',input,
528 self.shell.runlines(input)
528 self.shell.runlines(input)
529 return
529 return
530 print 'No previous input matching `%s` found.' % start
530 print 'No previous input matching `%s` found.' % start
531
531
532 def magic_page(self, parameter_s=''):
532 def magic_page(self, parameter_s=''):
533 """Pretty print the object and display it through a pager.
533 """Pretty print the object and display it through a pager.
534
534
535 If no parameter is given, use _ (last output)."""
535 If no parameter is given, use _ (last output)."""
536 # After a function contributed by Olivier Aubert, slightly modified.
536 # After a function contributed by Olivier Aubert, slightly modified.
537
537
538 oname = parameter_s and parameter_s or '_'
538 oname = parameter_s and parameter_s or '_'
539 info = self._ofind(oname)
539 info = self._ofind(oname)
540 if info['found']:
540 if info['found']:
541 page(pformat(info['obj']))
541 page(pformat(info['obj']))
542 else:
542 else:
543 print 'Object `%s` not found' % oname
543 print 'Object `%s` not found' % oname
544
544
545 def magic_profile(self, parameter_s=''):
545 def magic_profile(self, parameter_s=''):
546 """Print your currently active IPyhton profile."""
546 """Print your currently active IPyhton profile."""
547 if self.shell.rc.profile:
547 if self.shell.rc.profile:
548 printpl('Current IPython profile: $self.shell.rc.profile.')
548 printpl('Current IPython profile: $self.shell.rc.profile.')
549 else:
549 else:
550 print 'No profile active.'
550 print 'No profile active.'
551
551
552 def _inspect(self,meth,oname,**kw):
552 def _inspect(self,meth,oname,**kw):
553 """Generic interface to the inspector system.
553 """Generic interface to the inspector system.
554
554
555 This function is meant to be called by pdef, pdoc & friends."""
555 This function is meant to be called by pdef, pdoc & friends."""
556
556
557 oname = oname.strip()
557 oname = oname.strip()
558 info = Struct(self._ofind(oname))
558 info = Struct(self._ofind(oname))
559 if info.found:
559 if info.found:
560 pmethod = getattr(self.shell.inspector,meth)
560 pmethod = getattr(self.shell.inspector,meth)
561 formatter = info.ismagic and self.format_screen or None
561 formatter = info.ismagic and self.format_screen or None
562 if meth == 'pdoc':
562 if meth == 'pdoc':
563 pmethod(info.obj,oname,formatter)
563 pmethod(info.obj,oname,formatter)
564 elif meth == 'pinfo':
564 elif meth == 'pinfo':
565 pmethod(info.obj,oname,formatter,info,**kw)
565 pmethod(info.obj,oname,formatter,info,**kw)
566 else:
566 else:
567 pmethod(info.obj,oname)
567 pmethod(info.obj,oname)
568 else:
568 else:
569 print 'Object `%s` not found.' % oname
569 print 'Object `%s` not found.' % oname
570 return 'not found' # so callers can take other action
570 return 'not found' # so callers can take other action
571
571
572 def magic_pdef(self, parameter_s=''):
572 def magic_pdef(self, parameter_s=''):
573 """Print the definition header for any callable object.
573 """Print the definition header for any callable object.
574
574
575 If the object is a class, print the constructor information."""
575 If the object is a class, print the constructor information."""
576 self._inspect('pdef',parameter_s)
576 self._inspect('pdef',parameter_s)
577
577
578 def magic_pdoc(self, parameter_s=''):
578 def magic_pdoc(self, parameter_s=''):
579 """Print the docstring for an object.
579 """Print the docstring for an object.
580
580
581 If the given object is a class, it will print both the class and the
581 If the given object is a class, it will print both the class and the
582 constructor docstrings."""
582 constructor docstrings."""
583 self._inspect('pdoc',parameter_s)
583 self._inspect('pdoc',parameter_s)
584
584
585 def magic_psource(self, parameter_s=''):
585 def magic_psource(self, parameter_s=''):
586 """Print (or run through pager) the source code for an object."""
586 """Print (or run through pager) the source code for an object."""
587 self._inspect('psource',parameter_s)
587 self._inspect('psource',parameter_s)
588
588
589 def magic_pfile(self, parameter_s=''):
589 def magic_pfile(self, parameter_s=''):
590 """Print (or run through pager) the file where an object is defined.
590 """Print (or run through pager) the file where an object is defined.
591
591
592 The file opens at the line where the object definition begins. IPython
592 The file opens at the line where the object definition begins. IPython
593 will honor the environment variable PAGER if set, and otherwise will
593 will honor the environment variable PAGER if set, and otherwise will
594 do its best to print the file in a convenient form.
594 do its best to print the file in a convenient form.
595
595
596 If the given argument is not an object currently defined, IPython will
596 If the given argument is not an object currently defined, IPython will
597 try to interpret it as a filename (automatically adding a .py extension
597 try to interpret it as a filename (automatically adding a .py extension
598 if needed). You can thus use %pfile as a syntax highlighting code
598 if needed). You can thus use %pfile as a syntax highlighting code
599 viewer."""
599 viewer."""
600
600
601 # first interpret argument as an object name
601 # first interpret argument as an object name
602 out = self._inspect('pfile',parameter_s)
602 out = self._inspect('pfile',parameter_s)
603 # if not, try the input as a filename
603 # if not, try the input as a filename
604 if out == 'not found':
604 if out == 'not found':
605 try:
605 try:
606 filename = get_py_filename(parameter_s)
606 filename = get_py_filename(parameter_s)
607 except IOError,msg:
607 except IOError,msg:
608 print msg
608 print msg
609 return
609 return
610 page(self.shell.inspector.format(file(filename).read()))
610 page(self.shell.inspector.format(file(filename).read()))
611
611
612 def magic_pinfo(self, parameter_s=''):
612 def magic_pinfo(self, parameter_s=''):
613 """Provide detailed information about an object.
613 """Provide detailed information about an object.
614
614
615 '%pinfo object' is just a synonym for object? or ?object."""
615 '%pinfo object' is just a synonym for object? or ?object."""
616
616
617 #print 'pinfo par: <%s>' % parameter_s # dbg
617 #print 'pinfo par: <%s>' % parameter_s # dbg
618
618
619 # detail_level: 0 -> obj? , 1 -> obj??
619 # detail_level: 0 -> obj? , 1 -> obj??
620 detail_level = 0
620 detail_level = 0
621 # We need to detect if we got called as 'pinfo pinfo foo', which can
621 # We need to detect if we got called as 'pinfo pinfo foo', which can
622 # happen if the user types 'pinfo foo?' at the cmd line.
622 # happen if the user types 'pinfo foo?' at the cmd line.
623 pinfo,qmark1,oname,qmark2 = \
623 pinfo,qmark1,oname,qmark2 = \
624 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
624 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
625 if pinfo or qmark1 or qmark2:
625 if pinfo or qmark1 or qmark2:
626 detail_level = 1
626 detail_level = 1
627 if "*" in oname:
627 if "*" in oname:
628 self.magic_psearch(oname)
628 self.magic_psearch(oname)
629 else:
629 else:
630 self._inspect('pinfo',oname,detail_level=detail_level)
630 self._inspect('pinfo',oname,detail_level=detail_level)
631
631
632 def magic_psearch(self, parameter_s=''):
632 def magic_psearch(self, parameter_s=''):
633 """Search for object in namespaces by wildcard.
633 """Search for object in namespaces by wildcard.
634
634
635 %psearch [options] PATTERN [OBJECT TYPE]
635 %psearch [options] PATTERN [OBJECT TYPE]
636
636
637 Note: ? can be used as a synonym for %psearch, at the beginning or at
637 Note: ? can be used as a synonym for %psearch, at the beginning or at
638 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
638 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
639 rest of the command line must be unchanged (options come first), so
639 rest of the command line must be unchanged (options come first), so
640 for example the following forms are equivalent
640 for example the following forms are equivalent
641
641
642 %psearch -i a* function
642 %psearch -i a* function
643 -i a* function?
643 -i a* function?
644 ?-i a* function
644 ?-i a* function
645
645
646 Arguments:
646 Arguments:
647
647
648 PATTERN
648 PATTERN
649
649
650 where PATTERN is a string containing * as a wildcard similar to its
650 where PATTERN is a string containing * as a wildcard similar to its
651 use in a shell. The pattern is matched in all namespaces on the
651 use in a shell. The pattern is matched in all namespaces on the
652 search path. By default objects starting with a single _ are not
652 search path. By default objects starting with a single _ are not
653 matched, many IPython generated objects have a single
653 matched, many IPython generated objects have a single
654 underscore. The default is case insensitive matching. Matching is
654 underscore. The default is case insensitive matching. Matching is
655 also done on the attributes of objects and not only on the objects
655 also done on the attributes of objects and not only on the objects
656 in a module.
656 in a module.
657
657
658 [OBJECT TYPE]
658 [OBJECT TYPE]
659
659
660 Is the name of a python type from the types module. The name is
660 Is the name of a python type from the types module. The name is
661 given in lowercase without the ending type, ex. StringType is
661 given in lowercase without the ending type, ex. StringType is
662 written string. By adding a type here only objects matching the
662 written string. By adding a type here only objects matching the
663 given type are matched. Using all here makes the pattern match all
663 given type are matched. Using all here makes the pattern match all
664 types (this is the default).
664 types (this is the default).
665
665
666 Options:
666 Options:
667
667
668 -a: makes the pattern match even objects whose names start with a
668 -a: makes the pattern match even objects whose names start with a
669 single underscore. These names are normally ommitted from the
669 single underscore. These names are normally ommitted from the
670 search.
670 search.
671
671
672 -i/-c: make the pattern case insensitive/sensitive. If neither of
672 -i/-c: make the pattern case insensitive/sensitive. If neither of
673 these options is given, the default is read from your ipythonrc
673 these options is given, the default is read from your ipythonrc
674 file. The option name which sets this value is
674 file. The option name which sets this value is
675 'wildcards_case_sensitive'. If this option is not specified in your
675 'wildcards_case_sensitive'. If this option is not specified in your
676 ipythonrc file, IPython's internal default is to do a case sensitive
676 ipythonrc file, IPython's internal default is to do a case sensitive
677 search.
677 search.
678
678
679 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
679 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
680 specifiy can be searched in any of the following namespaces:
680 specifiy can be searched in any of the following namespaces:
681 'builtin', 'user', 'user_global','internal', 'alias', where
681 'builtin', 'user', 'user_global','internal', 'alias', where
682 'builtin' and 'user' are the search defaults. Note that you should
682 'builtin' and 'user' are the search defaults. Note that you should
683 not use quotes when specifying namespaces.
683 not use quotes when specifying namespaces.
684
684
685 'Builtin' contains the python module builtin, 'user' contains all
685 'Builtin' contains the python module builtin, 'user' contains all
686 user data, 'alias' only contain the shell aliases and no python
686 user data, 'alias' only contain the shell aliases and no python
687 objects, 'internal' contains objects used by IPython. The
687 objects, 'internal' contains objects used by IPython. The
688 'user_global' namespace is only used by embedded IPython instances,
688 'user_global' namespace is only used by embedded IPython instances,
689 and it contains module-level globals. You can add namespaces to the
689 and it contains module-level globals. You can add namespaces to the
690 search with -s or exclude them with -e (these options can be given
690 search with -s or exclude them with -e (these options can be given
691 more than once).
691 more than once).
692
692
693 Examples:
693 Examples:
694
694
695 %psearch a* -> objects beginning with an a
695 %psearch a* -> objects beginning with an a
696 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
696 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
697 %psearch a* function -> all functions beginning with an a
697 %psearch a* function -> all functions beginning with an a
698 %psearch re.e* -> objects beginning with an e in module re
698 %psearch re.e* -> objects beginning with an e in module re
699 %psearch r*.e* -> objects that start with e in modules starting in r
699 %psearch r*.e* -> objects that start with e in modules starting in r
700 %psearch r*.* string -> all strings in modules beginning with r
700 %psearch r*.* string -> all strings in modules beginning with r
701
701
702 Case sensitve search:
702 Case sensitve search:
703
703
704 %psearch -c a* list all object beginning with lower case a
704 %psearch -c a* list all object beginning with lower case a
705
705
706 Show objects beginning with a single _:
706 Show objects beginning with a single _:
707
707
708 %psearch -a _* list objects beginning with a single underscore"""
708 %psearch -a _* list objects beginning with a single underscore"""
709
709
710 # default namespaces to be searched
710 # default namespaces to be searched
711 def_search = ['user','builtin']
711 def_search = ['user','builtin']
712
712
713 # Process options/args
713 # Process options/args
714 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
714 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
715 opt = opts.get
715 opt = opts.get
716 shell = self.shell
716 shell = self.shell
717 psearch = shell.inspector.psearch
717 psearch = shell.inspector.psearch
718
718
719 # select case options
719 # select case options
720 if opts.has_key('i'):
720 if opts.has_key('i'):
721 ignore_case = True
721 ignore_case = True
722 elif opts.has_key('c'):
722 elif opts.has_key('c'):
723 ignore_case = False
723 ignore_case = False
724 else:
724 else:
725 ignore_case = not shell.rc.wildcards_case_sensitive
725 ignore_case = not shell.rc.wildcards_case_sensitive
726
726
727 # Build list of namespaces to search from user options
727 # Build list of namespaces to search from user options
728 def_search.extend(opt('s',[]))
728 def_search.extend(opt('s',[]))
729 ns_exclude = ns_exclude=opt('e',[])
729 ns_exclude = ns_exclude=opt('e',[])
730 ns_search = [nm for nm in def_search if nm not in ns_exclude]
730 ns_search = [nm for nm in def_search if nm not in ns_exclude]
731
731
732 # Call the actual search
732 # Call the actual search
733 try:
733 try:
734 psearch(args,shell.ns_table,ns_search,
734 psearch(args,shell.ns_table,ns_search,
735 show_all=opt('a'),ignore_case=ignore_case)
735 show_all=opt('a'),ignore_case=ignore_case)
736 except:
736 except:
737 shell.showtraceback()
737 shell.showtraceback()
738
738
739 def magic_who_ls(self, parameter_s=''):
739 def magic_who_ls(self, parameter_s=''):
740 """Return a sorted list of all interactive variables.
740 """Return a sorted list of all interactive variables.
741
741
742 If arguments are given, only variables of types matching these
742 If arguments are given, only variables of types matching these
743 arguments are returned."""
743 arguments are returned."""
744
744
745 user_ns = self.shell.user_ns
745 user_ns = self.shell.user_ns
746 out = []
746 out = []
747 typelist = parameter_s.split()
747 typelist = parameter_s.split()
748 for i in self.shell.user_ns.keys():
748 for i in self.shell.user_ns.keys():
749 if not (i.startswith('_') or i.startswith('_i')) \
749 if not (i.startswith('_') or i.startswith('_i')) \
750 and not (self.shell.internal_ns.has_key(i) or
750 and not (self.shell.internal_ns.has_key(i) or
751 self.shell.user_config_ns.has_key(i)):
751 self.shell.user_config_ns.has_key(i)):
752 if typelist:
752 if typelist:
753 if type(user_ns[i]).__name__ in typelist:
753 if type(user_ns[i]).__name__ in typelist:
754 out.append(i)
754 out.append(i)
755 else:
755 else:
756 out.append(i)
756 out.append(i)
757 out.sort()
757 out.sort()
758 return out
758 return out
759
759
760 def magic_who(self, parameter_s=''):
760 def magic_who(self, parameter_s=''):
761 """Print all interactive variables, with some minimal formatting.
761 """Print all interactive variables, with some minimal formatting.
762
762
763 If any arguments are given, only variables whose type matches one of
763 If any arguments are given, only variables whose type matches one of
764 these are printed. For example:
764 these are printed. For example:
765
765
766 %who function str
766 %who function str
767
767
768 will only list functions and strings, excluding all other types of
768 will only list functions and strings, excluding all other types of
769 variables. To find the proper type names, simply use type(var) at a
769 variables. To find the proper type names, simply use type(var) at a
770 command line to see how python prints type names. For example:
770 command line to see how python prints type names. For example:
771
771
772 In [1]: type('hello')\\
772 In [1]: type('hello')\\
773 Out[1]: <type 'str'>
773 Out[1]: <type 'str'>
774
774
775 indicates that the type name for strings is 'str'.
775 indicates that the type name for strings is 'str'.
776
776
777 %who always excludes executed names loaded through your configuration
777 %who always excludes executed names loaded through your configuration
778 file and things which are internal to IPython.
778 file and things which are internal to IPython.
779
779
780 This is deliberate, as typically you may load many modules and the
780 This is deliberate, as typically you may load many modules and the
781 purpose of %who is to show you only what you've manually defined."""
781 purpose of %who is to show you only what you've manually defined."""
782
782
783 varlist = self.magic_who_ls(parameter_s)
783 varlist = self.magic_who_ls(parameter_s)
784 if not varlist:
784 if not varlist:
785 print 'Interactive namespace is empty.'
785 print 'Interactive namespace is empty.'
786 return
786 return
787
787
788 # if we have variables, move on...
788 # if we have variables, move on...
789
789
790 # stupid flushing problem: when prompts have no separators, stdout is
790 # stupid flushing problem: when prompts have no separators, stdout is
791 # getting lost. I'm starting to think this is a python bug. I'm having
791 # getting lost. I'm starting to think this is a python bug. I'm having
792 # to force a flush with a print because even a sys.stdout.flush
792 # to force a flush with a print because even a sys.stdout.flush
793 # doesn't seem to do anything!
793 # doesn't seem to do anything!
794
794
795 count = 0
795 count = 0
796 for i in varlist:
796 for i in varlist:
797 print i+'\t',
797 print i+'\t',
798 count += 1
798 count += 1
799 if count > 8:
799 if count > 8:
800 count = 0
800 count = 0
801 print
801 print
802 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
802 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
803
803
804 print # well, this does force a flush at the expense of an extra \n
804 print # well, this does force a flush at the expense of an extra \n
805
805
806 def magic_whos(self, parameter_s=''):
806 def magic_whos(self, parameter_s=''):
807 """Like %who, but gives some extra information about each variable.
807 """Like %who, but gives some extra information about each variable.
808
808
809 The same type filtering of %who can be applied here.
809 The same type filtering of %who can be applied here.
810
810
811 For all variables, the type is printed. Additionally it prints:
811 For all variables, the type is printed. Additionally it prints:
812
812
813 - For {},[],(): their length.
813 - For {},[],(): their length.
814
814
815 - For Numeric arrays, a summary with shape, number of elements,
815 - For Numeric arrays, a summary with shape, number of elements,
816 typecode and size in memory.
816 typecode and size in memory.
817
817
818 - Everything else: a string representation, snipping their middle if
818 - Everything else: a string representation, snipping their middle if
819 too long."""
819 too long."""
820
820
821 varnames = self.magic_who_ls(parameter_s)
821 varnames = self.magic_who_ls(parameter_s)
822 if not varnames:
822 if not varnames:
823 print 'Interactive namespace is empty.'
823 print 'Interactive namespace is empty.'
824 return
824 return
825
825
826 # if we have variables, move on...
826 # if we have variables, move on...
827
827
828 # for these types, show len() instead of data:
828 # for these types, show len() instead of data:
829 seq_types = [types.DictType,types.ListType,types.TupleType]
829 seq_types = [types.DictType,types.ListType,types.TupleType]
830
830
831 # for Numeric arrays, display summary info
831 # for Numeric arrays, display summary info
832 try:
832 try:
833 import Numeric
833 import Numeric
834 except ImportError:
834 except ImportError:
835 array_type = None
835 array_type = None
836 else:
836 else:
837 array_type = Numeric.ArrayType.__name__
837 array_type = Numeric.ArrayType.__name__
838
838
839 # Find all variable names and types so we can figure out column sizes
839 # Find all variable names and types so we can figure out column sizes
840 get_vars = lambda i: self.shell.user_ns[i]
840 get_vars = lambda i: self.shell.user_ns[i]
841 type_name = lambda v: type(v).__name__
841 type_name = lambda v: type(v).__name__
842 varlist = map(get_vars,varnames)
842 varlist = map(get_vars,varnames)
843 typelist = map(type_name,varlist)
843 typelist = map(type_name,varlist)
844 # column labels and # of spaces as separator
844 # column labels and # of spaces as separator
845 varlabel = 'Variable'
845 varlabel = 'Variable'
846 typelabel = 'Type'
846 typelabel = 'Type'
847 datalabel = 'Data/Info'
847 datalabel = 'Data/Info'
848 colsep = 3
848 colsep = 3
849 # variable format strings
849 # variable format strings
850 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
850 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
851 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
851 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
852 aformat = "%s: %s elems, type `%s`, %s bytes"
852 aformat = "%s: %s elems, type `%s`, %s bytes"
853 # find the size of the columns to format the output nicely
853 # find the size of the columns to format the output nicely
854 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
854 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
855 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
855 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
856 # table header
856 # table header
857 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
857 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
858 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
858 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
859 # and the table itself
859 # and the table itself
860 kb = 1024
860 kb = 1024
861 Mb = 1048576 # kb**2
861 Mb = 1048576 # kb**2
862 for vname,var,vtype in zip(varnames,varlist,typelist):
862 for vname,var,vtype in zip(varnames,varlist,typelist):
863 print itpl(vformat),
863 print itpl(vformat),
864 if vtype in seq_types:
864 if vtype in seq_types:
865 print len(var)
865 print len(var)
866 elif vtype==array_type:
866 elif vtype==array_type:
867 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
867 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
868 vsize = Numeric.size(var)
868 vsize = Numeric.size(var)
869 vbytes = vsize*var.itemsize()
869 vbytes = vsize*var.itemsize()
870 if vbytes < 100000:
870 if vbytes < 100000:
871 print aformat % (vshape,vsize,var.typecode(),vbytes)
871 print aformat % (vshape,vsize,var.typecode(),vbytes)
872 else:
872 else:
873 print aformat % (vshape,vsize,var.typecode(),vbytes),
873 print aformat % (vshape,vsize,var.typecode(),vbytes),
874 if vbytes < Mb:
874 if vbytes < Mb:
875 print '(%s kb)' % (vbytes/kb,)
875 print '(%s kb)' % (vbytes/kb,)
876 else:
876 else:
877 print '(%s Mb)' % (vbytes/Mb,)
877 print '(%s Mb)' % (vbytes/Mb,)
878 else:
878 else:
879 vstr = str(var)
879 vstr = str(var)
880 if len(vstr) < 50:
880 if len(vstr) < 50:
881 print vstr
881 print vstr
882 else:
882 else:
883 printpl(vfmt_short)
883 printpl(vfmt_short)
884
884
885 def magic_reset(self, parameter_s=''):
885 def magic_reset(self, parameter_s=''):
886 """Resets the namespace by removing all names defined by the user.
886 """Resets the namespace by removing all names defined by the user.
887
887
888 Input/Output history are left around in case you need them."""
888 Input/Output history are left around in case you need them."""
889
889
890 ans = raw_input(
890 ans = raw_input(
891 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
891 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
892 if not ans.lower() == 'y':
892 if not ans.lower() == 'y':
893 print 'Nothing done.'
893 print 'Nothing done.'
894 return
894 return
895 user_ns = self.shell.user_ns
895 user_ns = self.shell.user_ns
896 for i in self.magic_who_ls():
896 for i in self.magic_who_ls():
897 del(user_ns[i])
897 del(user_ns[i])
898
898
899 def magic_config(self,parameter_s=''):
899 def magic_config(self,parameter_s=''):
900 """Show IPython's internal configuration."""
900 """Show IPython's internal configuration."""
901
901
902 page('Current configuration structure:\n'+
902 page('Current configuration structure:\n'+
903 pformat(self.shell.rc.dict()))
903 pformat(self.shell.rc.dict()))
904
904
905 def magic_logstart(self,parameter_s=''):
905 def magic_logstart(self,parameter_s=''):
906 """Start logging anywhere in a session.
906 """Start logging anywhere in a session.
907
907
908 %logstart [-o|-t] [log_name [log_mode]]
908 %logstart [-o|-t] [log_name [log_mode]]
909
909
910 If no name is given, it defaults to a file named 'ipython_log.py' in your
910 If no name is given, it defaults to a file named 'ipython_log.py' in your
911 current directory, in 'rotate' mode (see below).
911 current directory, in 'rotate' mode (see below).
912
912
913 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
913 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
914 history up to that point and then continues logging.
914 history up to that point and then continues logging.
915
915
916 %logstart takes a second optional parameter: logging mode. This can be one
916 %logstart takes a second optional parameter: logging mode. This can be one
917 of (note that the modes are given unquoted):\\
917 of (note that the modes are given unquoted):\\
918 append: well, that says it.\\
918 append: well, that says it.\\
919 backup: rename (if exists) to name~ and start name.\\
919 backup: rename (if exists) to name~ and start name.\\
920 global: single logfile in your home dir, appended to.\\
920 global: single logfile in your home dir, appended to.\\
921 over : overwrite existing log.\\
921 over : overwrite existing log.\\
922 rotate: create rotating logs name.1~, name.2~, etc.
922 rotate: create rotating logs name.1~, name.2~, etc.
923
923
924 Options:
924 Options:
925
925
926 -o: log also IPython's output. In this mode, all commands which
926 -o: log also IPython's output. In this mode, all commands which
927 generate an Out[NN] prompt are recorded to the logfile, right after
927 generate an Out[NN] prompt are recorded to the logfile, right after
928 their corresponding input line. The output lines are always
928 their corresponding input line. The output lines are always
929 prepended with a #[Out]# marker, so that the log remains valid
929 prepended with a #[Out]# marker, so that the log remains valid
930 Python code.
930 Python code.
931
931
932 -t: put timestamps before each input line logged (these are put in
932 -t: put timestamps before each input line logged (these are put in
933 comments)."""
933 comments)."""
934
934
935 opts,par = self.parse_options(parameter_s,'ot')
935 opts,par = self.parse_options(parameter_s,'ot')
936 log_output = 'o' in opts
936 log_output = 'o' in opts
937 timestamp = 't' in opts
937 timestamp = 't' in opts
938
938
939 rc = self.shell.rc
939 rc = self.shell.rc
940 logger = self.shell.logger
940 logger = self.shell.logger
941
941
942 # if no args are given, the defaults set in the logger constructor by
942 # if no args are given, the defaults set in the logger constructor by
943 # ipytohn remain valid
943 # ipytohn remain valid
944 if par:
944 if par:
945 try:
945 try:
946 logfname,logmode = par.split()
946 logfname,logmode = par.split()
947 except:
947 except:
948 logfname = par
948 logfname = par
949 logmode = 'backup'
949 logmode = 'backup'
950 else:
950 else:
951 logfname = logger.logfname
951 logfname = logger.logfname
952 logmode = logger.logmode
952 logmode = logger.logmode
953 # put logfname into rc struct as if it had been called on the command
953 # put logfname into rc struct as if it had been called on the command
954 # line, so it ends up saved in the log header Save it in case we need
954 # line, so it ends up saved in the log header Save it in case we need
955 # to restore it...
955 # to restore it...
956 old_logfile = rc.opts.get('logfile','')
956 old_logfile = rc.opts.get('logfile','')
957 if logfname:
957 if logfname:
958 logfname = os.path.expanduser(logfname)
958 logfname = os.path.expanduser(logfname)
959 rc.opts.logfile = logfname
959 rc.opts.logfile = logfname
960 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
960 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
961 try:
961 try:
962 started = logger.logstart(logfname,loghead,logmode,
962 started = logger.logstart(logfname,loghead,logmode,
963 log_output,timestamp)
963 log_output,timestamp)
964 except:
964 except:
965 rc.opts.logfile = old_logfile
965 rc.opts.logfile = old_logfile
966 warn("Couldn't start log: %s" % sys.exc_info()[1])
966 warn("Couldn't start log: %s" % sys.exc_info()[1])
967 else:
967 else:
968 # log input history up to this point, optionally interleaving
968 # log input history up to this point, optionally interleaving
969 # output if requested
969 # output if requested
970
970
971 if timestamp:
971 if timestamp:
972 # disable timestamping for the previous history, since we've
972 # disable timestamping for the previous history, since we've
973 # lost those already (no time machine here).
973 # lost those already (no time machine here).
974 logger.timestamp = False
974 logger.timestamp = False
975 if log_output:
975 if log_output:
976 log_write = logger.log_write
976 log_write = logger.log_write
977 input_hist = self.shell.input_hist
977 input_hist = self.shell.input_hist
978 output_hist = self.shell.output_hist
978 output_hist = self.shell.output_hist
979 for n in range(1,len(input_hist)-1):
979 for n in range(1,len(input_hist)-1):
980 log_write(input_hist[n].rstrip())
980 log_write(input_hist[n].rstrip())
981 if n in output_hist:
981 if n in output_hist:
982 log_write(repr(output_hist[n]),'output')
982 log_write(repr(output_hist[n]),'output')
983 else:
983 else:
984 logger.log_write(self.shell.input_hist[1:])
984 logger.log_write(self.shell.input_hist[1:])
985 if timestamp:
985 if timestamp:
986 # re-enable timestamping
986 # re-enable timestamping
987 logger.timestamp = True
987 logger.timestamp = True
988
988
989 print ('Activating auto-logging. '
989 print ('Activating auto-logging. '
990 'Current session state plus future input saved.')
990 'Current session state plus future input saved.')
991 logger.logstate()
991 logger.logstate()
992
992
993 def magic_logoff(self,parameter_s=''):
993 def magic_logoff(self,parameter_s=''):
994 """Temporarily stop logging.
994 """Temporarily stop logging.
995
995
996 You must have previously started logging."""
996 You must have previously started logging."""
997 self.shell.logger.switch_log(0)
997 self.shell.logger.switch_log(0)
998
998
999 def magic_logon(self,parameter_s=''):
999 def magic_logon(self,parameter_s=''):
1000 """Restart logging.
1000 """Restart logging.
1001
1001
1002 This function is for restarting logging which you've temporarily
1002 This function is for restarting logging which you've temporarily
1003 stopped with %logoff. For starting logging for the first time, you
1003 stopped with %logoff. For starting logging for the first time, you
1004 must use the %logstart function, which allows you to specify an
1004 must use the %logstart function, which allows you to specify an
1005 optional log filename."""
1005 optional log filename."""
1006
1006
1007 self.shell.logger.switch_log(1)
1007 self.shell.logger.switch_log(1)
1008
1008
1009 def magic_logstate(self,parameter_s=''):
1009 def magic_logstate(self,parameter_s=''):
1010 """Print the status of the logging system."""
1010 """Print the status of the logging system."""
1011
1011
1012 self.shell.logger.logstate()
1012 self.shell.logger.logstate()
1013
1013
1014 def magic_pdb(self, parameter_s=''):
1014 def magic_pdb(self, parameter_s=''):
1015 """Control the calling of the pdb interactive debugger.
1015 """Control the calling of the pdb interactive debugger.
1016
1016
1017 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1017 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1018 argument it works as a toggle.
1018 argument it works as a toggle.
1019
1019
1020 When an exception is triggered, IPython can optionally call the
1020 When an exception is triggered, IPython can optionally call the
1021 interactive pdb debugger after the traceback printout. %pdb toggles
1021 interactive pdb debugger after the traceback printout. %pdb toggles
1022 this feature on and off."""
1022 this feature on and off."""
1023
1023
1024 par = parameter_s.strip().lower()
1024 par = parameter_s.strip().lower()
1025
1025
1026 if par:
1026 if par:
1027 try:
1027 try:
1028 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1028 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1029 except KeyError:
1029 except KeyError:
1030 print ('Incorrect argument. Use on/1, off/0, '
1030 print ('Incorrect argument. Use on/1, off/0, '
1031 'or nothing for a toggle.')
1031 'or nothing for a toggle.')
1032 return
1032 return
1033 else:
1033 else:
1034 # toggle
1034 # toggle
1035 new_pdb = not self.shell.InteractiveTB.call_pdb
1035 new_pdb = not self.shell.InteractiveTB.call_pdb
1036
1036
1037 # set on the shell
1037 # set on the shell
1038 self.shell.call_pdb = new_pdb
1038 self.shell.call_pdb = new_pdb
1039 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1039 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1040
1040
1041 def magic_prun(self, parameter_s ='',user_mode=1,
1041 def magic_prun(self, parameter_s ='',user_mode=1,
1042 opts=None,arg_lst=None,prog_ns=None):
1042 opts=None,arg_lst=None,prog_ns=None):
1043
1043
1044 """Run a statement through the python code profiler.
1044 """Run a statement through the python code profiler.
1045
1045
1046 Usage:\\
1046 Usage:\\
1047 %prun [options] statement
1047 %prun [options] statement
1048
1048
1049 The given statement (which doesn't require quote marks) is run via the
1049 The given statement (which doesn't require quote marks) is run via the
1050 python profiler in a manner similar to the profile.run() function.
1050 python profiler in a manner similar to the profile.run() function.
1051 Namespaces are internally managed to work correctly; profile.run
1051 Namespaces are internally managed to work correctly; profile.run
1052 cannot be used in IPython because it makes certain assumptions about
1052 cannot be used in IPython because it makes certain assumptions about
1053 namespaces which do not hold under IPython.
1053 namespaces which do not hold under IPython.
1054
1054
1055 Options:
1055 Options:
1056
1056
1057 -l <limit>: you can place restrictions on what or how much of the
1057 -l <limit>: you can place restrictions on what or how much of the
1058 profile gets printed. The limit value can be:
1058 profile gets printed. The limit value can be:
1059
1059
1060 * A string: only information for function names containing this string
1060 * A string: only information for function names containing this string
1061 is printed.
1061 is printed.
1062
1062
1063 * An integer: only these many lines are printed.
1063 * An integer: only these many lines are printed.
1064
1064
1065 * A float (between 0 and 1): this fraction of the report is printed
1065 * A float (between 0 and 1): this fraction of the report is printed
1066 (for example, use a limit of 0.4 to see the topmost 40% only).
1066 (for example, use a limit of 0.4 to see the topmost 40% only).
1067
1067
1068 You can combine several limits with repeated use of the option. For
1068 You can combine several limits with repeated use of the option. For
1069 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1069 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1070 information about class constructors.
1070 information about class constructors.
1071
1071
1072 -r: return the pstats.Stats object generated by the profiling. This
1072 -r: return the pstats.Stats object generated by the profiling. This
1073 object has all the information about the profile in it, and you can
1073 object has all the information about the profile in it, and you can
1074 later use it for further analysis or in other functions.
1074 later use it for further analysis or in other functions.
1075
1075
1076 Since magic functions have a particular form of calling which prevents
1076 Since magic functions have a particular form of calling which prevents
1077 you from writing something like:\\
1077 you from writing something like:\\
1078 In [1]: p = %prun -r print 4 # invalid!\\
1078 In [1]: p = %prun -r print 4 # invalid!\\
1079 you must instead use IPython's automatic variables to assign this:\\
1079 you must instead use IPython's automatic variables to assign this:\\
1080 In [1]: %prun -r print 4 \\
1080 In [1]: %prun -r print 4 \\
1081 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1081 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1082 In [2]: stats = _
1082 In [2]: stats = _
1083
1083
1084 If you really need to assign this value via an explicit function call,
1084 If you really need to assign this value via an explicit function call,
1085 you can always tap directly into the true name of the magic function
1085 you can always tap directly into the true name of the magic function
1086 by using the ipmagic function (which IPython automatically adds to the
1086 by using the ipmagic function (which IPython automatically adds to the
1087 builtins):\\
1087 builtins):\\
1088 In [3]: stats = ipmagic('prun','-r print 4')
1088 In [3]: stats = ipmagic('prun','-r print 4')
1089
1089
1090 You can type ipmagic? for more details on ipmagic.
1090 You can type ipmagic? for more details on ipmagic.
1091
1091
1092 -s <key>: sort profile by given key. You can provide more than one key
1092 -s <key>: sort profile by given key. You can provide more than one key
1093 by using the option several times: '-s key1 -s key2 -s key3...'. The
1093 by using the option several times: '-s key1 -s key2 -s key3...'. The
1094 default sorting key is 'time'.
1094 default sorting key is 'time'.
1095
1095
1096 The following is copied verbatim from the profile documentation
1096 The following is copied verbatim from the profile documentation
1097 referenced below:
1097 referenced below:
1098
1098
1099 When more than one key is provided, additional keys are used as
1099 When more than one key is provided, additional keys are used as
1100 secondary criteria when the there is equality in all keys selected
1100 secondary criteria when the there is equality in all keys selected
1101 before them.
1101 before them.
1102
1102
1103 Abbreviations can be used for any key names, as long as the
1103 Abbreviations can be used for any key names, as long as the
1104 abbreviation is unambiguous. The following are the keys currently
1104 abbreviation is unambiguous. The following are the keys currently
1105 defined:
1105 defined:
1106
1106
1107 Valid Arg Meaning\\
1107 Valid Arg Meaning\\
1108 "calls" call count\\
1108 "calls" call count\\
1109 "cumulative" cumulative time\\
1109 "cumulative" cumulative time\\
1110 "file" file name\\
1110 "file" file name\\
1111 "module" file name\\
1111 "module" file name\\
1112 "pcalls" primitive call count\\
1112 "pcalls" primitive call count\\
1113 "line" line number\\
1113 "line" line number\\
1114 "name" function name\\
1114 "name" function name\\
1115 "nfl" name/file/line\\
1115 "nfl" name/file/line\\
1116 "stdname" standard name\\
1116 "stdname" standard name\\
1117 "time" internal time
1117 "time" internal time
1118
1118
1119 Note that all sorts on statistics are in descending order (placing
1119 Note that all sorts on statistics are in descending order (placing
1120 most time consuming items first), where as name, file, and line number
1120 most time consuming items first), where as name, file, and line number
1121 searches are in ascending order (i.e., alphabetical). The subtle
1121 searches are in ascending order (i.e., alphabetical). The subtle
1122 distinction between "nfl" and "stdname" is that the standard name is a
1122 distinction between "nfl" and "stdname" is that the standard name is a
1123 sort of the name as printed, which means that the embedded line
1123 sort of the name as printed, which means that the embedded line
1124 numbers get compared in an odd way. For example, lines 3, 20, and 40
1124 numbers get compared in an odd way. For example, lines 3, 20, and 40
1125 would (if the file names were the same) appear in the string order
1125 would (if the file names were the same) appear in the string order
1126 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1126 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1127 line numbers. In fact, sort_stats("nfl") is the same as
1127 line numbers. In fact, sort_stats("nfl") is the same as
1128 sort_stats("name", "file", "line").
1128 sort_stats("name", "file", "line").
1129
1129
1130 -T <filename>: save profile results as shown on screen to a text
1130 -T <filename>: save profile results as shown on screen to a text
1131 file. The profile is still shown on screen.
1131 file. The profile is still shown on screen.
1132
1132
1133 -D <filename>: save (via dump_stats) profile statistics to given
1133 -D <filename>: save (via dump_stats) profile statistics to given
1134 filename. This data is in a format understod by the pstats module, and
1134 filename. This data is in a format understod by the pstats module, and
1135 is generated by a call to the dump_stats() method of profile
1135 is generated by a call to the dump_stats() method of profile
1136 objects. The profile is still shown on screen.
1136 objects. The profile is still shown on screen.
1137
1137
1138 If you want to run complete programs under the profiler's control, use
1138 If you want to run complete programs under the profiler's control, use
1139 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1139 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1140 contains profiler specific options as described here.
1140 contains profiler specific options as described here.
1141
1141
1142 You can read the complete documentation for the profile module with:\\
1142 You can read the complete documentation for the profile module with:\\
1143 In [1]: import profile; profile.help() """
1143 In [1]: import profile; profile.help() """
1144
1144
1145 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1145 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1146 # protect user quote marks
1146 # protect user quote marks
1147 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1147 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1148
1148
1149 if user_mode: # regular user call
1149 if user_mode: # regular user call
1150 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1150 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1151 list_all=1)
1151 list_all=1)
1152 namespace = self.shell.user_ns
1152 namespace = self.shell.user_ns
1153 else: # called to run a program by %run -p
1153 else: # called to run a program by %run -p
1154 try:
1154 try:
1155 filename = get_py_filename(arg_lst[0])
1155 filename = get_py_filename(arg_lst[0])
1156 except IOError,msg:
1156 except IOError,msg:
1157 error(msg)
1157 error(msg)
1158 return
1158 return
1159
1159
1160 arg_str = 'execfile(filename,prog_ns)'
1160 arg_str = 'execfile(filename,prog_ns)'
1161 namespace = locals()
1161 namespace = locals()
1162
1162
1163 opts.merge(opts_def)
1163 opts.merge(opts_def)
1164
1164
1165 prof = profile.Profile()
1165 prof = profile.Profile()
1166 try:
1166 try:
1167 prof = prof.runctx(arg_str,namespace,namespace)
1167 prof = prof.runctx(arg_str,namespace,namespace)
1168 sys_exit = ''
1168 sys_exit = ''
1169 except SystemExit:
1169 except SystemExit:
1170 sys_exit = """*** SystemExit exception caught in code being profiled."""
1170 sys_exit = """*** SystemExit exception caught in code being profiled."""
1171
1171
1172 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1172 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1173
1173
1174 lims = opts.l
1174 lims = opts.l
1175 if lims:
1175 if lims:
1176 lims = [] # rebuild lims with ints/floats/strings
1176 lims = [] # rebuild lims with ints/floats/strings
1177 for lim in opts.l:
1177 for lim in opts.l:
1178 try:
1178 try:
1179 lims.append(int(lim))
1179 lims.append(int(lim))
1180 except ValueError:
1180 except ValueError:
1181 try:
1181 try:
1182 lims.append(float(lim))
1182 lims.append(float(lim))
1183 except ValueError:
1183 except ValueError:
1184 lims.append(lim)
1184 lims.append(lim)
1185
1185
1186 # trap output
1186 # trap output
1187 sys_stdout = sys.stdout
1187 sys_stdout = sys.stdout
1188 stdout_trap = StringIO()
1188 stdout_trap = StringIO()
1189 try:
1189 try:
1190 sys.stdout = stdout_trap
1190 sys.stdout = stdout_trap
1191 stats.print_stats(*lims)
1191 stats.print_stats(*lims)
1192 finally:
1192 finally:
1193 sys.stdout = sys_stdout
1193 sys.stdout = sys_stdout
1194 output = stdout_trap.getvalue()
1194 output = stdout_trap.getvalue()
1195 output = output.rstrip()
1195 output = output.rstrip()
1196
1196
1197 page(output,screen_lines=self.shell.rc.screen_length)
1197 page(output,screen_lines=self.shell.rc.screen_length)
1198 print sys_exit,
1198 print sys_exit,
1199
1199
1200 dump_file = opts.D[0]
1200 dump_file = opts.D[0]
1201 text_file = opts.T[0]
1201 text_file = opts.T[0]
1202 if dump_file:
1202 if dump_file:
1203 prof.dump_stats(dump_file)
1203 prof.dump_stats(dump_file)
1204 print '\n*** Profile stats marshalled to file',\
1204 print '\n*** Profile stats marshalled to file',\
1205 `dump_file`+'.',sys_exit
1205 `dump_file`+'.',sys_exit
1206 if text_file:
1206 if text_file:
1207 file(text_file,'w').write(output)
1207 file(text_file,'w').write(output)
1208 print '\n*** Profile printout saved to text file',\
1208 print '\n*** Profile printout saved to text file',\
1209 `text_file`+'.',sys_exit
1209 `text_file`+'.',sys_exit
1210
1210
1211 if opts.has_key('r'):
1211 if opts.has_key('r'):
1212 return stats
1212 return stats
1213 else:
1213 else:
1214 return None
1214 return None
1215
1215
1216 def magic_run(self, parameter_s ='',runner=None):
1216 def magic_run(self, parameter_s ='',runner=None):
1217 """Run the named file inside IPython as a program.
1217 """Run the named file inside IPython as a program.
1218
1218
1219 Usage:\\
1219 Usage:\\
1220 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1220 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1221
1221
1222 Parameters after the filename are passed as command-line arguments to
1222 Parameters after the filename are passed as command-line arguments to
1223 the program (put in sys.argv). Then, control returns to IPython's
1223 the program (put in sys.argv). Then, control returns to IPython's
1224 prompt.
1224 prompt.
1225
1225
1226 This is similar to running at a system prompt:\\
1226 This is similar to running at a system prompt:\\
1227 $ python file args\\
1227 $ python file args\\
1228 but with the advantage of giving you IPython's tracebacks, and of
1228 but with the advantage of giving you IPython's tracebacks, and of
1229 loading all variables into your interactive namespace for further use
1229 loading all variables into your interactive namespace for further use
1230 (unless -p is used, see below).
1230 (unless -p is used, see below).
1231
1231
1232 The file is executed in a namespace initially consisting only of
1232 The file is executed in a namespace initially consisting only of
1233 __name__=='__main__' and sys.argv constructed as indicated. It thus
1233 __name__=='__main__' and sys.argv constructed as indicated. It thus
1234 sees its environment as if it were being run as a stand-alone
1234 sees its environment as if it were being run as a stand-alone
1235 program. But after execution, the IPython interactive namespace gets
1235 program. But after execution, the IPython interactive namespace gets
1236 updated with all variables defined in the program (except for __name__
1236 updated with all variables defined in the program (except for __name__
1237 and sys.argv). This allows for very convenient loading of code for
1237 and sys.argv). This allows for very convenient loading of code for
1238 interactive work, while giving each program a 'clean sheet' to run in.
1238 interactive work, while giving each program a 'clean sheet' to run in.
1239
1239
1240 Options:
1240 Options:
1241
1241
1242 -n: __name__ is NOT set to '__main__', but to the running file's name
1242 -n: __name__ is NOT set to '__main__', but to the running file's name
1243 without extension (as python does under import). This allows running
1243 without extension (as python does under import). This allows running
1244 scripts and reloading the definitions in them without calling code
1244 scripts and reloading the definitions in them without calling code
1245 protected by an ' if __name__ == "__main__" ' clause.
1245 protected by an ' if __name__ == "__main__" ' clause.
1246
1246
1247 -i: run the file in IPython's namespace instead of an empty one. This
1247 -i: run the file in IPython's namespace instead of an empty one. This
1248 is useful if you are experimenting with code written in a text editor
1248 is useful if you are experimenting with code written in a text editor
1249 which depends on variables defined interactively.
1249 which depends on variables defined interactively.
1250
1250
1251 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1251 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1252 being run. This is particularly useful if IPython is being used to
1252 being run. This is particularly useful if IPython is being used to
1253 run unittests, which always exit with a sys.exit() call. In such
1253 run unittests, which always exit with a sys.exit() call. In such
1254 cases you are interested in the output of the test results, not in
1254 cases you are interested in the output of the test results, not in
1255 seeing a traceback of the unittest module.
1255 seeing a traceback of the unittest module.
1256
1256
1257 -t: print timing information at the end of the run. IPython will give
1257 -t: print timing information at the end of the run. IPython will give
1258 you an estimated CPU time consumption for your script, which under
1258 you an estimated CPU time consumption for your script, which under
1259 Unix uses the resource module to avoid the wraparound problems of
1259 Unix uses the resource module to avoid the wraparound problems of
1260 time.clock(). Under Unix, an estimate of time spent on system tasks
1260 time.clock(). Under Unix, an estimate of time spent on system tasks
1261 is also given (for Windows platforms this is reported as 0.0).
1261 is also given (for Windows platforms this is reported as 0.0).
1262
1262
1263 If -t is given, an additional -N<N> option can be given, where <N>
1263 If -t is given, an additional -N<N> option can be given, where <N>
1264 must be an integer indicating how many times you want the script to
1264 must be an integer indicating how many times you want the script to
1265 run. The final timing report will include total and per run results.
1265 run. The final timing report will include total and per run results.
1266
1266
1267 For example (testing the script uniq_stable.py):
1267 For example (testing the script uniq_stable.py):
1268
1268
1269 In [1]: run -t uniq_stable
1269 In [1]: run -t uniq_stable
1270
1270
1271 IPython CPU timings (estimated):\\
1271 IPython CPU timings (estimated):\\
1272 User : 0.19597 s.\\
1272 User : 0.19597 s.\\
1273 System: 0.0 s.\\
1273 System: 0.0 s.\\
1274
1274
1275 In [2]: run -t -N5 uniq_stable
1275 In [2]: run -t -N5 uniq_stable
1276
1276
1277 IPython CPU timings (estimated):\\
1277 IPython CPU timings (estimated):\\
1278 Total runs performed: 5\\
1278 Total runs performed: 5\\
1279 Times : Total Per run\\
1279 Times : Total Per run\\
1280 User : 0.910862 s, 0.1821724 s.\\
1280 User : 0.910862 s, 0.1821724 s.\\
1281 System: 0.0 s, 0.0 s.
1281 System: 0.0 s, 0.0 s.
1282
1282
1283 -d: run your program under the control of pdb, the Python debugger.
1283 -d: run your program under the control of pdb, the Python debugger.
1284 This allows you to execute your program step by step, watch variables,
1284 This allows you to execute your program step by step, watch variables,
1285 etc. Internally, what IPython does is similar to calling:
1285 etc. Internally, what IPython does is similar to calling:
1286
1286
1287 pdb.run('execfile("YOURFILENAME")')
1287 pdb.run('execfile("YOURFILENAME")')
1288
1288
1289 with a breakpoint set on line 1 of your file. You can change the line
1289 with a breakpoint set on line 1 of your file. You can change the line
1290 number for this automatic breakpoint to be <N> by using the -bN option
1290 number for this automatic breakpoint to be <N> by using the -bN option
1291 (where N must be an integer). For example:
1291 (where N must be an integer). For example:
1292
1292
1293 %run -d -b40 myscript
1293 %run -d -b40 myscript
1294
1294
1295 will set the first breakpoint at line 40 in myscript.py. Note that
1295 will set the first breakpoint at line 40 in myscript.py. Note that
1296 the first breakpoint must be set on a line which actually does
1296 the first breakpoint must be set on a line which actually does
1297 something (not a comment or docstring) for it to stop execution.
1297 something (not a comment or docstring) for it to stop execution.
1298
1298
1299 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1299 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1300 first enter 'c' (without qoutes) to start execution up to the first
1300 first enter 'c' (without qoutes) to start execution up to the first
1301 breakpoint.
1301 breakpoint.
1302
1302
1303 Entering 'help' gives information about the use of the debugger. You
1303 Entering 'help' gives information about the use of the debugger. You
1304 can easily see pdb's full documentation with "import pdb;pdb.help()"
1304 can easily see pdb's full documentation with "import pdb;pdb.help()"
1305 at a prompt.
1305 at a prompt.
1306
1306
1307 -p: run program under the control of the Python profiler module (which
1307 -p: run program under the control of the Python profiler module (which
1308 prints a detailed report of execution times, function calls, etc).
1308 prints a detailed report of execution times, function calls, etc).
1309
1309
1310 You can pass other options after -p which affect the behavior of the
1310 You can pass other options after -p which affect the behavior of the
1311 profiler itself. See the docs for %prun for details.
1311 profiler itself. See the docs for %prun for details.
1312
1312
1313 In this mode, the program's variables do NOT propagate back to the
1313 In this mode, the program's variables do NOT propagate back to the
1314 IPython interactive namespace (because they remain in the namespace
1314 IPython interactive namespace (because they remain in the namespace
1315 where the profiler executes them).
1315 where the profiler executes them).
1316
1316
1317 Internally this triggers a call to %prun, see its documentation for
1317 Internally this triggers a call to %prun, see its documentation for
1318 details on the options available specifically for profiling."""
1318 details on the options available specifically for profiling."""
1319
1319
1320 # get arguments and set sys.argv for program to be run.
1320 # get arguments and set sys.argv for program to be run.
1321 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1321 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1322 mode='list',list_all=1)
1322 mode='list',list_all=1)
1323
1323
1324 try:
1324 try:
1325 filename = get_py_filename(arg_lst[0])
1325 filename = get_py_filename(arg_lst[0])
1326 except IndexError:
1326 except IndexError:
1327 warn('you must provide at least a filename.')
1327 warn('you must provide at least a filename.')
1328 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1328 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1329 return
1329 return
1330 except IOError,msg:
1330 except IOError,msg:
1331 error(msg)
1331 error(msg)
1332 return
1332 return
1333
1333
1334 # Control the response to exit() calls made by the script being run
1334 # Control the response to exit() calls made by the script being run
1335 exit_ignore = opts.has_key('e')
1335 exit_ignore = opts.has_key('e')
1336
1336
1337 # Make sure that the running script gets a proper sys.argv as if it
1337 # Make sure that the running script gets a proper sys.argv as if it
1338 # were run from a system shell.
1338 # were run from a system shell.
1339 save_argv = sys.argv # save it for later restoring
1339 save_argv = sys.argv # save it for later restoring
1340 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1340 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1341
1341
1342 if opts.has_key('i'):
1342 if opts.has_key('i'):
1343 prog_ns = self.shell.user_ns
1343 prog_ns = self.shell.user_ns
1344 __name__save = self.shell.user_ns['__name__']
1344 __name__save = self.shell.user_ns['__name__']
1345 prog_ns['__name__'] = '__main__'
1345 prog_ns['__name__'] = '__main__'
1346 else:
1346 else:
1347 if opts.has_key('n'):
1347 if opts.has_key('n'):
1348 name = os.path.splitext(os.path.basename(filename))[0]
1348 name = os.path.splitext(os.path.basename(filename))[0]
1349 else:
1349 else:
1350 name = '__main__'
1350 name = '__main__'
1351 prog_ns = {'__name__':name}
1351 prog_ns = {'__name__':name}
1352
1352
1353 # pickle fix. See iplib for an explanation
1353 # pickle fix. See iplib for an explanation
1354 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1354 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1355
1355
1356 stats = None
1356 stats = None
1357 try:
1357 try:
1358 if opts.has_key('p'):
1358 if opts.has_key('p'):
1359 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1359 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1360 else:
1360 else:
1361 if opts.has_key('d'):
1361 if opts.has_key('d'):
1362 deb = Debugger.Pdb(self.shell.rc.colors)
1362 deb = Debugger.Pdb(self.shell.rc.colors)
1363 # reset Breakpoint state, which is moronically kept
1363 # reset Breakpoint state, which is moronically kept
1364 # in a class
1364 # in a class
1365 bdb.Breakpoint.next = 1
1365 bdb.Breakpoint.next = 1
1366 bdb.Breakpoint.bplist = {}
1366 bdb.Breakpoint.bplist = {}
1367 bdb.Breakpoint.bpbynumber = [None]
1367 bdb.Breakpoint.bpbynumber = [None]
1368 # Set an initial breakpoint to stop execution
1368 # Set an initial breakpoint to stop execution
1369 maxtries = 10
1369 maxtries = 10
1370 bp = int(opts.get('b',[1])[0])
1370 bp = int(opts.get('b',[1])[0])
1371 checkline = deb.checkline(filename,bp)
1371 checkline = deb.checkline(filename,bp)
1372 if not checkline:
1372 if not checkline:
1373 for bp in range(bp+1,bp+maxtries+1):
1373 for bp in range(bp+1,bp+maxtries+1):
1374 if deb.checkline(filename,bp):
1374 if deb.checkline(filename,bp):
1375 break
1375 break
1376 else:
1376 else:
1377 msg = ("\nI failed to find a valid line to set "
1377 msg = ("\nI failed to find a valid line to set "
1378 "a breakpoint\n"
1378 "a breakpoint\n"
1379 "after trying up to line: %s.\n"
1379 "after trying up to line: %s.\n"
1380 "Please set a valid breakpoint manually "
1380 "Please set a valid breakpoint manually "
1381 "with the -b option." % bp)
1381 "with the -b option." % bp)
1382 error(msg)
1382 error(msg)
1383 return
1383 return
1384 # if we find a good linenumber, set the breakpoint
1384 # if we find a good linenumber, set the breakpoint
1385 deb.do_break('%s:%s' % (filename,bp))
1385 deb.do_break('%s:%s' % (filename,bp))
1386 # Start file run
1386 # Start file run
1387 print "NOTE: Enter 'c' at the",
1387 print "NOTE: Enter 'c' at the",
1388 print "ipdb> prompt to start your script."
1388 print "ipdb> prompt to start your script."
1389 try:
1389 try:
1390 deb.run('execfile("%s")' % filename,prog_ns)
1390 deb.run('execfile("%s")' % filename,prog_ns)
1391 except:
1391 except:
1392 etype, value, tb = sys.exc_info()
1392 etype, value, tb = sys.exc_info()
1393 # Skip three frames in the traceback: the %run one,
1393 # Skip three frames in the traceback: the %run one,
1394 # one inside bdb.py, and the command-line typed by the
1394 # one inside bdb.py, and the command-line typed by the
1395 # user (run by exec in pdb itself).
1395 # user (run by exec in pdb itself).
1396 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1396 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1397 else:
1397 else:
1398 if runner is None:
1398 if runner is None:
1399 runner = self.shell.safe_execfile
1399 runner = self.shell.safe_execfile
1400 if opts.has_key('t'):
1400 if opts.has_key('t'):
1401 try:
1401 try:
1402 nruns = int(opts['N'][0])
1402 nruns = int(opts['N'][0])
1403 if nruns < 1:
1403 if nruns < 1:
1404 error('Number of runs must be >=1')
1404 error('Number of runs must be >=1')
1405 return
1405 return
1406 except (KeyError):
1406 except (KeyError):
1407 nruns = 1
1407 nruns = 1
1408 if nruns == 1:
1408 if nruns == 1:
1409 t0 = clock2()
1409 t0 = clock2()
1410 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1410 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1411 t1 = clock2()
1411 t1 = clock2()
1412 t_usr = t1[0]-t0[0]
1412 t_usr = t1[0]-t0[0]
1413 t_sys = t1[1]-t1[1]
1413 t_sys = t1[1]-t1[1]
1414 print "\nIPython CPU timings (estimated):"
1414 print "\nIPython CPU timings (estimated):"
1415 print " User : %10s s." % t_usr
1415 print " User : %10s s." % t_usr
1416 print " System: %10s s." % t_sys
1416 print " System: %10s s." % t_sys
1417 else:
1417 else:
1418 runs = range(nruns)
1418 runs = range(nruns)
1419 t0 = clock2()
1419 t0 = clock2()
1420 for nr in runs:
1420 for nr in runs:
1421 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1421 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1422 t1 = clock2()
1422 t1 = clock2()
1423 t_usr = t1[0]-t0[0]
1423 t_usr = t1[0]-t0[0]
1424 t_sys = t1[1]-t1[1]
1424 t_sys = t1[1]-t1[1]
1425 print "\nIPython CPU timings (estimated):"
1425 print "\nIPython CPU timings (estimated):"
1426 print "Total runs performed:",nruns
1426 print "Total runs performed:",nruns
1427 print " Times : %10s %10s" % ('Total','Per run')
1427 print " Times : %10s %10s" % ('Total','Per run')
1428 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1428 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1429 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1429 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1430
1430
1431 else:
1431 else:
1432 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1432 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1433 if opts.has_key('i'):
1433 if opts.has_key('i'):
1434 self.shell.user_ns['__name__'] = __name__save
1434 self.shell.user_ns['__name__'] = __name__save
1435 else:
1435 else:
1436 # update IPython interactive namespace
1436 # update IPython interactive namespace
1437 del prog_ns['__name__']
1437 del prog_ns['__name__']
1438 self.shell.user_ns.update(prog_ns)
1438 self.shell.user_ns.update(prog_ns)
1439 finally:
1439 finally:
1440 sys.argv = save_argv
1440 sys.argv = save_argv
1441 return stats
1441 return stats
1442
1442
1443 def magic_runlog(self, parameter_s =''):
1443 def magic_runlog(self, parameter_s =''):
1444 """Run files as logs.
1444 """Run files as logs.
1445
1445
1446 Usage:\\
1446 Usage:\\
1447 %runlog file1 file2 ...
1447 %runlog file1 file2 ...
1448
1448
1449 Run the named files (treating them as log files) in sequence inside
1449 Run the named files (treating them as log files) in sequence inside
1450 the interpreter, and return to the prompt. This is much slower than
1450 the interpreter, and return to the prompt. This is much slower than
1451 %run because each line is executed in a try/except block, but it
1451 %run because each line is executed in a try/except block, but it
1452 allows running files with syntax errors in them.
1452 allows running files with syntax errors in them.
1453
1453
1454 Normally IPython will guess when a file is one of its own logfiles, so
1454 Normally IPython will guess when a file is one of its own logfiles, so
1455 you can typically use %run even for logs. This shorthand allows you to
1455 you can typically use %run even for logs. This shorthand allows you to
1456 force any file to be treated as a log file."""
1456 force any file to be treated as a log file."""
1457
1457
1458 for f in parameter_s.split():
1458 for f in parameter_s.split():
1459 self.shell.safe_execfile(f,self.shell.user_ns,
1459 self.shell.safe_execfile(f,self.shell.user_ns,
1460 self.shell.user_ns,islog=1)
1460 self.shell.user_ns,islog=1)
1461
1461
1462 def magic_time(self,parameter_s = ''):
1462 def magic_time(self,parameter_s = ''):
1463 """Time execution of a Python statement or expression.
1463 """Time execution of a Python statement or expression.
1464
1464
1465 The CPU and wall clock times are printed, and the value of the
1465 The CPU and wall clock times are printed, and the value of the
1466 expression (if any) is returned. Note that under Win32, system time
1466 expression (if any) is returned. Note that under Win32, system time
1467 is always reported as 0, since it can not be measured.
1467 is always reported as 0, since it can not be measured.
1468
1468
1469 This function provides very basic timing functionality. In Python
1469 This function provides very basic timing functionality. In Python
1470 2.3, the timeit module offers more control and sophistication, but for
1470 2.3, the timeit module offers more control and sophistication, but for
1471 now IPython supports Python 2.2, so we can not rely on timeit being
1471 now IPython supports Python 2.2, so we can not rely on timeit being
1472 present.
1472 present.
1473
1473
1474 Some examples:
1474 Some examples:
1475
1475
1476 In [1]: time 2**128
1476 In [1]: time 2**128
1477 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1477 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1478 Wall time: 0.00
1478 Wall time: 0.00
1479 Out[1]: 340282366920938463463374607431768211456L
1479 Out[1]: 340282366920938463463374607431768211456L
1480
1480
1481 In [2]: n = 1000000
1481 In [2]: n = 1000000
1482
1482
1483 In [3]: time sum(range(n))
1483 In [3]: time sum(range(n))
1484 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1484 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1485 Wall time: 1.37
1485 Wall time: 1.37
1486 Out[3]: 499999500000L
1486 Out[3]: 499999500000L
1487
1487
1488 In [4]: time print 'hello world'
1488 In [4]: time print 'hello world'
1489 hello world
1489 hello world
1490 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1490 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1491 Wall time: 0.00
1491 Wall time: 0.00
1492 """
1492 """
1493
1493
1494 # fail immediately if the given expression can't be compiled
1494 # fail immediately if the given expression can't be compiled
1495 try:
1495 try:
1496 mode = 'eval'
1496 mode = 'eval'
1497 code = compile(parameter_s,'<timed eval>',mode)
1497 code = compile(parameter_s,'<timed eval>',mode)
1498 except SyntaxError:
1498 except SyntaxError:
1499 mode = 'exec'
1499 mode = 'exec'
1500 code = compile(parameter_s,'<timed exec>',mode)
1500 code = compile(parameter_s,'<timed exec>',mode)
1501 # skew measurement as little as possible
1501 # skew measurement as little as possible
1502 glob = self.shell.user_ns
1502 glob = self.shell.user_ns
1503 clk = clock2
1503 clk = clock2
1504 wtime = time.time
1504 wtime = time.time
1505 # time execution
1505 # time execution
1506 wall_st = wtime()
1506 wall_st = wtime()
1507 if mode=='eval':
1507 if mode=='eval':
1508 st = clk()
1508 st = clk()
1509 out = eval(code,glob)
1509 out = eval(code,glob)
1510 end = clk()
1510 end = clk()
1511 else:
1511 else:
1512 st = clk()
1512 st = clk()
1513 exec code in glob
1513 exec code in glob
1514 end = clk()
1514 end = clk()
1515 out = None
1515 out = None
1516 wall_end = wtime()
1516 wall_end = wtime()
1517 # Compute actual times and report
1517 # Compute actual times and report
1518 wall_time = wall_end-wall_st
1518 wall_time = wall_end-wall_st
1519 cpu_user = end[0]-st[0]
1519 cpu_user = end[0]-st[0]
1520 cpu_sys = end[1]-st[1]
1520 cpu_sys = end[1]-st[1]
1521 cpu_tot = cpu_user+cpu_sys
1521 cpu_tot = cpu_user+cpu_sys
1522 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1522 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1523 (cpu_user,cpu_sys,cpu_tot)
1523 (cpu_user,cpu_sys,cpu_tot)
1524 print "Wall time: %.2f" % wall_time
1524 print "Wall time: %.2f" % wall_time
1525 return out
1525 return out
1526
1526
1527 def magic_macro(self,parameter_s = ''):
1527 def magic_macro(self,parameter_s = ''):
1528 """Define a set of input lines as a macro for future re-execution.
1528 """Define a set of input lines as a macro for future re-execution.
1529
1529
1530 Usage:\\
1530 Usage:\\
1531 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1531 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1532
1532
1533 This will define a global variable called `name` which is a string
1533 This will define a global variable called `name` which is a string
1534 made of joining the slices and lines you specify (n1,n2,... numbers
1534 made of joining the slices and lines you specify (n1,n2,... numbers
1535 above) from your input history into a single string. This variable
1535 above) from your input history into a single string. This variable
1536 acts like an automatic function which re-executes those lines as if
1536 acts like an automatic function which re-executes those lines as if
1537 you had typed them. You just type 'name' at the prompt and the code
1537 you had typed them. You just type 'name' at the prompt and the code
1538 executes.
1538 executes.
1539
1539
1540 Note that the slices use the standard Python slicing notation (5:8
1540 Note that the slices use the standard Python slicing notation (5:8
1541 means include lines numbered 5,6,7).
1541 means include lines numbered 5,6,7).
1542
1542
1543 For example, if your history contains (%hist prints it):
1543 For example, if your history contains (%hist prints it):
1544
1544
1545 44: x=1\\
1545 44: x=1\\
1546 45: y=3\\
1546 45: y=3\\
1547 46: z=x+y\\
1547 46: z=x+y\\
1548 47: print x\\
1548 47: print x\\
1549 48: a=5\\
1549 48: a=5\\
1550 49: print 'x',x,'y',y\\
1550 49: print 'x',x,'y',y\\
1551
1551
1552 you can create a macro with lines 44 through 47 (included) and line 49
1552 you can create a macro with lines 44 through 47 (included) and line 49
1553 called my_macro with:
1553 called my_macro with:
1554
1554
1555 In [51]: %macro my_macro 44:48 49
1555 In [51]: %macro my_macro 44:48 49
1556
1556
1557 Now, typing `my_macro` (without quotes) will re-execute all this code
1557 Now, typing `my_macro` (without quotes) will re-execute all this code
1558 in one pass.
1558 in one pass.
1559
1559
1560 You don't need to give the line-numbers in order, and any given line
1560 You don't need to give the line-numbers in order, and any given line
1561 number can appear multiple times. You can assemble macros with any
1561 number can appear multiple times. You can assemble macros with any
1562 lines from your input history in any order.
1562 lines from your input history in any order.
1563
1563
1564 The macro is a simple object which holds its value in an attribute,
1564 The macro is a simple object which holds its value in an attribute,
1565 but IPython's display system checks for macros and executes them as
1565 but IPython's display system checks for macros and executes them as
1566 code instead of printing them when you type their name.
1566 code instead of printing them when you type their name.
1567
1567
1568 You can view a macro's contents by explicitly printing it with:
1568 You can view a macro's contents by explicitly printing it with:
1569
1569
1570 'print macro_name'.
1570 'print macro_name'.
1571
1571
1572 For one-off cases which DON'T contain magic function calls in them you
1572 For one-off cases which DON'T contain magic function calls in them you
1573 can obtain similar results by explicitly executing slices from your
1573 can obtain similar results by explicitly executing slices from your
1574 input history with:
1574 input history with:
1575
1575
1576 In [60]: exec In[44:48]+In[49]"""
1576 In [60]: exec In[44:48]+In[49]"""
1577
1577
1578 args = parameter_s.split()
1578 args = parameter_s.split()
1579 name,ranges = args[0], args[1:]
1579 name,ranges = args[0], args[1:]
1580 #print 'rng',ranges # dbg
1580 #print 'rng',ranges # dbg
1581 lines = self.extract_input_slices(ranges)
1581 lines = self.extract_input_slices(ranges)
1582 macro = Macro(lines)
1582 macro = Macro(lines)
1583 self.shell.user_ns.update({name:macro})
1583 self.shell.user_ns.update({name:macro})
1584 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1584 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1585 print 'Macro contents:'
1585 print 'Macro contents:'
1586 print macro
1586 print macro
1587
1587
1588 def magic_save(self,parameter_s = ''):
1588 def magic_save(self,parameter_s = ''):
1589 """Save a set of lines to a given filename.
1589 """Save a set of lines to a given filename.
1590
1590
1591 Usage:\\
1591 Usage:\\
1592 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1592 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1593
1593
1594 This function uses the same syntax as %macro for line extraction, but
1594 This function uses the same syntax as %macro for line extraction, but
1595 instead of creating a macro it saves the resulting string to the
1595 instead of creating a macro it saves the resulting string to the
1596 filename you specify.
1596 filename you specify.
1597
1597
1598 It adds a '.py' extension to the file if you don't do so yourself, and
1598 It adds a '.py' extension to the file if you don't do so yourself, and
1599 it asks for confirmation before overwriting existing files."""
1599 it asks for confirmation before overwriting existing files."""
1600
1600
1601 args = parameter_s.split()
1601 args = parameter_s.split()
1602 fname,ranges = args[0], args[1:]
1602 fname,ranges = args[0], args[1:]
1603 if not fname.endswith('.py'):
1603 if not fname.endswith('.py'):
1604 fname += '.py'
1604 fname += '.py'
1605 if os.path.isfile(fname):
1605 if os.path.isfile(fname):
1606 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1606 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1607 if ans.lower() not in ['y','yes']:
1607 if ans.lower() not in ['y','yes']:
1608 print 'Operation cancelled.'
1608 print 'Operation cancelled.'
1609 return
1609 return
1610 cmds = ''.join(self.extract_input_slices(ranges))
1610 cmds = ''.join(self.extract_input_slices(ranges))
1611 f = file(fname,'w')
1611 f = file(fname,'w')
1612 f.write(cmds)
1612 f.write(cmds)
1613 f.close()
1613 f.close()
1614 print 'The following commands were written to file `%s`:' % fname
1614 print 'The following commands were written to file `%s`:' % fname
1615 print cmds
1615 print cmds
1616
1616
1617 def magic_ed(self,parameter_s = ''):
1617 def magic_ed(self,parameter_s = ''):
1618 """Alias to %edit."""
1618 """Alias to %edit."""
1619 return self.magic_edit(parameter_s)
1619 return self.magic_edit(parameter_s)
1620
1620
1621 def magic_edit(self,parameter_s = '',last_call=['','']):
1621 def magic_edit(self,parameter_s = '',last_call=['','']):
1622 """Bring up an editor and execute the resulting code.
1622 """Bring up an editor and execute the resulting code.
1623
1623
1624 Usage:
1624 Usage:
1625 %edit [options] [args]
1625 %edit [options] [args]
1626
1626
1627 %edit runs IPython's editor hook. The default version of this hook is
1627 %edit runs IPython's editor hook. The default version of this hook is
1628 set to call the __IPYTHON__.rc.editor command. This is read from your
1628 set to call the __IPYTHON__.rc.editor command. This is read from your
1629 environment variable $EDITOR. If this isn't found, it will default to
1629 environment variable $EDITOR. If this isn't found, it will default to
1630 vi under Linux/Unix and to notepad under Windows. See the end of this
1630 vi under Linux/Unix and to notepad under Windows. See the end of this
1631 docstring for how to change the editor hook.
1631 docstring for how to change the editor hook.
1632
1632
1633 You can also set the value of this editor via the command line option
1633 You can also set the value of this editor via the command line option
1634 '-editor' or in your ipythonrc file. This is useful if you wish to use
1634 '-editor' or in your ipythonrc file. This is useful if you wish to use
1635 specifically for IPython an editor different from your typical default
1635 specifically for IPython an editor different from your typical default
1636 (and for Windows users who typically don't set environment variables).
1636 (and for Windows users who typically don't set environment variables).
1637
1637
1638 This command allows you to conveniently edit multi-line code right in
1638 This command allows you to conveniently edit multi-line code right in
1639 your IPython session.
1639 your IPython session.
1640
1640
1641 If called without arguments, %edit opens up an empty editor with a
1641 If called without arguments, %edit opens up an empty editor with a
1642 temporary file and will execute the contents of this file when you
1642 temporary file and will execute the contents of this file when you
1643 close it (don't forget to save it!).
1643 close it (don't forget to save it!).
1644
1644
1645 Options:
1645 Options:
1646
1646
1647 -p: this will call the editor with the same data as the previous time
1647 -p: this will call the editor with the same data as the previous time
1648 it was used, regardless of how long ago (in your current session) it
1648 it was used, regardless of how long ago (in your current session) it
1649 was.
1649 was.
1650
1650
1651 -x: do not execute the edited code immediately upon exit. This is
1651 -x: do not execute the edited code immediately upon exit. This is
1652 mainly useful if you are editing programs which need to be called with
1652 mainly useful if you are editing programs which need to be called with
1653 command line arguments, which you can then do using %run.
1653 command line arguments, which you can then do using %run.
1654
1654
1655 Arguments:
1655 Arguments:
1656
1656
1657 If arguments are given, the following possibilites exist:
1657 If arguments are given, the following possibilites exist:
1658
1658
1659 - The arguments are numbers or pairs of colon-separated numbers (like
1659 - The arguments are numbers or pairs of colon-separated numbers (like
1660 1 4:8 9). These are interpreted as lines of previous input to be
1660 1 4:8 9). These are interpreted as lines of previous input to be
1661 loaded into the editor. The syntax is the same of the %macro command.
1661 loaded into the editor. The syntax is the same of the %macro command.
1662
1662
1663 - If the argument doesn't start with a number, it is evaluated as a
1663 - If the argument doesn't start with a number, it is evaluated as a
1664 variable and its contents loaded into the editor. You can thus edit
1664 variable and its contents loaded into the editor. You can thus edit
1665 any string which contains python code (including the result of
1665 any string which contains python code (including the result of
1666 previous edits).
1666 previous edits).
1667
1667
1668 - If the argument is the name of an object (other than a string),
1668 - If the argument is the name of an object (other than a string),
1669 IPython will try to locate the file where it was defined and open the
1669 IPython will try to locate the file where it was defined and open the
1670 editor at the point where it is defined. You can use `%edit function`
1670 editor at the point where it is defined. You can use `%edit function`
1671 to load an editor exactly at the point where 'function' is defined,
1671 to load an editor exactly at the point where 'function' is defined,
1672 edit it and have the file be executed automatically.
1672 edit it and have the file be executed automatically.
1673
1673
1674 Note: opening at an exact line is only supported under Unix, and some
1674 Note: opening at an exact line is only supported under Unix, and some
1675 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1675 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1676 '+NUMBER' parameter necessary for this feature. Good editors like
1676 '+NUMBER' parameter necessary for this feature. Good editors like
1677 (X)Emacs, vi, jed, pico and joe all do.
1677 (X)Emacs, vi, jed, pico and joe all do.
1678
1678
1679 - If the argument is not found as a variable, IPython will look for a
1679 - If the argument is not found as a variable, IPython will look for a
1680 file with that name (adding .py if necessary) and load it into the
1680 file with that name (adding .py if necessary) and load it into the
1681 editor. It will execute its contents with execfile() when you exit,
1681 editor. It will execute its contents with execfile() when you exit,
1682 loading any code in the file into your interactive namespace.
1682 loading any code in the file into your interactive namespace.
1683
1683
1684 After executing your code, %edit will return as output the code you
1684 After executing your code, %edit will return as output the code you
1685 typed in the editor (except when it was an existing file). This way
1685 typed in the editor (except when it was an existing file). This way
1686 you can reload the code in further invocations of %edit as a variable,
1686 you can reload the code in further invocations of %edit as a variable,
1687 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1687 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1688 the output.
1688 the output.
1689
1689
1690 Note that %edit is also available through the alias %ed.
1690 Note that %edit is also available through the alias %ed.
1691
1691
1692 This is an example of creating a simple function inside the editor and
1692 This is an example of creating a simple function inside the editor and
1693 then modifying it. First, start up the editor:
1693 then modifying it. First, start up the editor:
1694
1694
1695 In [1]: ed\\
1695 In [1]: ed\\
1696 Editing... done. Executing edited code...\\
1696 Editing... done. Executing edited code...\\
1697 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1697 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1698
1698
1699 We can then call the function foo():
1699 We can then call the function foo():
1700
1700
1701 In [2]: foo()\\
1701 In [2]: foo()\\
1702 foo() was defined in an editing session
1702 foo() was defined in an editing session
1703
1703
1704 Now we edit foo. IPython automatically loads the editor with the
1704 Now we edit foo. IPython automatically loads the editor with the
1705 (temporary) file where foo() was previously defined:
1705 (temporary) file where foo() was previously defined:
1706
1706
1707 In [3]: ed foo\\
1707 In [3]: ed foo\\
1708 Editing... done. Executing edited code...
1708 Editing... done. Executing edited code...
1709
1709
1710 And if we call foo() again we get the modified version:
1710 And if we call foo() again we get the modified version:
1711
1711
1712 In [4]: foo()\\
1712 In [4]: foo()\\
1713 foo() has now been changed!
1713 foo() has now been changed!
1714
1714
1715 Here is an example of how to edit a code snippet successive
1715 Here is an example of how to edit a code snippet successive
1716 times. First we call the editor:
1716 times. First we call the editor:
1717
1717
1718 In [8]: ed\\
1718 In [8]: ed\\
1719 Editing... done. Executing edited code...\\
1719 Editing... done. Executing edited code...\\
1720 hello\\
1720 hello\\
1721 Out[8]: "print 'hello'\\n"
1721 Out[8]: "print 'hello'\\n"
1722
1722
1723 Now we call it again with the previous output (stored in _):
1723 Now we call it again with the previous output (stored in _):
1724
1724
1725 In [9]: ed _\\
1725 In [9]: ed _\\
1726 Editing... done. Executing edited code...\\
1726 Editing... done. Executing edited code...\\
1727 hello world\\
1727 hello world\\
1728 Out[9]: "print 'hello world'\\n"
1728 Out[9]: "print 'hello world'\\n"
1729
1729
1730 Now we call it with the output #8 (stored in _8, also as Out[8]):
1730 Now we call it with the output #8 (stored in _8, also as Out[8]):
1731
1731
1732 In [10]: ed _8\\
1732 In [10]: ed _8\\
1733 Editing... done. Executing edited code...\\
1733 Editing... done. Executing edited code...\\
1734 hello again\\
1734 hello again\\
1735 Out[10]: "print 'hello again'\\n"
1735 Out[10]: "print 'hello again'\\n"
1736
1736
1737
1737
1738 Changing the default editor hook:
1738 Changing the default editor hook:
1739
1739
1740 If you wish to write your own editor hook, you can put it in a
1740 If you wish to write your own editor hook, you can put it in a
1741 configuration file which you load at startup time. The default hook
1741 configuration file which you load at startup time. The default hook
1742 is defined in the IPython.hooks module, and you can use that as a
1742 is defined in the IPython.hooks module, and you can use that as a
1743 starting example for further modifications. That file also has
1743 starting example for further modifications. That file also has
1744 general instructions on how to set a new hook for use once you've
1744 general instructions on how to set a new hook for use once you've
1745 defined it."""
1745 defined it."""
1746
1746
1747 # FIXME: This function has become a convoluted mess. It needs a
1747 # FIXME: This function has become a convoluted mess. It needs a
1748 # ground-up rewrite with clean, simple logic.
1748 # ground-up rewrite with clean, simple logic.
1749
1749
1750 def make_filename(arg):
1750 def make_filename(arg):
1751 "Make a filename from the given args"
1751 "Make a filename from the given args"
1752 try:
1752 try:
1753 filename = get_py_filename(arg)
1753 filename = get_py_filename(arg)
1754 except IOError:
1754 except IOError:
1755 if args.endswith('.py'):
1755 if args.endswith('.py'):
1756 filename = arg
1756 filename = arg
1757 else:
1757 else:
1758 filename = None
1758 filename = None
1759 return filename
1759 return filename
1760
1760
1761 # custom exceptions
1761 # custom exceptions
1762 class DataIsObject(Exception): pass
1762 class DataIsObject(Exception): pass
1763
1763
1764 opts,args = self.parse_options(parameter_s,'px')
1764 opts,args = self.parse_options(parameter_s,'px')
1765
1765
1766 # Default line number value
1766 # Default line number value
1767 lineno = None
1767 lineno = None
1768 if opts.has_key('p'):
1768 if opts.has_key('p'):
1769 args = '_%s' % last_call[0]
1769 args = '_%s' % last_call[0]
1770 if not self.shell.user_ns.has_key(args):
1770 if not self.shell.user_ns.has_key(args):
1771 args = last_call[1]
1771 args = last_call[1]
1772
1772
1773 # use last_call to remember the state of the previous call, but don't
1773 # use last_call to remember the state of the previous call, but don't
1774 # let it be clobbered by successive '-p' calls.
1774 # let it be clobbered by successive '-p' calls.
1775 try:
1775 try:
1776 last_call[0] = self.shell.outputcache.prompt_count
1776 last_call[0] = self.shell.outputcache.prompt_count
1777 if not opts.has_key('p'):
1777 if not opts.has_key('p'):
1778 last_call[1] = parameter_s
1778 last_call[1] = parameter_s
1779 except:
1779 except:
1780 pass
1780 pass
1781
1781
1782 # by default this is done with temp files, except when the given
1782 # by default this is done with temp files, except when the given
1783 # arg is a filename
1783 # arg is a filename
1784 use_temp = 1
1784 use_temp = 1
1785
1785
1786 if re.match(r'\d',args):
1786 if re.match(r'\d',args):
1787 # Mode where user specifies ranges of lines, like in %macro.
1787 # Mode where user specifies ranges of lines, like in %macro.
1788 # This means that you can't edit files whose names begin with
1788 # This means that you can't edit files whose names begin with
1789 # numbers this way. Tough.
1789 # numbers this way. Tough.
1790 ranges = args.split()
1790 ranges = args.split()
1791 data = ''.join(self.extract_input_slices(ranges))
1791 data = ''.join(self.extract_input_slices(ranges))
1792 elif args.endswith('.py'):
1792 elif args.endswith('.py'):
1793 filename = make_filename(args)
1793 filename = make_filename(args)
1794 data = ''
1794 data = ''
1795 use_temp = 0
1795 use_temp = 0
1796 elif args:
1796 elif args:
1797 try:
1797 try:
1798 # Load the parameter given as a variable. If not a string,
1798 # Load the parameter given as a variable. If not a string,
1799 # process it as an object instead (below)
1799 # process it as an object instead (below)
1800
1800
1801 #print '*** args',args,'type',type(args) # dbg
1801 #print '*** args',args,'type',type(args) # dbg
1802 data = eval(args,self.shell.user_ns)
1802 data = eval(args,self.shell.user_ns)
1803 if not type(data) in StringTypes:
1803 if not type(data) in StringTypes:
1804 raise DataIsObject
1804 raise DataIsObject
1805 except (NameError,SyntaxError):
1805 except (NameError,SyntaxError):
1806 # given argument is not a variable, try as a filename
1806 # given argument is not a variable, try as a filename
1807 filename = make_filename(args)
1807 filename = make_filename(args)
1808 if filename is None:
1808 if filename is None:
1809 warn("Argument given (%s) can't be found as a variable "
1809 warn("Argument given (%s) can't be found as a variable "
1810 "or as a filename." % args)
1810 "or as a filename." % args)
1811 return
1811 return
1812 data = ''
1812 data = ''
1813 use_temp = 0
1813 use_temp = 0
1814 except DataIsObject:
1814 except DataIsObject:
1815 # For objects, try to edit the file where they are defined
1815 # For objects, try to edit the file where they are defined
1816 try:
1816 try:
1817 filename = inspect.getabsfile(data)
1817 filename = inspect.getabsfile(data)
1818 datafile = 1
1818 datafile = 1
1819 except TypeError:
1819 except TypeError:
1820 filename = make_filename(args)
1820 filename = make_filename(args)
1821 datafile = 1
1821 datafile = 1
1822 warn('Could not find file where `%s` is defined.\n'
1822 warn('Could not find file where `%s` is defined.\n'
1823 'Opening a file named `%s`' % (args,filename))
1823 'Opening a file named `%s`' % (args,filename))
1824 # Now, make sure we can actually read the source (if it was in
1824 # Now, make sure we can actually read the source (if it was in
1825 # a temp file it's gone by now).
1825 # a temp file it's gone by now).
1826 if datafile:
1826 if datafile:
1827 try:
1827 try:
1828 lineno = inspect.getsourcelines(data)[1]
1828 lineno = inspect.getsourcelines(data)[1]
1829 except IOError:
1829 except IOError:
1830 filename = make_filename(args)
1830 filename = make_filename(args)
1831 if filename is None:
1831 if filename is None:
1832 warn('The file `%s` where `%s` was defined cannot '
1832 warn('The file `%s` where `%s` was defined cannot '
1833 'be read.' % (filename,data))
1833 'be read.' % (filename,data))
1834 return
1834 return
1835 use_temp = 0
1835 use_temp = 0
1836 else:
1836 else:
1837 data = ''
1837 data = ''
1838
1838
1839 if use_temp:
1839 if use_temp:
1840 filename = tempfile.mktemp('.py')
1840 filename = tempfile.mktemp('.py')
1841 self.shell.tempfiles.append(filename)
1841 self.shell.tempfiles.append(filename)
1842
1842
1843 if data and use_temp:
1843 if data and use_temp:
1844 tmp_file = open(filename,'w')
1844 tmp_file = open(filename,'w')
1845 tmp_file.write(data)
1845 tmp_file.write(data)
1846 tmp_file.close()
1846 tmp_file.close()
1847
1847
1848 # do actual editing here
1848 # do actual editing here
1849 print 'Editing...',
1849 print 'Editing...',
1850 sys.stdout.flush()
1850 sys.stdout.flush()
1851 self.shell.hooks.editor(filename,lineno)
1851 self.shell.hooks.editor(filename,lineno)
1852 if opts.has_key('x'): # -x prevents actual execution
1852 if opts.has_key('x'): # -x prevents actual execution
1853 print
1853 print
1854 else:
1854 else:
1855 print 'done. Executing edited code...'
1855 print 'done. Executing edited code...'
1856 try:
1856 try:
1857 self.shell.safe_execfile(filename,self.shell.user_ns)
1857 self.shell.safe_execfile(filename,self.shell.user_ns)
1858 except IOError,msg:
1858 except IOError,msg:
1859 if msg.filename == filename:
1859 if msg.filename == filename:
1860 warn('File not found. Did you forget to save?')
1860 warn('File not found. Did you forget to save?')
1861 return
1861 return
1862 else:
1862 else:
1863 self.shell.showtraceback()
1863 self.shell.showtraceback()
1864 except:
1864 except:
1865 self.shell.showtraceback()
1865 self.shell.showtraceback()
1866 if use_temp:
1866 if use_temp:
1867 contents = open(filename).read()
1867 contents = open(filename).read()
1868 return contents
1868 return contents
1869
1869
1870 def magic_xmode(self,parameter_s = ''):
1870 def magic_xmode(self,parameter_s = ''):
1871 """Switch modes for the exception handlers.
1871 """Switch modes for the exception handlers.
1872
1872
1873 Valid modes: Plain, Context and Verbose.
1873 Valid modes: Plain, Context and Verbose.
1874
1874
1875 If called without arguments, acts as a toggle."""
1875 If called without arguments, acts as a toggle."""
1876
1876
1877 def xmode_switch_err(name):
1877 def xmode_switch_err(name):
1878 warn('Error changing %s exception modes.\n%s' %
1878 warn('Error changing %s exception modes.\n%s' %
1879 (name,sys.exc_info()[1]))
1879 (name,sys.exc_info()[1]))
1880
1880
1881 shell = self.shell
1881 shell = self.shell
1882 new_mode = parameter_s.strip().capitalize()
1882 new_mode = parameter_s.strip().capitalize()
1883 try:
1883 try:
1884 shell.InteractiveTB.set_mode(mode=new_mode)
1884 shell.InteractiveTB.set_mode(mode=new_mode)
1885 print 'Exception reporting mode:',shell.InteractiveTB.mode
1885 print 'Exception reporting mode:',shell.InteractiveTB.mode
1886 except:
1886 except:
1887 xmode_switch_err('user')
1887 xmode_switch_err('user')
1888
1888
1889 # threaded shells use a special handler in sys.excepthook
1889 # threaded shells use a special handler in sys.excepthook
1890 if shell.isthreaded:
1890 if shell.isthreaded:
1891 try:
1891 try:
1892 shell.sys_excepthook.set_mode(mode=new_mode)
1892 shell.sys_excepthook.set_mode(mode=new_mode)
1893 except:
1893 except:
1894 xmode_switch_err('threaded')
1894 xmode_switch_err('threaded')
1895
1895
1896 def magic_colors(self,parameter_s = ''):
1896 def magic_colors(self,parameter_s = ''):
1897 """Switch color scheme for prompts, info system and exception handlers.
1897 """Switch color scheme for prompts, info system and exception handlers.
1898
1898
1899 Currently implemented schemes: NoColor, Linux, LightBG.
1899 Currently implemented schemes: NoColor, Linux, LightBG.
1900
1900
1901 Color scheme names are not case-sensitive."""
1901 Color scheme names are not case-sensitive."""
1902
1902
1903 def color_switch_err(name):
1903 def color_switch_err(name):
1904 warn('Error changing %s color schemes.\n%s' %
1904 warn('Error changing %s color schemes.\n%s' %
1905 (name,sys.exc_info()[1]))
1905 (name,sys.exc_info()[1]))
1906
1906
1907
1907
1908 new_scheme = parameter_s.strip()
1908 new_scheme = parameter_s.strip()
1909 if not new_scheme:
1909 if not new_scheme:
1910 print 'You must specify a color scheme.'
1910 print 'You must specify a color scheme.'
1911 return
1911 return
1912 # Under Windows, check for Gary Bishop's readline, which is necessary
1912 # Under Windows, check for Gary Bishop's readline, which is necessary
1913 # for ANSI coloring
1913 # for ANSI coloring
1914 if os.name in ['nt','dos']:
1914 if os.name in ['nt','dos']:
1915 try:
1915 try:
1916 import readline
1916 import readline
1917 except ImportError:
1917 except ImportError:
1918 has_readline = 0
1918 has_readline = 0
1919 else:
1919 else:
1920 try:
1920 try:
1921 readline.GetOutputFile()
1921 readline.GetOutputFile()
1922 except AttributeError:
1922 except AttributeError:
1923 has_readline = 0
1923 has_readline = 0
1924 else:
1924 else:
1925 has_readline = 1
1925 has_readline = 1
1926 if not has_readline:
1926 if not has_readline:
1927 msg = """\
1927 msg = """\
1928 Proper color support under MS Windows requires Gary Bishop's readline library.
1928 Proper color support under MS Windows requires Gary Bishop's readline library.
1929 You can find it at:
1929 You can find it at:
1930 http://sourceforge.net/projects/uncpythontools
1930 http://sourceforge.net/projects/uncpythontools
1931 Gary's readline needs the ctypes module, from:
1931 Gary's readline needs the ctypes module, from:
1932 http://starship.python.net/crew/theller/ctypes
1932 http://starship.python.net/crew/theller/ctypes
1933
1933
1934 Defaulting color scheme to 'NoColor'"""
1934 Defaulting color scheme to 'NoColor'"""
1935 new_scheme = 'NoColor'
1935 new_scheme = 'NoColor'
1936 warn(msg)
1936 warn(msg)
1937 # local shortcut
1937 # local shortcut
1938 shell = self.shell
1938 shell = self.shell
1939
1939
1940 # Set prompt colors
1940 # Set prompt colors
1941 try:
1941 try:
1942 shell.outputcache.set_colors(new_scheme)
1942 shell.outputcache.set_colors(new_scheme)
1943 except:
1943 except:
1944 color_switch_err('prompt')
1944 color_switch_err('prompt')
1945 else:
1945 else:
1946 shell.rc.colors = \
1946 shell.rc.colors = \
1947 shell.outputcache.color_table.active_scheme_name
1947 shell.outputcache.color_table.active_scheme_name
1948 # Set exception colors
1948 # Set exception colors
1949 try:
1949 try:
1950 shell.InteractiveTB.set_colors(scheme = new_scheme)
1950 shell.InteractiveTB.set_colors(scheme = new_scheme)
1951 shell.SyntaxTB.set_colors(scheme = new_scheme)
1951 shell.SyntaxTB.set_colors(scheme = new_scheme)
1952 except:
1952 except:
1953 color_switch_err('exception')
1953 color_switch_err('exception')
1954
1954
1955 # threaded shells use a verbose traceback in sys.excepthook
1955 # threaded shells use a verbose traceback in sys.excepthook
1956 if shell.isthreaded:
1956 if shell.isthreaded:
1957 try:
1957 try:
1958 shell.sys_excepthook.set_colors(scheme=new_scheme)
1958 shell.sys_excepthook.set_colors(scheme=new_scheme)
1959 except:
1959 except:
1960 color_switch_err('system exception handler')
1960 color_switch_err('system exception handler')
1961
1961
1962 # Set info (for 'object?') colors
1962 # Set info (for 'object?') colors
1963 if shell.rc.color_info:
1963 if shell.rc.color_info:
1964 try:
1964 try:
1965 shell.inspector.set_active_scheme(new_scheme)
1965 shell.inspector.set_active_scheme(new_scheme)
1966 except:
1966 except:
1967 color_switch_err('object inspector')
1967 color_switch_err('object inspector')
1968 else:
1968 else:
1969 shell.inspector.set_active_scheme('NoColor')
1969 shell.inspector.set_active_scheme('NoColor')
1970
1970
1971 def magic_color_info(self,parameter_s = ''):
1971 def magic_color_info(self,parameter_s = ''):
1972 """Toggle color_info.
1972 """Toggle color_info.
1973
1973
1974 The color_info configuration parameter controls whether colors are
1974 The color_info configuration parameter controls whether colors are
1975 used for displaying object details (by things like %psource, %pfile or
1975 used for displaying object details (by things like %psource, %pfile or
1976 the '?' system). This function toggles this value with each call.
1976 the '?' system). This function toggles this value with each call.
1977
1977
1978 Note that unless you have a fairly recent pager (less works better
1978 Note that unless you have a fairly recent pager (less works better
1979 than more) in your system, using colored object information displays
1979 than more) in your system, using colored object information displays
1980 will not work properly. Test it and see."""
1980 will not work properly. Test it and see."""
1981
1981
1982 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1982 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1983 self.magic_colors(self.shell.rc.colors)
1983 self.magic_colors(self.shell.rc.colors)
1984 print 'Object introspection functions have now coloring:',
1984 print 'Object introspection functions have now coloring:',
1985 print ['OFF','ON'][self.shell.rc.color_info]
1985 print ['OFF','ON'][self.shell.rc.color_info]
1986
1986
1987 def magic_Pprint(self, parameter_s=''):
1987 def magic_Pprint(self, parameter_s=''):
1988 """Toggle pretty printing on/off."""
1988 """Toggle pretty printing on/off."""
1989
1989
1990 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1990 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1991 print 'Pretty printing has been turned', \
1991 print 'Pretty printing has been turned', \
1992 ['OFF','ON'][self.shell.outputcache.Pprint]
1992 ['OFF','ON'][self.shell.outputcache.Pprint]
1993
1993
1994 def magic_exit(self, parameter_s=''):
1994 def magic_exit(self, parameter_s=''):
1995 """Exit IPython, confirming if configured to do so.
1995 """Exit IPython, confirming if configured to do so.
1996
1996
1997 You can configure whether IPython asks for confirmation upon exit by
1997 You can configure whether IPython asks for confirmation upon exit by
1998 setting the confirm_exit flag in the ipythonrc file."""
1998 setting the confirm_exit flag in the ipythonrc file."""
1999
1999
2000 self.shell.exit()
2000 self.shell.exit()
2001
2001
2002 def magic_quit(self, parameter_s=''):
2002 def magic_quit(self, parameter_s=''):
2003 """Exit IPython, confirming if configured to do so (like %exit)"""
2003 """Exit IPython, confirming if configured to do so (like %exit)"""
2004
2004
2005 self.shell.exit()
2005 self.shell.exit()
2006
2006
2007 def magic_Exit(self, parameter_s=''):
2007 def magic_Exit(self, parameter_s=''):
2008 """Exit IPython without confirmation."""
2008 """Exit IPython without confirmation."""
2009
2009
2010 self.shell.exit_now = True
2010 self.shell.exit_now = True
2011
2011
2012 def magic_Quit(self, parameter_s=''):
2012 def magic_Quit(self, parameter_s=''):
2013 """Exit IPython without confirmation (like %Exit)."""
2013 """Exit IPython without confirmation (like %Exit)."""
2014
2014
2015 self.shell.exit_now = True
2015 self.shell.exit_now = True
2016
2016
2017 #......................................................................
2017 #......................................................................
2018 # Functions to implement unix shell-type things
2018 # Functions to implement unix shell-type things
2019
2019
2020 def magic_alias(self, parameter_s = ''):
2020 def magic_alias(self, parameter_s = ''):
2021 """Define an alias for a system command.
2021 """Define an alias for a system command.
2022
2022
2023 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2023 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2024
2024
2025 Then, typing 'alias_name params' will execute the system command 'cmd
2025 Then, typing 'alias_name params' will execute the system command 'cmd
2026 params' (from your underlying operating system).
2026 params' (from your underlying operating system).
2027
2027
2028 Aliases have lower precedence than magic functions and Python normal
2028 Aliases have lower precedence than magic functions and Python normal
2029 variables, so if 'foo' is both a Python variable and an alias, the
2029 variables, so if 'foo' is both a Python variable and an alias, the
2030 alias can not be executed until 'del foo' removes the Python variable.
2030 alias can not be executed until 'del foo' removes the Python variable.
2031
2031
2032 You can use the %l specifier in an alias definition to represent the
2032 You can use the %l specifier in an alias definition to represent the
2033 whole line when the alias is called. For example:
2033 whole line when the alias is called. For example:
2034
2034
2035 In [2]: alias all echo "Input in brackets: <%l>"\\
2035 In [2]: alias all echo "Input in brackets: <%l>"\\
2036 In [3]: all hello world\\
2036 In [3]: all hello world\\
2037 Input in brackets: <hello world>
2037 Input in brackets: <hello world>
2038
2038
2039 You can also define aliases with parameters using %s specifiers (one
2039 You can also define aliases with parameters using %s specifiers (one
2040 per parameter):
2040 per parameter):
2041
2041
2042 In [1]: alias parts echo first %s second %s\\
2042 In [1]: alias parts echo first %s second %s\\
2043 In [2]: %parts A B\\
2043 In [2]: %parts A B\\
2044 first A second B\\
2044 first A second B\\
2045 In [3]: %parts A\\
2045 In [3]: %parts A\\
2046 Incorrect number of arguments: 2 expected.\\
2046 Incorrect number of arguments: 2 expected.\\
2047 parts is an alias to: 'echo first %s second %s'
2047 parts is an alias to: 'echo first %s second %s'
2048
2048
2049 Note that %l and %s are mutually exclusive. You can only use one or
2049 Note that %l and %s are mutually exclusive. You can only use one or
2050 the other in your aliases.
2050 the other in your aliases.
2051
2051
2052 Aliases expand Python variables just like system calls using ! or !!
2052 Aliases expand Python variables just like system calls using ! or !!
2053 do: all expressions prefixed with '$' get expanded. For details of
2053 do: all expressions prefixed with '$' get expanded. For details of
2054 the semantic rules, see PEP-215:
2054 the semantic rules, see PEP-215:
2055 http://www.python.org/peps/pep-0215.html. This is the library used by
2055 http://www.python.org/peps/pep-0215.html. This is the library used by
2056 IPython for variable expansion. If you want to access a true shell
2056 IPython for variable expansion. If you want to access a true shell
2057 variable, an extra $ is necessary to prevent its expansion by IPython:
2057 variable, an extra $ is necessary to prevent its expansion by IPython:
2058
2058
2059 In [6]: alias show echo\\
2059 In [6]: alias show echo\\
2060 In [7]: PATH='A Python string'\\
2060 In [7]: PATH='A Python string'\\
2061 In [8]: show $PATH\\
2061 In [8]: show $PATH\\
2062 A Python string\\
2062 A Python string\\
2063 In [9]: show $$PATH\\
2063 In [9]: show $$PATH\\
2064 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2064 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2065
2065
2066 You can use the alias facility to acess all of $PATH. See the %rehash
2066 You can use the alias facility to acess all of $PATH. See the %rehash
2067 and %rehashx functions, which automatically create aliases for the
2067 and %rehashx functions, which automatically create aliases for the
2068 contents of your $PATH.
2068 contents of your $PATH.
2069
2069
2070 If called with no parameters, %alias prints the current alias table."""
2070 If called with no parameters, %alias prints the current alias table."""
2071
2071
2072 par = parameter_s.strip()
2072 par = parameter_s.strip()
2073 if not par:
2073 if not par:
2074 if self.shell.rc.automagic:
2074 if self.shell.rc.automagic:
2075 prechar = ''
2075 prechar = ''
2076 else:
2076 else:
2077 prechar = self.shell.ESC_MAGIC
2077 prechar = self.shell.ESC_MAGIC
2078 print 'Alias\t\tSystem Command\n'+'-'*30
2078 print 'Alias\t\tSystem Command\n'+'-'*30
2079 atab = self.shell.alias_table
2079 atab = self.shell.alias_table
2080 aliases = atab.keys()
2080 aliases = atab.keys()
2081 aliases.sort()
2081 aliases.sort()
2082 for alias in aliases:
2082 for alias in aliases:
2083 print prechar+alias+'\t\t'+atab[alias][1]
2083 print prechar+alias+'\t\t'+atab[alias][1]
2084 print '-'*30+'\nTotal number of aliases:',len(aliases)
2084 print '-'*30+'\nTotal number of aliases:',len(aliases)
2085 return
2085 return
2086 try:
2086 try:
2087 alias,cmd = par.split(None,1)
2087 alias,cmd = par.split(None,1)
2088 except:
2088 except:
2089 print OInspect.getdoc(self.magic_alias)
2089 print OInspect.getdoc(self.magic_alias)
2090 else:
2090 else:
2091 nargs = cmd.count('%s')
2091 nargs = cmd.count('%s')
2092 if nargs>0 and cmd.find('%l')>=0:
2092 if nargs>0 and cmd.find('%l')>=0:
2093 error('The %s and %l specifiers are mutually exclusive '
2093 error('The %s and %l specifiers are mutually exclusive '
2094 'in alias definitions.')
2094 'in alias definitions.')
2095 else: # all looks OK
2095 else: # all looks OK
2096 self.shell.alias_table[alias] = (nargs,cmd)
2096 self.shell.alias_table[alias] = (nargs,cmd)
2097 self.shell.alias_table_validate(verbose=1)
2097 self.shell.alias_table_validate(verbose=1)
2098 # end magic_alias
2098 # end magic_alias
2099
2099
2100 def magic_unalias(self, parameter_s = ''):
2100 def magic_unalias(self, parameter_s = ''):
2101 """Remove an alias"""
2101 """Remove an alias"""
2102
2102
2103 aname = parameter_s.strip()
2103 aname = parameter_s.strip()
2104 if aname in self.shell.alias_table:
2104 if aname in self.shell.alias_table:
2105 del self.shell.alias_table[aname]
2105 del self.shell.alias_table[aname]
2106
2106
2107 def magic_rehash(self, parameter_s = ''):
2107 def magic_rehash(self, parameter_s = ''):
2108 """Update the alias table with all entries in $PATH.
2108 """Update the alias table with all entries in $PATH.
2109
2109
2110 This version does no checks on execute permissions or whether the
2110 This version does no checks on execute permissions or whether the
2111 contents of $PATH are truly files (instead of directories or something
2111 contents of $PATH are truly files (instead of directories or something
2112 else). For such a safer (but slower) version, use %rehashx."""
2112 else). For such a safer (but slower) version, use %rehashx."""
2113
2113
2114 # This function (and rehashx) manipulate the alias_table directly
2114 # This function (and rehashx) manipulate the alias_table directly
2115 # rather than calling magic_alias, for speed reasons. A rehash on a
2115 # rather than calling magic_alias, for speed reasons. A rehash on a
2116 # typical Linux box involves several thousand entries, so efficiency
2116 # typical Linux box involves several thousand entries, so efficiency
2117 # here is a top concern.
2117 # here is a top concern.
2118
2118
2119 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2119 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2120 alias_table = self.shell.alias_table
2120 alias_table = self.shell.alias_table
2121 for pdir in path:
2121 for pdir in path:
2122 for ff in os.listdir(pdir):
2122 for ff in os.listdir(pdir):
2123 # each entry in the alias table must be (N,name), where
2123 # each entry in the alias table must be (N,name), where
2124 # N is the number of positional arguments of the alias.
2124 # N is the number of positional arguments of the alias.
2125 alias_table[ff] = (0,ff)
2125 alias_table[ff] = (0,ff)
2126 # Make sure the alias table doesn't contain keywords or builtins
2126 # Make sure the alias table doesn't contain keywords or builtins
2127 self.shell.alias_table_validate()
2127 self.shell.alias_table_validate()
2128 # Call again init_auto_alias() so we get 'rm -i' and other modified
2128 # Call again init_auto_alias() so we get 'rm -i' and other modified
2129 # aliases since %rehash will probably clobber them
2129 # aliases since %rehash will probably clobber them
2130 self.shell.init_auto_alias()
2130 self.shell.init_auto_alias()
2131
2131
2132 def magic_rehashx(self, parameter_s = ''):
2132 def magic_rehashx(self, parameter_s = ''):
2133 """Update the alias table with all executable files in $PATH.
2133 """Update the alias table with all executable files in $PATH.
2134
2134
2135 This version explicitly checks that every entry in $PATH is a file
2135 This version explicitly checks that every entry in $PATH is a file
2136 with execute access (os.X_OK), so it is much slower than %rehash.
2136 with execute access (os.X_OK), so it is much slower than %rehash.
2137
2137
2138 Under Windows, it checks executability as a match agains a
2138 Under Windows, it checks executability as a match agains a
2139 '|'-separated string of extensions, stored in the IPython config
2139 '|'-separated string of extensions, stored in the IPython config
2140 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2140 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2141
2141
2142 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2142 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2143 alias_table = self.shell.alias_table
2143 alias_table = self.shell.alias_table
2144
2144
2145 if os.name == 'posix':
2145 if os.name == 'posix':
2146 isexec = lambda fname:os.path.isfile(fname) and \
2146 isexec = lambda fname:os.path.isfile(fname) and \
2147 os.access(fname,os.X_OK)
2147 os.access(fname,os.X_OK)
2148 else:
2148 else:
2149
2149
2150 try:
2150 try:
2151 winext = os.environ['pathext'].replace(';','|').replace('.','')
2151 winext = os.environ['pathext'].replace(';','|').replace('.','')
2152 except KeyError:
2152 except KeyError:
2153 winext = 'exe|com|bat'
2153 winext = 'exe|com|bat'
2154
2154
2155 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2155 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2156 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2156 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2157 savedir = os.getcwd()
2157 savedir = os.getcwd()
2158 try:
2158 try:
2159 # write the whole loop for posix/Windows so we don't have an if in
2159 # write the whole loop for posix/Windows so we don't have an if in
2160 # the innermost part
2160 # the innermost part
2161 if os.name == 'posix':
2161 if os.name == 'posix':
2162 for pdir in path:
2162 for pdir in path:
2163 os.chdir(pdir)
2163 os.chdir(pdir)
2164 for ff in os.listdir(pdir):
2164 for ff in os.listdir(pdir):
2165 if isexec(ff):
2165 if isexec(ff):
2166 # each entry in the alias table must be (N,name),
2166 # each entry in the alias table must be (N,name),
2167 # where N is the number of positional arguments of the
2167 # where N is the number of positional arguments of the
2168 # alias.
2168 # alias.
2169 alias_table[ff] = (0,ff)
2169 alias_table[ff] = (0,ff)
2170 else:
2170 else:
2171 for pdir in path:
2171 for pdir in path:
2172 os.chdir(pdir)
2172 os.chdir(pdir)
2173 for ff in os.listdir(pdir):
2173 for ff in os.listdir(pdir):
2174 if isexec(ff):
2174 if isexec(ff):
2175 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2175 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2176 # Make sure the alias table doesn't contain keywords or builtins
2176 # Make sure the alias table doesn't contain keywords or builtins
2177 self.shell.alias_table_validate()
2177 self.shell.alias_table_validate()
2178 # Call again init_auto_alias() so we get 'rm -i' and other
2178 # Call again init_auto_alias() so we get 'rm -i' and other
2179 # modified aliases since %rehashx will probably clobber them
2179 # modified aliases since %rehashx will probably clobber them
2180 self.shell.init_auto_alias()
2180 self.shell.init_auto_alias()
2181 finally:
2181 finally:
2182 os.chdir(savedir)
2182 os.chdir(savedir)
2183
2183
2184 def magic_pwd(self, parameter_s = ''):
2184 def magic_pwd(self, parameter_s = ''):
2185 """Return the current working directory path."""
2185 """Return the current working directory path."""
2186 return os.getcwd()
2186 return os.getcwd()
2187
2187
2188 def magic_cd(self, parameter_s=''):
2188 def magic_cd(self, parameter_s=''):
2189 """Change the current working directory.
2189 """Change the current working directory.
2190
2190
2191 This command automatically maintains an internal list of directories
2191 This command automatically maintains an internal list of directories
2192 you visit during your IPython session, in the variable _dh. The
2192 you visit during your IPython session, in the variable _dh. The
2193 command %dhist shows this history nicely formatted.
2193 command %dhist shows this history nicely formatted.
2194
2194
2195 Usage:
2195 Usage:
2196
2196
2197 cd 'dir': changes to directory 'dir'.
2197 cd 'dir': changes to directory 'dir'.
2198
2198
2199 cd -: changes to the last visited directory.
2199 cd -: changes to the last visited directory.
2200
2200
2201 cd -<n>: changes to the n-th directory in the directory history.
2201 cd -<n>: changes to the n-th directory in the directory history.
2202
2202
2203 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2203 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2204 (note: cd <bookmark_name> is enough if there is no
2204 (note: cd <bookmark_name> is enough if there is no
2205 directory <bookmark_name>, but a bookmark with the name exists.)
2205 directory <bookmark_name>, but a bookmark with the name exists.)
2206
2206
2207 Options:
2207 Options:
2208
2208
2209 -q: quiet. Do not print the working directory after the cd command is
2209 -q: quiet. Do not print the working directory after the cd command is
2210 executed. By default IPython's cd command does print this directory,
2210 executed. By default IPython's cd command does print this directory,
2211 since the default prompts do not display path information.
2211 since the default prompts do not display path information.
2212
2212
2213 Note that !cd doesn't work for this purpose because the shell where
2213 Note that !cd doesn't work for this purpose because the shell where
2214 !command runs is immediately discarded after executing 'command'."""
2214 !command runs is immediately discarded after executing 'command'."""
2215
2215
2216 parameter_s = parameter_s.strip()
2216 parameter_s = parameter_s.strip()
2217 bkms = self.shell.persist.get("bookmarks",{})
2217 bkms = self.shell.persist.get("bookmarks",{})
2218
2218
2219 numcd = re.match(r'(-)(\d+)$',parameter_s)
2219 numcd = re.match(r'(-)(\d+)$',parameter_s)
2220 # jump in directory history by number
2220 # jump in directory history by number
2221 if numcd:
2221 if numcd:
2222 nn = int(numcd.group(2))
2222 nn = int(numcd.group(2))
2223 try:
2223 try:
2224 ps = self.shell.user_ns['_dh'][nn]
2224 ps = self.shell.user_ns['_dh'][nn]
2225 except IndexError:
2225 except IndexError:
2226 print 'The requested directory does not exist in history.'
2226 print 'The requested directory does not exist in history.'
2227 return
2227 return
2228 else:
2228 else:
2229 opts = {}
2229 opts = {}
2230 else:
2230 else:
2231 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2231 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2232 # jump to previous
2232 # jump to previous
2233 if ps == '-':
2233 if ps == '-':
2234 try:
2234 try:
2235 ps = self.shell.user_ns['_dh'][-2]
2235 ps = self.shell.user_ns['_dh'][-2]
2236 except IndexError:
2236 except IndexError:
2237 print 'No previous directory to change to.'
2237 print 'No previous directory to change to.'
2238 return
2238 return
2239 # jump to bookmark
2239 # jump to bookmark
2240 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2240 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2241 if bkms.has_key(ps):
2241 if bkms.has_key(ps):
2242 target = bkms[ps]
2242 target = bkms[ps]
2243 print '(bookmark:%s) -> %s' % (ps,target)
2243 print '(bookmark:%s) -> %s' % (ps,target)
2244 ps = target
2244 ps = target
2245 else:
2245 else:
2246 if bkms:
2246 if bkms:
2247 error("Bookmark '%s' not found. "
2247 error("Bookmark '%s' not found. "
2248 "Use '%bookmark -l' to see your bookmarks." % ps)
2248 "Use '%bookmark -l' to see your bookmarks." % ps)
2249 else:
2249 else:
2250 print "Bookmarks not set - use %bookmark <bookmarkname>"
2250 print "Bookmarks not set - use %bookmark <bookmarkname>"
2251 return
2251 return
2252
2252
2253 # at this point ps should point to the target dir
2253 # at this point ps should point to the target dir
2254 if ps:
2254 if ps:
2255 try:
2255 try:
2256 os.chdir(os.path.expanduser(ps))
2256 os.chdir(os.path.expanduser(ps))
2257 except OSError:
2257 except OSError:
2258 print sys.exc_info()[1]
2258 print sys.exc_info()[1]
2259 else:
2259 else:
2260 self.shell.user_ns['_dh'].append(os.getcwd())
2260 self.shell.user_ns['_dh'].append(os.getcwd())
2261 else:
2261 else:
2262 os.chdir(self.shell.home_dir)
2262 os.chdir(self.shell.home_dir)
2263 self.shell.user_ns['_dh'].append(os.getcwd())
2263 self.shell.user_ns['_dh'].append(os.getcwd())
2264 if not 'q' in opts:
2264 if not 'q' in opts:
2265 print self.shell.user_ns['_dh'][-1]
2265 print self.shell.user_ns['_dh'][-1]
2266
2266
2267 def magic_dhist(self, parameter_s=''):
2267 def magic_dhist(self, parameter_s=''):
2268 """Print your history of visited directories.
2268 """Print your history of visited directories.
2269
2269
2270 %dhist -> print full history\\
2270 %dhist -> print full history\\
2271 %dhist n -> print last n entries only\\
2271 %dhist n -> print last n entries only\\
2272 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2272 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2273
2273
2274 This history is automatically maintained by the %cd command, and
2274 This history is automatically maintained by the %cd command, and
2275 always available as the global list variable _dh. You can use %cd -<n>
2275 always available as the global list variable _dh. You can use %cd -<n>
2276 to go to directory number <n>."""
2276 to go to directory number <n>."""
2277
2277
2278 dh = self.shell.user_ns['_dh']
2278 dh = self.shell.user_ns['_dh']
2279 if parameter_s:
2279 if parameter_s:
2280 try:
2280 try:
2281 args = map(int,parameter_s.split())
2281 args = map(int,parameter_s.split())
2282 except:
2282 except:
2283 self.arg_err(Magic.magic_dhist)
2283 self.arg_err(Magic.magic_dhist)
2284 return
2284 return
2285 if len(args) == 1:
2285 if len(args) == 1:
2286 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2286 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2287 elif len(args) == 2:
2287 elif len(args) == 2:
2288 ini,fin = args
2288 ini,fin = args
2289 else:
2289 else:
2290 self.arg_err(Magic.magic_dhist)
2290 self.arg_err(Magic.magic_dhist)
2291 return
2291 return
2292 else:
2292 else:
2293 ini,fin = 0,len(dh)
2293 ini,fin = 0,len(dh)
2294 nlprint(dh,
2294 nlprint(dh,
2295 header = 'Directory history (kept in _dh)',
2295 header = 'Directory history (kept in _dh)',
2296 start=ini,stop=fin)
2296 start=ini,stop=fin)
2297
2297
2298 def magic_env(self, parameter_s=''):
2298 def magic_env(self, parameter_s=''):
2299 """List environment variables."""
2299 """List environment variables."""
2300
2300
2301 return os.environ.data
2301 return os.environ.data
2302
2302
2303 def magic_pushd(self, parameter_s=''):
2303 def magic_pushd(self, parameter_s=''):
2304 """Place the current dir on stack and change directory.
2304 """Place the current dir on stack and change directory.
2305
2305
2306 Usage:\\
2306 Usage:\\
2307 %pushd ['dirname']
2307 %pushd ['dirname']
2308
2308
2309 %pushd with no arguments does a %pushd to your home directory.
2309 %pushd with no arguments does a %pushd to your home directory.
2310 """
2310 """
2311 if parameter_s == '': parameter_s = '~'
2311 if parameter_s == '': parameter_s = '~'
2312 dir_s = self.shell.dir_stack
2312 dir_s = self.shell.dir_stack
2313 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2313 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2314 os.path.expanduser(self.shell.dir_stack[0]):
2314 os.path.expanduser(self.shell.dir_stack[0]):
2315 try:
2315 try:
2316 self.magic_cd(parameter_s)
2316 self.magic_cd(parameter_s)
2317 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2317 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2318 self.magic_dirs()
2318 self.magic_dirs()
2319 except:
2319 except:
2320 print 'Invalid directory'
2320 print 'Invalid directory'
2321 else:
2321 else:
2322 print 'You are already there!'
2322 print 'You are already there!'
2323
2323
2324 def magic_popd(self, parameter_s=''):
2324 def magic_popd(self, parameter_s=''):
2325 """Change to directory popped off the top of the stack.
2325 """Change to directory popped off the top of the stack.
2326 """
2326 """
2327 if len (self.shell.dir_stack) > 1:
2327 if len (self.shell.dir_stack) > 1:
2328 self.shell.dir_stack.pop(0)
2328 self.shell.dir_stack.pop(0)
2329 self.magic_cd(self.shell.dir_stack[0])
2329 self.magic_cd(self.shell.dir_stack[0])
2330 print self.shell.dir_stack[0]
2330 print self.shell.dir_stack[0]
2331 else:
2331 else:
2332 print "You can't remove the starting directory from the stack:",\
2332 print "You can't remove the starting directory from the stack:",\
2333 self.shell.dir_stack
2333 self.shell.dir_stack
2334
2334
2335 def magic_dirs(self, parameter_s=''):
2335 def magic_dirs(self, parameter_s=''):
2336 """Return the current directory stack."""
2336 """Return the current directory stack."""
2337
2337
2338 return self.shell.dir_stack[:]
2338 return self.shell.dir_stack[:]
2339
2339
2340 def magic_sc(self, parameter_s=''):
2340 def magic_sc(self, parameter_s=''):
2341 """Shell capture - execute a shell command and capture its output.
2341 """Shell capture - execute a shell command and capture its output.
2342
2342
2343 %sc [options] varname=command
2343 %sc [options] varname=command
2344
2344
2345 IPython will run the given command using commands.getoutput(), and
2345 IPython will run the given command using commands.getoutput(), and
2346 will then update the user's interactive namespace with a variable
2346 will then update the user's interactive namespace with a variable
2347 called varname, containing the value of the call. Your command can
2347 called varname, containing the value of the call. Your command can
2348 contain shell wildcards, pipes, etc.
2348 contain shell wildcards, pipes, etc.
2349
2349
2350 The '=' sign in the syntax is mandatory, and the variable name you
2350 The '=' sign in the syntax is mandatory, and the variable name you
2351 supply must follow Python's standard conventions for valid names.
2351 supply must follow Python's standard conventions for valid names.
2352
2352
2353 Options:
2353 Options:
2354
2354
2355 -l: list output. Split the output on newlines into a list before
2355 -l: list output. Split the output on newlines into a list before
2356 assigning it to the given variable. By default the output is stored
2356 assigning it to the given variable. By default the output is stored
2357 as a single string.
2357 as a single string.
2358
2358
2359 -v: verbose. Print the contents of the variable.
2359 -v: verbose. Print the contents of the variable.
2360
2360
2361 In most cases you should not need to split as a list, because the
2361 In most cases you should not need to split as a list, because the
2362 returned value is a special type of string which can automatically
2362 returned value is a special type of string which can automatically
2363 provide its contents either as a list (split on newlines) or as a
2363 provide its contents either as a list (split on newlines) or as a
2364 space-separated string. These are convenient, respectively, either
2364 space-separated string. These are convenient, respectively, either
2365 for sequential processing or to be passed to a shell command.
2365 for sequential processing or to be passed to a shell command.
2366
2366
2367 For example:
2367 For example:
2368
2368
2369 # Capture into variable a
2369 # Capture into variable a
2370 In [9]: sc a=ls *py
2370 In [9]: sc a=ls *py
2371
2371
2372 # a is a string with embedded newlines
2372 # a is a string with embedded newlines
2373 In [10]: a
2373 In [10]: a
2374 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2374 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2375
2375
2376 # which can be seen as a list:
2376 # which can be seen as a list:
2377 In [11]: a.l
2377 In [11]: a.l
2378 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2378 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2379
2379
2380 # or as a whitespace-separated string:
2380 # or as a whitespace-separated string:
2381 In [12]: a.s
2381 In [12]: a.s
2382 Out[12]: 'setup.py win32_manual_post_install.py'
2382 Out[12]: 'setup.py win32_manual_post_install.py'
2383
2383
2384 # a.s is useful to pass as a single command line:
2384 # a.s is useful to pass as a single command line:
2385 In [13]: !wc -l $a.s
2385 In [13]: !wc -l $a.s
2386 146 setup.py
2386 146 setup.py
2387 130 win32_manual_post_install.py
2387 130 win32_manual_post_install.py
2388 276 total
2388 276 total
2389
2389
2390 # while the list form is useful to loop over:
2390 # while the list form is useful to loop over:
2391 In [14]: for f in a.l:
2391 In [14]: for f in a.l:
2392 ....: !wc -l $f
2392 ....: !wc -l $f
2393 ....:
2393 ....:
2394 146 setup.py
2394 146 setup.py
2395 130 win32_manual_post_install.py
2395 130 win32_manual_post_install.py
2396
2396
2397 Similiarly, the lists returned by the -l option are also special, in
2397 Similiarly, the lists returned by the -l option are also special, in
2398 the sense that you can equally invoke the .s attribute on them to
2398 the sense that you can equally invoke the .s attribute on them to
2399 automatically get a whitespace-separated string from their contents:
2399 automatically get a whitespace-separated string from their contents:
2400
2400
2401 In [1]: sc -l b=ls *py
2401 In [1]: sc -l b=ls *py
2402
2402
2403 In [2]: b
2403 In [2]: b
2404 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2404 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2405
2405
2406 In [3]: b.s
2406 In [3]: b.s
2407 Out[3]: 'setup.py win32_manual_post_install.py'
2407 Out[3]: 'setup.py win32_manual_post_install.py'
2408
2408
2409 In summary, both the lists and strings used for ouptut capture have
2409 In summary, both the lists and strings used for ouptut capture have
2410 the following special attributes:
2410 the following special attributes:
2411
2411
2412 .l (or .list) : value as list.
2412 .l (or .list) : value as list.
2413 .n (or .nlstr): value as newline-separated string.
2413 .n (or .nlstr): value as newline-separated string.
2414 .s (or .spstr): value as space-separated string.
2414 .s (or .spstr): value as space-separated string.
2415 """
2415 """
2416
2416
2417 opts,args = self.parse_options(parameter_s,'lv')
2417 opts,args = self.parse_options(parameter_s,'lv')
2418 # Try to get a variable name and command to run
2418 # Try to get a variable name and command to run
2419 try:
2419 try:
2420 # the variable name must be obtained from the parse_options
2420 # the variable name must be obtained from the parse_options
2421 # output, which uses shlex.split to strip options out.
2421 # output, which uses shlex.split to strip options out.
2422 var,_ = args.split('=',1)
2422 var,_ = args.split('=',1)
2423 var = var.strip()
2423 var = var.strip()
2424 # But the the command has to be extracted from the original input
2424 # But the the command has to be extracted from the original input
2425 # parameter_s, not on what parse_options returns, to avoid the
2425 # parameter_s, not on what parse_options returns, to avoid the
2426 # quote stripping which shlex.split performs on it.
2426 # quote stripping which shlex.split performs on it.
2427 _,cmd = parameter_s.split('=',1)
2427 _,cmd = parameter_s.split('=',1)
2428 except ValueError:
2428 except ValueError:
2429 var,cmd = '',''
2429 var,cmd = '',''
2430 if not var:
2430 if not var:
2431 error('you must specify a variable to assign the command to.')
2431 error('you must specify a variable to assign the command to.')
2432 return
2432 return
2433 # If all looks ok, proceed
2433 # If all looks ok, proceed
2434 out,err = self.shell.getoutputerror(cmd)
2434 out,err = self.shell.getoutputerror(cmd)
2435 if err:
2435 if err:
2436 print >> Term.cerr,err
2436 print >> Term.cerr,err
2437 if opts.has_key('l'):
2437 if opts.has_key('l'):
2438 out = SList(out.split('\n'))
2438 out = SList(out.split('\n'))
2439 else:
2439 else:
2440 out = LSString(out)
2440 out = LSString(out)
2441 if opts.has_key('v'):
2441 if opts.has_key('v'):
2442 print '%s ==\n%s' % (var,pformat(out))
2442 print '%s ==\n%s' % (var,pformat(out))
2443 self.shell.user_ns.update({var:out})
2443 self.shell.user_ns.update({var:out})
2444
2444
2445 def magic_sx(self, parameter_s=''):
2445 def magic_sx(self, parameter_s=''):
2446 """Shell execute - run a shell command and capture its output.
2446 """Shell execute - run a shell command and capture its output.
2447
2447
2448 %sx command
2448 %sx command
2449
2449
2450 IPython will run the given command using commands.getoutput(), and
2450 IPython will run the given command using commands.getoutput(), and
2451 return the result formatted as a list (split on '\\n'). Since the
2451 return the result formatted as a list (split on '\\n'). Since the
2452 output is _returned_, it will be stored in ipython's regular output
2452 output is _returned_, it will be stored in ipython's regular output
2453 cache Out[N] and in the '_N' automatic variables.
2453 cache Out[N] and in the '_N' automatic variables.
2454
2454
2455 Notes:
2455 Notes:
2456
2456
2457 1) If an input line begins with '!!', then %sx is automatically
2457 1) If an input line begins with '!!', then %sx is automatically
2458 invoked. That is, while:
2458 invoked. That is, while:
2459 !ls
2459 !ls
2460 causes ipython to simply issue system('ls'), typing
2460 causes ipython to simply issue system('ls'), typing
2461 !!ls
2461 !!ls
2462 is a shorthand equivalent to:
2462 is a shorthand equivalent to:
2463 %sx ls
2463 %sx ls
2464
2464
2465 2) %sx differs from %sc in that %sx automatically splits into a list,
2465 2) %sx differs from %sc in that %sx automatically splits into a list,
2466 like '%sc -l'. The reason for this is to make it as easy as possible
2466 like '%sc -l'. The reason for this is to make it as easy as possible
2467 to process line-oriented shell output via further python commands.
2467 to process line-oriented shell output via further python commands.
2468 %sc is meant to provide much finer control, but requires more
2468 %sc is meant to provide much finer control, but requires more
2469 typing.
2469 typing.
2470
2470
2471 3) Just like %sc -l, this is a list with special attributes:
2471 3) Just like %sc -l, this is a list with special attributes:
2472
2472
2473 .l (or .list) : value as list.
2473 .l (or .list) : value as list.
2474 .n (or .nlstr): value as newline-separated string.
2474 .n (or .nlstr): value as newline-separated string.
2475 .s (or .spstr): value as whitespace-separated string.
2475 .s (or .spstr): value as whitespace-separated string.
2476
2476
2477 This is very useful when trying to use such lists as arguments to
2477 This is very useful when trying to use such lists as arguments to
2478 system commands."""
2478 system commands."""
2479
2479
2480 if parameter_s:
2480 if parameter_s:
2481 out,err = self.shell.getoutputerror(parameter_s)
2481 out,err = self.shell.getoutputerror(parameter_s)
2482 if err:
2482 if err:
2483 print >> Term.cerr,err
2483 print >> Term.cerr,err
2484 return SList(out.split('\n'))
2484 return SList(out.split('\n'))
2485
2485
2486 def magic_bg(self, parameter_s=''):
2486 def magic_bg(self, parameter_s=''):
2487 """Run a job in the background, in a separate thread.
2487 """Run a job in the background, in a separate thread.
2488
2488
2489 For example,
2489 For example,
2490
2490
2491 %bg myfunc(x,y,z=1)
2491 %bg myfunc(x,y,z=1)
2492
2492
2493 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2493 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2494 execution starts, a message will be printed indicating the job
2494 execution starts, a message will be printed indicating the job
2495 number. If your job number is 5, you can use
2495 number. If your job number is 5, you can use
2496
2496
2497 myvar = jobs.result(5) or myvar = jobs[5].result
2497 myvar = jobs.result(5) or myvar = jobs[5].result
2498
2498
2499 to assign this result to variable 'myvar'.
2499 to assign this result to variable 'myvar'.
2500
2500
2501 IPython has a job manager, accessible via the 'jobs' object. You can
2501 IPython has a job manager, accessible via the 'jobs' object. You can
2502 type jobs? to get more information about it, and use jobs.<TAB> to see
2502 type jobs? to get more information about it, and use jobs.<TAB> to see
2503 its attributes. All attributes not starting with an underscore are
2503 its attributes. All attributes not starting with an underscore are
2504 meant for public use.
2504 meant for public use.
2505
2505
2506 In particular, look at the jobs.new() method, which is used to create
2506 In particular, look at the jobs.new() method, which is used to create
2507 new jobs. This magic %bg function is just a convenience wrapper
2507 new jobs. This magic %bg function is just a convenience wrapper
2508 around jobs.new(), for expression-based jobs. If you want to create a
2508 around jobs.new(), for expression-based jobs. If you want to create a
2509 new job with an explicit function object and arguments, you must call
2509 new job with an explicit function object and arguments, you must call
2510 jobs.new() directly.
2510 jobs.new() directly.
2511
2511
2512 The jobs.new docstring also describes in detail several important
2512 The jobs.new docstring also describes in detail several important
2513 caveats associated with a thread-based model for background job
2513 caveats associated with a thread-based model for background job
2514 execution. Type jobs.new? for details.
2514 execution. Type jobs.new? for details.
2515
2515
2516 You can check the status of all jobs with jobs.status().
2516 You can check the status of all jobs with jobs.status().
2517
2517
2518 The jobs variable is set by IPython into the Python builtin namespace.
2518 The jobs variable is set by IPython into the Python builtin namespace.
2519 If you ever declare a variable named 'jobs', you will shadow this
2519 If you ever declare a variable named 'jobs', you will shadow this
2520 name. You can either delete your global jobs variable to regain
2520 name. You can either delete your global jobs variable to regain
2521 access to the job manager, or make a new name and assign it manually
2521 access to the job manager, or make a new name and assign it manually
2522 to the manager (stored in IPython's namespace). For example, to
2522 to the manager (stored in IPython's namespace). For example, to
2523 assign the job manager to the Jobs name, use:
2523 assign the job manager to the Jobs name, use:
2524
2524
2525 Jobs = __builtins__.jobs"""
2525 Jobs = __builtins__.jobs"""
2526
2526
2527 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2527 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2528
2528
2529 def magic_store(self, parameter_s=''):
2529 def magic_store(self, parameter_s=''):
2530 """Lightweight persistence for ipython variables
2530 """Lightweight persistence for python variables.
2531
2531
2532 Example:
2532 Example:
2533
2533
2534 ville@badger[~]|1> A = ['hello',10,'world']
2534 ville@badger[~]|1> A = ['hello',10,'world']\\
2535 ville@badger[~]|2> %store A
2535 ville@badger[~]|2> %store A\\
2536 ville@badger[~]|3> Exit
2536 ville@badger[~]|3> Exit
2537
2537
2538 (IPython session is closed and started again...)
2538 (IPython session is closed and started again...)
2539
2539
2540 ville@badger:~$ ipython -p pysh
2540 ville@badger:~$ ipython -p pysh\\
2541 ville@badger[~]|1> print A
2541 ville@badger[~]|1> print A
2542
2542
2543 ['hello', 10, 'world']
2543 ['hello', 10, 'world']
2544
2544
2545 Usage:
2545 Usage:
2546
2546
2547 %store - Show list of all variables and their current values\\
2547 %store - Show list of all variables and their current values\\
2548 %store <var> - Store the *current* value of the variable to disk\\
2548 %store <var> - Store the *current* value of the variable to disk\\
2549 %store -d - Remove the variable and its value from storage\\
2549 %store -d - Remove the variable and its value from storage\\
2550 %store -r - Remove all variables from storage
2550 %store -r - Remove all variables from storage
2551
2551
2552 It should be noted that if you change the value of a variable, you
2552 It should be noted that if you change the value of a variable, you
2553 need to %store it again if you want to persist the new value.
2553 need to %store it again if you want to persist the new value.
2554
2554
2555 Note also that the variables will need to be pickleable; most basic
2555 Note also that the variables will need to be pickleable; most basic
2556 python types can be safely %stored.
2556 python types can be safely %stored.
2557 """
2557 """
2558
2558
2559 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2559 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2560 # delete
2560 # delete
2561 if opts.has_key('d'):
2561 if opts.has_key('d'):
2562 try:
2562 try:
2563 todel = args[0]
2563 todel = args[0]
2564 except IndexError:
2564 except IndexError:
2565 error('You must provide the variable to forget')
2565 error('You must provide the variable to forget')
2566 else:
2566 else:
2567 try:
2567 try:
2568 del self.shell.persist['S:' + todel]
2568 del self.shell.persist['S:' + todel]
2569 except:
2569 except:
2570 error("Can't delete variable '%s'" % todel)
2570 error("Can't delete variable '%s'" % todel)
2571 # reset
2571 # reset
2572 elif opts.has_key('r'):
2572 elif opts.has_key('r'):
2573 for k in self.shell.persist.keys():
2573 for k in self.shell.persist.keys():
2574 if k.startswith('S:'):
2574 if k.startswith('S:'):
2575 del self.shell.persist[k]
2575 del self.shell.persist[k]
2576
2576
2577 # run without arguments -> list variables & values
2577 # run without arguments -> list variables & values
2578 elif not args:
2578 elif not args:
2579 vars = [v[2:] for v in self.shell.persist.keys() if v.startswith('S:')]
2579 vars = [v[2:] for v in self.shell.persist.keys() if v.startswith('S:')]
2580 vars.sort()
2580 vars.sort()
2581 if vars:
2581 if vars:
2582 size = max(map(len,vars))
2582 size = max(map(len,vars))
2583 else:
2583 else:
2584 size = 0
2584 size = 0
2585
2585
2586 fmt = '%-'+str(size)+'s -> %s'
2586 fmt = '%-'+str(size)+'s -> %s'
2587 print 'Stored variables and their in-memory values:'
2587 print 'Stored variables and their in-memory values:'
2588 for var in vars:
2588 for var in vars:
2589 # print 30 first characters from every var
2589 # print 30 first characters from every var
2590 print fmt % (var,repr(self.shell.user_ns.get(var, '<unavailable>'))[:50])
2590 print fmt % (var,repr(self.shell.user_ns.get(var, '<unavailable>'))[:50])
2591
2591
2592 # default action - store the variable
2592 # default action - store the variable
2593 else:
2593 else:
2594 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2594 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2595 self.shell.persist[ 'S:' + args[0] ] = pickled
2595 self.shell.persist[ 'S:' + args[0] ] = pickled
2596 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2596 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2597
2597
2598
2598
2599
2599
2600
2600
2601
2601
2602
2602
2603 def magic_bookmark(self, parameter_s=''):
2603 def magic_bookmark(self, parameter_s=''):
2604 """Manage IPython's bookmark system.
2604 """Manage IPython's bookmark system.
2605
2605
2606 %bookmark <name> - set bookmark to current dir
2606 %bookmark <name> - set bookmark to current dir
2607 %bookmark <name> <dir> - set bookmark to <dir>
2607 %bookmark <name> <dir> - set bookmark to <dir>
2608 %bookmark -l - list all bookmarks
2608 %bookmark -l - list all bookmarks
2609 %bookmark -d <name> - remove bookmark
2609 %bookmark -d <name> - remove bookmark
2610 %bookmark -r - remove all bookmarks
2610 %bookmark -r - remove all bookmarks
2611
2611
2612 You can later on access a bookmarked folder with:
2612 You can later on access a bookmarked folder with:
2613 %cd -b <name>
2613 %cd -b <name>
2614 or simply '%cd <name>' if there is no directory called <name> AND
2614 or simply '%cd <name>' if there is no directory called <name> AND
2615 there is such a bookmark defined.
2615 there is such a bookmark defined.
2616
2616
2617 Your bookmarks persist through IPython sessions, but they are
2617 Your bookmarks persist through IPython sessions, but they are
2618 associated with each profile."""
2618 associated with each profile."""
2619
2619
2620 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2620 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2621 if len(args) > 2:
2621 if len(args) > 2:
2622 error('You can only give at most two arguments')
2622 error('You can only give at most two arguments')
2623 return
2623 return
2624
2624
2625 bkms = self.shell.persist.get('bookmarks',{})
2625 bkms = self.shell.persist.get('bookmarks',{})
2626
2626
2627 if opts.has_key('d'):
2627 if opts.has_key('d'):
2628 try:
2628 try:
2629 todel = args[0]
2629 todel = args[0]
2630 except IndexError:
2630 except IndexError:
2631 error('You must provide a bookmark to delete')
2631 error('You must provide a bookmark to delete')
2632 else:
2632 else:
2633 try:
2633 try:
2634 del bkms[todel]
2634 del bkms[todel]
2635 except:
2635 except:
2636 error("Can't delete bookmark '%s'" % todel)
2636 error("Can't delete bookmark '%s'" % todel)
2637 elif opts.has_key('r'):
2637 elif opts.has_key('r'):
2638 bkms = {}
2638 bkms = {}
2639 elif opts.has_key('l'):
2639 elif opts.has_key('l'):
2640 bks = bkms.keys()
2640 bks = bkms.keys()
2641 bks.sort()
2641 bks.sort()
2642 if bks:
2642 if bks:
2643 size = max(map(len,bks))
2643 size = max(map(len,bks))
2644 else:
2644 else:
2645 size = 0
2645 size = 0
2646 fmt = '%-'+str(size)+'s -> %s'
2646 fmt = '%-'+str(size)+'s -> %s'
2647 print 'Current bookmarks:'
2647 print 'Current bookmarks:'
2648 for bk in bks:
2648 for bk in bks:
2649 print fmt % (bk,bkms[bk])
2649 print fmt % (bk,bkms[bk])
2650 else:
2650 else:
2651 if not args:
2651 if not args:
2652 error("You must specify the bookmark name")
2652 error("You must specify the bookmark name")
2653 elif len(args)==1:
2653 elif len(args)==1:
2654 bkms[args[0]] = os.getcwd()
2654 bkms[args[0]] = os.getcwd()
2655 elif len(args)==2:
2655 elif len(args)==2:
2656 bkms[args[0]] = args[1]
2656 bkms[args[0]] = args[1]
2657 self.shell.persist['bookmarks'] = bkms
2657 self.shell.persist['bookmarks'] = bkms
2658
2658
2659 def magic_pycat(self, parameter_s=''):
2659 def magic_pycat(self, parameter_s=''):
2660 """Show a syntax-highlighted file through a pager.
2660 """Show a syntax-highlighted file through a pager.
2661
2661
2662 This magic is similar to the cat utility, but it will assume the file
2662 This magic is similar to the cat utility, but it will assume the file
2663 to be Python source and will show it with syntax highlighting. """
2663 to be Python source and will show it with syntax highlighting. """
2664
2664
2665 filename = get_py_filename(parameter_s)
2665 filename = get_py_filename(parameter_s)
2666 page(self.shell.colorize(file_read(filename)),
2666 page(self.shell.colorize(file_read(filename)),
2667 screen_lines=self.shell.rc.screen_length)
2667 screen_lines=self.shell.rc.screen_length)
2668
2668
2669 # end Magic
2669 # end Magic
General Comments 0
You need to be logged in to leave comments. Login now