##// END OF EJS Templates
- improve support for tab-completion under emacs...
fperez -
Show More

The requested changes are too big and content was truncated. Show full diff

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