##// END OF EJS Templates
Changes for demos and access to raw history in %macro, %save and %edit....
fperez -
Show More

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

@@ -1,2765 +1,2804 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 1121 2006-02-01 21:12:20Z vivainio $"""
4 $Id: Magic.py 1126 2006-02-06 02:31:40Z 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-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 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 import textwrap
34 import textwrap
35 from cStringIO import StringIO
35 from cStringIO import StringIO
36 from getopt import getopt,GetoptError
36 from getopt import getopt,GetoptError
37 from pprint import pprint, pformat
37 from pprint import pprint, pformat
38
38
39 # profile isn't bundled by default in Debian for license reasons
39 # profile isn't bundled by default in Debian for license reasons
40 try:
40 try:
41 import profile,pstats
41 import profile,pstats
42 except ImportError:
42 except ImportError:
43 profile = pstats = None
43 profile = pstats = None
44
44
45 # Homebrewed
45 # Homebrewed
46 from IPython import Debugger, OInspect, wildcard
46 from IPython import Debugger, OInspect, wildcard
47 from IPython.FakeModule import FakeModule
47 from IPython.FakeModule import FakeModule
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
49 from IPython.PyColorize import Parser
49 from IPython.PyColorize import Parser
50 from IPython.ipstruct import Struct
50 from IPython.ipstruct import Struct
51 from IPython.macro import Macro
51 from IPython.macro import Macro
52 from IPython.genutils import *
52 from IPython.genutils import *
53 from IPython import platutils
53 from IPython import platutils
54
54
55 #***************************************************************************
55 #***************************************************************************
56 # Utility functions
56 # Utility functions
57 def on_off(tag):
57 def on_off(tag):
58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
59 return ['OFF','ON'][tag]
59 return ['OFF','ON'][tag]
60
60
61 class Bunch: pass
61 class Bunch: pass
62
62
63 #***************************************************************************
63 #***************************************************************************
64 # Main class implementing Magic functionality
64 # Main class implementing Magic functionality
65 class Magic:
65 class Magic:
66 """Magic functions for InteractiveShell.
66 """Magic functions for InteractiveShell.
67
67
68 Shell functions which can be reached as %function_name. All magic
68 Shell functions which can be reached as %function_name. All magic
69 functions should accept a string, which they can parse for their own
69 functions should accept a string, which they can parse for their own
70 needs. This can make some functions easier to type, eg `%cd ../`
70 needs. This can make some functions easier to type, eg `%cd ../`
71 vs. `%cd("../")`
71 vs. `%cd("../")`
72
72
73 ALL definitions MUST begin with the prefix magic_. The user won't need it
73 ALL definitions MUST begin with the prefix magic_. The user won't need it
74 at the command line, but it is is needed in the definition. """
74 at the command line, but it is is needed in the definition. """
75
75
76 # class globals
76 # class globals
77 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
77 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
78 'Automagic is ON, % prefix NOT needed for magic functions.']
78 'Automagic is ON, % prefix NOT needed for magic functions.']
79
79
80 #......................................................................
80 #......................................................................
81 # some utility functions
81 # some utility functions
82
82
83 def __init__(self,shell):
83 def __init__(self,shell):
84
84
85 self.options_table = {}
85 self.options_table = {}
86 if profile is None:
86 if profile is None:
87 self.magic_prun = self.profile_missing_notice
87 self.magic_prun = self.profile_missing_notice
88 self.shell = shell
88 self.shell = shell
89
89
90 # namespace for holding state we may need
90 # namespace for holding state we may need
91 self._magic_state = Bunch()
91 self._magic_state = Bunch()
92
92
93 def profile_missing_notice(self, *args, **kwargs):
93 def profile_missing_notice(self, *args, **kwargs):
94 error("""\
94 error("""\
95 The profile module could not be found. If you are a Debian user,
95 The profile module could not be found. If you are a Debian user,
96 it has been removed from the standard Debian package because of its non-free
96 it has been removed from the standard Debian package because of its non-free
97 license. To use profiling, please install"python2.3-profiler" from non-free.""")
97 license. To use profiling, please install"python2.3-profiler" from non-free.""")
98
98
99 def default_option(self,fn,optstr):
99 def default_option(self,fn,optstr):
100 """Make an entry in the options_table for fn, with value optstr"""
100 """Make an entry in the options_table for fn, with value optstr"""
101
101
102 if fn not in self.lsmagic():
102 if fn not in self.lsmagic():
103 error("%s is not a magic function" % fn)
103 error("%s is not a magic function" % fn)
104 self.options_table[fn] = optstr
104 self.options_table[fn] = optstr
105
105
106 def lsmagic(self):
106 def lsmagic(self):
107 """Return a list of currently available magic functions.
107 """Return a list of currently available magic functions.
108
108
109 Gives a list of the bare names after mangling (['ls','cd', ...], not
109 Gives a list of the bare names after mangling (['ls','cd', ...], not
110 ['magic_ls','magic_cd',...]"""
110 ['magic_ls','magic_cd',...]"""
111
111
112 # FIXME. This needs a cleanup, in the way the magics list is built.
112 # FIXME. This needs a cleanup, in the way the magics list is built.
113
113
114 # magics in class definition
114 # magics in class definition
115 class_magic = lambda fn: fn.startswith('magic_') and \
115 class_magic = lambda fn: fn.startswith('magic_') and \
116 callable(Magic.__dict__[fn])
116 callable(Magic.__dict__[fn])
117 # in instance namespace (run-time user additions)
117 # in instance namespace (run-time user additions)
118 inst_magic = lambda fn: fn.startswith('magic_') and \
118 inst_magic = lambda fn: fn.startswith('magic_') and \
119 callable(self.__dict__[fn])
119 callable(self.__dict__[fn])
120 # and bound magics by user (so they can access self):
120 # and bound magics by user (so they can access self):
121 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
121 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
122 callable(self.__class__.__dict__[fn])
122 callable(self.__class__.__dict__[fn])
123 magics = filter(class_magic,Magic.__dict__.keys()) + \
123 magics = filter(class_magic,Magic.__dict__.keys()) + \
124 filter(inst_magic,self.__dict__.keys()) + \
124 filter(inst_magic,self.__dict__.keys()) + \
125 filter(inst_bound_magic,self.__class__.__dict__.keys())
125 filter(inst_bound_magic,self.__class__.__dict__.keys())
126 out = []
126 out = []
127 for fn in magics:
127 for fn in magics:
128 out.append(fn.replace('magic_','',1))
128 out.append(fn.replace('magic_','',1))
129 out.sort()
129 out.sort()
130 return out
130 return out
131
131
132 def extract_input_slices(self,slices):
132 def extract_input_slices(self,slices,raw=False):
133 """Return as a string a set of input history slices.
133 """Return as a string a set of input history slices.
134
134
135 The set of slices is given as a list of strings (like ['1','4:8','9'],
135 Inputs:
136 since this function is for use by magic functions which get their
136
137 arguments as strings.
137 - slices: the set of slices is given as a list of strings (like
138 ['1','4:8','9'], since this function is for use by magic functions
139 which get their arguments as strings.
140
141 Optional inputs:
142
143 - raw(False): by default, the processed input is used. If this is
144 true, the raw input history is used instead.
138
145
139 Note that slices can be called with two notations:
146 Note that slices can be called with two notations:
140
147
141 N:M -> standard python form, means including items N...(M-1).
148 N:M -> standard python form, means including items N...(M-1).
142
149
143 N-M -> include items N..M (closed endpoint)."""
150 N-M -> include items N..M (closed endpoint)."""
144
151
152 if raw:
153 hist = self.shell.input_hist_raw
154 else:
155 hist = self.shell.input_hist
156
145 cmds = []
157 cmds = []
146 for chunk in slices:
158 for chunk in slices:
147 if ':' in chunk:
159 if ':' in chunk:
148 ini,fin = map(int,chunk.split(':'))
160 ini,fin = map(int,chunk.split(':'))
149 elif '-' in chunk:
161 elif '-' in chunk:
150 ini,fin = map(int,chunk.split('-'))
162 ini,fin = map(int,chunk.split('-'))
151 fin += 1
163 fin += 1
152 else:
164 else:
153 ini = int(chunk)
165 ini = int(chunk)
154 fin = ini+1
166 fin = ini+1
155 cmds.append(self.shell.input_hist[ini:fin])
167 cmds.append(hist[ini:fin])
156 return cmds
168 return cmds
157
169
158 def _ofind(self,oname):
170 def _ofind(self,oname):
159 """Find an object in the available namespaces.
171 """Find an object in the available namespaces.
160
172
161 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
173 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
162
174
163 Has special code to detect magic functions.
175 Has special code to detect magic functions.
164 """
176 """
165
177
166 oname = oname.strip()
178 oname = oname.strip()
167
179
168 # Namespaces to search in:
180 # Namespaces to search in:
169 user_ns = self.shell.user_ns
181 user_ns = self.shell.user_ns
170 internal_ns = self.shell.internal_ns
182 internal_ns = self.shell.internal_ns
171 builtin_ns = __builtin__.__dict__
183 builtin_ns = __builtin__.__dict__
172 alias_ns = self.shell.alias_table
184 alias_ns = self.shell.alias_table
173
185
174 # Put them in a list. The order is important so that we find things in
186 # Put them in a list. The order is important so that we find things in
175 # the same order that Python finds them.
187 # the same order that Python finds them.
176 namespaces = [ ('Interactive',user_ns),
188 namespaces = [ ('Interactive',user_ns),
177 ('IPython internal',internal_ns),
189 ('IPython internal',internal_ns),
178 ('Python builtin',builtin_ns),
190 ('Python builtin',builtin_ns),
179 ('Alias',alias_ns),
191 ('Alias',alias_ns),
180 ]
192 ]
181
193
182 # initialize results to 'null'
194 # initialize results to 'null'
183 found = 0; obj = None; ospace = None; ds = None;
195 found = 0; obj = None; ospace = None; ds = None;
184 ismagic = 0; isalias = 0
196 ismagic = 0; isalias = 0
185
197
186 # Look for the given name by splitting it in parts. If the head is
198 # Look for the given name by splitting it in parts. If the head is
187 # found, then we look for all the remaining parts as members, and only
199 # found, then we look for all the remaining parts as members, and only
188 # declare success if we can find them all.
200 # declare success if we can find them all.
189 oname_parts = oname.split('.')
201 oname_parts = oname.split('.')
190 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
202 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
191 for nsname,ns in namespaces:
203 for nsname,ns in namespaces:
192 try:
204 try:
193 obj = ns[oname_head]
205 obj = ns[oname_head]
194 except KeyError:
206 except KeyError:
195 continue
207 continue
196 else:
208 else:
197 for part in oname_rest:
209 for part in oname_rest:
198 try:
210 try:
199 obj = getattr(obj,part)
211 obj = getattr(obj,part)
200 except:
212 except:
201 # Blanket except b/c some badly implemented objects
213 # Blanket except b/c some badly implemented objects
202 # allow __getattr__ to raise exceptions other than
214 # allow __getattr__ to raise exceptions other than
203 # AttributeError, which then crashes IPython.
215 # AttributeError, which then crashes IPython.
204 break
216 break
205 else:
217 else:
206 # If we finish the for loop (no break), we got all members
218 # If we finish the for loop (no break), we got all members
207 found = 1
219 found = 1
208 ospace = nsname
220 ospace = nsname
209 if ns == alias_ns:
221 if ns == alias_ns:
210 isalias = 1
222 isalias = 1
211 break # namespace loop
223 break # namespace loop
212
224
213 # Try to see if it's magic
225 # Try to see if it's magic
214 if not found:
226 if not found:
215 if oname.startswith(self.shell.ESC_MAGIC):
227 if oname.startswith(self.shell.ESC_MAGIC):
216 oname = oname[1:]
228 oname = oname[1:]
217 obj = getattr(self,'magic_'+oname,None)
229 obj = getattr(self,'magic_'+oname,None)
218 if obj is not None:
230 if obj is not None:
219 found = 1
231 found = 1
220 ospace = 'IPython internal'
232 ospace = 'IPython internal'
221 ismagic = 1
233 ismagic = 1
222
234
223 # Last try: special-case some literals like '', [], {}, etc:
235 # Last try: special-case some literals like '', [], {}, etc:
224 if not found and oname_head in ["''",'""','[]','{}','()']:
236 if not found and oname_head in ["''",'""','[]','{}','()']:
225 obj = eval(oname_head)
237 obj = eval(oname_head)
226 found = 1
238 found = 1
227 ospace = 'Interactive'
239 ospace = 'Interactive'
228
240
229 return {'found':found, 'obj':obj, 'namespace':ospace,
241 return {'found':found, 'obj':obj, 'namespace':ospace,
230 'ismagic':ismagic, 'isalias':isalias}
242 'ismagic':ismagic, 'isalias':isalias}
231
243
232 def arg_err(self,func):
244 def arg_err(self,func):
233 """Print docstring if incorrect arguments were passed"""
245 """Print docstring if incorrect arguments were passed"""
234 print 'Error in arguments:'
246 print 'Error in arguments:'
235 print OInspect.getdoc(func)
247 print OInspect.getdoc(func)
236
248
237 def format_latex(self,strng):
249 def format_latex(self,strng):
238 """Format a string for latex inclusion."""
250 """Format a string for latex inclusion."""
239
251
240 # Characters that need to be escaped for latex:
252 # Characters that need to be escaped for latex:
241 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
253 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
242 # Magic command names as headers:
254 # Magic command names as headers:
243 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
255 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
244 re.MULTILINE)
256 re.MULTILINE)
245 # Magic commands
257 # Magic commands
246 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
258 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
247 re.MULTILINE)
259 re.MULTILINE)
248 # Paragraph continue
260 # Paragraph continue
249 par_re = re.compile(r'\\$',re.MULTILINE)
261 par_re = re.compile(r'\\$',re.MULTILINE)
250
262
251 # The "\n" symbol
263 # The "\n" symbol
252 newline_re = re.compile(r'\\n')
264 newline_re = re.compile(r'\\n')
253
265
254 # Now build the string for output:
266 # Now build the string for output:
255 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
267 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
256 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
268 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
257 strng)
269 strng)
258 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
270 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
259 strng = par_re.sub(r'\\\\',strng)
271 strng = par_re.sub(r'\\\\',strng)
260 strng = escape_re.sub(r'\\\1',strng)
272 strng = escape_re.sub(r'\\\1',strng)
261 strng = newline_re.sub(r'\\textbackslash{}n',strng)
273 strng = newline_re.sub(r'\\textbackslash{}n',strng)
262 return strng
274 return strng
263
275
264 def format_screen(self,strng):
276 def format_screen(self,strng):
265 """Format a string for screen printing.
277 """Format a string for screen printing.
266
278
267 This removes some latex-type format codes."""
279 This removes some latex-type format codes."""
268 # Paragraph continue
280 # Paragraph continue
269 par_re = re.compile(r'\\$',re.MULTILINE)
281 par_re = re.compile(r'\\$',re.MULTILINE)
270 strng = par_re.sub('',strng)
282 strng = par_re.sub('',strng)
271 return strng
283 return strng
272
284
273 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
285 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
274 """Parse options passed to an argument string.
286 """Parse options passed to an argument string.
275
287
276 The interface is similar to that of getopt(), but it returns back a
288 The interface is similar to that of getopt(), but it returns back a
277 Struct with the options as keys and the stripped argument string still
289 Struct with the options as keys and the stripped argument string still
278 as a string.
290 as a string.
279
291
280 arg_str is quoted as a true sys.argv vector by using shlex.split.
292 arg_str is quoted as a true sys.argv vector by using shlex.split.
281 This allows us to easily expand variables, glob files, quote
293 This allows us to easily expand variables, glob files, quote
282 arguments, etc.
294 arguments, etc.
283
295
284 Options:
296 Options:
285 -mode: default 'string'. If given as 'list', the argument string is
297 -mode: default 'string'. If given as 'list', the argument string is
286 returned as a list (split on whitespace) instead of a string.
298 returned as a list (split on whitespace) instead of a string.
287
299
288 -list_all: put all option values in lists. Normally only options
300 -list_all: put all option values in lists. Normally only options
289 appearing more than once are put in a list."""
301 appearing more than once are put in a list."""
290
302
291 # inject default options at the beginning of the input line
303 # inject default options at the beginning of the input line
292 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
304 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
293 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
305 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
294
306
295 mode = kw.get('mode','string')
307 mode = kw.get('mode','string')
296 if mode not in ['string','list']:
308 if mode not in ['string','list']:
297 raise ValueError,'incorrect mode given: %s' % mode
309 raise ValueError,'incorrect mode given: %s' % mode
298 # Get options
310 # Get options
299 list_all = kw.get('list_all',0)
311 list_all = kw.get('list_all',0)
300
312
301 # Check if we have more than one argument to warrant extra processing:
313 # Check if we have more than one argument to warrant extra processing:
302 odict = {} # Dictionary with options
314 odict = {} # Dictionary with options
303 args = arg_str.split()
315 args = arg_str.split()
304 if len(args) >= 1:
316 if len(args) >= 1:
305 # If the list of inputs only has 0 or 1 thing in it, there's no
317 # If the list of inputs only has 0 or 1 thing in it, there's no
306 # need to look for options
318 # need to look for options
307 argv = shlex_split(arg_str)
319 argv = shlex_split(arg_str)
308 # Do regular option processing
320 # Do regular option processing
309 try:
321 try:
310 opts,args = getopt(argv,opt_str,*long_opts)
322 opts,args = getopt(argv,opt_str,*long_opts)
311 except GetoptError,e:
323 except GetoptError,e:
312 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
324 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
313 " ".join(long_opts)))
325 " ".join(long_opts)))
314 for o,a in opts:
326 for o,a in opts:
315 if o.startswith('--'):
327 if o.startswith('--'):
316 o = o[2:]
328 o = o[2:]
317 else:
329 else:
318 o = o[1:]
330 o = o[1:]
319 try:
331 try:
320 odict[o].append(a)
332 odict[o].append(a)
321 except AttributeError:
333 except AttributeError:
322 odict[o] = [odict[o],a]
334 odict[o] = [odict[o],a]
323 except KeyError:
335 except KeyError:
324 if list_all:
336 if list_all:
325 odict[o] = [a]
337 odict[o] = [a]
326 else:
338 else:
327 odict[o] = a
339 odict[o] = a
328
340
329 # Prepare opts,args for return
341 # Prepare opts,args for return
330 opts = Struct(odict)
342 opts = Struct(odict)
331 if mode == 'string':
343 if mode == 'string':
332 args = ' '.join(args)
344 args = ' '.join(args)
333
345
334 return opts,args
346 return opts,args
335
347
336 #......................................................................
348 #......................................................................
337 # And now the actual magic functions
349 # And now the actual magic functions
338
350
339 # Functions for IPython shell work (vars,funcs, config, etc)
351 # Functions for IPython shell work (vars,funcs, config, etc)
340 def magic_lsmagic(self, parameter_s = ''):
352 def magic_lsmagic(self, parameter_s = ''):
341 """List currently available magic functions."""
353 """List currently available magic functions."""
342 mesc = self.shell.ESC_MAGIC
354 mesc = self.shell.ESC_MAGIC
343 print 'Available magic functions:\n'+mesc+\
355 print 'Available magic functions:\n'+mesc+\
344 (' '+mesc).join(self.lsmagic())
356 (' '+mesc).join(self.lsmagic())
345 print '\n' + Magic.auto_status[self.shell.rc.automagic]
357 print '\n' + Magic.auto_status[self.shell.rc.automagic]
346 return None
358 return None
347
359
348 def magic_magic(self, parameter_s = ''):
360 def magic_magic(self, parameter_s = ''):
349 """Print information about the magic function system."""
361 """Print information about the magic function system."""
350
362
351 mode = ''
363 mode = ''
352 try:
364 try:
353 if parameter_s.split()[0] == '-latex':
365 if parameter_s.split()[0] == '-latex':
354 mode = 'latex'
366 mode = 'latex'
355 except:
367 except:
356 pass
368 pass
357
369
358 magic_docs = []
370 magic_docs = []
359 for fname in self.lsmagic():
371 for fname in self.lsmagic():
360 mname = 'magic_' + fname
372 mname = 'magic_' + fname
361 for space in (Magic,self,self.__class__):
373 for space in (Magic,self,self.__class__):
362 try:
374 try:
363 fn = space.__dict__[mname]
375 fn = space.__dict__[mname]
364 except KeyError:
376 except KeyError:
365 pass
377 pass
366 else:
378 else:
367 break
379 break
368 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
380 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
369 fname,fn.__doc__))
381 fname,fn.__doc__))
370 magic_docs = ''.join(magic_docs)
382 magic_docs = ''.join(magic_docs)
371
383
372 if mode == 'latex':
384 if mode == 'latex':
373 print self.format_latex(magic_docs)
385 print self.format_latex(magic_docs)
374 return
386 return
375 else:
387 else:
376 magic_docs = self.format_screen(magic_docs)
388 magic_docs = self.format_screen(magic_docs)
377
389
378 outmsg = """
390 outmsg = """
379 IPython's 'magic' functions
391 IPython's 'magic' functions
380 ===========================
392 ===========================
381
393
382 The magic function system provides a series of functions which allow you to
394 The magic function system provides a series of functions which allow you to
383 control the behavior of IPython itself, plus a lot of system-type
395 control the behavior of IPython itself, plus a lot of system-type
384 features. All these functions are prefixed with a % character, but parameters
396 features. All these functions are prefixed with a % character, but parameters
385 are given without parentheses or quotes.
397 are given without parentheses or quotes.
386
398
387 NOTE: If you have 'automagic' enabled (via the command line option or with the
399 NOTE: If you have 'automagic' enabled (via the command line option or with the
388 %automagic function), you don't need to type in the % explicitly. By default,
400 %automagic function), you don't need to type in the % explicitly. By default,
389 IPython ships with automagic on, so you should only rarely need the % escape.
401 IPython ships with automagic on, so you should only rarely need the % escape.
390
402
391 Example: typing '%cd mydir' (without the quotes) changes you working directory
403 Example: typing '%cd mydir' (without the quotes) changes you working directory
392 to 'mydir', if it exists.
404 to 'mydir', if it exists.
393
405
394 You can define your own magic functions to extend the system. See the supplied
406 You can define your own magic functions to extend the system. See the supplied
395 ipythonrc and example-magic.py files for details (in your ipython
407 ipythonrc and example-magic.py files for details (in your ipython
396 configuration directory, typically $HOME/.ipython/).
408 configuration directory, typically $HOME/.ipython/).
397
409
398 You can also define your own aliased names for magic functions. In your
410 You can also define your own aliased names for magic functions. In your
399 ipythonrc file, placing a line like:
411 ipythonrc file, placing a line like:
400
412
401 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
413 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
402
414
403 will define %pf as a new name for %profile.
415 will define %pf as a new name for %profile.
404
416
405 You can also call magics in code using the ipmagic() function, which IPython
417 You can also call magics in code using the ipmagic() function, which IPython
406 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
418 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
407
419
408 For a list of the available magic functions, use %lsmagic. For a description
420 For a list of the available magic functions, use %lsmagic. For a description
409 of any of them, type %magic_name?, e.g. '%cd?'.
421 of any of them, type %magic_name?, e.g. '%cd?'.
410
422
411 Currently the magic system has the following functions:\n"""
423 Currently the magic system has the following functions:\n"""
412
424
413 mesc = self.shell.ESC_MAGIC
425 mesc = self.shell.ESC_MAGIC
414 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
426 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
415 "\n\n%s%s\n\n%s" % (outmsg,
427 "\n\n%s%s\n\n%s" % (outmsg,
416 magic_docs,mesc,mesc,
428 magic_docs,mesc,mesc,
417 (' '+mesc).join(self.lsmagic()),
429 (' '+mesc).join(self.lsmagic()),
418 Magic.auto_status[self.shell.rc.automagic] ) )
430 Magic.auto_status[self.shell.rc.automagic] ) )
419
431
420 page(outmsg,screen_lines=self.shell.rc.screen_length)
432 page(outmsg,screen_lines=self.shell.rc.screen_length)
421
433
422 def magic_automagic(self, parameter_s = ''):
434 def magic_automagic(self, parameter_s = ''):
423 """Make magic functions callable without having to type the initial %.
435 """Make magic functions callable without having to type the initial %.
424
436
425 Toggles on/off (when off, you must call it as %automagic, of
437 Toggles on/off (when off, you must call it as %automagic, of
426 course). Note that magic functions have lowest priority, so if there's
438 course). Note that magic functions have lowest priority, so if there's
427 a variable whose name collides with that of a magic fn, automagic
439 a variable whose name collides with that of a magic fn, automagic
428 won't work for that function (you get the variable instead). However,
440 won't work for that function (you get the variable instead). However,
429 if you delete the variable (del var), the previously shadowed magic
441 if you delete the variable (del var), the previously shadowed magic
430 function becomes visible to automagic again."""
442 function becomes visible to automagic again."""
431
443
432 rc = self.shell.rc
444 rc = self.shell.rc
433 rc.automagic = not rc.automagic
445 rc.automagic = not rc.automagic
434 print '\n' + Magic.auto_status[rc.automagic]
446 print '\n' + Magic.auto_status[rc.automagic]
435
447
436 def magic_autocall(self, parameter_s = ''):
448 def magic_autocall(self, parameter_s = ''):
437 """Make functions callable without having to type parentheses.
449 """Make functions callable without having to type parentheses.
438
450
439 Usage:
451 Usage:
440
452
441 %autocall [mode]
453 %autocall [mode]
442
454
443 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
455 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
444 value is toggled on and off (remembering the previous state)."""
456 value is toggled on and off (remembering the previous state)."""
445
457
446 rc = self.shell.rc
458 rc = self.shell.rc
447
459
448 if parameter_s:
460 if parameter_s:
449 arg = int(parameter_s)
461 arg = int(parameter_s)
450 else:
462 else:
451 arg = 'toggle'
463 arg = 'toggle'
452
464
453 if not arg in (0,1,2,'toggle'):
465 if not arg in (0,1,2,'toggle'):
454 error('Valid modes: (0->Off, 1->Smart, 2->Full')
466 error('Valid modes: (0->Off, 1->Smart, 2->Full')
455 return
467 return
456
468
457 if arg in (0,1,2):
469 if arg in (0,1,2):
458 rc.autocall = arg
470 rc.autocall = arg
459 else: # toggle
471 else: # toggle
460 if rc.autocall:
472 if rc.autocall:
461 self._magic_state.autocall_save = rc.autocall
473 self._magic_state.autocall_save = rc.autocall
462 rc.autocall = 0
474 rc.autocall = 0
463 else:
475 else:
464 try:
476 try:
465 rc.autocall = self._magic_state.autocall_save
477 rc.autocall = self._magic_state.autocall_save
466 except AttributeError:
478 except AttributeError:
467 rc.autocall = self._magic_state.autocall_save = 1
479 rc.autocall = self._magic_state.autocall_save = 1
468
480
469 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
481 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
470
482
471 def magic_autoindent(self, parameter_s = ''):
483 def magic_autoindent(self, parameter_s = ''):
472 """Toggle autoindent on/off (if available)."""
484 """Toggle autoindent on/off (if available)."""
473
485
474 self.shell.set_autoindent()
486 self.shell.set_autoindent()
475 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
487 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
476
488
477 def magic_system_verbose(self, parameter_s = ''):
489 def magic_system_verbose(self, parameter_s = ''):
478 """Toggle verbose printing of system calls on/off."""
490 """Toggle verbose printing of system calls on/off."""
479
491
480 self.shell.rc_set_toggle('system_verbose')
492 self.shell.rc_set_toggle('system_verbose')
481 print "System verbose printing is:",\
493 print "System verbose printing is:",\
482 ['OFF','ON'][self.shell.rc.system_verbose]
494 ['OFF','ON'][self.shell.rc.system_verbose]
483
495
484 def magic_history(self, parameter_s = ''):
496 def magic_history(self, parameter_s = ''):
485 """Print input history (_i<n> variables), with most recent last.
497 """Print input history (_i<n> variables), with most recent last.
486
498
487 %history -> print at most 40 inputs (some may be multi-line)\\
499 %history -> print at most 40 inputs (some may be multi-line)\\
488 %history n -> print at most n inputs\\
500 %history n -> print at most n inputs\\
489 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
501 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
490
502
491 Each input's number <n> is shown, and is accessible as the
503 Each input's number <n> is shown, and is accessible as the
492 automatically generated variable _i<n>. Multi-line statements are
504 automatically generated variable _i<n>. Multi-line statements are
493 printed starting at a new line for easy copy/paste.
505 printed starting at a new line for easy copy/paste.
494
506
495
507
496 Options:
508 Options:
497
509
498 -n: do NOT print line numbers. This is useful if you want to get a
510 -n: do NOT print line numbers. This is useful if you want to get a
499 printout of many lines which can be directly pasted into a text
511 printout of many lines which can be directly pasted into a text
500 editor.
512 editor.
501
513
502 This feature is only available if numbered prompts are in use.
514 This feature is only available if numbered prompts are in use.
503
515
504 -r: print the 'raw' history. IPython filters your input and
516 -r: print the 'raw' history. IPython filters your input and
505 converts it all into valid Python source before executing it (things
517 converts it all into valid Python source before executing it (things
506 like magics or aliases are turned into function calls, for
518 like magics or aliases are turned into function calls, for
507 example). With this option, you'll see the unfiltered history
519 example). With this option, you'll see the unfiltered history
508 instead of the filtered version: '%cd /' will be seen as '%cd /'
520 instead of the filtered version: '%cd /' will be seen as '%cd /'
509 instead of '_ip.magic("%cd /")'.
521 instead of '_ip.magic("%cd /")'.
510 """
522 """
511
523
512 shell = self.shell
524 shell = self.shell
513 if not shell.outputcache.do_full_cache:
525 if not shell.outputcache.do_full_cache:
514 print 'This feature is only available if numbered prompts are in use.'
526 print 'This feature is only available if numbered prompts are in use.'
515 return
527 return
516 opts,args = self.parse_options(parameter_s,'nr',mode='list')
528 opts,args = self.parse_options(parameter_s,'nr',mode='list')
517
529
518 if opts.has_key('r'):
530 if opts.has_key('r'):
519 input_hist = shell.input_hist_raw
531 input_hist = shell.input_hist_raw
520 else:
532 else:
521 input_hist = shell.input_hist
533 input_hist = shell.input_hist
522
534
523 default_length = 40
535 default_length = 40
524 if len(args) == 0:
536 if len(args) == 0:
525 final = len(input_hist)
537 final = len(input_hist)
526 init = max(1,final-default_length)
538 init = max(1,final-default_length)
527 elif len(args) == 1:
539 elif len(args) == 1:
528 final = len(input_hist)
540 final = len(input_hist)
529 init = max(1,final-int(args[0]))
541 init = max(1,final-int(args[0]))
530 elif len(args) == 2:
542 elif len(args) == 2:
531 init,final = map(int,args)
543 init,final = map(int,args)
532 else:
544 else:
533 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
545 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
534 print self.magic_hist.__doc__
546 print self.magic_hist.__doc__
535 return
547 return
536 width = len(str(final))
548 width = len(str(final))
537 line_sep = ['','\n']
549 line_sep = ['','\n']
538 print_nums = not opts.has_key('n')
550 print_nums = not opts.has_key('n')
539 for in_num in range(init,final):
551 for in_num in range(init,final):
540 inline = input_hist[in_num]
552 inline = input_hist[in_num]
541 multiline = int(inline.count('\n') > 1)
553 multiline = int(inline.count('\n') > 1)
542 if print_nums:
554 if print_nums:
543 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
555 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
544 print inline,
556 print inline,
545
557
546 def magic_hist(self, parameter_s=''):
558 def magic_hist(self, parameter_s=''):
547 """Alternate name for %history."""
559 """Alternate name for %history."""
548 return self.magic_history(parameter_s)
560 return self.magic_history(parameter_s)
549
561
550 def magic_p(self, parameter_s=''):
562 def magic_p(self, parameter_s=''):
551 """Just a short alias for Python's 'print'."""
563 """Just a short alias for Python's 'print'."""
552 exec 'print ' + parameter_s in self.shell.user_ns
564 exec 'print ' + parameter_s in self.shell.user_ns
553
565
554 def magic_r(self, parameter_s=''):
566 def magic_r(self, parameter_s=''):
555 """Repeat previous input.
567 """Repeat previous input.
556
568
557 If given an argument, repeats the previous command which starts with
569 If given an argument, repeats the previous command which starts with
558 the same string, otherwise it just repeats the previous input.
570 the same string, otherwise it just repeats the previous input.
559
571
560 Shell escaped commands (with ! as first character) are not recognized
572 Shell escaped commands (with ! as first character) are not recognized
561 by this system, only pure python code and magic commands.
573 by this system, only pure python code and magic commands.
562 """
574 """
563
575
564 start = parameter_s.strip()
576 start = parameter_s.strip()
565 esc_magic = self.shell.ESC_MAGIC
577 esc_magic = self.shell.ESC_MAGIC
566 # Identify magic commands even if automagic is on (which means
578 # Identify magic commands even if automagic is on (which means
567 # the in-memory version is different from that typed by the user).
579 # the in-memory version is different from that typed by the user).
568 if self.shell.rc.automagic:
580 if self.shell.rc.automagic:
569 start_magic = esc_magic+start
581 start_magic = esc_magic+start
570 else:
582 else:
571 start_magic = start
583 start_magic = start
572 # Look through the input history in reverse
584 # Look through the input history in reverse
573 for n in range(len(self.shell.input_hist)-2,0,-1):
585 for n in range(len(self.shell.input_hist)-2,0,-1):
574 input = self.shell.input_hist[n]
586 input = self.shell.input_hist[n]
575 # skip plain 'r' lines so we don't recurse to infinity
587 # skip plain 'r' lines so we don't recurse to infinity
576 if input != '_ip.magic("r")\n' and \
588 if input != '_ip.magic("r")\n' and \
577 (input.startswith(start) or input.startswith(start_magic)):
589 (input.startswith(start) or input.startswith(start_magic)):
578 #print 'match',`input` # dbg
590 #print 'match',`input` # dbg
579 print 'Executing:',input,
591 print 'Executing:',input,
580 self.shell.runlines(input)
592 self.shell.runlines(input)
581 return
593 return
582 print 'No previous input matching `%s` found.' % start
594 print 'No previous input matching `%s` found.' % start
583
595
584 def magic_page(self, parameter_s=''):
596 def magic_page(self, parameter_s=''):
585 """Pretty print the object and display it through a pager.
597 """Pretty print the object and display it through a pager.
586
598
587 If no parameter is given, use _ (last output)."""
599 If no parameter is given, use _ (last output)."""
588 # After a function contributed by Olivier Aubert, slightly modified.
600 # After a function contributed by Olivier Aubert, slightly modified.
589
601
590 oname = parameter_s and parameter_s or '_'
602 oname = parameter_s and parameter_s or '_'
591 info = self._ofind(oname)
603 info = self._ofind(oname)
592 if info['found']:
604 if info['found']:
593 page(pformat(info['obj']))
605 page(pformat(info['obj']))
594 else:
606 else:
595 print 'Object `%s` not found' % oname
607 print 'Object `%s` not found' % oname
596
608
597 def magic_profile(self, parameter_s=''):
609 def magic_profile(self, parameter_s=''):
598 """Print your currently active IPyhton profile."""
610 """Print your currently active IPyhton profile."""
599 if self.shell.rc.profile:
611 if self.shell.rc.profile:
600 printpl('Current IPython profile: $self.shell.rc.profile.')
612 printpl('Current IPython profile: $self.shell.rc.profile.')
601 else:
613 else:
602 print 'No profile active.'
614 print 'No profile active.'
603
615
604 def _inspect(self,meth,oname,**kw):
616 def _inspect(self,meth,oname,**kw):
605 """Generic interface to the inspector system.
617 """Generic interface to the inspector system.
606
618
607 This function is meant to be called by pdef, pdoc & friends."""
619 This function is meant to be called by pdef, pdoc & friends."""
608
620
609 oname = oname.strip()
621 oname = oname.strip()
610 info = Struct(self._ofind(oname))
622 info = Struct(self._ofind(oname))
611 if info.found:
623 if info.found:
612 pmethod = getattr(self.shell.inspector,meth)
624 pmethod = getattr(self.shell.inspector,meth)
613 formatter = info.ismagic and self.format_screen or None
625 formatter = info.ismagic and self.format_screen or None
614 if meth == 'pdoc':
626 if meth == 'pdoc':
615 pmethod(info.obj,oname,formatter)
627 pmethod(info.obj,oname,formatter)
616 elif meth == 'pinfo':
628 elif meth == 'pinfo':
617 pmethod(info.obj,oname,formatter,info,**kw)
629 pmethod(info.obj,oname,formatter,info,**kw)
618 else:
630 else:
619 pmethod(info.obj,oname)
631 pmethod(info.obj,oname)
620 else:
632 else:
621 print 'Object `%s` not found.' % oname
633 print 'Object `%s` not found.' % oname
622 return 'not found' # so callers can take other action
634 return 'not found' # so callers can take other action
623
635
624 def magic_pdef(self, parameter_s=''):
636 def magic_pdef(self, parameter_s=''):
625 """Print the definition header for any callable object.
637 """Print the definition header for any callable object.
626
638
627 If the object is a class, print the constructor information."""
639 If the object is a class, print the constructor information."""
628 self._inspect('pdef',parameter_s)
640 self._inspect('pdef',parameter_s)
629
641
630 def magic_pdoc(self, parameter_s=''):
642 def magic_pdoc(self, parameter_s=''):
631 """Print the docstring for an object.
643 """Print the docstring for an object.
632
644
633 If the given object is a class, it will print both the class and the
645 If the given object is a class, it will print both the class and the
634 constructor docstrings."""
646 constructor docstrings."""
635 self._inspect('pdoc',parameter_s)
647 self._inspect('pdoc',parameter_s)
636
648
637 def magic_psource(self, parameter_s=''):
649 def magic_psource(self, parameter_s=''):
638 """Print (or run through pager) the source code for an object."""
650 """Print (or run through pager) the source code for an object."""
639 self._inspect('psource',parameter_s)
651 self._inspect('psource',parameter_s)
640
652
641 def magic_pfile(self, parameter_s=''):
653 def magic_pfile(self, parameter_s=''):
642 """Print (or run through pager) the file where an object is defined.
654 """Print (or run through pager) the file where an object is defined.
643
655
644 The file opens at the line where the object definition begins. IPython
656 The file opens at the line where the object definition begins. IPython
645 will honor the environment variable PAGER if set, and otherwise will
657 will honor the environment variable PAGER if set, and otherwise will
646 do its best to print the file in a convenient form.
658 do its best to print the file in a convenient form.
647
659
648 If the given argument is not an object currently defined, IPython will
660 If the given argument is not an object currently defined, IPython will
649 try to interpret it as a filename (automatically adding a .py extension
661 try to interpret it as a filename (automatically adding a .py extension
650 if needed). You can thus use %pfile as a syntax highlighting code
662 if needed). You can thus use %pfile as a syntax highlighting code
651 viewer."""
663 viewer."""
652
664
653 # first interpret argument as an object name
665 # first interpret argument as an object name
654 out = self._inspect('pfile',parameter_s)
666 out = self._inspect('pfile',parameter_s)
655 # if not, try the input as a filename
667 # if not, try the input as a filename
656 if out == 'not found':
668 if out == 'not found':
657 try:
669 try:
658 filename = get_py_filename(parameter_s)
670 filename = get_py_filename(parameter_s)
659 except IOError,msg:
671 except IOError,msg:
660 print msg
672 print msg
661 return
673 return
662 page(self.shell.inspector.format(file(filename).read()))
674 page(self.shell.inspector.format(file(filename).read()))
663
675
664 def magic_pinfo(self, parameter_s=''):
676 def magic_pinfo(self, parameter_s=''):
665 """Provide detailed information about an object.
677 """Provide detailed information about an object.
666
678
667 '%pinfo object' is just a synonym for object? or ?object."""
679 '%pinfo object' is just a synonym for object? or ?object."""
668
680
669 #print 'pinfo par: <%s>' % parameter_s # dbg
681 #print 'pinfo par: <%s>' % parameter_s # dbg
670
682
671 # detail_level: 0 -> obj? , 1 -> obj??
683 # detail_level: 0 -> obj? , 1 -> obj??
672 detail_level = 0
684 detail_level = 0
673 # We need to detect if we got called as 'pinfo pinfo foo', which can
685 # We need to detect if we got called as 'pinfo pinfo foo', which can
674 # happen if the user types 'pinfo foo?' at the cmd line.
686 # happen if the user types 'pinfo foo?' at the cmd line.
675 pinfo,qmark1,oname,qmark2 = \
687 pinfo,qmark1,oname,qmark2 = \
676 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
688 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
677 if pinfo or qmark1 or qmark2:
689 if pinfo or qmark1 or qmark2:
678 detail_level = 1
690 detail_level = 1
679 if "*" in oname:
691 if "*" in oname:
680 self.magic_psearch(oname)
692 self.magic_psearch(oname)
681 else:
693 else:
682 self._inspect('pinfo',oname,detail_level=detail_level)
694 self._inspect('pinfo',oname,detail_level=detail_level)
683
695
684 def magic_psearch(self, parameter_s=''):
696 def magic_psearch(self, parameter_s=''):
685 """Search for object in namespaces by wildcard.
697 """Search for object in namespaces by wildcard.
686
698
687 %psearch [options] PATTERN [OBJECT TYPE]
699 %psearch [options] PATTERN [OBJECT TYPE]
688
700
689 Note: ? can be used as a synonym for %psearch, at the beginning or at
701 Note: ? can be used as a synonym for %psearch, at the beginning or at
690 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
702 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
691 rest of the command line must be unchanged (options come first), so
703 rest of the command line must be unchanged (options come first), so
692 for example the following forms are equivalent
704 for example the following forms are equivalent
693
705
694 %psearch -i a* function
706 %psearch -i a* function
695 -i a* function?
707 -i a* function?
696 ?-i a* function
708 ?-i a* function
697
709
698 Arguments:
710 Arguments:
699
711
700 PATTERN
712 PATTERN
701
713
702 where PATTERN is a string containing * as a wildcard similar to its
714 where PATTERN is a string containing * as a wildcard similar to its
703 use in a shell. The pattern is matched in all namespaces on the
715 use in a shell. The pattern is matched in all namespaces on the
704 search path. By default objects starting with a single _ are not
716 search path. By default objects starting with a single _ are not
705 matched, many IPython generated objects have a single
717 matched, many IPython generated objects have a single
706 underscore. The default is case insensitive matching. Matching is
718 underscore. The default is case insensitive matching. Matching is
707 also done on the attributes of objects and not only on the objects
719 also done on the attributes of objects and not only on the objects
708 in a module.
720 in a module.
709
721
710 [OBJECT TYPE]
722 [OBJECT TYPE]
711
723
712 Is the name of a python type from the types module. The name is
724 Is the name of a python type from the types module. The name is
713 given in lowercase without the ending type, ex. StringType is
725 given in lowercase without the ending type, ex. StringType is
714 written string. By adding a type here only objects matching the
726 written string. By adding a type here only objects matching the
715 given type are matched. Using all here makes the pattern match all
727 given type are matched. Using all here makes the pattern match all
716 types (this is the default).
728 types (this is the default).
717
729
718 Options:
730 Options:
719
731
720 -a: makes the pattern match even objects whose names start with a
732 -a: makes the pattern match even objects whose names start with a
721 single underscore. These names are normally ommitted from the
733 single underscore. These names are normally ommitted from the
722 search.
734 search.
723
735
724 -i/-c: make the pattern case insensitive/sensitive. If neither of
736 -i/-c: make the pattern case insensitive/sensitive. If neither of
725 these options is given, the default is read from your ipythonrc
737 these options is given, the default is read from your ipythonrc
726 file. The option name which sets this value is
738 file. The option name which sets this value is
727 'wildcards_case_sensitive'. If this option is not specified in your
739 'wildcards_case_sensitive'. If this option is not specified in your
728 ipythonrc file, IPython's internal default is to do a case sensitive
740 ipythonrc file, IPython's internal default is to do a case sensitive
729 search.
741 search.
730
742
731 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
743 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
732 specifiy can be searched in any of the following namespaces:
744 specifiy can be searched in any of the following namespaces:
733 'builtin', 'user', 'user_global','internal', 'alias', where
745 'builtin', 'user', 'user_global','internal', 'alias', where
734 'builtin' and 'user' are the search defaults. Note that you should
746 'builtin' and 'user' are the search defaults. Note that you should
735 not use quotes when specifying namespaces.
747 not use quotes when specifying namespaces.
736
748
737 'Builtin' contains the python module builtin, 'user' contains all
749 'Builtin' contains the python module builtin, 'user' contains all
738 user data, 'alias' only contain the shell aliases and no python
750 user data, 'alias' only contain the shell aliases and no python
739 objects, 'internal' contains objects used by IPython. The
751 objects, 'internal' contains objects used by IPython. The
740 'user_global' namespace is only used by embedded IPython instances,
752 'user_global' namespace is only used by embedded IPython instances,
741 and it contains module-level globals. You can add namespaces to the
753 and it contains module-level globals. You can add namespaces to the
742 search with -s or exclude them with -e (these options can be given
754 search with -s or exclude them with -e (these options can be given
743 more than once).
755 more than once).
744
756
745 Examples:
757 Examples:
746
758
747 %psearch a* -> objects beginning with an a
759 %psearch a* -> objects beginning with an a
748 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
760 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
749 %psearch a* function -> all functions beginning with an a
761 %psearch a* function -> all functions beginning with an a
750 %psearch re.e* -> objects beginning with an e in module re
762 %psearch re.e* -> objects beginning with an e in module re
751 %psearch r*.e* -> objects that start with e in modules starting in r
763 %psearch r*.e* -> objects that start with e in modules starting in r
752 %psearch r*.* string -> all strings in modules beginning with r
764 %psearch r*.* string -> all strings in modules beginning with r
753
765
754 Case sensitve search:
766 Case sensitve search:
755
767
756 %psearch -c a* list all object beginning with lower case a
768 %psearch -c a* list all object beginning with lower case a
757
769
758 Show objects beginning with a single _:
770 Show objects beginning with a single _:
759
771
760 %psearch -a _* list objects beginning with a single underscore"""
772 %psearch -a _* list objects beginning with a single underscore"""
761
773
762 # default namespaces to be searched
774 # default namespaces to be searched
763 def_search = ['user','builtin']
775 def_search = ['user','builtin']
764
776
765 # Process options/args
777 # Process options/args
766 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
778 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
767 opt = opts.get
779 opt = opts.get
768 shell = self.shell
780 shell = self.shell
769 psearch = shell.inspector.psearch
781 psearch = shell.inspector.psearch
770
782
771 # select case options
783 # select case options
772 if opts.has_key('i'):
784 if opts.has_key('i'):
773 ignore_case = True
785 ignore_case = True
774 elif opts.has_key('c'):
786 elif opts.has_key('c'):
775 ignore_case = False
787 ignore_case = False
776 else:
788 else:
777 ignore_case = not shell.rc.wildcards_case_sensitive
789 ignore_case = not shell.rc.wildcards_case_sensitive
778
790
779 # Build list of namespaces to search from user options
791 # Build list of namespaces to search from user options
780 def_search.extend(opt('s',[]))
792 def_search.extend(opt('s',[]))
781 ns_exclude = ns_exclude=opt('e',[])
793 ns_exclude = ns_exclude=opt('e',[])
782 ns_search = [nm for nm in def_search if nm not in ns_exclude]
794 ns_search = [nm for nm in def_search if nm not in ns_exclude]
783
795
784 # Call the actual search
796 # Call the actual search
785 try:
797 try:
786 psearch(args,shell.ns_table,ns_search,
798 psearch(args,shell.ns_table,ns_search,
787 show_all=opt('a'),ignore_case=ignore_case)
799 show_all=opt('a'),ignore_case=ignore_case)
788 except:
800 except:
789 shell.showtraceback()
801 shell.showtraceback()
790
802
791 def magic_who_ls(self, parameter_s=''):
803 def magic_who_ls(self, parameter_s=''):
792 """Return a sorted list of all interactive variables.
804 """Return a sorted list of all interactive variables.
793
805
794 If arguments are given, only variables of types matching these
806 If arguments are given, only variables of types matching these
795 arguments are returned."""
807 arguments are returned."""
796
808
797 user_ns = self.shell.user_ns
809 user_ns = self.shell.user_ns
798 internal_ns = self.shell.internal_ns
810 internal_ns = self.shell.internal_ns
799 user_config_ns = self.shell.user_config_ns
811 user_config_ns = self.shell.user_config_ns
800 out = []
812 out = []
801 typelist = parameter_s.split()
813 typelist = parameter_s.split()
802
814
803 for i in user_ns:
815 for i in user_ns:
804 if not (i.startswith('_') or i.startswith('_i')) \
816 if not (i.startswith('_') or i.startswith('_i')) \
805 and not (i in internal_ns or i in user_config_ns):
817 and not (i in internal_ns or i in user_config_ns):
806 if typelist:
818 if typelist:
807 if type(user_ns[i]).__name__ in typelist:
819 if type(user_ns[i]).__name__ in typelist:
808 out.append(i)
820 out.append(i)
809 else:
821 else:
810 out.append(i)
822 out.append(i)
811 out.sort()
823 out.sort()
812 return out
824 return out
813
825
814 def magic_who(self, parameter_s=''):
826 def magic_who(self, parameter_s=''):
815 """Print all interactive variables, with some minimal formatting.
827 """Print all interactive variables, with some minimal formatting.
816
828
817 If any arguments are given, only variables whose type matches one of
829 If any arguments are given, only variables whose type matches one of
818 these are printed. For example:
830 these are printed. For example:
819
831
820 %who function str
832 %who function str
821
833
822 will only list functions and strings, excluding all other types of
834 will only list functions and strings, excluding all other types of
823 variables. To find the proper type names, simply use type(var) at a
835 variables. To find the proper type names, simply use type(var) at a
824 command line to see how python prints type names. For example:
836 command line to see how python prints type names. For example:
825
837
826 In [1]: type('hello')\\
838 In [1]: type('hello')\\
827 Out[1]: <type 'str'>
839 Out[1]: <type 'str'>
828
840
829 indicates that the type name for strings is 'str'.
841 indicates that the type name for strings is 'str'.
830
842
831 %who always excludes executed names loaded through your configuration
843 %who always excludes executed names loaded through your configuration
832 file and things which are internal to IPython.
844 file and things which are internal to IPython.
833
845
834 This is deliberate, as typically you may load many modules and the
846 This is deliberate, as typically you may load many modules and the
835 purpose of %who is to show you only what you've manually defined."""
847 purpose of %who is to show you only what you've manually defined."""
836
848
837 varlist = self.magic_who_ls(parameter_s)
849 varlist = self.magic_who_ls(parameter_s)
838 if not varlist:
850 if not varlist:
839 print 'Interactive namespace is empty.'
851 print 'Interactive namespace is empty.'
840 return
852 return
841
853
842 # if we have variables, move on...
854 # if we have variables, move on...
843
855
844 # stupid flushing problem: when prompts have no separators, stdout is
856 # stupid flushing problem: when prompts have no separators, stdout is
845 # getting lost. I'm starting to think this is a python bug. I'm having
857 # getting lost. I'm starting to think this is a python bug. I'm having
846 # to force a flush with a print because even a sys.stdout.flush
858 # to force a flush with a print because even a sys.stdout.flush
847 # doesn't seem to do anything!
859 # doesn't seem to do anything!
848
860
849 count = 0
861 count = 0
850 for i in varlist:
862 for i in varlist:
851 print i+'\t',
863 print i+'\t',
852 count += 1
864 count += 1
853 if count > 8:
865 if count > 8:
854 count = 0
866 count = 0
855 print
867 print
856 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
868 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
857
869
858 print # well, this does force a flush at the expense of an extra \n
870 print # well, this does force a flush at the expense of an extra \n
859
871
860 def magic_whos(self, parameter_s=''):
872 def magic_whos(self, parameter_s=''):
861 """Like %who, but gives some extra information about each variable.
873 """Like %who, but gives some extra information about each variable.
862
874
863 The same type filtering of %who can be applied here.
875 The same type filtering of %who can be applied here.
864
876
865 For all variables, the type is printed. Additionally it prints:
877 For all variables, the type is printed. Additionally it prints:
866
878
867 - For {},[],(): their length.
879 - For {},[],(): their length.
868
880
869 - For Numeric arrays, a summary with shape, number of elements,
881 - For Numeric arrays, a summary with shape, number of elements,
870 typecode and size in memory.
882 typecode and size in memory.
871
883
872 - Everything else: a string representation, snipping their middle if
884 - Everything else: a string representation, snipping their middle if
873 too long."""
885 too long."""
874
886
875 varnames = self.magic_who_ls(parameter_s)
887 varnames = self.magic_who_ls(parameter_s)
876 if not varnames:
888 if not varnames:
877 print 'Interactive namespace is empty.'
889 print 'Interactive namespace is empty.'
878 return
890 return
879
891
880 # if we have variables, move on...
892 # if we have variables, move on...
881
893
882 # for these types, show len() instead of data:
894 # for these types, show len() instead of data:
883 seq_types = [types.DictType,types.ListType,types.TupleType]
895 seq_types = [types.DictType,types.ListType,types.TupleType]
884
896
885 # for Numeric arrays, display summary info
897 # for Numeric arrays, display summary info
886 try:
898 try:
887 import Numeric
899 import Numeric
888 except ImportError:
900 except ImportError:
889 array_type = None
901 array_type = None
890 else:
902 else:
891 array_type = Numeric.ArrayType.__name__
903 array_type = Numeric.ArrayType.__name__
892
904
893 # Find all variable names and types so we can figure out column sizes
905 # Find all variable names and types so we can figure out column sizes
894 get_vars = lambda i: self.shell.user_ns[i]
906 get_vars = lambda i: self.shell.user_ns[i]
895 type_name = lambda v: type(v).__name__
907 type_name = lambda v: type(v).__name__
896 varlist = map(get_vars,varnames)
908 varlist = map(get_vars,varnames)
897
909
898 typelist = []
910 typelist = []
899 for vv in varlist:
911 for vv in varlist:
900 tt = type_name(vv)
912 tt = type_name(vv)
901 if tt=='instance':
913 if tt=='instance':
902 typelist.append(str(vv.__class__))
914 typelist.append(str(vv.__class__))
903 else:
915 else:
904 typelist.append(tt)
916 typelist.append(tt)
905
917
906 # column labels and # of spaces as separator
918 # column labels and # of spaces as separator
907 varlabel = 'Variable'
919 varlabel = 'Variable'
908 typelabel = 'Type'
920 typelabel = 'Type'
909 datalabel = 'Data/Info'
921 datalabel = 'Data/Info'
910 colsep = 3
922 colsep = 3
911 # variable format strings
923 # variable format strings
912 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
924 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
913 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
925 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
914 aformat = "%s: %s elems, type `%s`, %s bytes"
926 aformat = "%s: %s elems, type `%s`, %s bytes"
915 # find the size of the columns to format the output nicely
927 # find the size of the columns to format the output nicely
916 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
928 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
917 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
929 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
918 # table header
930 # table header
919 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
931 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
920 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
932 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
921 # and the table itself
933 # and the table itself
922 kb = 1024
934 kb = 1024
923 Mb = 1048576 # kb**2
935 Mb = 1048576 # kb**2
924 for vname,var,vtype in zip(varnames,varlist,typelist):
936 for vname,var,vtype in zip(varnames,varlist,typelist):
925 print itpl(vformat),
937 print itpl(vformat),
926 if vtype in seq_types:
938 if vtype in seq_types:
927 print len(var)
939 print len(var)
928 elif vtype==array_type:
940 elif vtype==array_type:
929 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
941 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
930 vsize = Numeric.size(var)
942 vsize = Numeric.size(var)
931 vbytes = vsize*var.itemsize()
943 vbytes = vsize*var.itemsize()
932 if vbytes < 100000:
944 if vbytes < 100000:
933 print aformat % (vshape,vsize,var.typecode(),vbytes)
945 print aformat % (vshape,vsize,var.typecode(),vbytes)
934 else:
946 else:
935 print aformat % (vshape,vsize,var.typecode(),vbytes),
947 print aformat % (vshape,vsize,var.typecode(),vbytes),
936 if vbytes < Mb:
948 if vbytes < Mb:
937 print '(%s kb)' % (vbytes/kb,)
949 print '(%s kb)' % (vbytes/kb,)
938 else:
950 else:
939 print '(%s Mb)' % (vbytes/Mb,)
951 print '(%s Mb)' % (vbytes/Mb,)
940 else:
952 else:
941 vstr = str(var).replace('\n','\\n')
953 vstr = str(var).replace('\n','\\n')
942 if len(vstr) < 50:
954 if len(vstr) < 50:
943 print vstr
955 print vstr
944 else:
956 else:
945 printpl(vfmt_short)
957 printpl(vfmt_short)
946
958
947 def magic_reset(self, parameter_s=''):
959 def magic_reset(self, parameter_s=''):
948 """Resets the namespace by removing all names defined by the user.
960 """Resets the namespace by removing all names defined by the user.
949
961
950 Input/Output history are left around in case you need them."""
962 Input/Output history are left around in case you need them."""
951
963
952 ans = raw_input(
964 ans = raw_input(
953 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
965 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
954 if not ans.lower() == 'y':
966 if not ans.lower() == 'y':
955 print 'Nothing done.'
967 print 'Nothing done.'
956 return
968 return
957 user_ns = self.shell.user_ns
969 user_ns = self.shell.user_ns
958 for i in self.magic_who_ls():
970 for i in self.magic_who_ls():
959 del(user_ns[i])
971 del(user_ns[i])
960
972
961 def magic_config(self,parameter_s=''):
973 def magic_config(self,parameter_s=''):
962 """Show IPython's internal configuration."""
974 """Show IPython's internal configuration."""
963
975
964 page('Current configuration structure:\n'+
976 page('Current configuration structure:\n'+
965 pformat(self.shell.rc.dict()))
977 pformat(self.shell.rc.dict()))
966
978
967 def magic_logstart(self,parameter_s=''):
979 def magic_logstart(self,parameter_s=''):
968 """Start logging anywhere in a session.
980 """Start logging anywhere in a session.
969
981
970 %logstart [-o|-t] [log_name [log_mode]]
982 %logstart [-o|-t] [log_name [log_mode]]
971
983
972 If no name is given, it defaults to a file named 'ipython_log.py' in your
984 If no name is given, it defaults to a file named 'ipython_log.py' in your
973 current directory, in 'rotate' mode (see below).
985 current directory, in 'rotate' mode (see below).
974
986
975 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
987 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
976 history up to that point and then continues logging.
988 history up to that point and then continues logging.
977
989
978 %logstart takes a second optional parameter: logging mode. This can be one
990 %logstart takes a second optional parameter: logging mode. This can be one
979 of (note that the modes are given unquoted):\\
991 of (note that the modes are given unquoted):\\
980 append: well, that says it.\\
992 append: well, that says it.\\
981 backup: rename (if exists) to name~ and start name.\\
993 backup: rename (if exists) to name~ and start name.\\
982 global: single logfile in your home dir, appended to.\\
994 global: single logfile in your home dir, appended to.\\
983 over : overwrite existing log.\\
995 over : overwrite existing log.\\
984 rotate: create rotating logs name.1~, name.2~, etc.
996 rotate: create rotating logs name.1~, name.2~, etc.
985
997
986 Options:
998 Options:
987
999
988 -o: log also IPython's output. In this mode, all commands which
1000 -o: log also IPython's output. In this mode, all commands which
989 generate an Out[NN] prompt are recorded to the logfile, right after
1001 generate an Out[NN] prompt are recorded to the logfile, right after
990 their corresponding input line. The output lines are always
1002 their corresponding input line. The output lines are always
991 prepended with a '#[Out]# ' marker, so that the log remains valid
1003 prepended with a '#[Out]# ' marker, so that the log remains valid
992 Python code.
1004 Python code.
993
1005
994 Since this marker is always the same, filtering only the output from
1006 Since this marker is always the same, filtering only the output from
995 a log is very easy, using for example a simple awk call:
1007 a log is very easy, using for example a simple awk call:
996
1008
997 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1009 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
998
1010
999 -t: put timestamps before each input line logged (these are put in
1011 -t: put timestamps before each input line logged (these are put in
1000 comments)."""
1012 comments)."""
1001
1013
1002 opts,par = self.parse_options(parameter_s,'ot')
1014 opts,par = self.parse_options(parameter_s,'ot')
1003 log_output = 'o' in opts
1015 log_output = 'o' in opts
1004 timestamp = 't' in opts
1016 timestamp = 't' in opts
1005
1017
1006 rc = self.shell.rc
1018 rc = self.shell.rc
1007 logger = self.shell.logger
1019 logger = self.shell.logger
1008
1020
1009 # if no args are given, the defaults set in the logger constructor by
1021 # if no args are given, the defaults set in the logger constructor by
1010 # ipytohn remain valid
1022 # ipytohn remain valid
1011 if par:
1023 if par:
1012 try:
1024 try:
1013 logfname,logmode = par.split()
1025 logfname,logmode = par.split()
1014 except:
1026 except:
1015 logfname = par
1027 logfname = par
1016 logmode = 'backup'
1028 logmode = 'backup'
1017 else:
1029 else:
1018 logfname = logger.logfname
1030 logfname = logger.logfname
1019 logmode = logger.logmode
1031 logmode = logger.logmode
1020 # put logfname into rc struct as if it had been called on the command
1032 # put logfname into rc struct as if it had been called on the command
1021 # line, so it ends up saved in the log header Save it in case we need
1033 # line, so it ends up saved in the log header Save it in case we need
1022 # to restore it...
1034 # to restore it...
1023 old_logfile = rc.opts.get('logfile','')
1035 old_logfile = rc.opts.get('logfile','')
1024 if logfname:
1036 if logfname:
1025 logfname = os.path.expanduser(logfname)
1037 logfname = os.path.expanduser(logfname)
1026 rc.opts.logfile = logfname
1038 rc.opts.logfile = logfname
1027 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1039 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1028 try:
1040 try:
1029 started = logger.logstart(logfname,loghead,logmode,
1041 started = logger.logstart(logfname,loghead,logmode,
1030 log_output,timestamp)
1042 log_output,timestamp)
1031 except:
1043 except:
1032 rc.opts.logfile = old_logfile
1044 rc.opts.logfile = old_logfile
1033 warn("Couldn't start log: %s" % sys.exc_info()[1])
1045 warn("Couldn't start log: %s" % sys.exc_info()[1])
1034 else:
1046 else:
1035 # log input history up to this point, optionally interleaving
1047 # log input history up to this point, optionally interleaving
1036 # output if requested
1048 # output if requested
1037
1049
1038 if timestamp:
1050 if timestamp:
1039 # disable timestamping for the previous history, since we've
1051 # disable timestamping for the previous history, since we've
1040 # lost those already (no time machine here).
1052 # lost those already (no time machine here).
1041 logger.timestamp = False
1053 logger.timestamp = False
1042 if log_output:
1054 if log_output:
1043 log_write = logger.log_write
1055 log_write = logger.log_write
1044 input_hist = self.shell.input_hist
1056 input_hist = self.shell.input_hist
1045 output_hist = self.shell.output_hist
1057 output_hist = self.shell.output_hist
1046 for n in range(1,len(input_hist)-1):
1058 for n in range(1,len(input_hist)-1):
1047 log_write(input_hist[n].rstrip())
1059 log_write(input_hist[n].rstrip())
1048 if n in output_hist:
1060 if n in output_hist:
1049 log_write(repr(output_hist[n]),'output')
1061 log_write(repr(output_hist[n]),'output')
1050 else:
1062 else:
1051 logger.log_write(self.shell.input_hist[1:])
1063 logger.log_write(self.shell.input_hist[1:])
1052 if timestamp:
1064 if timestamp:
1053 # re-enable timestamping
1065 # re-enable timestamping
1054 logger.timestamp = True
1066 logger.timestamp = True
1055
1067
1056 print ('Activating auto-logging. '
1068 print ('Activating auto-logging. '
1057 'Current session state plus future input saved.')
1069 'Current session state plus future input saved.')
1058 logger.logstate()
1070 logger.logstate()
1059
1071
1060 def magic_logoff(self,parameter_s=''):
1072 def magic_logoff(self,parameter_s=''):
1061 """Temporarily stop logging.
1073 """Temporarily stop logging.
1062
1074
1063 You must have previously started logging."""
1075 You must have previously started logging."""
1064 self.shell.logger.switch_log(0)
1076 self.shell.logger.switch_log(0)
1065
1077
1066 def magic_logon(self,parameter_s=''):
1078 def magic_logon(self,parameter_s=''):
1067 """Restart logging.
1079 """Restart logging.
1068
1080
1069 This function is for restarting logging which you've temporarily
1081 This function is for restarting logging which you've temporarily
1070 stopped with %logoff. For starting logging for the first time, you
1082 stopped with %logoff. For starting logging for the first time, you
1071 must use the %logstart function, which allows you to specify an
1083 must use the %logstart function, which allows you to specify an
1072 optional log filename."""
1084 optional log filename."""
1073
1085
1074 self.shell.logger.switch_log(1)
1086 self.shell.logger.switch_log(1)
1075
1087
1076 def magic_logstate(self,parameter_s=''):
1088 def magic_logstate(self,parameter_s=''):
1077 """Print the status of the logging system."""
1089 """Print the status of the logging system."""
1078
1090
1079 self.shell.logger.logstate()
1091 self.shell.logger.logstate()
1080
1092
1081 def magic_pdb(self, parameter_s=''):
1093 def magic_pdb(self, parameter_s=''):
1082 """Control the calling of the pdb interactive debugger.
1094 """Control the calling of the pdb interactive debugger.
1083
1095
1084 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1096 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1085 argument it works as a toggle.
1097 argument it works as a toggle.
1086
1098
1087 When an exception is triggered, IPython can optionally call the
1099 When an exception is triggered, IPython can optionally call the
1088 interactive pdb debugger after the traceback printout. %pdb toggles
1100 interactive pdb debugger after the traceback printout. %pdb toggles
1089 this feature on and off."""
1101 this feature on and off."""
1090
1102
1091 par = parameter_s.strip().lower()
1103 par = parameter_s.strip().lower()
1092
1104
1093 if par:
1105 if par:
1094 try:
1106 try:
1095 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1107 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1096 except KeyError:
1108 except KeyError:
1097 print ('Incorrect argument. Use on/1, off/0, '
1109 print ('Incorrect argument. Use on/1, off/0, '
1098 'or nothing for a toggle.')
1110 'or nothing for a toggle.')
1099 return
1111 return
1100 else:
1112 else:
1101 # toggle
1113 # toggle
1102 new_pdb = not self.shell.InteractiveTB.call_pdb
1114 new_pdb = not self.shell.InteractiveTB.call_pdb
1103
1115
1104 # set on the shell
1116 # set on the shell
1105 self.shell.call_pdb = new_pdb
1117 self.shell.call_pdb = new_pdb
1106 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1118 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1107
1119
1108 def magic_prun(self, parameter_s ='',user_mode=1,
1120 def magic_prun(self, parameter_s ='',user_mode=1,
1109 opts=None,arg_lst=None,prog_ns=None):
1121 opts=None,arg_lst=None,prog_ns=None):
1110
1122
1111 """Run a statement through the python code profiler.
1123 """Run a statement through the python code profiler.
1112
1124
1113 Usage:\\
1125 Usage:\\
1114 %prun [options] statement
1126 %prun [options] statement
1115
1127
1116 The given statement (which doesn't require quote marks) is run via the
1128 The given statement (which doesn't require quote marks) is run via the
1117 python profiler in a manner similar to the profile.run() function.
1129 python profiler in a manner similar to the profile.run() function.
1118 Namespaces are internally managed to work correctly; profile.run
1130 Namespaces are internally managed to work correctly; profile.run
1119 cannot be used in IPython because it makes certain assumptions about
1131 cannot be used in IPython because it makes certain assumptions about
1120 namespaces which do not hold under IPython.
1132 namespaces which do not hold under IPython.
1121
1133
1122 Options:
1134 Options:
1123
1135
1124 -l <limit>: you can place restrictions on what or how much of the
1136 -l <limit>: you can place restrictions on what or how much of the
1125 profile gets printed. The limit value can be:
1137 profile gets printed. The limit value can be:
1126
1138
1127 * A string: only information for function names containing this string
1139 * A string: only information for function names containing this string
1128 is printed.
1140 is printed.
1129
1141
1130 * An integer: only these many lines are printed.
1142 * An integer: only these many lines are printed.
1131
1143
1132 * A float (between 0 and 1): this fraction of the report is printed
1144 * A float (between 0 and 1): this fraction of the report is printed
1133 (for example, use a limit of 0.4 to see the topmost 40% only).
1145 (for example, use a limit of 0.4 to see the topmost 40% only).
1134
1146
1135 You can combine several limits with repeated use of the option. For
1147 You can combine several limits with repeated use of the option. For
1136 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1148 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1137 information about class constructors.
1149 information about class constructors.
1138
1150
1139 -r: return the pstats.Stats object generated by the profiling. This
1151 -r: return the pstats.Stats object generated by the profiling. This
1140 object has all the information about the profile in it, and you can
1152 object has all the information about the profile in it, and you can
1141 later use it for further analysis or in other functions.
1153 later use it for further analysis or in other functions.
1142
1154
1143 Since magic functions have a particular form of calling which prevents
1155 Since magic functions have a particular form of calling which prevents
1144 you from writing something like:\\
1156 you from writing something like:\\
1145 In [1]: p = %prun -r print 4 # invalid!\\
1157 In [1]: p = %prun -r print 4 # invalid!\\
1146 you must instead use IPython's automatic variables to assign this:\\
1158 you must instead use IPython's automatic variables to assign this:\\
1147 In [1]: %prun -r print 4 \\
1159 In [1]: %prun -r print 4 \\
1148 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1160 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1149 In [2]: stats = _
1161 In [2]: stats = _
1150
1162
1151 If you really need to assign this value via an explicit function call,
1163 If you really need to assign this value via an explicit function call,
1152 you can always tap directly into the true name of the magic function
1164 you can always tap directly into the true name of the magic function
1153 by using the _ip.magic function:\\
1165 by using the _ip.magic function:\\
1154 In [3]: stats = _ip.magic('prun','-r print 4')
1166 In [3]: stats = _ip.magic('prun','-r print 4')
1155
1167
1156 You can type _ip.magic? for more details.
1168 You can type _ip.magic? for more details.
1157
1169
1158 -s <key>: sort profile by given key. You can provide more than one key
1170 -s <key>: sort profile by given key. You can provide more than one key
1159 by using the option several times: '-s key1 -s key2 -s key3...'. The
1171 by using the option several times: '-s key1 -s key2 -s key3...'. The
1160 default sorting key is 'time'.
1172 default sorting key is 'time'.
1161
1173
1162 The following is copied verbatim from the profile documentation
1174 The following is copied verbatim from the profile documentation
1163 referenced below:
1175 referenced below:
1164
1176
1165 When more than one key is provided, additional keys are used as
1177 When more than one key is provided, additional keys are used as
1166 secondary criteria when the there is equality in all keys selected
1178 secondary criteria when the there is equality in all keys selected
1167 before them.
1179 before them.
1168
1180
1169 Abbreviations can be used for any key names, as long as the
1181 Abbreviations can be used for any key names, as long as the
1170 abbreviation is unambiguous. The following are the keys currently
1182 abbreviation is unambiguous. The following are the keys currently
1171 defined:
1183 defined:
1172
1184
1173 Valid Arg Meaning\\
1185 Valid Arg Meaning\\
1174 "calls" call count\\
1186 "calls" call count\\
1175 "cumulative" cumulative time\\
1187 "cumulative" cumulative time\\
1176 "file" file name\\
1188 "file" file name\\
1177 "module" file name\\
1189 "module" file name\\
1178 "pcalls" primitive call count\\
1190 "pcalls" primitive call count\\
1179 "line" line number\\
1191 "line" line number\\
1180 "name" function name\\
1192 "name" function name\\
1181 "nfl" name/file/line\\
1193 "nfl" name/file/line\\
1182 "stdname" standard name\\
1194 "stdname" standard name\\
1183 "time" internal time
1195 "time" internal time
1184
1196
1185 Note that all sorts on statistics are in descending order (placing
1197 Note that all sorts on statistics are in descending order (placing
1186 most time consuming items first), where as name, file, and line number
1198 most time consuming items first), where as name, file, and line number
1187 searches are in ascending order (i.e., alphabetical). The subtle
1199 searches are in ascending order (i.e., alphabetical). The subtle
1188 distinction between "nfl" and "stdname" is that the standard name is a
1200 distinction between "nfl" and "stdname" is that the standard name is a
1189 sort of the name as printed, which means that the embedded line
1201 sort of the name as printed, which means that the embedded line
1190 numbers get compared in an odd way. For example, lines 3, 20, and 40
1202 numbers get compared in an odd way. For example, lines 3, 20, and 40
1191 would (if the file names were the same) appear in the string order
1203 would (if the file names were the same) appear in the string order
1192 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1204 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1193 line numbers. In fact, sort_stats("nfl") is the same as
1205 line numbers. In fact, sort_stats("nfl") is the same as
1194 sort_stats("name", "file", "line").
1206 sort_stats("name", "file", "line").
1195
1207
1196 -T <filename>: save profile results as shown on screen to a text
1208 -T <filename>: save profile results as shown on screen to a text
1197 file. The profile is still shown on screen.
1209 file. The profile is still shown on screen.
1198
1210
1199 -D <filename>: save (via dump_stats) profile statistics to given
1211 -D <filename>: save (via dump_stats) profile statistics to given
1200 filename. This data is in a format understod by the pstats module, and
1212 filename. This data is in a format understod by the pstats module, and
1201 is generated by a call to the dump_stats() method of profile
1213 is generated by a call to the dump_stats() method of profile
1202 objects. The profile is still shown on screen.
1214 objects. The profile is still shown on screen.
1203
1215
1204 If you want to run complete programs under the profiler's control, use
1216 If you want to run complete programs under the profiler's control, use
1205 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1217 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1206 contains profiler specific options as described here.
1218 contains profiler specific options as described here.
1207
1219
1208 You can read the complete documentation for the profile module with:\\
1220 You can read the complete documentation for the profile module with:\\
1209 In [1]: import profile; profile.help() """
1221 In [1]: import profile; profile.help() """
1210
1222
1211 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1223 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1212 # protect user quote marks
1224 # protect user quote marks
1213 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1225 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1214
1226
1215 if user_mode: # regular user call
1227 if user_mode: # regular user call
1216 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1228 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1217 list_all=1)
1229 list_all=1)
1218 namespace = self.shell.user_ns
1230 namespace = self.shell.user_ns
1219 else: # called to run a program by %run -p
1231 else: # called to run a program by %run -p
1220 try:
1232 try:
1221 filename = get_py_filename(arg_lst[0])
1233 filename = get_py_filename(arg_lst[0])
1222 except IOError,msg:
1234 except IOError,msg:
1223 error(msg)
1235 error(msg)
1224 return
1236 return
1225
1237
1226 arg_str = 'execfile(filename,prog_ns)'
1238 arg_str = 'execfile(filename,prog_ns)'
1227 namespace = locals()
1239 namespace = locals()
1228
1240
1229 opts.merge(opts_def)
1241 opts.merge(opts_def)
1230
1242
1231 prof = profile.Profile()
1243 prof = profile.Profile()
1232 try:
1244 try:
1233 prof = prof.runctx(arg_str,namespace,namespace)
1245 prof = prof.runctx(arg_str,namespace,namespace)
1234 sys_exit = ''
1246 sys_exit = ''
1235 except SystemExit:
1247 except SystemExit:
1236 sys_exit = """*** SystemExit exception caught in code being profiled."""
1248 sys_exit = """*** SystemExit exception caught in code being profiled."""
1237
1249
1238 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1250 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1239
1251
1240 lims = opts.l
1252 lims = opts.l
1241 if lims:
1253 if lims:
1242 lims = [] # rebuild lims with ints/floats/strings
1254 lims = [] # rebuild lims with ints/floats/strings
1243 for lim in opts.l:
1255 for lim in opts.l:
1244 try:
1256 try:
1245 lims.append(int(lim))
1257 lims.append(int(lim))
1246 except ValueError:
1258 except ValueError:
1247 try:
1259 try:
1248 lims.append(float(lim))
1260 lims.append(float(lim))
1249 except ValueError:
1261 except ValueError:
1250 lims.append(lim)
1262 lims.append(lim)
1251
1263
1252 # trap output
1264 # trap output
1253 sys_stdout = sys.stdout
1265 sys_stdout = sys.stdout
1254 stdout_trap = StringIO()
1266 stdout_trap = StringIO()
1255 try:
1267 try:
1256 sys.stdout = stdout_trap
1268 sys.stdout = stdout_trap
1257 stats.print_stats(*lims)
1269 stats.print_stats(*lims)
1258 finally:
1270 finally:
1259 sys.stdout = sys_stdout
1271 sys.stdout = sys_stdout
1260 output = stdout_trap.getvalue()
1272 output = stdout_trap.getvalue()
1261 output = output.rstrip()
1273 output = output.rstrip()
1262
1274
1263 page(output,screen_lines=self.shell.rc.screen_length)
1275 page(output,screen_lines=self.shell.rc.screen_length)
1264 print sys_exit,
1276 print sys_exit,
1265
1277
1266 dump_file = opts.D[0]
1278 dump_file = opts.D[0]
1267 text_file = opts.T[0]
1279 text_file = opts.T[0]
1268 if dump_file:
1280 if dump_file:
1269 prof.dump_stats(dump_file)
1281 prof.dump_stats(dump_file)
1270 print '\n*** Profile stats marshalled to file',\
1282 print '\n*** Profile stats marshalled to file',\
1271 `dump_file`+'.',sys_exit
1283 `dump_file`+'.',sys_exit
1272 if text_file:
1284 if text_file:
1273 file(text_file,'w').write(output)
1285 file(text_file,'w').write(output)
1274 print '\n*** Profile printout saved to text file',\
1286 print '\n*** Profile printout saved to text file',\
1275 `text_file`+'.',sys_exit
1287 `text_file`+'.',sys_exit
1276
1288
1277 if opts.has_key('r'):
1289 if opts.has_key('r'):
1278 return stats
1290 return stats
1279 else:
1291 else:
1280 return None
1292 return None
1281
1293
1282 def magic_run(self, parameter_s ='',runner=None):
1294 def magic_run(self, parameter_s ='',runner=None):
1283 """Run the named file inside IPython as a program.
1295 """Run the named file inside IPython as a program.
1284
1296
1285 Usage:\\
1297 Usage:\\
1286 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1298 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1287
1299
1288 Parameters after the filename are passed as command-line arguments to
1300 Parameters after the filename are passed as command-line arguments to
1289 the program (put in sys.argv). Then, control returns to IPython's
1301 the program (put in sys.argv). Then, control returns to IPython's
1290 prompt.
1302 prompt.
1291
1303
1292 This is similar to running at a system prompt:\\
1304 This is similar to running at a system prompt:\\
1293 $ python file args\\
1305 $ python file args\\
1294 but with the advantage of giving you IPython's tracebacks, and of
1306 but with the advantage of giving you IPython's tracebacks, and of
1295 loading all variables into your interactive namespace for further use
1307 loading all variables into your interactive namespace for further use
1296 (unless -p is used, see below).
1308 (unless -p is used, see below).
1297
1309
1298 The file is executed in a namespace initially consisting only of
1310 The file is executed in a namespace initially consisting only of
1299 __name__=='__main__' and sys.argv constructed as indicated. It thus
1311 __name__=='__main__' and sys.argv constructed as indicated. It thus
1300 sees its environment as if it were being run as a stand-alone
1312 sees its environment as if it were being run as a stand-alone
1301 program. But after execution, the IPython interactive namespace gets
1313 program. But after execution, the IPython interactive namespace gets
1302 updated with all variables defined in the program (except for __name__
1314 updated with all variables defined in the program (except for __name__
1303 and sys.argv). This allows for very convenient loading of code for
1315 and sys.argv). This allows for very convenient loading of code for
1304 interactive work, while giving each program a 'clean sheet' to run in.
1316 interactive work, while giving each program a 'clean sheet' to run in.
1305
1317
1306 Options:
1318 Options:
1307
1319
1308 -n: __name__ is NOT set to '__main__', but to the running file's name
1320 -n: __name__ is NOT set to '__main__', but to the running file's name
1309 without extension (as python does under import). This allows running
1321 without extension (as python does under import). This allows running
1310 scripts and reloading the definitions in them without calling code
1322 scripts and reloading the definitions in them without calling code
1311 protected by an ' if __name__ == "__main__" ' clause.
1323 protected by an ' if __name__ == "__main__" ' clause.
1312
1324
1313 -i: run the file in IPython's namespace instead of an empty one. This
1325 -i: run the file in IPython's namespace instead of an empty one. This
1314 is useful if you are experimenting with code written in a text editor
1326 is useful if you are experimenting with code written in a text editor
1315 which depends on variables defined interactively.
1327 which depends on variables defined interactively.
1316
1328
1317 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1329 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1318 being run. This is particularly useful if IPython is being used to
1330 being run. This is particularly useful if IPython is being used to
1319 run unittests, which always exit with a sys.exit() call. In such
1331 run unittests, which always exit with a sys.exit() call. In such
1320 cases you are interested in the output of the test results, not in
1332 cases you are interested in the output of the test results, not in
1321 seeing a traceback of the unittest module.
1333 seeing a traceback of the unittest module.
1322
1334
1323 -t: print timing information at the end of the run. IPython will give
1335 -t: print timing information at the end of the run. IPython will give
1324 you an estimated CPU time consumption for your script, which under
1336 you an estimated CPU time consumption for your script, which under
1325 Unix uses the resource module to avoid the wraparound problems of
1337 Unix uses the resource module to avoid the wraparound problems of
1326 time.clock(). Under Unix, an estimate of time spent on system tasks
1338 time.clock(). Under Unix, an estimate of time spent on system tasks
1327 is also given (for Windows platforms this is reported as 0.0).
1339 is also given (for Windows platforms this is reported as 0.0).
1328
1340
1329 If -t is given, an additional -N<N> option can be given, where <N>
1341 If -t is given, an additional -N<N> option can be given, where <N>
1330 must be an integer indicating how many times you want the script to
1342 must be an integer indicating how many times you want the script to
1331 run. The final timing report will include total and per run results.
1343 run. The final timing report will include total and per run results.
1332
1344
1333 For example (testing the script uniq_stable.py):
1345 For example (testing the script uniq_stable.py):
1334
1346
1335 In [1]: run -t uniq_stable
1347 In [1]: run -t uniq_stable
1336
1348
1337 IPython CPU timings (estimated):\\
1349 IPython CPU timings (estimated):\\
1338 User : 0.19597 s.\\
1350 User : 0.19597 s.\\
1339 System: 0.0 s.\\
1351 System: 0.0 s.\\
1340
1352
1341 In [2]: run -t -N5 uniq_stable
1353 In [2]: run -t -N5 uniq_stable
1342
1354
1343 IPython CPU timings (estimated):\\
1355 IPython CPU timings (estimated):\\
1344 Total runs performed: 5\\
1356 Total runs performed: 5\\
1345 Times : Total Per run\\
1357 Times : Total Per run\\
1346 User : 0.910862 s, 0.1821724 s.\\
1358 User : 0.910862 s, 0.1821724 s.\\
1347 System: 0.0 s, 0.0 s.
1359 System: 0.0 s, 0.0 s.
1348
1360
1349 -d: run your program under the control of pdb, the Python debugger.
1361 -d: run your program under the control of pdb, the Python debugger.
1350 This allows you to execute your program step by step, watch variables,
1362 This allows you to execute your program step by step, watch variables,
1351 etc. Internally, what IPython does is similar to calling:
1363 etc. Internally, what IPython does is similar to calling:
1352
1364
1353 pdb.run('execfile("YOURFILENAME")')
1365 pdb.run('execfile("YOURFILENAME")')
1354
1366
1355 with a breakpoint set on line 1 of your file. You can change the line
1367 with a breakpoint set on line 1 of your file. You can change the line
1356 number for this automatic breakpoint to be <N> by using the -bN option
1368 number for this automatic breakpoint to be <N> by using the -bN option
1357 (where N must be an integer). For example:
1369 (where N must be an integer). For example:
1358
1370
1359 %run -d -b40 myscript
1371 %run -d -b40 myscript
1360
1372
1361 will set the first breakpoint at line 40 in myscript.py. Note that
1373 will set the first breakpoint at line 40 in myscript.py. Note that
1362 the first breakpoint must be set on a line which actually does
1374 the first breakpoint must be set on a line which actually does
1363 something (not a comment or docstring) for it to stop execution.
1375 something (not a comment or docstring) for it to stop execution.
1364
1376
1365 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1377 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1366 first enter 'c' (without qoutes) to start execution up to the first
1378 first enter 'c' (without qoutes) to start execution up to the first
1367 breakpoint.
1379 breakpoint.
1368
1380
1369 Entering 'help' gives information about the use of the debugger. You
1381 Entering 'help' gives information about the use of the debugger. You
1370 can easily see pdb's full documentation with "import pdb;pdb.help()"
1382 can easily see pdb's full documentation with "import pdb;pdb.help()"
1371 at a prompt.
1383 at a prompt.
1372
1384
1373 -p: run program under the control of the Python profiler module (which
1385 -p: run program under the control of the Python profiler module (which
1374 prints a detailed report of execution times, function calls, etc).
1386 prints a detailed report of execution times, function calls, etc).
1375
1387
1376 You can pass other options after -p which affect the behavior of the
1388 You can pass other options after -p which affect the behavior of the
1377 profiler itself. See the docs for %prun for details.
1389 profiler itself. See the docs for %prun for details.
1378
1390
1379 In this mode, the program's variables do NOT propagate back to the
1391 In this mode, the program's variables do NOT propagate back to the
1380 IPython interactive namespace (because they remain in the namespace
1392 IPython interactive namespace (because they remain in the namespace
1381 where the profiler executes them).
1393 where the profiler executes them).
1382
1394
1383 Internally this triggers a call to %prun, see its documentation for
1395 Internally this triggers a call to %prun, see its documentation for
1384 details on the options available specifically for profiling."""
1396 details on the options available specifically for profiling."""
1385
1397
1386 # get arguments and set sys.argv for program to be run.
1398 # get arguments and set sys.argv for program to be run.
1387 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1399 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1388 mode='list',list_all=1)
1400 mode='list',list_all=1)
1389
1401
1390 try:
1402 try:
1391 filename = get_py_filename(arg_lst[0])
1403 filename = get_py_filename(arg_lst[0])
1392 except IndexError:
1404 except IndexError:
1393 warn('you must provide at least a filename.')
1405 warn('you must provide at least a filename.')
1394 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1406 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1395 return
1407 return
1396 except IOError,msg:
1408 except IOError,msg:
1397 error(msg)
1409 error(msg)
1398 return
1410 return
1399
1411
1400 # Control the response to exit() calls made by the script being run
1412 # Control the response to exit() calls made by the script being run
1401 exit_ignore = opts.has_key('e')
1413 exit_ignore = opts.has_key('e')
1402
1414
1403 # Make sure that the running script gets a proper sys.argv as if it
1415 # Make sure that the running script gets a proper sys.argv as if it
1404 # were run from a system shell.
1416 # were run from a system shell.
1405 save_argv = sys.argv # save it for later restoring
1417 save_argv = sys.argv # save it for later restoring
1406 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1418 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1407
1419
1408 if opts.has_key('i'):
1420 if opts.has_key('i'):
1409 prog_ns = self.shell.user_ns
1421 prog_ns = self.shell.user_ns
1410 __name__save = self.shell.user_ns['__name__']
1422 __name__save = self.shell.user_ns['__name__']
1411 prog_ns['__name__'] = '__main__'
1423 prog_ns['__name__'] = '__main__'
1412 else:
1424 else:
1413 if opts.has_key('n'):
1425 if opts.has_key('n'):
1414 name = os.path.splitext(os.path.basename(filename))[0]
1426 name = os.path.splitext(os.path.basename(filename))[0]
1415 else:
1427 else:
1416 name = '__main__'
1428 name = '__main__'
1417 prog_ns = {'__name__':name}
1429 prog_ns = {'__name__':name}
1418
1430
1419 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1431 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1420 # set the __file__ global in the script's namespace
1432 # set the __file__ global in the script's namespace
1421 prog_ns['__file__'] = filename
1433 prog_ns['__file__'] = filename
1422
1434
1423 # pickle fix. See iplib for an explanation. But we need to make sure
1435 # pickle fix. See iplib for an explanation. But we need to make sure
1424 # that, if we overwrite __main__, we replace it at the end
1436 # that, if we overwrite __main__, we replace it at the end
1425 if prog_ns['__name__'] == '__main__':
1437 if prog_ns['__name__'] == '__main__':
1426 restore_main = sys.modules['__main__']
1438 restore_main = sys.modules['__main__']
1427 else:
1439 else:
1428 restore_main = False
1440 restore_main = False
1429
1441
1430 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1442 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1431
1443
1432 stats = None
1444 stats = None
1433 try:
1445 try:
1434 if opts.has_key('p'):
1446 if opts.has_key('p'):
1435 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1447 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1436 else:
1448 else:
1437 if opts.has_key('d'):
1449 if opts.has_key('d'):
1438 deb = Debugger.Pdb(self.shell.rc.colors)
1450 deb = Debugger.Pdb(self.shell.rc.colors)
1439 # reset Breakpoint state, which is moronically kept
1451 # reset Breakpoint state, which is moronically kept
1440 # in a class
1452 # in a class
1441 bdb.Breakpoint.next = 1
1453 bdb.Breakpoint.next = 1
1442 bdb.Breakpoint.bplist = {}
1454 bdb.Breakpoint.bplist = {}
1443 bdb.Breakpoint.bpbynumber = [None]
1455 bdb.Breakpoint.bpbynumber = [None]
1444 # Set an initial breakpoint to stop execution
1456 # Set an initial breakpoint to stop execution
1445 maxtries = 10
1457 maxtries = 10
1446 bp = int(opts.get('b',[1])[0])
1458 bp = int(opts.get('b',[1])[0])
1447 checkline = deb.checkline(filename,bp)
1459 checkline = deb.checkline(filename,bp)
1448 if not checkline:
1460 if not checkline:
1449 for bp in range(bp+1,bp+maxtries+1):
1461 for bp in range(bp+1,bp+maxtries+1):
1450 if deb.checkline(filename,bp):
1462 if deb.checkline(filename,bp):
1451 break
1463 break
1452 else:
1464 else:
1453 msg = ("\nI failed to find a valid line to set "
1465 msg = ("\nI failed to find a valid line to set "
1454 "a breakpoint\n"
1466 "a breakpoint\n"
1455 "after trying up to line: %s.\n"
1467 "after trying up to line: %s.\n"
1456 "Please set a valid breakpoint manually "
1468 "Please set a valid breakpoint manually "
1457 "with the -b option." % bp)
1469 "with the -b option." % bp)
1458 error(msg)
1470 error(msg)
1459 return
1471 return
1460 # if we find a good linenumber, set the breakpoint
1472 # if we find a good linenumber, set the breakpoint
1461 deb.do_break('%s:%s' % (filename,bp))
1473 deb.do_break('%s:%s' % (filename,bp))
1462 # Start file run
1474 # Start file run
1463 print "NOTE: Enter 'c' at the",
1475 print "NOTE: Enter 'c' at the",
1464 print "ipdb> prompt to start your script."
1476 print "ipdb> prompt to start your script."
1465 try:
1477 try:
1466 deb.run('execfile("%s")' % filename,prog_ns)
1478 deb.run('execfile("%s")' % filename,prog_ns)
1467 except:
1479 except:
1468 etype, value, tb = sys.exc_info()
1480 etype, value, tb = sys.exc_info()
1469 # Skip three frames in the traceback: the %run one,
1481 # Skip three frames in the traceback: the %run one,
1470 # one inside bdb.py, and the command-line typed by the
1482 # one inside bdb.py, and the command-line typed by the
1471 # user (run by exec in pdb itself).
1483 # user (run by exec in pdb itself).
1472 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1484 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1473 else:
1485 else:
1474 if runner is None:
1486 if runner is None:
1475 runner = self.shell.safe_execfile
1487 runner = self.shell.safe_execfile
1476 if opts.has_key('t'):
1488 if opts.has_key('t'):
1477 try:
1489 try:
1478 nruns = int(opts['N'][0])
1490 nruns = int(opts['N'][0])
1479 if nruns < 1:
1491 if nruns < 1:
1480 error('Number of runs must be >=1')
1492 error('Number of runs must be >=1')
1481 return
1493 return
1482 except (KeyError):
1494 except (KeyError):
1483 nruns = 1
1495 nruns = 1
1484 if nruns == 1:
1496 if nruns == 1:
1485 t0 = clock2()
1497 t0 = clock2()
1486 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1498 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1487 t1 = clock2()
1499 t1 = clock2()
1488 t_usr = t1[0]-t0[0]
1500 t_usr = t1[0]-t0[0]
1489 t_sys = t1[1]-t1[1]
1501 t_sys = t1[1]-t1[1]
1490 print "\nIPython CPU timings (estimated):"
1502 print "\nIPython CPU timings (estimated):"
1491 print " User : %10s s." % t_usr
1503 print " User : %10s s." % t_usr
1492 print " System: %10s s." % t_sys
1504 print " System: %10s s." % t_sys
1493 else:
1505 else:
1494 runs = range(nruns)
1506 runs = range(nruns)
1495 t0 = clock2()
1507 t0 = clock2()
1496 for nr in runs:
1508 for nr in runs:
1497 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1509 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1498 t1 = clock2()
1510 t1 = clock2()
1499 t_usr = t1[0]-t0[0]
1511 t_usr = t1[0]-t0[0]
1500 t_sys = t1[1]-t1[1]
1512 t_sys = t1[1]-t1[1]
1501 print "\nIPython CPU timings (estimated):"
1513 print "\nIPython CPU timings (estimated):"
1502 print "Total runs performed:",nruns
1514 print "Total runs performed:",nruns
1503 print " Times : %10s %10s" % ('Total','Per run')
1515 print " Times : %10s %10s" % ('Total','Per run')
1504 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1516 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1505 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1517 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1506
1518
1507 else:
1519 else:
1508 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1520 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1509 if opts.has_key('i'):
1521 if opts.has_key('i'):
1510 self.shell.user_ns['__name__'] = __name__save
1522 self.shell.user_ns['__name__'] = __name__save
1511 else:
1523 else:
1512 # update IPython interactive namespace
1524 # update IPython interactive namespace
1513 del prog_ns['__name__']
1525 del prog_ns['__name__']
1514 self.shell.user_ns.update(prog_ns)
1526 self.shell.user_ns.update(prog_ns)
1515 finally:
1527 finally:
1516 sys.argv = save_argv
1528 sys.argv = save_argv
1517 if restore_main:
1529 if restore_main:
1518 sys.modules['__main__'] = restore_main
1530 sys.modules['__main__'] = restore_main
1519 return stats
1531 return stats
1520
1532
1521 def magic_runlog(self, parameter_s =''):
1533 def magic_runlog(self, parameter_s =''):
1522 """Run files as logs.
1534 """Run files as logs.
1523
1535
1524 Usage:\\
1536 Usage:\\
1525 %runlog file1 file2 ...
1537 %runlog file1 file2 ...
1526
1538
1527 Run the named files (treating them as log files) in sequence inside
1539 Run the named files (treating them as log files) in sequence inside
1528 the interpreter, and return to the prompt. This is much slower than
1540 the interpreter, and return to the prompt. This is much slower than
1529 %run because each line is executed in a try/except block, but it
1541 %run because each line is executed in a try/except block, but it
1530 allows running files with syntax errors in them.
1542 allows running files with syntax errors in them.
1531
1543
1532 Normally IPython will guess when a file is one of its own logfiles, so
1544 Normally IPython will guess when a file is one of its own logfiles, so
1533 you can typically use %run even for logs. This shorthand allows you to
1545 you can typically use %run even for logs. This shorthand allows you to
1534 force any file to be treated as a log file."""
1546 force any file to be treated as a log file."""
1535
1547
1536 for f in parameter_s.split():
1548 for f in parameter_s.split():
1537 self.shell.safe_execfile(f,self.shell.user_ns,
1549 self.shell.safe_execfile(f,self.shell.user_ns,
1538 self.shell.user_ns,islog=1)
1550 self.shell.user_ns,islog=1)
1539
1551
1540 def magic_time(self,parameter_s = ''):
1552 def magic_time(self,parameter_s = ''):
1541 """Time execution of a Python statement or expression.
1553 """Time execution of a Python statement or expression.
1542
1554
1543 The CPU and wall clock times are printed, and the value of the
1555 The CPU and wall clock times are printed, and the value of the
1544 expression (if any) is returned. Note that under Win32, system time
1556 expression (if any) is returned. Note that under Win32, system time
1545 is always reported as 0, since it can not be measured.
1557 is always reported as 0, since it can not be measured.
1546
1558
1547 This function provides very basic timing functionality. In Python
1559 This function provides very basic timing functionality. In Python
1548 2.3, the timeit module offers more control and sophistication, but for
1560 2.3, the timeit module offers more control and sophistication, but for
1549 now IPython supports Python 2.2, so we can not rely on timeit being
1561 now IPython supports Python 2.2, so we can not rely on timeit being
1550 present.
1562 present.
1551
1563
1552 Some examples:
1564 Some examples:
1553
1565
1554 In [1]: time 2**128
1566 In [1]: time 2**128
1555 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1567 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1556 Wall time: 0.00
1568 Wall time: 0.00
1557 Out[1]: 340282366920938463463374607431768211456L
1569 Out[1]: 340282366920938463463374607431768211456L
1558
1570
1559 In [2]: n = 1000000
1571 In [2]: n = 1000000
1560
1572
1561 In [3]: time sum(range(n))
1573 In [3]: time sum(range(n))
1562 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1574 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1563 Wall time: 1.37
1575 Wall time: 1.37
1564 Out[3]: 499999500000L
1576 Out[3]: 499999500000L
1565
1577
1566 In [4]: time print 'hello world'
1578 In [4]: time print 'hello world'
1567 hello world
1579 hello world
1568 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1580 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1569 Wall time: 0.00
1581 Wall time: 0.00
1570 """
1582 """
1571
1583
1572 # fail immediately if the given expression can't be compiled
1584 # fail immediately if the given expression can't be compiled
1573 try:
1585 try:
1574 mode = 'eval'
1586 mode = 'eval'
1575 code = compile(parameter_s,'<timed eval>',mode)
1587 code = compile(parameter_s,'<timed eval>',mode)
1576 except SyntaxError:
1588 except SyntaxError:
1577 mode = 'exec'
1589 mode = 'exec'
1578 code = compile(parameter_s,'<timed exec>',mode)
1590 code = compile(parameter_s,'<timed exec>',mode)
1579 # skew measurement as little as possible
1591 # skew measurement as little as possible
1580 glob = self.shell.user_ns
1592 glob = self.shell.user_ns
1581 clk = clock2
1593 clk = clock2
1582 wtime = time.time
1594 wtime = time.time
1583 # time execution
1595 # time execution
1584 wall_st = wtime()
1596 wall_st = wtime()
1585 if mode=='eval':
1597 if mode=='eval':
1586 st = clk()
1598 st = clk()
1587 out = eval(code,glob)
1599 out = eval(code,glob)
1588 end = clk()
1600 end = clk()
1589 else:
1601 else:
1590 st = clk()
1602 st = clk()
1591 exec code in glob
1603 exec code in glob
1592 end = clk()
1604 end = clk()
1593 out = None
1605 out = None
1594 wall_end = wtime()
1606 wall_end = wtime()
1595 # Compute actual times and report
1607 # Compute actual times and report
1596 wall_time = wall_end-wall_st
1608 wall_time = wall_end-wall_st
1597 cpu_user = end[0]-st[0]
1609 cpu_user = end[0]-st[0]
1598 cpu_sys = end[1]-st[1]
1610 cpu_sys = end[1]-st[1]
1599 cpu_tot = cpu_user+cpu_sys
1611 cpu_tot = cpu_user+cpu_sys
1600 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1612 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1601 (cpu_user,cpu_sys,cpu_tot)
1613 (cpu_user,cpu_sys,cpu_tot)
1602 print "Wall time: %.2f" % wall_time
1614 print "Wall time: %.2f" % wall_time
1603 return out
1615 return out
1604
1616
1605 def magic_macro(self,parameter_s = ''):
1617 def magic_macro(self,parameter_s = ''):
1606 """Define a set of input lines as a macro for future re-execution.
1618 """Define a set of input lines as a macro for future re-execution.
1607
1619
1608 Usage:\\
1620 Usage:\\
1609 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1621 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1622
1623 Options:
1624
1625 -r: use 'raw' input. By default, the 'processed' history is used,
1626 so that magics are loaded in their transformed version to valid
1627 Python. If this option is given, the raw input as typed as the
1628 command line is used instead.
1610
1629
1611 This will define a global variable called `name` which is a string
1630 This will define a global variable called `name` which is a string
1612 made of joining the slices and lines you specify (n1,n2,... numbers
1631 made of joining the slices and lines you specify (n1,n2,... numbers
1613 above) from your input history into a single string. This variable
1632 above) from your input history into a single string. This variable
1614 acts like an automatic function which re-executes those lines as if
1633 acts like an automatic function which re-executes those lines as if
1615 you had typed them. You just type 'name' at the prompt and the code
1634 you had typed them. You just type 'name' at the prompt and the code
1616 executes.
1635 executes.
1617
1636
1618 The notation for indicating number ranges is: n1-n2 means 'use line
1637 The notation for indicating number ranges is: n1-n2 means 'use line
1619 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1638 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1620 using the lines numbered 5,6 and 7.
1639 using the lines numbered 5,6 and 7.
1621
1640
1622 Note: as a 'hidden' feature, you can also use traditional python slice
1641 Note: as a 'hidden' feature, you can also use traditional python slice
1623 notation, where N:M means numbers N through M-1.
1642 notation, where N:M means numbers N through M-1.
1624
1643
1625 For example, if your history contains (%hist prints it):
1644 For example, if your history contains (%hist prints it):
1626
1645
1627 44: x=1\\
1646 44: x=1\\
1628 45: y=3\\
1647 45: y=3\\
1629 46: z=x+y\\
1648 46: z=x+y\\
1630 47: print x\\
1649 47: print x\\
1631 48: a=5\\
1650 48: a=5\\
1632 49: print 'x',x,'y',y\\
1651 49: print 'x',x,'y',y\\
1633
1652
1634 you can create a macro with lines 44 through 47 (included) and line 49
1653 you can create a macro with lines 44 through 47 (included) and line 49
1635 called my_macro with:
1654 called my_macro with:
1636
1655
1637 In [51]: %macro my_macro 44-47 49
1656 In [51]: %macro my_macro 44-47 49
1638
1657
1639 Now, typing `my_macro` (without quotes) will re-execute all this code
1658 Now, typing `my_macro` (without quotes) will re-execute all this code
1640 in one pass.
1659 in one pass.
1641
1660
1642 You don't need to give the line-numbers in order, and any given line
1661 You don't need to give the line-numbers in order, and any given line
1643 number can appear multiple times. You can assemble macros with any
1662 number can appear multiple times. You can assemble macros with any
1644 lines from your input history in any order.
1663 lines from your input history in any order.
1645
1664
1646 The macro is a simple object which holds its value in an attribute,
1665 The macro is a simple object which holds its value in an attribute,
1647 but IPython's display system checks for macros and executes them as
1666 but IPython's display system checks for macros and executes them as
1648 code instead of printing them when you type their name.
1667 code instead of printing them when you type their name.
1649
1668
1650 You can view a macro's contents by explicitly printing it with:
1669 You can view a macro's contents by explicitly printing it with:
1651
1670
1652 'print macro_name'.
1671 'print macro_name'.
1653
1672
1654 For one-off cases which DON'T contain magic function calls in them you
1673 For one-off cases which DON'T contain magic function calls in them you
1655 can obtain similar results by explicitly executing slices from your
1674 can obtain similar results by explicitly executing slices from your
1656 input history with:
1675 input history with:
1657
1676
1658 In [60]: exec In[44:48]+In[49]"""
1677 In [60]: exec In[44:48]+In[49]"""
1659
1678
1660 args = parameter_s.split()
1679 opts,args = self.parse_options(parameter_s,'r')
1661 name,ranges = args[0], args[1:]
1680 name,ranges = args[0], args[1:]
1662 #print 'rng',ranges # dbg
1681 #print 'rng',ranges # dbg
1663 lines = self.extract_input_slices(ranges)
1682 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1664 macro = Macro(lines)
1683 macro = Macro(lines)
1665 self.shell.user_ns.update({name:macro})
1684 self.shell.user_ns.update({name:macro})
1666 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1685 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1667 print 'Macro contents:'
1686 print 'Macro contents:'
1668 print macro,
1687 print macro,
1669
1688
1670 def magic_save(self,parameter_s = ''):
1689 def magic_save(self,parameter_s = ''):
1671 """Save a set of lines to a given filename.
1690 """Save a set of lines to a given filename.
1672
1691
1673 Usage:\\
1692 Usage:\\
1674 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1693 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1694
1695 Options:
1696
1697 -r: use 'raw' input. By default, the 'processed' history is used,
1698 so that magics are loaded in their transformed version to valid
1699 Python. If this option is given, the raw input as typed as the
1700 command line is used instead.
1675
1701
1676 This function uses the same syntax as %macro for line extraction, but
1702 This function uses the same syntax as %macro for line extraction, but
1677 instead of creating a macro it saves the resulting string to the
1703 instead of creating a macro it saves the resulting string to the
1678 filename you specify.
1704 filename you specify.
1679
1705
1680 It adds a '.py' extension to the file if you don't do so yourself, and
1706 It adds a '.py' extension to the file if you don't do so yourself, and
1681 it asks for confirmation before overwriting existing files."""
1707 it asks for confirmation before overwriting existing files."""
1682
1708
1683 args = parameter_s.split()
1709 opts,args = self.parse_options(parameter_s,'r')
1684 fname,ranges = args[0], args[1:]
1710 fname,ranges = args[0], args[1:]
1685 if not fname.endswith('.py'):
1711 if not fname.endswith('.py'):
1686 fname += '.py'
1712 fname += '.py'
1687 if os.path.isfile(fname):
1713 if os.path.isfile(fname):
1688 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1714 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1689 if ans.lower() not in ['y','yes']:
1715 if ans.lower() not in ['y','yes']:
1690 print 'Operation cancelled.'
1716 print 'Operation cancelled.'
1691 return
1717 return
1692 cmds = ''.join(self.extract_input_slices(ranges))
1718 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1693 f = file(fname,'w')
1719 f = file(fname,'w')
1694 f.write(cmds)
1720 f.write(cmds)
1695 f.close()
1721 f.close()
1696 print 'The following commands were written to file `%s`:' % fname
1722 print 'The following commands were written to file `%s`:' % fname
1697 print cmds
1723 print cmds
1698
1724
1699 def _edit_macro(self,mname,macro):
1725 def _edit_macro(self,mname,macro):
1700 """open an editor with the macro data in a file"""
1726 """open an editor with the macro data in a file"""
1701 filename = self.shell.mktempfile(macro.value)
1727 filename = self.shell.mktempfile(macro.value)
1702 self.shell.hooks.editor(filename)
1728 self.shell.hooks.editor(filename)
1703
1729
1704 # and make a new macro object, to replace the old one
1730 # and make a new macro object, to replace the old one
1705 mfile = open(filename)
1731 mfile = open(filename)
1706 mvalue = mfile.read()
1732 mvalue = mfile.read()
1707 mfile.close()
1733 mfile.close()
1708 self.shell.user_ns[mname] = Macro(mvalue)
1734 self.shell.user_ns[mname] = Macro(mvalue)
1709
1735
1710 def magic_ed(self,parameter_s=''):
1736 def magic_ed(self,parameter_s=''):
1711 """Alias to %edit."""
1737 """Alias to %edit."""
1712 return self.magic_edit(parameter_s)
1738 return self.magic_edit(parameter_s)
1713
1739
1714 def magic_edit(self,parameter_s='',last_call=['','']):
1740 def magic_edit(self,parameter_s='',last_call=['','']):
1715 """Bring up an editor and execute the resulting code.
1741 """Bring up an editor and execute the resulting code.
1716
1742
1717 Usage:
1743 Usage:
1718 %edit [options] [args]
1744 %edit [options] [args]
1719
1745
1720 %edit runs IPython's editor hook. The default version of this hook is
1746 %edit runs IPython's editor hook. The default version of this hook is
1721 set to call the __IPYTHON__.rc.editor command. This is read from your
1747 set to call the __IPYTHON__.rc.editor command. This is read from your
1722 environment variable $EDITOR. If this isn't found, it will default to
1748 environment variable $EDITOR. If this isn't found, it will default to
1723 vi under Linux/Unix and to notepad under Windows. See the end of this
1749 vi under Linux/Unix and to notepad under Windows. See the end of this
1724 docstring for how to change the editor hook.
1750 docstring for how to change the editor hook.
1725
1751
1726 You can also set the value of this editor via the command line option
1752 You can also set the value of this editor via the command line option
1727 '-editor' or in your ipythonrc file. This is useful if you wish to use
1753 '-editor' or in your ipythonrc file. This is useful if you wish to use
1728 specifically for IPython an editor different from your typical default
1754 specifically for IPython an editor different from your typical default
1729 (and for Windows users who typically don't set environment variables).
1755 (and for Windows users who typically don't set environment variables).
1730
1756
1731 This command allows you to conveniently edit multi-line code right in
1757 This command allows you to conveniently edit multi-line code right in
1732 your IPython session.
1758 your IPython session.
1733
1759
1734 If called without arguments, %edit opens up an empty editor with a
1760 If called without arguments, %edit opens up an empty editor with a
1735 temporary file and will execute the contents of this file when you
1761 temporary file and will execute the contents of this file when you
1736 close it (don't forget to save it!).
1762 close it (don't forget to save it!).
1737
1763
1738
1764
1739 Options:
1765 Options:
1740
1766
1741 -p: this will call the editor with the same data as the previous time
1767 -p: this will call the editor with the same data as the previous time
1742 it was used, regardless of how long ago (in your current session) it
1768 it was used, regardless of how long ago (in your current session) it
1743 was.
1769 was.
1744
1770
1771 -r: use 'raw' input. This option only applies to input taken from the
1772 user's history. By default, the 'processed' history is used, so that
1773 magics are loaded in their transformed version to valid Python. If
1774 this option is given, the raw input as typed as the command line is
1775 used instead. When you exit the editor, it will be executed by
1776 IPython's own processor.
1777
1745 -x: do not execute the edited code immediately upon exit. This is
1778 -x: do not execute the edited code immediately upon exit. This is
1746 mainly useful if you are editing programs which need to be called with
1779 mainly useful if you are editing programs which need to be called with
1747 command line arguments, which you can then do using %run.
1780 command line arguments, which you can then do using %run.
1748
1781
1749
1782
1750 Arguments:
1783 Arguments:
1751
1784
1752 If arguments are given, the following possibilites exist:
1785 If arguments are given, the following possibilites exist:
1753
1786
1754 - The arguments are numbers or pairs of colon-separated numbers (like
1787 - The arguments are numbers or pairs of colon-separated numbers (like
1755 1 4:8 9). These are interpreted as lines of previous input to be
1788 1 4:8 9). These are interpreted as lines of previous input to be
1756 loaded into the editor. The syntax is the same of the %macro command.
1789 loaded into the editor. The syntax is the same of the %macro command.
1757
1790
1758 - If the argument doesn't start with a number, it is evaluated as a
1791 - If the argument doesn't start with a number, it is evaluated as a
1759 variable and its contents loaded into the editor. You can thus edit
1792 variable and its contents loaded into the editor. You can thus edit
1760 any string which contains python code (including the result of
1793 any string which contains python code (including the result of
1761 previous edits).
1794 previous edits).
1762
1795
1763 - If the argument is the name of an object (other than a string),
1796 - If the argument is the name of an object (other than a string),
1764 IPython will try to locate the file where it was defined and open the
1797 IPython will try to locate the file where it was defined and open the
1765 editor at the point where it is defined. You can use `%edit function`
1798 editor at the point where it is defined. You can use `%edit function`
1766 to load an editor exactly at the point where 'function' is defined,
1799 to load an editor exactly at the point where 'function' is defined,
1767 edit it and have the file be executed automatically.
1800 edit it and have the file be executed automatically.
1768
1801
1769 If the object is a macro (see %macro for details), this opens up your
1802 If the object is a macro (see %macro for details), this opens up your
1770 specified editor with a temporary file containing the macro's data.
1803 specified editor with a temporary file containing the macro's data.
1771 Upon exit, the macro is reloaded with the contents of the file.
1804 Upon exit, the macro is reloaded with the contents of the file.
1772
1805
1773 Note: opening at an exact line is only supported under Unix, and some
1806 Note: opening at an exact line is only supported under Unix, and some
1774 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1807 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1775 '+NUMBER' parameter necessary for this feature. Good editors like
1808 '+NUMBER' parameter necessary for this feature. Good editors like
1776 (X)Emacs, vi, jed, pico and joe all do.
1809 (X)Emacs, vi, jed, pico and joe all do.
1777
1810
1778 - If the argument is not found as a variable, IPython will look for a
1811 - If the argument is not found as a variable, IPython will look for a
1779 file with that name (adding .py if necessary) and load it into the
1812 file with that name (adding .py if necessary) and load it into the
1780 editor. It will execute its contents with execfile() when you exit,
1813 editor. It will execute its contents with execfile() when you exit,
1781 loading any code in the file into your interactive namespace.
1814 loading any code in the file into your interactive namespace.
1782
1815
1783 After executing your code, %edit will return as output the code you
1816 After executing your code, %edit will return as output the code you
1784 typed in the editor (except when it was an existing file). This way
1817 typed in the editor (except when it was an existing file). This way
1785 you can reload the code in further invocations of %edit as a variable,
1818 you can reload the code in further invocations of %edit as a variable,
1786 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1819 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1787 the output.
1820 the output.
1788
1821
1789 Note that %edit is also available through the alias %ed.
1822 Note that %edit is also available through the alias %ed.
1790
1823
1791 This is an example of creating a simple function inside the editor and
1824 This is an example of creating a simple function inside the editor and
1792 then modifying it. First, start up the editor:
1825 then modifying it. First, start up the editor:
1793
1826
1794 In [1]: ed\\
1827 In [1]: ed\\
1795 Editing... done. Executing edited code...\\
1828 Editing... done. Executing edited code...\\
1796 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1829 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1797
1830
1798 We can then call the function foo():
1831 We can then call the function foo():
1799
1832
1800 In [2]: foo()\\
1833 In [2]: foo()\\
1801 foo() was defined in an editing session
1834 foo() was defined in an editing session
1802
1835
1803 Now we edit foo. IPython automatically loads the editor with the
1836 Now we edit foo. IPython automatically loads the editor with the
1804 (temporary) file where foo() was previously defined:
1837 (temporary) file where foo() was previously defined:
1805
1838
1806 In [3]: ed foo\\
1839 In [3]: ed foo\\
1807 Editing... done. Executing edited code...
1840 Editing... done. Executing edited code...
1808
1841
1809 And if we call foo() again we get the modified version:
1842 And if we call foo() again we get the modified version:
1810
1843
1811 In [4]: foo()\\
1844 In [4]: foo()\\
1812 foo() has now been changed!
1845 foo() has now been changed!
1813
1846
1814 Here is an example of how to edit a code snippet successive
1847 Here is an example of how to edit a code snippet successive
1815 times. First we call the editor:
1848 times. First we call the editor:
1816
1849
1817 In [8]: ed\\
1850 In [8]: ed\\
1818 Editing... done. Executing edited code...\\
1851 Editing... done. Executing edited code...\\
1819 hello\\
1852 hello\\
1820 Out[8]: "print 'hello'\\n"
1853 Out[8]: "print 'hello'\\n"
1821
1854
1822 Now we call it again with the previous output (stored in _):
1855 Now we call it again with the previous output (stored in _):
1823
1856
1824 In [9]: ed _\\
1857 In [9]: ed _\\
1825 Editing... done. Executing edited code...\\
1858 Editing... done. Executing edited code...\\
1826 hello world\\
1859 hello world\\
1827 Out[9]: "print 'hello world'\\n"
1860 Out[9]: "print 'hello world'\\n"
1828
1861
1829 Now we call it with the output #8 (stored in _8, also as Out[8]):
1862 Now we call it with the output #8 (stored in _8, also as Out[8]):
1830
1863
1831 In [10]: ed _8\\
1864 In [10]: ed _8\\
1832 Editing... done. Executing edited code...\\
1865 Editing... done. Executing edited code...\\
1833 hello again\\
1866 hello again\\
1834 Out[10]: "print 'hello again'\\n"
1867 Out[10]: "print 'hello again'\\n"
1835
1868
1836
1869
1837 Changing the default editor hook:
1870 Changing the default editor hook:
1838
1871
1839 If you wish to write your own editor hook, you can put it in a
1872 If you wish to write your own editor hook, you can put it in a
1840 configuration file which you load at startup time. The default hook
1873 configuration file which you load at startup time. The default hook
1841 is defined in the IPython.hooks module, and you can use that as a
1874 is defined in the IPython.hooks module, and you can use that as a
1842 starting example for further modifications. That file also has
1875 starting example for further modifications. That file also has
1843 general instructions on how to set a new hook for use once you've
1876 general instructions on how to set a new hook for use once you've
1844 defined it."""
1877 defined it."""
1845
1878
1846 # FIXME: This function has become a convoluted mess. It needs a
1879 # FIXME: This function has become a convoluted mess. It needs a
1847 # ground-up rewrite with clean, simple logic.
1880 # ground-up rewrite with clean, simple logic.
1848
1881
1849 def make_filename(arg):
1882 def make_filename(arg):
1850 "Make a filename from the given args"
1883 "Make a filename from the given args"
1851 try:
1884 try:
1852 filename = get_py_filename(arg)
1885 filename = get_py_filename(arg)
1853 except IOError:
1886 except IOError:
1854 if args.endswith('.py'):
1887 if args.endswith('.py'):
1855 filename = arg
1888 filename = arg
1856 else:
1889 else:
1857 filename = None
1890 filename = None
1858 return filename
1891 return filename
1859
1892
1860 # custom exceptions
1893 # custom exceptions
1861 class DataIsObject(Exception): pass
1894 class DataIsObject(Exception): pass
1862
1895
1863 opts,args = self.parse_options(parameter_s,'px')
1896 opts,args = self.parse_options(parameter_s,'prx')
1897 # Set a few locals from the options for convenience:
1898 opts_p = opts.has_key('p')
1899 opts_r = opts.has_key('r')
1864
1900
1865 # Default line number value
1901 # Default line number value
1866 lineno = None
1902 lineno = None
1867 if opts.has_key('p'):
1903 if opts_p:
1868 args = '_%s' % last_call[0]
1904 args = '_%s' % last_call[0]
1869 if not self.shell.user_ns.has_key(args):
1905 if not self.shell.user_ns.has_key(args):
1870 args = last_call[1]
1906 args = last_call[1]
1871
1907
1872 # use last_call to remember the state of the previous call, but don't
1908 # use last_call to remember the state of the previous call, but don't
1873 # let it be clobbered by successive '-p' calls.
1909 # let it be clobbered by successive '-p' calls.
1874 try:
1910 try:
1875 last_call[0] = self.shell.outputcache.prompt_count
1911 last_call[0] = self.shell.outputcache.prompt_count
1876 if not opts.has_key('p'):
1912 if not opts_p:
1877 last_call[1] = parameter_s
1913 last_call[1] = parameter_s
1878 except:
1914 except:
1879 pass
1915 pass
1880
1916
1881 # by default this is done with temp files, except when the given
1917 # by default this is done with temp files, except when the given
1882 # arg is a filename
1918 # arg is a filename
1883 use_temp = 1
1919 use_temp = 1
1884
1920
1885 if re.match(r'\d',args):
1921 if re.match(r'\d',args):
1886 # Mode where user specifies ranges of lines, like in %macro.
1922 # Mode where user specifies ranges of lines, like in %macro.
1887 # This means that you can't edit files whose names begin with
1923 # This means that you can't edit files whose names begin with
1888 # numbers this way. Tough.
1924 # numbers this way. Tough.
1889 ranges = args.split()
1925 ranges = args.split()
1890 data = ''.join(self.extract_input_slices(ranges))
1926 data = ''.join(self.extract_input_slices(ranges,opts_r))
1891 elif args.endswith('.py'):
1927 elif args.endswith('.py'):
1892 filename = make_filename(args)
1928 filename = make_filename(args)
1893 data = ''
1929 data = ''
1894 use_temp = 0
1930 use_temp = 0
1895 elif args:
1931 elif args:
1896 try:
1932 try:
1897 # Load the parameter given as a variable. If not a string,
1933 # Load the parameter given as a variable. If not a string,
1898 # process it as an object instead (below)
1934 # process it as an object instead (below)
1899
1935
1900 #print '*** args',args,'type',type(args) # dbg
1936 #print '*** args',args,'type',type(args) # dbg
1901 data = eval(args,self.shell.user_ns)
1937 data = eval(args,self.shell.user_ns)
1902 if not type(data) in StringTypes:
1938 if not type(data) in StringTypes:
1903 raise DataIsObject
1939 raise DataIsObject
1904
1940
1905 except (NameError,SyntaxError):
1941 except (NameError,SyntaxError):
1906 # given argument is not a variable, try as a filename
1942 # given argument is not a variable, try as a filename
1907 filename = make_filename(args)
1943 filename = make_filename(args)
1908 if filename is None:
1944 if filename is None:
1909 warn("Argument given (%s) can't be found as a variable "
1945 warn("Argument given (%s) can't be found as a variable "
1910 "or as a filename." % args)
1946 "or as a filename." % args)
1911 return
1947 return
1912
1948
1913 data = ''
1949 data = ''
1914 use_temp = 0
1950 use_temp = 0
1915 except DataIsObject:
1951 except DataIsObject:
1916
1952
1917 # macros have a special edit function
1953 # macros have a special edit function
1918 if isinstance(data,Macro):
1954 if isinstance(data,Macro):
1919 self._edit_macro(args,data)
1955 self._edit_macro(args,data)
1920 return
1956 return
1921
1957
1922 # For objects, try to edit the file where they are defined
1958 # For objects, try to edit the file where they are defined
1923 try:
1959 try:
1924 filename = inspect.getabsfile(data)
1960 filename = inspect.getabsfile(data)
1925 datafile = 1
1961 datafile = 1
1926 except TypeError:
1962 except TypeError:
1927 filename = make_filename(args)
1963 filename = make_filename(args)
1928 datafile = 1
1964 datafile = 1
1929 warn('Could not find file where `%s` is defined.\n'
1965 warn('Could not find file where `%s` is defined.\n'
1930 'Opening a file named `%s`' % (args,filename))
1966 'Opening a file named `%s`' % (args,filename))
1931 # Now, make sure we can actually read the source (if it was in
1967 # Now, make sure we can actually read the source (if it was in
1932 # a temp file it's gone by now).
1968 # a temp file it's gone by now).
1933 if datafile:
1969 if datafile:
1934 try:
1970 try:
1935 lineno = inspect.getsourcelines(data)[1]
1971 lineno = inspect.getsourcelines(data)[1]
1936 except IOError:
1972 except IOError:
1937 filename = make_filename(args)
1973 filename = make_filename(args)
1938 if filename is None:
1974 if filename is None:
1939 warn('The file `%s` where `%s` was defined cannot '
1975 warn('The file `%s` where `%s` was defined cannot '
1940 'be read.' % (filename,data))
1976 'be read.' % (filename,data))
1941 return
1977 return
1942 use_temp = 0
1978 use_temp = 0
1943 else:
1979 else:
1944 data = ''
1980 data = ''
1945
1981
1946 if use_temp:
1982 if use_temp:
1947 filename = self.shell.mktempfile(data)
1983 filename = self.shell.mktempfile(data)
1948 print 'IPython will make a temporary file named:',filename
1984 print 'IPython will make a temporary file named:',filename
1949
1985
1950 # do actual editing here
1986 # do actual editing here
1951 print 'Editing...',
1987 print 'Editing...',
1952 sys.stdout.flush()
1988 sys.stdout.flush()
1953 self.shell.hooks.editor(filename,lineno)
1989 self.shell.hooks.editor(filename,lineno)
1954 if opts.has_key('x'): # -x prevents actual execution
1990 if opts.has_key('x'): # -x prevents actual execution
1955 print
1991 print
1956 else:
1992 else:
1957 print 'done. Executing edited code...'
1993 print 'done. Executing edited code...'
1958 self.shell.safe_execfile(filename,self.shell.user_ns)
1994 if opts_r:
1995 self.shell.runlines(file_read(filename))
1996 else:
1997 self.shell.safe_execfile(filename,self.shell.user_ns)
1959 if use_temp:
1998 if use_temp:
1960 try:
1999 try:
1961 return open(filename).read()
2000 return open(filename).read()
1962 except IOError,msg:
2001 except IOError,msg:
1963 if msg.filename == filename:
2002 if msg.filename == filename:
1964 warn('File not found. Did you forget to save?')
2003 warn('File not found. Did you forget to save?')
1965 return
2004 return
1966 else:
2005 else:
1967 self.shell.showtraceback()
2006 self.shell.showtraceback()
1968
2007
1969 def magic_xmode(self,parameter_s = ''):
2008 def magic_xmode(self,parameter_s = ''):
1970 """Switch modes for the exception handlers.
2009 """Switch modes for the exception handlers.
1971
2010
1972 Valid modes: Plain, Context and Verbose.
2011 Valid modes: Plain, Context and Verbose.
1973
2012
1974 If called without arguments, acts as a toggle."""
2013 If called without arguments, acts as a toggle."""
1975
2014
1976 def xmode_switch_err(name):
2015 def xmode_switch_err(name):
1977 warn('Error changing %s exception modes.\n%s' %
2016 warn('Error changing %s exception modes.\n%s' %
1978 (name,sys.exc_info()[1]))
2017 (name,sys.exc_info()[1]))
1979
2018
1980 shell = self.shell
2019 shell = self.shell
1981 new_mode = parameter_s.strip().capitalize()
2020 new_mode = parameter_s.strip().capitalize()
1982 try:
2021 try:
1983 shell.InteractiveTB.set_mode(mode=new_mode)
2022 shell.InteractiveTB.set_mode(mode=new_mode)
1984 print 'Exception reporting mode:',shell.InteractiveTB.mode
2023 print 'Exception reporting mode:',shell.InteractiveTB.mode
1985 except:
2024 except:
1986 xmode_switch_err('user')
2025 xmode_switch_err('user')
1987
2026
1988 # threaded shells use a special handler in sys.excepthook
2027 # threaded shells use a special handler in sys.excepthook
1989 if shell.isthreaded:
2028 if shell.isthreaded:
1990 try:
2029 try:
1991 shell.sys_excepthook.set_mode(mode=new_mode)
2030 shell.sys_excepthook.set_mode(mode=new_mode)
1992 except:
2031 except:
1993 xmode_switch_err('threaded')
2032 xmode_switch_err('threaded')
1994
2033
1995 def magic_colors(self,parameter_s = ''):
2034 def magic_colors(self,parameter_s = ''):
1996 """Switch color scheme for prompts, info system and exception handlers.
2035 """Switch color scheme for prompts, info system and exception handlers.
1997
2036
1998 Currently implemented schemes: NoColor, Linux, LightBG.
2037 Currently implemented schemes: NoColor, Linux, LightBG.
1999
2038
2000 Color scheme names are not case-sensitive."""
2039 Color scheme names are not case-sensitive."""
2001
2040
2002 def color_switch_err(name):
2041 def color_switch_err(name):
2003 warn('Error changing %s color schemes.\n%s' %
2042 warn('Error changing %s color schemes.\n%s' %
2004 (name,sys.exc_info()[1]))
2043 (name,sys.exc_info()[1]))
2005
2044
2006
2045
2007 new_scheme = parameter_s.strip()
2046 new_scheme = parameter_s.strip()
2008 if not new_scheme:
2047 if not new_scheme:
2009 print 'You must specify a color scheme.'
2048 print 'You must specify a color scheme.'
2010 return
2049 return
2011 import IPython.rlineimpl as readline
2050 import IPython.rlineimpl as readline
2012 if not readline.have_readline:
2051 if not readline.have_readline:
2013 msg = """\
2052 msg = """\
2014 Proper color support under MS Windows requires Gary Bishop's readline library.
2053 Proper color support under MS Windows requires Gary Bishop's readline library.
2015 You can find it at:
2054 You can find it at:
2016 http://sourceforge.net/projects/uncpythontools
2055 http://sourceforge.net/projects/uncpythontools
2017 Gary's readline needs the ctypes module, from:
2056 Gary's readline needs the ctypes module, from:
2018 http://starship.python.net/crew/theller/ctypes
2057 http://starship.python.net/crew/theller/ctypes
2019
2058
2020 Defaulting color scheme to 'NoColor'"""
2059 Defaulting color scheme to 'NoColor'"""
2021 new_scheme = 'NoColor'
2060 new_scheme = 'NoColor'
2022 warn(msg)
2061 warn(msg)
2023 # local shortcut
2062 # local shortcut
2024 shell = self.shell
2063 shell = self.shell
2025
2064
2026 # Set prompt colors
2065 # Set prompt colors
2027 try:
2066 try:
2028 shell.outputcache.set_colors(new_scheme)
2067 shell.outputcache.set_colors(new_scheme)
2029 except:
2068 except:
2030 color_switch_err('prompt')
2069 color_switch_err('prompt')
2031 else:
2070 else:
2032 shell.rc.colors = \
2071 shell.rc.colors = \
2033 shell.outputcache.color_table.active_scheme_name
2072 shell.outputcache.color_table.active_scheme_name
2034 # Set exception colors
2073 # Set exception colors
2035 try:
2074 try:
2036 shell.InteractiveTB.set_colors(scheme = new_scheme)
2075 shell.InteractiveTB.set_colors(scheme = new_scheme)
2037 shell.SyntaxTB.set_colors(scheme = new_scheme)
2076 shell.SyntaxTB.set_colors(scheme = new_scheme)
2038 except:
2077 except:
2039 color_switch_err('exception')
2078 color_switch_err('exception')
2040
2079
2041 # threaded shells use a verbose traceback in sys.excepthook
2080 # threaded shells use a verbose traceback in sys.excepthook
2042 if shell.isthreaded:
2081 if shell.isthreaded:
2043 try:
2082 try:
2044 shell.sys_excepthook.set_colors(scheme=new_scheme)
2083 shell.sys_excepthook.set_colors(scheme=new_scheme)
2045 except:
2084 except:
2046 color_switch_err('system exception handler')
2085 color_switch_err('system exception handler')
2047
2086
2048 # Set info (for 'object?') colors
2087 # Set info (for 'object?') colors
2049 if shell.rc.color_info:
2088 if shell.rc.color_info:
2050 try:
2089 try:
2051 shell.inspector.set_active_scheme(new_scheme)
2090 shell.inspector.set_active_scheme(new_scheme)
2052 except:
2091 except:
2053 color_switch_err('object inspector')
2092 color_switch_err('object inspector')
2054 else:
2093 else:
2055 shell.inspector.set_active_scheme('NoColor')
2094 shell.inspector.set_active_scheme('NoColor')
2056
2095
2057 def magic_color_info(self,parameter_s = ''):
2096 def magic_color_info(self,parameter_s = ''):
2058 """Toggle color_info.
2097 """Toggle color_info.
2059
2098
2060 The color_info configuration parameter controls whether colors are
2099 The color_info configuration parameter controls whether colors are
2061 used for displaying object details (by things like %psource, %pfile or
2100 used for displaying object details (by things like %psource, %pfile or
2062 the '?' system). This function toggles this value with each call.
2101 the '?' system). This function toggles this value with each call.
2063
2102
2064 Note that unless you have a fairly recent pager (less works better
2103 Note that unless you have a fairly recent pager (less works better
2065 than more) in your system, using colored object information displays
2104 than more) in your system, using colored object information displays
2066 will not work properly. Test it and see."""
2105 will not work properly. Test it and see."""
2067
2106
2068 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2107 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2069 self.magic_colors(self.shell.rc.colors)
2108 self.magic_colors(self.shell.rc.colors)
2070 print 'Object introspection functions have now coloring:',
2109 print 'Object introspection functions have now coloring:',
2071 print ['OFF','ON'][self.shell.rc.color_info]
2110 print ['OFF','ON'][self.shell.rc.color_info]
2072
2111
2073 def magic_Pprint(self, parameter_s=''):
2112 def magic_Pprint(self, parameter_s=''):
2074 """Toggle pretty printing on/off."""
2113 """Toggle pretty printing on/off."""
2075
2114
2076 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2115 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2077 print 'Pretty printing has been turned', \
2116 print 'Pretty printing has been turned', \
2078 ['OFF','ON'][self.shell.outputcache.Pprint]
2117 ['OFF','ON'][self.shell.outputcache.Pprint]
2079
2118
2080 def magic_exit(self, parameter_s=''):
2119 def magic_exit(self, parameter_s=''):
2081 """Exit IPython, confirming if configured to do so.
2120 """Exit IPython, confirming if configured to do so.
2082
2121
2083 You can configure whether IPython asks for confirmation upon exit by
2122 You can configure whether IPython asks for confirmation upon exit by
2084 setting the confirm_exit flag in the ipythonrc file."""
2123 setting the confirm_exit flag in the ipythonrc file."""
2085
2124
2086 self.shell.exit()
2125 self.shell.exit()
2087
2126
2088 def magic_quit(self, parameter_s=''):
2127 def magic_quit(self, parameter_s=''):
2089 """Exit IPython, confirming if configured to do so (like %exit)"""
2128 """Exit IPython, confirming if configured to do so (like %exit)"""
2090
2129
2091 self.shell.exit()
2130 self.shell.exit()
2092
2131
2093 def magic_Exit(self, parameter_s=''):
2132 def magic_Exit(self, parameter_s=''):
2094 """Exit IPython without confirmation."""
2133 """Exit IPython without confirmation."""
2095
2134
2096 self.shell.exit_now = True
2135 self.shell.exit_now = True
2097
2136
2098 def magic_Quit(self, parameter_s=''):
2137 def magic_Quit(self, parameter_s=''):
2099 """Exit IPython without confirmation (like %Exit)."""
2138 """Exit IPython without confirmation (like %Exit)."""
2100
2139
2101 self.shell.exit_now = True
2140 self.shell.exit_now = True
2102
2141
2103 #......................................................................
2142 #......................................................................
2104 # Functions to implement unix shell-type things
2143 # Functions to implement unix shell-type things
2105
2144
2106 def magic_alias(self, parameter_s = ''):
2145 def magic_alias(self, parameter_s = ''):
2107 """Define an alias for a system command.
2146 """Define an alias for a system command.
2108
2147
2109 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2148 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2110
2149
2111 Then, typing 'alias_name params' will execute the system command 'cmd
2150 Then, typing 'alias_name params' will execute the system command 'cmd
2112 params' (from your underlying operating system).
2151 params' (from your underlying operating system).
2113
2152
2114 Aliases have lower precedence than magic functions and Python normal
2153 Aliases have lower precedence than magic functions and Python normal
2115 variables, so if 'foo' is both a Python variable and an alias, the
2154 variables, so if 'foo' is both a Python variable and an alias, the
2116 alias can not be executed until 'del foo' removes the Python variable.
2155 alias can not be executed until 'del foo' removes the Python variable.
2117
2156
2118 You can use the %l specifier in an alias definition to represent the
2157 You can use the %l specifier in an alias definition to represent the
2119 whole line when the alias is called. For example:
2158 whole line when the alias is called. For example:
2120
2159
2121 In [2]: alias all echo "Input in brackets: <%l>"\\
2160 In [2]: alias all echo "Input in brackets: <%l>"\\
2122 In [3]: all hello world\\
2161 In [3]: all hello world\\
2123 Input in brackets: <hello world>
2162 Input in brackets: <hello world>
2124
2163
2125 You can also define aliases with parameters using %s specifiers (one
2164 You can also define aliases with parameters using %s specifiers (one
2126 per parameter):
2165 per parameter):
2127
2166
2128 In [1]: alias parts echo first %s second %s\\
2167 In [1]: alias parts echo first %s second %s\\
2129 In [2]: %parts A B\\
2168 In [2]: %parts A B\\
2130 first A second B\\
2169 first A second B\\
2131 In [3]: %parts A\\
2170 In [3]: %parts A\\
2132 Incorrect number of arguments: 2 expected.\\
2171 Incorrect number of arguments: 2 expected.\\
2133 parts is an alias to: 'echo first %s second %s'
2172 parts is an alias to: 'echo first %s second %s'
2134
2173
2135 Note that %l and %s are mutually exclusive. You can only use one or
2174 Note that %l and %s are mutually exclusive. You can only use one or
2136 the other in your aliases.
2175 the other in your aliases.
2137
2176
2138 Aliases expand Python variables just like system calls using ! or !!
2177 Aliases expand Python variables just like system calls using ! or !!
2139 do: all expressions prefixed with '$' get expanded. For details of
2178 do: all expressions prefixed with '$' get expanded. For details of
2140 the semantic rules, see PEP-215:
2179 the semantic rules, see PEP-215:
2141 http://www.python.org/peps/pep-0215.html. This is the library used by
2180 http://www.python.org/peps/pep-0215.html. This is the library used by
2142 IPython for variable expansion. If you want to access a true shell
2181 IPython for variable expansion. If you want to access a true shell
2143 variable, an extra $ is necessary to prevent its expansion by IPython:
2182 variable, an extra $ is necessary to prevent its expansion by IPython:
2144
2183
2145 In [6]: alias show echo\\
2184 In [6]: alias show echo\\
2146 In [7]: PATH='A Python string'\\
2185 In [7]: PATH='A Python string'\\
2147 In [8]: show $PATH\\
2186 In [8]: show $PATH\\
2148 A Python string\\
2187 A Python string\\
2149 In [9]: show $$PATH\\
2188 In [9]: show $$PATH\\
2150 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2189 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2151
2190
2152 You can use the alias facility to acess all of $PATH. See the %rehash
2191 You can use the alias facility to acess all of $PATH. See the %rehash
2153 and %rehashx functions, which automatically create aliases for the
2192 and %rehashx functions, which automatically create aliases for the
2154 contents of your $PATH.
2193 contents of your $PATH.
2155
2194
2156 If called with no parameters, %alias prints the current alias table."""
2195 If called with no parameters, %alias prints the current alias table."""
2157
2196
2158 par = parameter_s.strip()
2197 par = parameter_s.strip()
2159 if not par:
2198 if not par:
2160 if self.shell.rc.automagic:
2199 if self.shell.rc.automagic:
2161 prechar = ''
2200 prechar = ''
2162 else:
2201 else:
2163 prechar = self.shell.ESC_MAGIC
2202 prechar = self.shell.ESC_MAGIC
2164 #print 'Alias\t\tSystem Command\n'+'-'*30
2203 #print 'Alias\t\tSystem Command\n'+'-'*30
2165 atab = self.shell.alias_table
2204 atab = self.shell.alias_table
2166 aliases = atab.keys()
2205 aliases = atab.keys()
2167 aliases.sort()
2206 aliases.sort()
2168 res = []
2207 res = []
2169 for alias in aliases:
2208 for alias in aliases:
2170 res.append((alias, atab[alias][1]))
2209 res.append((alias, atab[alias][1]))
2171 print "Total number of aliases:",len(aliases)
2210 print "Total number of aliases:",len(aliases)
2172 return res
2211 return res
2173 try:
2212 try:
2174 alias,cmd = par.split(None,1)
2213 alias,cmd = par.split(None,1)
2175 except:
2214 except:
2176 print OInspect.getdoc(self.magic_alias)
2215 print OInspect.getdoc(self.magic_alias)
2177 else:
2216 else:
2178 nargs = cmd.count('%s')
2217 nargs = cmd.count('%s')
2179 if nargs>0 and cmd.find('%l')>=0:
2218 if nargs>0 and cmd.find('%l')>=0:
2180 error('The %s and %l specifiers are mutually exclusive '
2219 error('The %s and %l specifiers are mutually exclusive '
2181 'in alias definitions.')
2220 'in alias definitions.')
2182 else: # all looks OK
2221 else: # all looks OK
2183 self.shell.alias_table[alias] = (nargs,cmd)
2222 self.shell.alias_table[alias] = (nargs,cmd)
2184 self.shell.alias_table_validate(verbose=1)
2223 self.shell.alias_table_validate(verbose=1)
2185 # end magic_alias
2224 # end magic_alias
2186
2225
2187 def magic_unalias(self, parameter_s = ''):
2226 def magic_unalias(self, parameter_s = ''):
2188 """Remove an alias"""
2227 """Remove an alias"""
2189
2228
2190 aname = parameter_s.strip()
2229 aname = parameter_s.strip()
2191 if aname in self.shell.alias_table:
2230 if aname in self.shell.alias_table:
2192 del self.shell.alias_table[aname]
2231 del self.shell.alias_table[aname]
2193
2232
2194 def magic_rehash(self, parameter_s = ''):
2233 def magic_rehash(self, parameter_s = ''):
2195 """Update the alias table with all entries in $PATH.
2234 """Update the alias table with all entries in $PATH.
2196
2235
2197 This version does no checks on execute permissions or whether the
2236 This version does no checks on execute permissions or whether the
2198 contents of $PATH are truly files (instead of directories or something
2237 contents of $PATH are truly files (instead of directories or something
2199 else). For such a safer (but slower) version, use %rehashx."""
2238 else). For such a safer (but slower) version, use %rehashx."""
2200
2239
2201 # This function (and rehashx) manipulate the alias_table directly
2240 # This function (and rehashx) manipulate the alias_table directly
2202 # rather than calling magic_alias, for speed reasons. A rehash on a
2241 # rather than calling magic_alias, for speed reasons. A rehash on a
2203 # typical Linux box involves several thousand entries, so efficiency
2242 # typical Linux box involves several thousand entries, so efficiency
2204 # here is a top concern.
2243 # here is a top concern.
2205
2244
2206 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2245 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2207 alias_table = self.shell.alias_table
2246 alias_table = self.shell.alias_table
2208 for pdir in path:
2247 for pdir in path:
2209 for ff in os.listdir(pdir):
2248 for ff in os.listdir(pdir):
2210 # each entry in the alias table must be (N,name), where
2249 # each entry in the alias table must be (N,name), where
2211 # N is the number of positional arguments of the alias.
2250 # N is the number of positional arguments of the alias.
2212 alias_table[ff] = (0,ff)
2251 alias_table[ff] = (0,ff)
2213 # Make sure the alias table doesn't contain keywords or builtins
2252 # Make sure the alias table doesn't contain keywords or builtins
2214 self.shell.alias_table_validate()
2253 self.shell.alias_table_validate()
2215 # Call again init_auto_alias() so we get 'rm -i' and other modified
2254 # Call again init_auto_alias() so we get 'rm -i' and other modified
2216 # aliases since %rehash will probably clobber them
2255 # aliases since %rehash will probably clobber them
2217 self.shell.init_auto_alias()
2256 self.shell.init_auto_alias()
2218
2257
2219 def magic_rehashx(self, parameter_s = ''):
2258 def magic_rehashx(self, parameter_s = ''):
2220 """Update the alias table with all executable files in $PATH.
2259 """Update the alias table with all executable files in $PATH.
2221
2260
2222 This version explicitly checks that every entry in $PATH is a file
2261 This version explicitly checks that every entry in $PATH is a file
2223 with execute access (os.X_OK), so it is much slower than %rehash.
2262 with execute access (os.X_OK), so it is much slower than %rehash.
2224
2263
2225 Under Windows, it checks executability as a match agains a
2264 Under Windows, it checks executability as a match agains a
2226 '|'-separated string of extensions, stored in the IPython config
2265 '|'-separated string of extensions, stored in the IPython config
2227 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2266 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2228
2267
2229 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2268 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2230 alias_table = self.shell.alias_table
2269 alias_table = self.shell.alias_table
2231
2270
2232 if os.name == 'posix':
2271 if os.name == 'posix':
2233 isexec = lambda fname:os.path.isfile(fname) and \
2272 isexec = lambda fname:os.path.isfile(fname) and \
2234 os.access(fname,os.X_OK)
2273 os.access(fname,os.X_OK)
2235 else:
2274 else:
2236
2275
2237 try:
2276 try:
2238 winext = os.environ['pathext'].replace(';','|').replace('.','')
2277 winext = os.environ['pathext'].replace(';','|').replace('.','')
2239 except KeyError:
2278 except KeyError:
2240 winext = 'exe|com|bat'
2279 winext = 'exe|com|bat'
2241
2280
2242 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2281 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2243 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2282 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2244 savedir = os.getcwd()
2283 savedir = os.getcwd()
2245 try:
2284 try:
2246 # write the whole loop for posix/Windows so we don't have an if in
2285 # write the whole loop for posix/Windows so we don't have an if in
2247 # the innermost part
2286 # the innermost part
2248 if os.name == 'posix':
2287 if os.name == 'posix':
2249 for pdir in path:
2288 for pdir in path:
2250 os.chdir(pdir)
2289 os.chdir(pdir)
2251 for ff in os.listdir(pdir):
2290 for ff in os.listdir(pdir):
2252 if isexec(ff):
2291 if isexec(ff):
2253 # each entry in the alias table must be (N,name),
2292 # each entry in the alias table must be (N,name),
2254 # where N is the number of positional arguments of the
2293 # where N is the number of positional arguments of the
2255 # alias.
2294 # alias.
2256 alias_table[ff] = (0,ff)
2295 alias_table[ff] = (0,ff)
2257 else:
2296 else:
2258 for pdir in path:
2297 for pdir in path:
2259 os.chdir(pdir)
2298 os.chdir(pdir)
2260 for ff in os.listdir(pdir):
2299 for ff in os.listdir(pdir):
2261 if isexec(ff):
2300 if isexec(ff):
2262 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2301 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2263 # Make sure the alias table doesn't contain keywords or builtins
2302 # Make sure the alias table doesn't contain keywords or builtins
2264 self.shell.alias_table_validate()
2303 self.shell.alias_table_validate()
2265 # Call again init_auto_alias() so we get 'rm -i' and other
2304 # Call again init_auto_alias() so we get 'rm -i' and other
2266 # modified aliases since %rehashx will probably clobber them
2305 # modified aliases since %rehashx will probably clobber them
2267 self.shell.init_auto_alias()
2306 self.shell.init_auto_alias()
2268 finally:
2307 finally:
2269 os.chdir(savedir)
2308 os.chdir(savedir)
2270
2309
2271 def magic_pwd(self, parameter_s = ''):
2310 def magic_pwd(self, parameter_s = ''):
2272 """Return the current working directory path."""
2311 """Return the current working directory path."""
2273 return os.getcwd()
2312 return os.getcwd()
2274
2313
2275 def magic_cd(self, parameter_s=''):
2314 def magic_cd(self, parameter_s=''):
2276 """Change the current working directory.
2315 """Change the current working directory.
2277
2316
2278 This command automatically maintains an internal list of directories
2317 This command automatically maintains an internal list of directories
2279 you visit during your IPython session, in the variable _dh. The
2318 you visit during your IPython session, in the variable _dh. The
2280 command %dhist shows this history nicely formatted.
2319 command %dhist shows this history nicely formatted.
2281
2320
2282 Usage:
2321 Usage:
2283
2322
2284 cd 'dir': changes to directory 'dir'.
2323 cd 'dir': changes to directory 'dir'.
2285
2324
2286 cd -: changes to the last visited directory.
2325 cd -: changes to the last visited directory.
2287
2326
2288 cd -<n>: changes to the n-th directory in the directory history.
2327 cd -<n>: changes to the n-th directory in the directory history.
2289
2328
2290 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2329 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2291 (note: cd <bookmark_name> is enough if there is no
2330 (note: cd <bookmark_name> is enough if there is no
2292 directory <bookmark_name>, but a bookmark with the name exists.)
2331 directory <bookmark_name>, but a bookmark with the name exists.)
2293
2332
2294 Options:
2333 Options:
2295
2334
2296 -q: quiet. Do not print the working directory after the cd command is
2335 -q: quiet. Do not print the working directory after the cd command is
2297 executed. By default IPython's cd command does print this directory,
2336 executed. By default IPython's cd command does print this directory,
2298 since the default prompts do not display path information.
2337 since the default prompts do not display path information.
2299
2338
2300 Note that !cd doesn't work for this purpose because the shell where
2339 Note that !cd doesn't work for this purpose because the shell where
2301 !command runs is immediately discarded after executing 'command'."""
2340 !command runs is immediately discarded after executing 'command'."""
2302
2341
2303 parameter_s = parameter_s.strip()
2342 parameter_s = parameter_s.strip()
2304 #bkms = self.shell.persist.get("bookmarks",{})
2343 #bkms = self.shell.persist.get("bookmarks",{})
2305
2344
2306 numcd = re.match(r'(-)(\d+)$',parameter_s)
2345 numcd = re.match(r'(-)(\d+)$',parameter_s)
2307 # jump in directory history by number
2346 # jump in directory history by number
2308 if numcd:
2347 if numcd:
2309 nn = int(numcd.group(2))
2348 nn = int(numcd.group(2))
2310 try:
2349 try:
2311 ps = self.shell.user_ns['_dh'][nn]
2350 ps = self.shell.user_ns['_dh'][nn]
2312 except IndexError:
2351 except IndexError:
2313 print 'The requested directory does not exist in history.'
2352 print 'The requested directory does not exist in history.'
2314 return
2353 return
2315 else:
2354 else:
2316 opts = {}
2355 opts = {}
2317 else:
2356 else:
2318 #turn all non-space-escaping backslashes to slashes,
2357 #turn all non-space-escaping backslashes to slashes,
2319 # for c:\windows\directory\names\
2358 # for c:\windows\directory\names\
2320 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2359 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2321 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2360 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2322 # jump to previous
2361 # jump to previous
2323 if ps == '-':
2362 if ps == '-':
2324 try:
2363 try:
2325 ps = self.shell.user_ns['_dh'][-2]
2364 ps = self.shell.user_ns['_dh'][-2]
2326 except IndexError:
2365 except IndexError:
2327 print 'No previous directory to change to.'
2366 print 'No previous directory to change to.'
2328 return
2367 return
2329 # jump to bookmark if needed
2368 # jump to bookmark if needed
2330 else:
2369 else:
2331 if not os.path.isdir(ps) or opts.has_key('b'):
2370 if not os.path.isdir(ps) or opts.has_key('b'):
2332 bkms = self.db.get('bookmarks', {})
2371 bkms = self.db.get('bookmarks', {})
2333
2372
2334 if bkms.has_key(ps):
2373 if bkms.has_key(ps):
2335 target = bkms[ps]
2374 target = bkms[ps]
2336 print '(bookmark:%s) -> %s' % (ps,target)
2375 print '(bookmark:%s) -> %s' % (ps,target)
2337 ps = target
2376 ps = target
2338 else:
2377 else:
2339 if opts.has_key('b'):
2378 if opts.has_key('b'):
2340 error("Bookmark '%s' not found. "
2379 error("Bookmark '%s' not found. "
2341 "Use '%%bookmark -l' to see your bookmarks." % ps)
2380 "Use '%%bookmark -l' to see your bookmarks." % ps)
2342 return
2381 return
2343
2382
2344 # at this point ps should point to the target dir
2383 # at this point ps should point to the target dir
2345 if ps:
2384 if ps:
2346 try:
2385 try:
2347 os.chdir(os.path.expanduser(ps))
2386 os.chdir(os.path.expanduser(ps))
2348 ttitle = ("IPy:" + (
2387 ttitle = ("IPy:" + (
2349 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2388 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2350 platutils.set_term_title(ttitle)
2389 platutils.set_term_title(ttitle)
2351 except OSError:
2390 except OSError:
2352 print sys.exc_info()[1]
2391 print sys.exc_info()[1]
2353 else:
2392 else:
2354 self.shell.user_ns['_dh'].append(os.getcwd())
2393 self.shell.user_ns['_dh'].append(os.getcwd())
2355 else:
2394 else:
2356 os.chdir(self.shell.home_dir)
2395 os.chdir(self.shell.home_dir)
2357 platutils.set_term_title("IPy:~")
2396 platutils.set_term_title("IPy:~")
2358 self.shell.user_ns['_dh'].append(os.getcwd())
2397 self.shell.user_ns['_dh'].append(os.getcwd())
2359 if not 'q' in opts:
2398 if not 'q' in opts:
2360 print self.shell.user_ns['_dh'][-1]
2399 print self.shell.user_ns['_dh'][-1]
2361
2400
2362 def magic_dhist(self, parameter_s=''):
2401 def magic_dhist(self, parameter_s=''):
2363 """Print your history of visited directories.
2402 """Print your history of visited directories.
2364
2403
2365 %dhist -> print full history\\
2404 %dhist -> print full history\\
2366 %dhist n -> print last n entries only\\
2405 %dhist n -> print last n entries only\\
2367 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2406 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2368
2407
2369 This history is automatically maintained by the %cd command, and
2408 This history is automatically maintained by the %cd command, and
2370 always available as the global list variable _dh. You can use %cd -<n>
2409 always available as the global list variable _dh. You can use %cd -<n>
2371 to go to directory number <n>."""
2410 to go to directory number <n>."""
2372
2411
2373 dh = self.shell.user_ns['_dh']
2412 dh = self.shell.user_ns['_dh']
2374 if parameter_s:
2413 if parameter_s:
2375 try:
2414 try:
2376 args = map(int,parameter_s.split())
2415 args = map(int,parameter_s.split())
2377 except:
2416 except:
2378 self.arg_err(Magic.magic_dhist)
2417 self.arg_err(Magic.magic_dhist)
2379 return
2418 return
2380 if len(args) == 1:
2419 if len(args) == 1:
2381 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2420 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2382 elif len(args) == 2:
2421 elif len(args) == 2:
2383 ini,fin = args
2422 ini,fin = args
2384 else:
2423 else:
2385 self.arg_err(Magic.magic_dhist)
2424 self.arg_err(Magic.magic_dhist)
2386 return
2425 return
2387 else:
2426 else:
2388 ini,fin = 0,len(dh)
2427 ini,fin = 0,len(dh)
2389 nlprint(dh,
2428 nlprint(dh,
2390 header = 'Directory history (kept in _dh)',
2429 header = 'Directory history (kept in _dh)',
2391 start=ini,stop=fin)
2430 start=ini,stop=fin)
2392
2431
2393 def magic_env(self, parameter_s=''):
2432 def magic_env(self, parameter_s=''):
2394 """List environment variables."""
2433 """List environment variables."""
2395
2434
2396 return os.environ.data
2435 return os.environ.data
2397
2436
2398 def magic_pushd(self, parameter_s=''):
2437 def magic_pushd(self, parameter_s=''):
2399 """Place the current dir on stack and change directory.
2438 """Place the current dir on stack and change directory.
2400
2439
2401 Usage:\\
2440 Usage:\\
2402 %pushd ['dirname']
2441 %pushd ['dirname']
2403
2442
2404 %pushd with no arguments does a %pushd to your home directory.
2443 %pushd with no arguments does a %pushd to your home directory.
2405 """
2444 """
2406 if parameter_s == '': parameter_s = '~'
2445 if parameter_s == '': parameter_s = '~'
2407 dir_s = self.shell.dir_stack
2446 dir_s = self.shell.dir_stack
2408 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2447 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2409 os.path.expanduser(self.shell.dir_stack[0]):
2448 os.path.expanduser(self.shell.dir_stack[0]):
2410 try:
2449 try:
2411 self.magic_cd(parameter_s)
2450 self.magic_cd(parameter_s)
2412 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2451 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2413 self.magic_dirs()
2452 self.magic_dirs()
2414 except:
2453 except:
2415 print 'Invalid directory'
2454 print 'Invalid directory'
2416 else:
2455 else:
2417 print 'You are already there!'
2456 print 'You are already there!'
2418
2457
2419 def magic_popd(self, parameter_s=''):
2458 def magic_popd(self, parameter_s=''):
2420 """Change to directory popped off the top of the stack.
2459 """Change to directory popped off the top of the stack.
2421 """
2460 """
2422 if len (self.shell.dir_stack) > 1:
2461 if len (self.shell.dir_stack) > 1:
2423 self.shell.dir_stack.pop(0)
2462 self.shell.dir_stack.pop(0)
2424 self.magic_cd(self.shell.dir_stack[0])
2463 self.magic_cd(self.shell.dir_stack[0])
2425 print self.shell.dir_stack[0]
2464 print self.shell.dir_stack[0]
2426 else:
2465 else:
2427 print "You can't remove the starting directory from the stack:",\
2466 print "You can't remove the starting directory from the stack:",\
2428 self.shell.dir_stack
2467 self.shell.dir_stack
2429
2468
2430 def magic_dirs(self, parameter_s=''):
2469 def magic_dirs(self, parameter_s=''):
2431 """Return the current directory stack."""
2470 """Return the current directory stack."""
2432
2471
2433 return self.shell.dir_stack[:]
2472 return self.shell.dir_stack[:]
2434
2473
2435 def magic_sc(self, parameter_s=''):
2474 def magic_sc(self, parameter_s=''):
2436 """Shell capture - execute a shell command and capture its output.
2475 """Shell capture - execute a shell command and capture its output.
2437
2476
2438 DEPRECATED. Suboptimal, retained for backwards compatibility.
2477 DEPRECATED. Suboptimal, retained for backwards compatibility.
2439
2478
2440 You should use the form 'var = !command' instead. Example:
2479 You should use the form 'var = !command' instead. Example:
2441
2480
2442 "%sc -l myfiles = ls ~" should now be written as
2481 "%sc -l myfiles = ls ~" should now be written as
2443
2482
2444 "myfiles = !ls ~"
2483 "myfiles = !ls ~"
2445
2484
2446 myfiles.s, myfiles.l and myfiles.n still apply as documented
2485 myfiles.s, myfiles.l and myfiles.n still apply as documented
2447 below.
2486 below.
2448
2487
2449 --
2488 --
2450 %sc [options] varname=command
2489 %sc [options] varname=command
2451
2490
2452 IPython will run the given command using commands.getoutput(), and
2491 IPython will run the given command using commands.getoutput(), and
2453 will then update the user's interactive namespace with a variable
2492 will then update the user's interactive namespace with a variable
2454 called varname, containing the value of the call. Your command can
2493 called varname, containing the value of the call. Your command can
2455 contain shell wildcards, pipes, etc.
2494 contain shell wildcards, pipes, etc.
2456
2495
2457 The '=' sign in the syntax is mandatory, and the variable name you
2496 The '=' sign in the syntax is mandatory, and the variable name you
2458 supply must follow Python's standard conventions for valid names.
2497 supply must follow Python's standard conventions for valid names.
2459
2498
2460 (A special format without variable name exists for internal use)
2499 (A special format without variable name exists for internal use)
2461
2500
2462 Options:
2501 Options:
2463
2502
2464 -l: list output. Split the output on newlines into a list before
2503 -l: list output. Split the output on newlines into a list before
2465 assigning it to the given variable. By default the output is stored
2504 assigning it to the given variable. By default the output is stored
2466 as a single string.
2505 as a single string.
2467
2506
2468 -v: verbose. Print the contents of the variable.
2507 -v: verbose. Print the contents of the variable.
2469
2508
2470 In most cases you should not need to split as a list, because the
2509 In most cases you should not need to split as a list, because the
2471 returned value is a special type of string which can automatically
2510 returned value is a special type of string which can automatically
2472 provide its contents either as a list (split on newlines) or as a
2511 provide its contents either as a list (split on newlines) or as a
2473 space-separated string. These are convenient, respectively, either
2512 space-separated string. These are convenient, respectively, either
2474 for sequential processing or to be passed to a shell command.
2513 for sequential processing or to be passed to a shell command.
2475
2514
2476 For example:
2515 For example:
2477
2516
2478 # Capture into variable a
2517 # Capture into variable a
2479 In [9]: sc a=ls *py
2518 In [9]: sc a=ls *py
2480
2519
2481 # a is a string with embedded newlines
2520 # a is a string with embedded newlines
2482 In [10]: a
2521 In [10]: a
2483 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2522 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2484
2523
2485 # which can be seen as a list:
2524 # which can be seen as a list:
2486 In [11]: a.l
2525 In [11]: a.l
2487 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2526 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2488
2527
2489 # or as a whitespace-separated string:
2528 # or as a whitespace-separated string:
2490 In [12]: a.s
2529 In [12]: a.s
2491 Out[12]: 'setup.py win32_manual_post_install.py'
2530 Out[12]: 'setup.py win32_manual_post_install.py'
2492
2531
2493 # a.s is useful to pass as a single command line:
2532 # a.s is useful to pass as a single command line:
2494 In [13]: !wc -l $a.s
2533 In [13]: !wc -l $a.s
2495 146 setup.py
2534 146 setup.py
2496 130 win32_manual_post_install.py
2535 130 win32_manual_post_install.py
2497 276 total
2536 276 total
2498
2537
2499 # while the list form is useful to loop over:
2538 # while the list form is useful to loop over:
2500 In [14]: for f in a.l:
2539 In [14]: for f in a.l:
2501 ....: !wc -l $f
2540 ....: !wc -l $f
2502 ....:
2541 ....:
2503 146 setup.py
2542 146 setup.py
2504 130 win32_manual_post_install.py
2543 130 win32_manual_post_install.py
2505
2544
2506 Similiarly, the lists returned by the -l option are also special, in
2545 Similiarly, the lists returned by the -l option are also special, in
2507 the sense that you can equally invoke the .s attribute on them to
2546 the sense that you can equally invoke the .s attribute on them to
2508 automatically get a whitespace-separated string from their contents:
2547 automatically get a whitespace-separated string from their contents:
2509
2548
2510 In [1]: sc -l b=ls *py
2549 In [1]: sc -l b=ls *py
2511
2550
2512 In [2]: b
2551 In [2]: b
2513 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2552 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2514
2553
2515 In [3]: b.s
2554 In [3]: b.s
2516 Out[3]: 'setup.py win32_manual_post_install.py'
2555 Out[3]: 'setup.py win32_manual_post_install.py'
2517
2556
2518 In summary, both the lists and strings used for ouptut capture have
2557 In summary, both the lists and strings used for ouptut capture have
2519 the following special attributes:
2558 the following special attributes:
2520
2559
2521 .l (or .list) : value as list.
2560 .l (or .list) : value as list.
2522 .n (or .nlstr): value as newline-separated string.
2561 .n (or .nlstr): value as newline-separated string.
2523 .s (or .spstr): value as space-separated string.
2562 .s (or .spstr): value as space-separated string.
2524 """
2563 """
2525
2564
2526 opts,args = self.parse_options(parameter_s,'lv')
2565 opts,args = self.parse_options(parameter_s,'lv')
2527 # Try to get a variable name and command to run
2566 # Try to get a variable name and command to run
2528 try:
2567 try:
2529 # the variable name must be obtained from the parse_options
2568 # the variable name must be obtained from the parse_options
2530 # output, which uses shlex.split to strip options out.
2569 # output, which uses shlex.split to strip options out.
2531 var,_ = args.split('=',1)
2570 var,_ = args.split('=',1)
2532 var = var.strip()
2571 var = var.strip()
2533 # But the the command has to be extracted from the original input
2572 # But the the command has to be extracted from the original input
2534 # parameter_s, not on what parse_options returns, to avoid the
2573 # parameter_s, not on what parse_options returns, to avoid the
2535 # quote stripping which shlex.split performs on it.
2574 # quote stripping which shlex.split performs on it.
2536 _,cmd = parameter_s.split('=',1)
2575 _,cmd = parameter_s.split('=',1)
2537 except ValueError:
2576 except ValueError:
2538 var,cmd = '',''
2577 var,cmd = '',''
2539 # If all looks ok, proceed
2578 # If all looks ok, proceed
2540 out,err = self.shell.getoutputerror(cmd)
2579 out,err = self.shell.getoutputerror(cmd)
2541 if err:
2580 if err:
2542 print >> Term.cerr,err
2581 print >> Term.cerr,err
2543 if opts.has_key('l'):
2582 if opts.has_key('l'):
2544 out = SList(out.split('\n'))
2583 out = SList(out.split('\n'))
2545 else:
2584 else:
2546 out = LSString(out)
2585 out = LSString(out)
2547 if opts.has_key('v'):
2586 if opts.has_key('v'):
2548 print '%s ==\n%s' % (var,pformat(out))
2587 print '%s ==\n%s' % (var,pformat(out))
2549 if var:
2588 if var:
2550 self.shell.user_ns.update({var:out})
2589 self.shell.user_ns.update({var:out})
2551 else:
2590 else:
2552 return out
2591 return out
2553
2592
2554 def magic_sx(self, parameter_s=''):
2593 def magic_sx(self, parameter_s=''):
2555 """Shell execute - run a shell command and capture its output.
2594 """Shell execute - run a shell command and capture its output.
2556
2595
2557 %sx command
2596 %sx command
2558
2597
2559 IPython will run the given command using commands.getoutput(), and
2598 IPython will run the given command using commands.getoutput(), and
2560 return the result formatted as a list (split on '\\n'). Since the
2599 return the result formatted as a list (split on '\\n'). Since the
2561 output is _returned_, it will be stored in ipython's regular output
2600 output is _returned_, it will be stored in ipython's regular output
2562 cache Out[N] and in the '_N' automatic variables.
2601 cache Out[N] and in the '_N' automatic variables.
2563
2602
2564 Notes:
2603 Notes:
2565
2604
2566 1) If an input line begins with '!!', then %sx is automatically
2605 1) If an input line begins with '!!', then %sx is automatically
2567 invoked. That is, while:
2606 invoked. That is, while:
2568 !ls
2607 !ls
2569 causes ipython to simply issue system('ls'), typing
2608 causes ipython to simply issue system('ls'), typing
2570 !!ls
2609 !!ls
2571 is a shorthand equivalent to:
2610 is a shorthand equivalent to:
2572 %sx ls
2611 %sx ls
2573
2612
2574 2) %sx differs from %sc in that %sx automatically splits into a list,
2613 2) %sx differs from %sc in that %sx automatically splits into a list,
2575 like '%sc -l'. The reason for this is to make it as easy as possible
2614 like '%sc -l'. The reason for this is to make it as easy as possible
2576 to process line-oriented shell output via further python commands.
2615 to process line-oriented shell output via further python commands.
2577 %sc is meant to provide much finer control, but requires more
2616 %sc is meant to provide much finer control, but requires more
2578 typing.
2617 typing.
2579
2618
2580 3) Just like %sc -l, this is a list with special attributes:
2619 3) Just like %sc -l, this is a list with special attributes:
2581
2620
2582 .l (or .list) : value as list.
2621 .l (or .list) : value as list.
2583 .n (or .nlstr): value as newline-separated string.
2622 .n (or .nlstr): value as newline-separated string.
2584 .s (or .spstr): value as whitespace-separated string.
2623 .s (or .spstr): value as whitespace-separated string.
2585
2624
2586 This is very useful when trying to use such lists as arguments to
2625 This is very useful when trying to use such lists as arguments to
2587 system commands."""
2626 system commands."""
2588
2627
2589 if parameter_s:
2628 if parameter_s:
2590 out,err = self.shell.getoutputerror(parameter_s)
2629 out,err = self.shell.getoutputerror(parameter_s)
2591 if err:
2630 if err:
2592 print >> Term.cerr,err
2631 print >> Term.cerr,err
2593 return SList(out.split('\n'))
2632 return SList(out.split('\n'))
2594
2633
2595 def magic_bg(self, parameter_s=''):
2634 def magic_bg(self, parameter_s=''):
2596 """Run a job in the background, in a separate thread.
2635 """Run a job in the background, in a separate thread.
2597
2636
2598 For example,
2637 For example,
2599
2638
2600 %bg myfunc(x,y,z=1)
2639 %bg myfunc(x,y,z=1)
2601
2640
2602 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2641 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2603 execution starts, a message will be printed indicating the job
2642 execution starts, a message will be printed indicating the job
2604 number. If your job number is 5, you can use
2643 number. If your job number is 5, you can use
2605
2644
2606 myvar = jobs.result(5) or myvar = jobs[5].result
2645 myvar = jobs.result(5) or myvar = jobs[5].result
2607
2646
2608 to assign this result to variable 'myvar'.
2647 to assign this result to variable 'myvar'.
2609
2648
2610 IPython has a job manager, accessible via the 'jobs' object. You can
2649 IPython has a job manager, accessible via the 'jobs' object. You can
2611 type jobs? to get more information about it, and use jobs.<TAB> to see
2650 type jobs? to get more information about it, and use jobs.<TAB> to see
2612 its attributes. All attributes not starting with an underscore are
2651 its attributes. All attributes not starting with an underscore are
2613 meant for public use.
2652 meant for public use.
2614
2653
2615 In particular, look at the jobs.new() method, which is used to create
2654 In particular, look at the jobs.new() method, which is used to create
2616 new jobs. This magic %bg function is just a convenience wrapper
2655 new jobs. This magic %bg function is just a convenience wrapper
2617 around jobs.new(), for expression-based jobs. If you want to create a
2656 around jobs.new(), for expression-based jobs. If you want to create a
2618 new job with an explicit function object and arguments, you must call
2657 new job with an explicit function object and arguments, you must call
2619 jobs.new() directly.
2658 jobs.new() directly.
2620
2659
2621 The jobs.new docstring also describes in detail several important
2660 The jobs.new docstring also describes in detail several important
2622 caveats associated with a thread-based model for background job
2661 caveats associated with a thread-based model for background job
2623 execution. Type jobs.new? for details.
2662 execution. Type jobs.new? for details.
2624
2663
2625 You can check the status of all jobs with jobs.status().
2664 You can check the status of all jobs with jobs.status().
2626
2665
2627 The jobs variable is set by IPython into the Python builtin namespace.
2666 The jobs variable is set by IPython into the Python builtin namespace.
2628 If you ever declare a variable named 'jobs', you will shadow this
2667 If you ever declare a variable named 'jobs', you will shadow this
2629 name. You can either delete your global jobs variable to regain
2668 name. You can either delete your global jobs variable to regain
2630 access to the job manager, or make a new name and assign it manually
2669 access to the job manager, or make a new name and assign it manually
2631 to the manager (stored in IPython's namespace). For example, to
2670 to the manager (stored in IPython's namespace). For example, to
2632 assign the job manager to the Jobs name, use:
2671 assign the job manager to the Jobs name, use:
2633
2672
2634 Jobs = __builtins__.jobs"""
2673 Jobs = __builtins__.jobs"""
2635
2674
2636 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2675 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2637
2676
2638
2677
2639 def magic_bookmark(self, parameter_s=''):
2678 def magic_bookmark(self, parameter_s=''):
2640 """Manage IPython's bookmark system.
2679 """Manage IPython's bookmark system.
2641
2680
2642 %bookmark <name> - set bookmark to current dir
2681 %bookmark <name> - set bookmark to current dir
2643 %bookmark <name> <dir> - set bookmark to <dir>
2682 %bookmark <name> <dir> - set bookmark to <dir>
2644 %bookmark -l - list all bookmarks
2683 %bookmark -l - list all bookmarks
2645 %bookmark -d <name> - remove bookmark
2684 %bookmark -d <name> - remove bookmark
2646 %bookmark -r - remove all bookmarks
2685 %bookmark -r - remove all bookmarks
2647
2686
2648 You can later on access a bookmarked folder with:
2687 You can later on access a bookmarked folder with:
2649 %cd -b <name>
2688 %cd -b <name>
2650 or simply '%cd <name>' if there is no directory called <name> AND
2689 or simply '%cd <name>' if there is no directory called <name> AND
2651 there is such a bookmark defined.
2690 there is such a bookmark defined.
2652
2691
2653 Your bookmarks persist through IPython sessions, but they are
2692 Your bookmarks persist through IPython sessions, but they are
2654 associated with each profile."""
2693 associated with each profile."""
2655
2694
2656 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2695 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2657 if len(args) > 2:
2696 if len(args) > 2:
2658 error('You can only give at most two arguments')
2697 error('You can only give at most two arguments')
2659 return
2698 return
2660
2699
2661 bkms = self.db.get('bookmarks',{})
2700 bkms = self.db.get('bookmarks',{})
2662
2701
2663 if opts.has_key('d'):
2702 if opts.has_key('d'):
2664 try:
2703 try:
2665 todel = args[0]
2704 todel = args[0]
2666 except IndexError:
2705 except IndexError:
2667 error('You must provide a bookmark to delete')
2706 error('You must provide a bookmark to delete')
2668 else:
2707 else:
2669 try:
2708 try:
2670 del bkms[todel]
2709 del bkms[todel]
2671 except:
2710 except:
2672 error("Can't delete bookmark '%s'" % todel)
2711 error("Can't delete bookmark '%s'" % todel)
2673 elif opts.has_key('r'):
2712 elif opts.has_key('r'):
2674 bkms = {}
2713 bkms = {}
2675 elif opts.has_key('l'):
2714 elif opts.has_key('l'):
2676 bks = bkms.keys()
2715 bks = bkms.keys()
2677 bks.sort()
2716 bks.sort()
2678 if bks:
2717 if bks:
2679 size = max(map(len,bks))
2718 size = max(map(len,bks))
2680 else:
2719 else:
2681 size = 0
2720 size = 0
2682 fmt = '%-'+str(size)+'s -> %s'
2721 fmt = '%-'+str(size)+'s -> %s'
2683 print 'Current bookmarks:'
2722 print 'Current bookmarks:'
2684 for bk in bks:
2723 for bk in bks:
2685 print fmt % (bk,bkms[bk])
2724 print fmt % (bk,bkms[bk])
2686 else:
2725 else:
2687 if not args:
2726 if not args:
2688 error("You must specify the bookmark name")
2727 error("You must specify the bookmark name")
2689 elif len(args)==1:
2728 elif len(args)==1:
2690 bkms[args[0]] = os.getcwd()
2729 bkms[args[0]] = os.getcwd()
2691 elif len(args)==2:
2730 elif len(args)==2:
2692 bkms[args[0]] = args[1]
2731 bkms[args[0]] = args[1]
2693 self.db['bookmarks'] = bkms
2732 self.db['bookmarks'] = bkms
2694
2733
2695 def magic_pycat(self, parameter_s=''):
2734 def magic_pycat(self, parameter_s=''):
2696 """Show a syntax-highlighted file through a pager.
2735 """Show a syntax-highlighted file through a pager.
2697
2736
2698 This magic is similar to the cat utility, but it will assume the file
2737 This magic is similar to the cat utility, but it will assume the file
2699 to be Python source and will show it with syntax highlighting. """
2738 to be Python source and will show it with syntax highlighting. """
2700
2739
2701 try:
2740 try:
2702 filename = get_py_filename(parameter_s)
2741 filename = get_py_filename(parameter_s)
2703 cont = file_read(filename)
2742 cont = file_read(filename)
2704 except IOError:
2743 except IOError:
2705 try:
2744 try:
2706 cont = eval(parameter_s,self.user_ns)
2745 cont = eval(parameter_s,self.user_ns)
2707 except NameError:
2746 except NameError:
2708 cont = None
2747 cont = None
2709 if cont is None:
2748 if cont is None:
2710 print "Error: no such file or variable"
2749 print "Error: no such file or variable"
2711 return
2750 return
2712
2751
2713 page(self.shell.pycolorize(cont),
2752 page(self.shell.pycolorize(cont),
2714 screen_lines=self.shell.rc.screen_length)
2753 screen_lines=self.shell.rc.screen_length)
2715
2754
2716 def magic_cpaste(self, parameter_s=''):
2755 def magic_cpaste(self, parameter_s=''):
2717 """Allows you to paste & execute a pre-formatted code block from
2756 """Allows you to paste & execute a pre-formatted code block from
2718 clipboard.
2757 clipboard.
2719
2758
2720 You must terminate the block with '--' (two minus-signs) alone on the
2759 You must terminate the block with '--' (two minus-signs) alone on the
2721 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2760 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2722 is the new sentinel for this operation)
2761 is the new sentinel for this operation)
2723
2762
2724 The block is dedented prior to execution to enable execution of
2763 The block is dedented prior to execution to enable execution of
2725 method definitions. The executed block is also assigned to variable
2764 method definitions. The executed block is also assigned to variable
2726 named 'pasted_block' for later editing with '%edit pasted_block'.
2765 named 'pasted_block' for later editing with '%edit pasted_block'.
2727
2766
2728 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2767 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2729 This assigns the pasted block to variable 'foo' as string, without
2768 This assigns the pasted block to variable 'foo' as string, without
2730 dedenting or executing it.
2769 dedenting or executing it.
2731
2770
2732 Do not be alarmed by garbled output on Windows (it's a readline bug).
2771 Do not be alarmed by garbled output on Windows (it's a readline bug).
2733 Just press enter and type -- (and press enter again) and the block
2772 Just press enter and type -- (and press enter again) and the block
2734 will be what was just pasted.
2773 will be what was just pasted.
2735
2774
2736 IPython statements (magics, shell escapes) are not supported (yet).
2775 IPython statements (magics, shell escapes) are not supported (yet).
2737 """
2776 """
2738 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2777 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2739 par = args.strip()
2778 par = args.strip()
2740 sentinel = opts.get('s','--')
2779 sentinel = opts.get('s','--')
2741
2780
2742 from IPython import iplib
2781 from IPython import iplib
2743 lines = []
2782 lines = []
2744 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2783 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2745 while 1:
2784 while 1:
2746 l = iplib.raw_input_original(':')
2785 l = iplib.raw_input_original(':')
2747 if l ==sentinel:
2786 if l ==sentinel:
2748 break
2787 break
2749 lines.append(l)
2788 lines.append(l)
2750 block = "\n".join(lines) + '\n'
2789 block = "\n".join(lines) + '\n'
2751 #print "block:\n",block
2790 #print "block:\n",block
2752 if not par:
2791 if not par:
2753 b = textwrap.dedent(block)
2792 b = textwrap.dedent(block)
2754 exec b in self.user_ns
2793 exec b in self.user_ns
2755 self.user_ns['pasted_block'] = b
2794 self.user_ns['pasted_block'] = b
2756 else:
2795 else:
2757 self.user_ns[par] = block
2796 self.user_ns[par] = block
2758 print "Block assigned to '%s'" % par
2797 print "Block assigned to '%s'" % par
2759 def magic_quickref(self,arg):
2798 def magic_quickref(self,arg):
2760 import IPython.usage
2799 import IPython.usage
2761 page(IPython.usage.quick_reference)
2800 page(IPython.usage.quick_reference)
2762 del IPython.usage
2801 del IPython.usage
2763
2802
2764
2803
2765 # end Magic
2804 # end Magic
@@ -1,311 +1,418 b''
1 """Module for interactive demos using IPython.
1 """Module for interactive demos using IPython.
2
2
3 This module implements a single class, Demo, for running Python scripts
3 This module implements a few classes for running Python scripts interactively
4 interactively in IPython for demonstrations. With very simple markup (a few
4 in IPython for demonstrations. With very simple markup (a few tags in
5 tags in comments), you can control points where the script stops executing and
5 comments), you can control points where the script stops executing and returns
6 returns control to IPython.
6 control to IPython.
7
8 The classes are (see their docstrings for further details):
9
10 - Demo: pure python demos
11
12 - IPythonDemo: demos with input to be processed by IPython as if it had been
13 typed interactively (so magics work, as well as any other special syntax you
14 may have added via input prefilters).
15
16 - LineDemo: single-line version of the Demo class. These demos are executed
17 one line at a time, and require no markup.
18
19 - IPythonLineDemo: IPython version of the LineDemo class (the demo is
20 executed a line at a time, but processed via IPython).
21
7
22
8 The file is run in its own empty namespace (though you can pass it a string of
23 The file is run in its own empty namespace (though you can pass it a string of
9 arguments as if in a command line environment, and it will see those as
24 arguments as if in a command line environment, and it will see those as
10 sys.argv). But at each stop, the global IPython namespace is updated with the
25 sys.argv). But at each stop, the global IPython namespace is updated with the
11 current internal demo namespace, so you can work interactively with the data
26 current internal demo namespace, so you can work interactively with the data
12 accumulated so far.
27 accumulated so far.
13
28
14 By default, each block of code is printed (with syntax highlighting) before
29 By default, each block of code is printed (with syntax highlighting) before
15 executing it and you have to confirm execution. This is intended to show the
30 executing it and you have to confirm execution. This is intended to show the
16 code to an audience first so you can discuss it, and only proceed with
31 code to an audience first so you can discuss it, and only proceed with
17 execution once you agree. There are a few tags which allow you to modify this
32 execution once you agree. There are a few tags which allow you to modify this
18 behavior.
33 behavior.
19
34
20 The supported tags are:
35 The supported tags are:
21
36
22 # <demo> --- stop ---
37 # <demo> --- stop ---
23
38
24 Defines block boundaries, the points where IPython stops execution of the
39 Defines block boundaries, the points where IPython stops execution of the
25 file and returns to the interactive prompt.
40 file and returns to the interactive prompt.
26
41
27 # <demo> silent
42 # <demo> silent
28
43
29 Make a block execute silently (and hence automatically). Typically used in
44 Make a block execute silently (and hence automatically). Typically used in
30 cases where you have some boilerplate or initialization code which you need
45 cases where you have some boilerplate or initialization code which you need
31 executed but do not want to be seen in the demo.
46 executed but do not want to be seen in the demo.
32
47
33 # <demo> auto
48 # <demo> auto
34
49
35 Make a block execute automatically, but still being printed. Useful for
50 Make a block execute automatically, but still being printed. Useful for
36 simple code which does not warrant discussion, since it avoids the extra
51 simple code which does not warrant discussion, since it avoids the extra
37 manual confirmation.
52 manual confirmation.
38
53
39 # <demo> auto_all
54 # <demo> auto_all
40
55
41 This tag can _only_ be in the first block, and if given it overrides the
56 This tag can _only_ be in the first block, and if given it overrides the
42 individual auto tags to make the whole demo fully automatic (no block asks
57 individual auto tags to make the whole demo fully automatic (no block asks
43 for confirmation). It can also be given at creation time (or the attribute
58 for confirmation). It can also be given at creation time (or the attribute
44 set later) to override what's in the file.
59 set later) to override what's in the file.
45
60
46 While _any_ python file can be run as a Demo instance, if there are no stop
61 While _any_ python file can be run as a Demo instance, if there are no stop
47 tags the whole file will run in a single block (no different that calling
62 tags the whole file will run in a single block (no different that calling
48 first %pycat and then %run). The minimal markup to make this useful is to
63 first %pycat and then %run). The minimal markup to make this useful is to
49 place a set of stop tags; the other tags are only there to let you fine-tune
64 place a set of stop tags; the other tags are only there to let you fine-tune
50 the execution.
65 the execution.
51
66
52 This is probably best explained with the simple example file below. You can
67 This is probably best explained with the simple example file below. You can
53 copy this into a file named ex_demo.py, and try running it via:
68 copy this into a file named ex_demo.py, and try running it via:
54
69
55 from IPython.demo import Demo
70 from IPython.demo import Demo
56 d = Demo('ex_demo.py')
71 d = Demo('ex_demo.py')
57 d() <--- Call the d object (omit the parens if you have autocall on).
72 d() <--- Call the d object (omit the parens if you have autocall set to 2).
58
73
59 Each time you call the demo object, it runs the next block. The demo object
74 Each time you call the demo object, it runs the next block. The demo object
60 has a few useful methods for navigation, like again(), jump(), seek() and
75 has a few useful methods for navigation, like again(), edit(), jump(), seek()
61 back(). It can be reset for a new run via reset() or reloaded from disk (in
76 and back(). It can be reset for a new run via reset() or reloaded from disk
62 case you've edited the source) via reload(). See their docstrings below.
77 (in case you've edited the source) via reload(). See their docstrings below.
63
78
64 #################### EXAMPLE DEMO <ex_demo.py> ###############################
79 #################### EXAMPLE DEMO <ex_demo.py> ###############################
65 '''A simple interactive demo to illustrate the use of IPython's Demo class.'''
80 '''A simple interactive demo to illustrate the use of IPython's Demo class.'''
66
81
67 print 'Hello, welcome to an interactive IPython demo.'
82 print 'Hello, welcome to an interactive IPython demo.'
68
83
69 # The mark below defines a block boundary, which is a point where IPython will
84 # The mark below defines a block boundary, which is a point where IPython will
70 # stop execution and return to the interactive prompt.
85 # stop execution and return to the interactive prompt.
71 # Note that in actual interactive execution,
86 # Note that in actual interactive execution,
72 # <demo> --- stop ---
87 # <demo> --- stop ---
73
88
74 x = 1
89 x = 1
75 y = 2
90 y = 2
76
91
77 # <demo> --- stop ---
92 # <demo> --- stop ---
78
93
79 # the mark below makes this block as silent
94 # the mark below makes this block as silent
80 # <demo> silent
95 # <demo> silent
81
96
82 print 'This is a silent block, which gets executed but not printed.'
97 print 'This is a silent block, which gets executed but not printed.'
83
98
84 # <demo> --- stop ---
99 # <demo> --- stop ---
85 # <demo> auto
100 # <demo> auto
86 print 'This is an automatic block.'
101 print 'This is an automatic block.'
87 print 'It is executed without asking for confirmation, but printed.'
102 print 'It is executed without asking for confirmation, but printed.'
88 z = x+y
103 z = x+y
89
104
90 print 'z=',x
105 print 'z=',x
91
106
92 # <demo> --- stop ---
107 # <demo> --- stop ---
93 # This is just another normal block.
108 # This is just another normal block.
94 print 'z is now:', z
109 print 'z is now:', z
95
110
96 print 'bye!'
111 print 'bye!'
97 ################### END EXAMPLE DEMO <ex_demo.py> ############################
112 ################### END EXAMPLE DEMO <ex_demo.py> ############################
98
99 WARNING: this module uses Python 2.3 features, so it won't work in 2.2
100 environments.
101 """
113 """
102 #*****************************************************************************
114 #*****************************************************************************
103 # Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>
115 # Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>
104 #
116 #
105 # Distributed under the terms of the BSD License. The full license is in
117 # Distributed under the terms of the BSD License. The full license is in
106 # the file COPYING, distributed as part of this software.
118 # the file COPYING, distributed as part of this software.
107 #
119 #
108 #*****************************************************************************
120 #*****************************************************************************
109
121
110 import exceptions
122 import exceptions
123 import os
111 import re
124 import re
112 import sys
125 import sys
113
126
114 from IPython.PyColorize import Parser
127 from IPython.PyColorize import Parser
115 from IPython.genutils import marquee, shlex_split, file_read
128 from IPython.genutils import marquee, shlex_split, file_read, file_readlines
116
129
117 __all__ = ['Demo','DemoError']
130 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
118
131
119 class DemoError(exceptions.Exception): pass
132 class DemoError(exceptions.Exception): pass
120
133
121 def re_mark(mark):
134 def re_mark(mark):
122 return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
135 return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
123
136
124 class Demo:
137 class Demo:
125
138
126 re_stop = re_mark('---\s?stop\s?---')
139 re_stop = re_mark('---\s?stop\s?---')
127 re_silent = re_mark('silent')
140 re_silent = re_mark('silent')
128 re_auto = re_mark('auto')
141 re_auto = re_mark('auto')
129 re_auto_all = re_mark('auto_all')
142 re_auto_all = re_mark('auto_all')
130
143
131 def __init__(self,fname,arg_str='',auto_all=None):
144 def __init__(self,fname,arg_str='',auto_all=None):
132 """Make a new demo object. To run the demo, simply call the object.
145 """Make a new demo object. To run the demo, simply call the object.
133
146
134 See the module docstring for full details and an example (you can use
147 See the module docstring for full details and an example (you can use
135 IPython.Demo? in IPython to see it).
148 IPython.Demo? in IPython to see it).
136
149
137 Inputs:
150 Inputs:
138
151
139 - fname = filename.
152 - fname = filename.
140
153
141 Optional inputs:
154 Optional inputs:
142
155
143 - arg_str(''): a string of arguments, internally converted to a list
156 - arg_str(''): a string of arguments, internally converted to a list
144 just like sys.argv, so the demo script can see a similar
157 just like sys.argv, so the demo script can see a similar
145 environment.
158 environment.
146
159
147 - auto_all(None): global flag to run all blocks automatically without
160 - auto_all(None): global flag to run all blocks automatically without
148 confirmation. This attribute overrides the block-level tags and
161 confirmation. This attribute overrides the block-level tags and
149 applies to the whole demo. It is an attribute of the object, and
162 applies to the whole demo. It is an attribute of the object, and
150 can be changed at runtime simply by reassigning it to a boolean
163 can be changed at runtime simply by reassigning it to a boolean
151 value.
164 value.
152 """
165 """
153
166
154 self.fname = fname
167 self.fname = fname
155 self.sys_argv = [fname] + shlex_split(arg_str)
168 self.sys_argv = [fname] + shlex_split(arg_str)
156 self.auto_all = auto_all
169 self.auto_all = auto_all
157
170
158 # get a few things from ipython. While it's a bit ugly design-wise,
171 # get a few things from ipython. While it's a bit ugly design-wise,
159 # it ensures that things like color scheme and the like are always in
172 # it ensures that things like color scheme and the like are always in
160 # sync with the ipython mode being used. This class is only meant to
173 # sync with the ipython mode being used. This class is only meant to
161 # be used inside ipython anyways, so it's OK.
174 # be used inside ipython anyways, so it's OK.
162 self.ip_showtb = __IPYTHON__.showtraceback
163 self.ip_ns = __IPYTHON__.user_ns
175 self.ip_ns = __IPYTHON__.user_ns
164 self.ip_colorize = __IPYTHON__.pycolorize
176 self.ip_colorize = __IPYTHON__.pycolorize
177 self.ip_showtb = __IPYTHON__.showtraceback
178 self.ip_runlines = __IPYTHON__.runlines
179 self.shell = __IPYTHON__
165
180
166 # load user data and initialize data structures
181 # load user data and initialize data structures
167 self.reload()
182 self.reload()
168
183
169 def reload(self):
184 def reload(self):
170 """Reload source from disk and initialize state."""
185 """Reload source from disk and initialize state."""
171 # read data and parse into blocks
186 # read data and parse into blocks
172 self.src = file_read(self.fname)
187 self.src = file_read(self.fname)
173 src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
188 src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
174 self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
189 self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
175 self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
190 self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
176
191
177 # if auto_all is not given (def. None), we read it from the file
192 # if auto_all is not given (def. None), we read it from the file
178 if self.auto_all is None:
193 if self.auto_all is None:
179 self.auto_all = bool(self.re_auto_all.findall(src_b[0]))
194 self.auto_all = bool(self.re_auto_all.findall(src_b[0]))
180 else:
195 else:
181 self.auto_all = bool(self.auto_all)
196 self.auto_all = bool(self.auto_all)
182
197
183 # Clean the sources from all markup so it doesn't get displayed when
198 # Clean the sources from all markup so it doesn't get displayed when
184 # running the demo
199 # running the demo
185 src_blocks = []
200 src_blocks = []
186 auto_strip = lambda s: self.re_auto.sub('',s)
201 auto_strip = lambda s: self.re_auto.sub('',s)
187 for i,b in enumerate(src_b):
202 for i,b in enumerate(src_b):
188 if self._auto[i]:
203 if self._auto[i]:
189 src_blocks.append(auto_strip(b))
204 src_blocks.append(auto_strip(b))
190 else:
205 else:
191 src_blocks.append(b)
206 src_blocks.append(b)
192 # remove the auto_all marker
207 # remove the auto_all marker
193 src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
208 src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
194
209
195 self.nblocks = len(src_blocks)
210 self.nblocks = len(src_blocks)
196 self.src_blocks = src_blocks
211 self.src_blocks = src_blocks
197
212
198 # also build syntax-highlighted source
213 # also build syntax-highlighted source
199 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
214 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
200
215
201 # ensure clean namespace and seek offset
216 # ensure clean namespace and seek offset
202 self.reset()
217 self.reset()
203
218
204 def reset(self):
219 def reset(self):
205 """Reset the namespace and seek pointer to restart the demo"""
220 """Reset the namespace and seek pointer to restart the demo"""
206 self.user_ns = {}
221 self.user_ns = {}
207 self.finished = False
222 self.finished = False
208 self.block_index = 0
223 self.block_index = 0
209
224
210 def _validate_index(self,index):
225 def _validate_index(self,index):
211 if index<0 or index>=self.nblocks:
226 if index<0 or index>=self.nblocks:
212 raise ValueError('invalid block index %s' % index)
227 raise ValueError('invalid block index %s' % index)
213
228
229 def _get_index(self,index):
230 """Get the current block index, validating and checking status.
231
232 Returns None if the demo is finished"""
233
234 if index is None:
235 if self.finished:
236 print 'Demo finished. Use reset() if you want to rerun it.'
237 return None
238 index = self.block_index
239 else:
240 self._validate_index(index)
241 return index
242
214 def seek(self,index):
243 def seek(self,index):
215 """Move the current seek pointer to the given block"""
244 """Move the current seek pointer to the given block"""
216 self._validate_index(index)
245 self._validate_index(index)
217 self.block_index = index
246 self.block_index = index
218 self.finished = False
247 self.finished = False
219
248
220 def back(self,num=1):
249 def back(self,num=1):
221 """Move the seek pointer back num blocks (default is 1)."""
250 """Move the seek pointer back num blocks (default is 1)."""
222 self.seek(self.block_index-num)
251 self.seek(self.block_index-num)
223
252
224 def jump(self,num):
253 def jump(self,num):
225 """Jump a given number of blocks relative to the current one."""
254 """Jump a given number of blocks relative to the current one."""
226 self.seek(self.block_index+num)
255 self.seek(self.block_index+num)
227
256
228 def again(self):
257 def again(self):
229 """Move the seek pointer back one block and re-execute."""
258 """Move the seek pointer back one block and re-execute."""
230 self.back(1)
259 self.back(1)
231 self()
260 self()
232
261
262 def edit(self,index=None):
263 """Edit a block.
264
265 If no number is given, use the last block executed.
266
267 This edits the in-memory copy of the demo, it does NOT modify the
268 original source file. If you want to do that, simply open the file in
269 an editor and use reload() when you make changes to the file. This
270 method is meant to let you change a block during a demonstration for
271 explanatory purposes, without damaging your original script."""
272
273 index = self._get_index(index)
274 if index is None:
275 return
276 # decrease the index by one (unless we're at the very beginning), so
277 # that the default demo.edit() call opens up the sblock we've last run
278 if index>0:
279 index -= 1
280
281 filename = self.shell.mktempfile(self.src_blocks[index])
282 self.shell.hooks.editor(filename,1)
283 new_block = file_read(filename)
284 # update the source and colored block
285 self.src_blocks[index] = new_block
286 self.src_blocks_colored[index] = self.ip_colorize(new_block)
287 self.block_index = index
288 # call to run with the newly edited index
289 self()
290
233 def show(self,index=None):
291 def show(self,index=None):
234 """Show a single block on screen"""
292 """Show a single block on screen"""
293
294 index = self._get_index(index)
235 if index is None:
295 if index is None:
236 if self.finished:
296 return
237 print 'Demo finished. Use reset() if you want to rerun it.'
297
238 return
239 index = self.block_index
240 else:
241 self._validate_index(index)
242 print marquee('<%s> block # %s (%s remaining)' %
298 print marquee('<%s> block # %s (%s remaining)' %
243 (self.fname,index,self.nblocks-index-1))
299 (self.fname,index,self.nblocks-index-1))
244 print self.src_blocks_colored[index],
300 print self.src_blocks_colored[index],
245 sys.stdout.flush()
301 sys.stdout.flush()
246
302
247 def show_all(self):
303 def show_all(self):
248 """Show entire demo on screen, block by block"""
304 """Show entire demo on screen, block by block"""
249
305
250 fname = self.fname
306 fname = self.fname
251 nblocks = self.nblocks
307 nblocks = self.nblocks
252 silent = self._silent
308 silent = self._silent
253 for index,block in enumerate(self.src_blocks_colored):
309 for index,block in enumerate(self.src_blocks_colored):
254 if silent[index]:
310 if silent[index]:
255 print marquee('<%s> SILENT block # %s (%s remaining)' %
311 print marquee('<%s> SILENT block # %s (%s remaining)' %
256 (fname,index,nblocks-index-1))
312 (fname,index,nblocks-index-1))
257 else:
313 else:
258 print marquee('<%s> block # %s (%s remaining)' %
314 print marquee('<%s> block # %s (%s remaining)' %
259 (fname,index,nblocks-index-1))
315 (fname,index,nblocks-index-1))
260 print block,
316 print block,
261 sys.stdout.flush()
317 sys.stdout.flush()
262
318
319 def runlines(self,source):
320 """Execute a string with one or more lines of code"""
321
322 exec source in self.user_ns
323
263 def __call__(self,index=None):
324 def __call__(self,index=None):
264 """run a block of the demo.
325 """run a block of the demo.
265
326
266 If index is given, it should be an integer >=1 and <= nblocks. This
327 If index is given, it should be an integer >=1 and <= nblocks. This
267 means that the calling convention is one off from typical Python
328 means that the calling convention is one off from typical Python
268 lists. The reason for the inconsistency is that the demo always
329 lists. The reason for the inconsistency is that the demo always
269 prints 'Block n/N, and N is the total, so it would be very odd to use
330 prints 'Block n/N, and N is the total, so it would be very odd to use
270 zero-indexing here."""
331 zero-indexing here."""
271
332
272 if index is None and self.finished:
333 index = self._get_index(index)
273 print 'Demo finished. Use reset() if you want to rerun it.'
274 return
275 if index is None:
334 if index is None:
276 index = self.block_index
335 return
277 self._validate_index(index)
278 try:
336 try:
279 next_block = self.src_blocks[index]
337 next_block = self.src_blocks[index]
280 self.block_index += 1
338 self.block_index += 1
281 if self._silent[index]:
339 if self._silent[index]:
282 print marquee('Executing silent block # %s (%s remaining)' %
340 print marquee('Executing silent block # %s (%s remaining)' %
283 (index,self.nblocks-index-1))
341 (index,self.nblocks-index-1))
284 else:
342 else:
285 self.show(index)
343 self.show(index)
286 if self.auto_all or self._auto[index]:
344 if self.auto_all or self._auto[index]:
287 print marquee('output')
345 print marquee('output')
288 else:
346 else:
289 print marquee('Press <q> to quit, <Enter> to execute...'),
347 print marquee('Press <q> to quit, <Enter> to execute...'),
290 ans = raw_input().strip()
348 ans = raw_input().strip()
291 if ans:
349 if ans:
292 print marquee('Block NOT executed')
350 print marquee('Block NOT executed')
293 return
351 return
294 try:
352 try:
295 save_argv = sys.argv
353 save_argv = sys.argv
296 sys.argv = self.sys_argv
354 sys.argv = self.sys_argv
297 exec next_block in self.user_ns
355 self.runlines(next_block)
298 finally:
356 finally:
299 sys.argv = save_argv
357 sys.argv = save_argv
300
358
301 except:
359 except:
302 self.ip_showtb(filename=self.fname)
360 self.ip_showtb(filename=self.fname)
303 else:
361 else:
304 self.ip_ns.update(self.user_ns)
362 self.ip_ns.update(self.user_ns)
305
363
306 if self.block_index == self.nblocks:
364 if self.block_index == self.nblocks:
307 print
365 print
308 print marquee(' END OF DEMO ')
366 print marquee(' END OF DEMO ')
309 print marquee('Use reset() if you want to rerun it.')
367 print marquee('Use reset() if you want to rerun it.')
310 self.finished = True
368 self.finished = True
311
369
370 class IPythonDemo(Demo):
371 """Class for interactive demos with IPython's input processing applied.
372
373 This subclasses Demo, but instead of executing each block by the Python
374 interpreter (via exec), it actually calls IPython on it, so that any input
375 filters which may be in place are applied to the input block.
376
377 If you have an interactive environment which exposes special input
378 processing, you can use this class instead to write demo scripts which
379 operate exactly as if you had typed them interactively. The default Demo
380 class requires the input to be valid, pure Python code.
381 """
382
383 def runlines(self,source):
384 """Execute a string with one or more lines of code"""
385
386 self.runlines(source)
387
388 class LineDemo(Demo):
389 """Demo where each line is executed as a separate block.
390
391 The input script should be valid Python code.
392
393 This class doesn't require any markup at all, and it's meant for simple
394 scripts (with no nesting or any kind of indentation) which consist of
395 multiple lines of input to be executed, one at a time, as if they had been
396 typed in the interactive prompt."""
397
398 def reload(self):
399 """Reload source from disk and initialize state."""
400 # read data and parse into blocks
401 src_b = [l for l in file_readlines(self.fname) if l.strip()]
402 nblocks = len(src_b)
403 self.src = os.linesep.join(file_readlines(self.fname))
404 self._silent = [False]*nblocks
405 self._auto = [True]*nblocks
406 self.auto_all = True
407 self.nblocks = nblocks
408 self.src_blocks = src_b
409
410 # also build syntax-highlighted source
411 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
412
413 # ensure clean namespace and seek offset
414 self.reset()
415
416 class IPythonLineDemo(IPythonDemo,LineDemo):
417 """Variant of the LineDemo class whose input is processed by IPython."""
418 pass
@@ -1,1761 +1,1768 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 General purpose utilities.
3 General purpose utilities.
4
4
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 these things are also convenient when working at the command line.
6 these things are also convenient when working at the command line.
7
7
8 $Id: genutils.py 1110 2006-01-30 20:43:30Z vivainio $"""
8 $Id: genutils.py 1126 2006-02-06 02:31:40Z fperez $"""
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 from __future__ import generators # 2.2 compatibility
17 from __future__ import generators # 2.2 compatibility
18
18
19 from IPython import Release
19 from IPython import Release
20 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 __license__ = Release.license
21 __license__ = Release.license
22
22
23 #****************************************************************************
23 #****************************************************************************
24 # required modules from the Python standard library
24 # required modules from the Python standard library
25 import __main__
25 import __main__
26 import commands
26 import commands
27 import os
27 import os
28 import re
28 import re
29 import shlex
29 import shlex
30 import shutil
30 import shutil
31 import sys
31 import sys
32 import tempfile
32 import tempfile
33 import time
33 import time
34 import types
34 import types
35
35
36 # Other IPython utilities
36 # Other IPython utilities
37 from IPython.Itpl import Itpl,itpl,printpl
37 from IPython.Itpl import Itpl,itpl,printpl
38 from IPython import DPyGetOpt
38 from IPython import DPyGetOpt
39 from path import path
39 from path import path
40 if os.name == "nt":
40 if os.name == "nt":
41 from IPython.winconsole import get_console_size
41 from IPython.winconsole import get_console_size
42
42
43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
44 # 2.2-friendly
44 # 2.2-friendly
45 try:
45 try:
46 basestring
46 basestring
47 except NameError:
47 except NameError:
48 import types
48 import types
49 basestring = (types.StringType, types.UnicodeType)
49 basestring = (types.StringType, types.UnicodeType)
50 True = 1==1
50 True = 1==1
51 False = 1==0
51 False = 1==0
52
52
53 def enumerate(obj):
53 def enumerate(obj):
54 i = -1
54 i = -1
55 for item in obj:
55 for item in obj:
56 i += 1
56 i += 1
57 yield i, item
57 yield i, item
58
58
59 # add these to the builtin namespace, so that all modules find them
59 # add these to the builtin namespace, so that all modules find them
60 import __builtin__
60 import __builtin__
61 __builtin__.basestring = basestring
61 __builtin__.basestring = basestring
62 __builtin__.True = True
62 __builtin__.True = True
63 __builtin__.False = False
63 __builtin__.False = False
64 __builtin__.enumerate = enumerate
64 __builtin__.enumerate = enumerate
65
65
66 # Try to use shlex.split for converting an input string into a sys.argv-type
66 # Try to use shlex.split for converting an input string into a sys.argv-type
67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
68 try:
68 try:
69 shlex_split = shlex.split
69 shlex_split = shlex.split
70 except AttributeError:
70 except AttributeError:
71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
75 'À�ÂÃÄÅÆÇÈÉÊËÌ�Î��ÑÒÓÔÕÖØÙÚÛÜ�Þ%s'
75 'À�ÂÃÄÅÆÇÈÉÊËÌ�Î��ÑÒÓÔÕÖØÙÚÛÜ�Þ%s'
76 % os.sep)
76 % os.sep)
77
77
78 def shlex_split(s):
78 def shlex_split(s):
79 """Simplified backport to Python 2.2 of shlex.split().
79 """Simplified backport to Python 2.2 of shlex.split().
80
80
81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
82 several of the features needed to really match the functionality of
82 several of the features needed to really match the functionality of
83 shlex.split() in 2.3."""
83 shlex.split() in 2.3."""
84
84
85 lex = shlex.shlex(StringIO(s))
85 lex = shlex.shlex(StringIO(s))
86 # Try to get options, extensions and path separators as characters
86 # Try to get options, extensions and path separators as characters
87 lex.wordchars = _wordchars
87 lex.wordchars = _wordchars
88 lex.commenters = ''
88 lex.commenters = ''
89 # Make a list out of the lexer by hand, since in 2.2 it's not an
89 # Make a list out of the lexer by hand, since in 2.2 it's not an
90 # iterator.
90 # iterator.
91 lout = []
91 lout = []
92 while 1:
92 while 1:
93 token = lex.get_token()
93 token = lex.get_token()
94 if token == '':
94 if token == '':
95 break
95 break
96 # Try to handle quoted tokens correctly
96 # Try to handle quoted tokens correctly
97 quotes = _quotesre.match(token)
97 quotes = _quotesre.match(token)
98 if quotes:
98 if quotes:
99 token = quotes.group(1)
99 token = quotes.group(1)
100 lout.append(token)
100 lout.append(token)
101 return lout
101 return lout
102
102
103 #****************************************************************************
103 #****************************************************************************
104 # Exceptions
104 # Exceptions
105 class Error(Exception):
105 class Error(Exception):
106 """Base class for exceptions in this module."""
106 """Base class for exceptions in this module."""
107 pass
107 pass
108
108
109 #----------------------------------------------------------------------------
109 #----------------------------------------------------------------------------
110 class IOStream:
110 class IOStream:
111 def __init__(self,stream,fallback):
111 def __init__(self,stream,fallback):
112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
113 stream = fallback
113 stream = fallback
114 self.stream = stream
114 self.stream = stream
115 self._swrite = stream.write
115 self._swrite = stream.write
116 self.flush = stream.flush
116 self.flush = stream.flush
117
117
118 def write(self,data):
118 def write(self,data):
119 try:
119 try:
120 self._swrite(data)
120 self._swrite(data)
121 except:
121 except:
122 try:
122 try:
123 # print handles some unicode issues which may trip a plain
123 # print handles some unicode issues which may trip a plain
124 # write() call. Attempt to emulate write() by using a
124 # write() call. Attempt to emulate write() by using a
125 # trailing comma
125 # trailing comma
126 print >> self.stream, data,
126 print >> self.stream, data,
127 except:
127 except:
128 # if we get here, something is seriously broken.
128 # if we get here, something is seriously broken.
129 print >> sys.stderr, \
129 print >> sys.stderr, \
130 'ERROR - failed to write data to stream:', stream
130 'ERROR - failed to write data to stream:', stream
131
131
132 class IOTerm:
132 class IOTerm:
133 """ Term holds the file or file-like objects for handling I/O operations.
133 """ Term holds the file or file-like objects for handling I/O operations.
134
134
135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
136 Windows they can can replaced to allow editing the strings before they are
136 Windows they can can replaced to allow editing the strings before they are
137 displayed."""
137 displayed."""
138
138
139 # In the future, having IPython channel all its I/O operations through
139 # In the future, having IPython channel all its I/O operations through
140 # this class will make it easier to embed it into other environments which
140 # this class will make it easier to embed it into other environments which
141 # are not a normal terminal (such as a GUI-based shell)
141 # are not a normal terminal (such as a GUI-based shell)
142 def __init__(self,cin=None,cout=None,cerr=None):
142 def __init__(self,cin=None,cout=None,cerr=None):
143 self.cin = IOStream(cin,sys.stdin)
143 self.cin = IOStream(cin,sys.stdin)
144 self.cout = IOStream(cout,sys.stdout)
144 self.cout = IOStream(cout,sys.stdout)
145 self.cerr = IOStream(cerr,sys.stderr)
145 self.cerr = IOStream(cerr,sys.stderr)
146
146
147 # Global variable to be used for all I/O
147 # Global variable to be used for all I/O
148 Term = IOTerm()
148 Term = IOTerm()
149
149
150 import IPython.rlineimpl as readline
150 import IPython.rlineimpl as readline
151 # Remake Term to use the readline i/o facilities
151 # Remake Term to use the readline i/o facilities
152 if sys.platform == 'win32' and readline.have_readline:
152 if sys.platform == 'win32' and readline.have_readline:
153
153
154 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
154 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
155
155
156
156
157 #****************************************************************************
157 #****************************************************************************
158 # Generic warning/error printer, used by everything else
158 # Generic warning/error printer, used by everything else
159 def warn(msg,level=2,exit_val=1):
159 def warn(msg,level=2,exit_val=1):
160 """Standard warning printer. Gives formatting consistency.
160 """Standard warning printer. Gives formatting consistency.
161
161
162 Output is sent to Term.cerr (sys.stderr by default).
162 Output is sent to Term.cerr (sys.stderr by default).
163
163
164 Options:
164 Options:
165
165
166 -level(2): allows finer control:
166 -level(2): allows finer control:
167 0 -> Do nothing, dummy function.
167 0 -> Do nothing, dummy function.
168 1 -> Print message.
168 1 -> Print message.
169 2 -> Print 'WARNING:' + message. (Default level).
169 2 -> Print 'WARNING:' + message. (Default level).
170 3 -> Print 'ERROR:' + message.
170 3 -> Print 'ERROR:' + message.
171 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
171 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
172
172
173 -exit_val (1): exit value returned by sys.exit() for a level 4
173 -exit_val (1): exit value returned by sys.exit() for a level 4
174 warning. Ignored for all other levels."""
174 warning. Ignored for all other levels."""
175
175
176 if level>0:
176 if level>0:
177 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
177 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
178 print >> Term.cerr, '%s%s' % (header[level],msg)
178 print >> Term.cerr, '%s%s' % (header[level],msg)
179 if level == 4:
179 if level == 4:
180 print >> Term.cerr,'Exiting.\n'
180 print >> Term.cerr,'Exiting.\n'
181 sys.exit(exit_val)
181 sys.exit(exit_val)
182
182
183 def info(msg):
183 def info(msg):
184 """Equivalent to warn(msg,level=1)."""
184 """Equivalent to warn(msg,level=1)."""
185
185
186 warn(msg,level=1)
186 warn(msg,level=1)
187
187
188 def error(msg):
188 def error(msg):
189 """Equivalent to warn(msg,level=3)."""
189 """Equivalent to warn(msg,level=3)."""
190
190
191 warn(msg,level=3)
191 warn(msg,level=3)
192
192
193 def fatal(msg,exit_val=1):
193 def fatal(msg,exit_val=1):
194 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
194 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
195
195
196 warn(msg,exit_val=exit_val,level=4)
196 warn(msg,exit_val=exit_val,level=4)
197
197
198 #---------------------------------------------------------------------------
198 #---------------------------------------------------------------------------
199 # Debugging routines
199 # Debugging routines
200 #
200 #
201 def debugx(expr,pre_msg=''):
201 def debugx(expr,pre_msg=''):
202 """Print the value of an expression from the caller's frame.
202 """Print the value of an expression from the caller's frame.
203
203
204 Takes an expression, evaluates it in the caller's frame and prints both
204 Takes an expression, evaluates it in the caller's frame and prints both
205 the given expression and the resulting value (as well as a debug mark
205 the given expression and the resulting value (as well as a debug mark
206 indicating the name of the calling function. The input must be of a form
206 indicating the name of the calling function. The input must be of a form
207 suitable for eval().
207 suitable for eval().
208
208
209 An optional message can be passed, which will be prepended to the printed
209 An optional message can be passed, which will be prepended to the printed
210 expr->value pair."""
210 expr->value pair."""
211
211
212 cf = sys._getframe(1)
212 cf = sys._getframe(1)
213 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
213 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
214 eval(expr,cf.f_globals,cf.f_locals))
214 eval(expr,cf.f_globals,cf.f_locals))
215
215
216 # deactivate it by uncommenting the following line, which makes it a no-op
216 # deactivate it by uncommenting the following line, which makes it a no-op
217 #def debugx(expr,pre_msg=''): pass
217 #def debugx(expr,pre_msg=''): pass
218
218
219 #----------------------------------------------------------------------------
219 #----------------------------------------------------------------------------
220 StringTypes = types.StringTypes
220 StringTypes = types.StringTypes
221
221
222 # Basic timing functionality
222 # Basic timing functionality
223
223
224 # If possible (Unix), use the resource module instead of time.clock()
224 # If possible (Unix), use the resource module instead of time.clock()
225 try:
225 try:
226 import resource
226 import resource
227 def clock():
227 def clock():
228 """clock() -> floating point number
228 """clock() -> floating point number
229
229
230 Return the CPU time in seconds (user time only, system time is
230 Return the CPU time in seconds (user time only, system time is
231 ignored) since the start of the process. This is done via a call to
231 ignored) since the start of the process. This is done via a call to
232 resource.getrusage, so it avoids the wraparound problems in
232 resource.getrusage, so it avoids the wraparound problems in
233 time.clock()."""
233 time.clock()."""
234
234
235 return resource.getrusage(resource.RUSAGE_SELF)[0]
235 return resource.getrusage(resource.RUSAGE_SELF)[0]
236
236
237 def clock2():
237 def clock2():
238 """clock2() -> (t_user,t_system)
238 """clock2() -> (t_user,t_system)
239
239
240 Similar to clock(), but return a tuple of user/system times."""
240 Similar to clock(), but return a tuple of user/system times."""
241 return resource.getrusage(resource.RUSAGE_SELF)[:2]
241 return resource.getrusage(resource.RUSAGE_SELF)[:2]
242
242
243 except ImportError:
243 except ImportError:
244 clock = time.clock
244 clock = time.clock
245 def clock2():
245 def clock2():
246 """Under windows, system CPU time can't be measured.
246 """Under windows, system CPU time can't be measured.
247
247
248 This just returns clock() and zero."""
248 This just returns clock() and zero."""
249 return time.clock(),0.0
249 return time.clock(),0.0
250
250
251 def timings_out(reps,func,*args,**kw):
251 def timings_out(reps,func,*args,**kw):
252 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
252 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
253
253
254 Execute a function reps times, return a tuple with the elapsed total
254 Execute a function reps times, return a tuple with the elapsed total
255 CPU time in seconds, the time per call and the function's output.
255 CPU time in seconds, the time per call and the function's output.
256
256
257 Under Unix, the return value is the sum of user+system time consumed by
257 Under Unix, the return value is the sum of user+system time consumed by
258 the process, computed via the resource module. This prevents problems
258 the process, computed via the resource module. This prevents problems
259 related to the wraparound effect which the time.clock() function has.
259 related to the wraparound effect which the time.clock() function has.
260
260
261 Under Windows the return value is in wall clock seconds. See the
261 Under Windows the return value is in wall clock seconds. See the
262 documentation for the time module for more details."""
262 documentation for the time module for more details."""
263
263
264 reps = int(reps)
264 reps = int(reps)
265 assert reps >=1, 'reps must be >= 1'
265 assert reps >=1, 'reps must be >= 1'
266 if reps==1:
266 if reps==1:
267 start = clock()
267 start = clock()
268 out = func(*args,**kw)
268 out = func(*args,**kw)
269 tot_time = clock()-start
269 tot_time = clock()-start
270 else:
270 else:
271 rng = xrange(reps-1) # the last time is executed separately to store output
271 rng = xrange(reps-1) # the last time is executed separately to store output
272 start = clock()
272 start = clock()
273 for dummy in rng: func(*args,**kw)
273 for dummy in rng: func(*args,**kw)
274 out = func(*args,**kw) # one last time
274 out = func(*args,**kw) # one last time
275 tot_time = clock()-start
275 tot_time = clock()-start
276 av_time = tot_time / reps
276 av_time = tot_time / reps
277 return tot_time,av_time,out
277 return tot_time,av_time,out
278
278
279 def timings(reps,func,*args,**kw):
279 def timings(reps,func,*args,**kw):
280 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
280 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
281
281
282 Execute a function reps times, return a tuple with the elapsed total CPU
282 Execute a function reps times, return a tuple with the elapsed total CPU
283 time in seconds and the time per call. These are just the first two values
283 time in seconds and the time per call. These are just the first two values
284 in timings_out()."""
284 in timings_out()."""
285
285
286 return timings_out(reps,func,*args,**kw)[0:2]
286 return timings_out(reps,func,*args,**kw)[0:2]
287
287
288 def timing(func,*args,**kw):
288 def timing(func,*args,**kw):
289 """timing(func,*args,**kw) -> t_total
289 """timing(func,*args,**kw) -> t_total
290
290
291 Execute a function once, return the elapsed total CPU time in
291 Execute a function once, return the elapsed total CPU time in
292 seconds. This is just the first value in timings_out()."""
292 seconds. This is just the first value in timings_out()."""
293
293
294 return timings_out(1,func,*args,**kw)[0]
294 return timings_out(1,func,*args,**kw)[0]
295
295
296 #****************************************************************************
296 #****************************************************************************
297 # file and system
297 # file and system
298
298
299 def system(cmd,verbose=0,debug=0,header=''):
299 def system(cmd,verbose=0,debug=0,header=''):
300 """Execute a system command, return its exit status.
300 """Execute a system command, return its exit status.
301
301
302 Options:
302 Options:
303
303
304 - verbose (0): print the command to be executed.
304 - verbose (0): print the command to be executed.
305
305
306 - debug (0): only print, do not actually execute.
306 - debug (0): only print, do not actually execute.
307
307
308 - header (''): Header to print on screen prior to the executed command (it
308 - header (''): Header to print on screen prior to the executed command (it
309 is only prepended to the command, no newlines are added).
309 is only prepended to the command, no newlines are added).
310
310
311 Note: a stateful version of this function is available through the
311 Note: a stateful version of this function is available through the
312 SystemExec class."""
312 SystemExec class."""
313
313
314 stat = 0
314 stat = 0
315 if verbose or debug: print header+cmd
315 if verbose or debug: print header+cmd
316 sys.stdout.flush()
316 sys.stdout.flush()
317 if not debug: stat = os.system(cmd)
317 if not debug: stat = os.system(cmd)
318 return stat
318 return stat
319
319
320 # This function is used by ipython in a lot of places to make system calls.
320 # This function is used by ipython in a lot of places to make system calls.
321 # We need it to be slightly different under win32, due to the vagaries of
321 # We need it to be slightly different under win32, due to the vagaries of
322 # 'network shares'. A win32 override is below.
322 # 'network shares'. A win32 override is below.
323
323
324 def shell(cmd,verbose=0,debug=0,header=''):
324 def shell(cmd,verbose=0,debug=0,header=''):
325 """Execute a command in the system shell, always return None.
325 """Execute a command in the system shell, always return None.
326
326
327 Options:
327 Options:
328
328
329 - verbose (0): print the command to be executed.
329 - verbose (0): print the command to be executed.
330
330
331 - debug (0): only print, do not actually execute.
331 - debug (0): only print, do not actually execute.
332
332
333 - header (''): Header to print on screen prior to the executed command (it
333 - header (''): Header to print on screen prior to the executed command (it
334 is only prepended to the command, no newlines are added).
334 is only prepended to the command, no newlines are added).
335
335
336 Note: this is similar to genutils.system(), but it returns None so it can
336 Note: this is similar to genutils.system(), but it returns None so it can
337 be conveniently used in interactive loops without getting the return value
337 be conveniently used in interactive loops without getting the return value
338 (typically 0) printed many times."""
338 (typically 0) printed many times."""
339
339
340 stat = 0
340 stat = 0
341 if verbose or debug: print header+cmd
341 if verbose or debug: print header+cmd
342 # flush stdout so we don't mangle python's buffering
342 # flush stdout so we don't mangle python's buffering
343 sys.stdout.flush()
343 sys.stdout.flush()
344 if not debug:
344 if not debug:
345 os.system(cmd)
345 os.system(cmd)
346
346
347 # override shell() for win32 to deal with network shares
347 # override shell() for win32 to deal with network shares
348 if os.name in ('nt','dos'):
348 if os.name in ('nt','dos'):
349
349
350 shell_ori = shell
350 shell_ori = shell
351
351
352 def shell(cmd,verbose=0,debug=0,header=''):
352 def shell(cmd,verbose=0,debug=0,header=''):
353 if os.getcwd().startswith(r"\\"):
353 if os.getcwd().startswith(r"\\"):
354 path = os.getcwd()
354 path = os.getcwd()
355 # change to c drive (cannot be on UNC-share when issuing os.system,
355 # change to c drive (cannot be on UNC-share when issuing os.system,
356 # as cmd.exe cannot handle UNC addresses)
356 # as cmd.exe cannot handle UNC addresses)
357 os.chdir("c:")
357 os.chdir("c:")
358 # issue pushd to the UNC-share and then run the command
358 # issue pushd to the UNC-share and then run the command
359 try:
359 try:
360 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
360 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
361 finally:
361 finally:
362 os.chdir(path)
362 os.chdir(path)
363 else:
363 else:
364 shell_ori(cmd,verbose,debug,header)
364 shell_ori(cmd,verbose,debug,header)
365
365
366 shell.__doc__ = shell_ori.__doc__
366 shell.__doc__ = shell_ori.__doc__
367
367
368 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
368 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
369 """Dummy substitute for perl's backquotes.
369 """Dummy substitute for perl's backquotes.
370
370
371 Executes a command and returns the output.
371 Executes a command and returns the output.
372
372
373 Accepts the same arguments as system(), plus:
373 Accepts the same arguments as system(), plus:
374
374
375 - split(0): if true, the output is returned as a list split on newlines.
375 - split(0): if true, the output is returned as a list split on newlines.
376
376
377 Note: a stateful version of this function is available through the
377 Note: a stateful version of this function is available through the
378 SystemExec class."""
378 SystemExec class."""
379
379
380 if verbose or debug: print header+cmd
380 if verbose or debug: print header+cmd
381 if not debug:
381 if not debug:
382 output = commands.getoutput(cmd)
382 output = commands.getoutput(cmd)
383 if split:
383 if split:
384 return output.split('\n')
384 return output.split('\n')
385 else:
385 else:
386 return output
386 return output
387
387
388 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
388 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
389 """Return (standard output,standard error) of executing cmd in a shell.
389 """Return (standard output,standard error) of executing cmd in a shell.
390
390
391 Accepts the same arguments as system(), plus:
391 Accepts the same arguments as system(), plus:
392
392
393 - split(0): if true, each of stdout/err is returned as a list split on
393 - split(0): if true, each of stdout/err is returned as a list split on
394 newlines.
394 newlines.
395
395
396 Note: a stateful version of this function is available through the
396 Note: a stateful version of this function is available through the
397 SystemExec class."""
397 SystemExec class."""
398
398
399 if verbose or debug: print header+cmd
399 if verbose or debug: print header+cmd
400 if not cmd:
400 if not cmd:
401 if split:
401 if split:
402 return [],[]
402 return [],[]
403 else:
403 else:
404 return '',''
404 return '',''
405 if not debug:
405 if not debug:
406 pin,pout,perr = os.popen3(cmd)
406 pin,pout,perr = os.popen3(cmd)
407 tout = pout.read().rstrip()
407 tout = pout.read().rstrip()
408 terr = perr.read().rstrip()
408 terr = perr.read().rstrip()
409 pin.close()
409 pin.close()
410 pout.close()
410 pout.close()
411 perr.close()
411 perr.close()
412 if split:
412 if split:
413 return tout.split('\n'),terr.split('\n')
413 return tout.split('\n'),terr.split('\n')
414 else:
414 else:
415 return tout,terr
415 return tout,terr
416
416
417 # for compatibility with older naming conventions
417 # for compatibility with older naming conventions
418 xsys = system
418 xsys = system
419 bq = getoutput
419 bq = getoutput
420
420
421 class SystemExec:
421 class SystemExec:
422 """Access the system and getoutput functions through a stateful interface.
422 """Access the system and getoutput functions through a stateful interface.
423
423
424 Note: here we refer to the system and getoutput functions from this
424 Note: here we refer to the system and getoutput functions from this
425 library, not the ones from the standard python library.
425 library, not the ones from the standard python library.
426
426
427 This class offers the system and getoutput functions as methods, but the
427 This class offers the system and getoutput functions as methods, but the
428 verbose, debug and header parameters can be set for the instance (at
428 verbose, debug and header parameters can be set for the instance (at
429 creation time or later) so that they don't need to be specified on each
429 creation time or later) so that they don't need to be specified on each
430 call.
430 call.
431
431
432 For efficiency reasons, there's no way to override the parameters on a
432 For efficiency reasons, there's no way to override the parameters on a
433 per-call basis other than by setting instance attributes. If you need
433 per-call basis other than by setting instance attributes. If you need
434 local overrides, it's best to directly call system() or getoutput().
434 local overrides, it's best to directly call system() or getoutput().
435
435
436 The following names are provided as alternate options:
436 The following names are provided as alternate options:
437 - xsys: alias to system
437 - xsys: alias to system
438 - bq: alias to getoutput
438 - bq: alias to getoutput
439
439
440 An instance can then be created as:
440 An instance can then be created as:
441 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
441 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
442
442
443 And used as:
443 And used as:
444 >>> sysexec.xsys('pwd')
444 >>> sysexec.xsys('pwd')
445 >>> dirlist = sysexec.bq('ls -l')
445 >>> dirlist = sysexec.bq('ls -l')
446 """
446 """
447
447
448 def __init__(self,verbose=0,debug=0,header='',split=0):
448 def __init__(self,verbose=0,debug=0,header='',split=0):
449 """Specify the instance's values for verbose, debug and header."""
449 """Specify the instance's values for verbose, debug and header."""
450 setattr_list(self,'verbose debug header split')
450 setattr_list(self,'verbose debug header split')
451
451
452 def system(self,cmd):
452 def system(self,cmd):
453 """Stateful interface to system(), with the same keyword parameters."""
453 """Stateful interface to system(), with the same keyword parameters."""
454
454
455 system(cmd,self.verbose,self.debug,self.header)
455 system(cmd,self.verbose,self.debug,self.header)
456
456
457 def shell(self,cmd):
457 def shell(self,cmd):
458 """Stateful interface to shell(), with the same keyword parameters."""
458 """Stateful interface to shell(), with the same keyword parameters."""
459
459
460 shell(cmd,self.verbose,self.debug,self.header)
460 shell(cmd,self.verbose,self.debug,self.header)
461
461
462 xsys = system # alias
462 xsys = system # alias
463
463
464 def getoutput(self,cmd):
464 def getoutput(self,cmd):
465 """Stateful interface to getoutput()."""
465 """Stateful interface to getoutput()."""
466
466
467 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
467 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
468
468
469 def getoutputerror(self,cmd):
469 def getoutputerror(self,cmd):
470 """Stateful interface to getoutputerror()."""
470 """Stateful interface to getoutputerror()."""
471
471
472 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
472 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
473
473
474 bq = getoutput # alias
474 bq = getoutput # alias
475
475
476 #-----------------------------------------------------------------------------
476 #-----------------------------------------------------------------------------
477 def mutex_opts(dict,ex_op):
477 def mutex_opts(dict,ex_op):
478 """Check for presence of mutually exclusive keys in a dict.
478 """Check for presence of mutually exclusive keys in a dict.
479
479
480 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
480 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
481 for op1,op2 in ex_op:
481 for op1,op2 in ex_op:
482 if op1 in dict and op2 in dict:
482 if op1 in dict and op2 in dict:
483 raise ValueError,'\n*** ERROR in Arguments *** '\
483 raise ValueError,'\n*** ERROR in Arguments *** '\
484 'Options '+op1+' and '+op2+' are mutually exclusive.'
484 'Options '+op1+' and '+op2+' are mutually exclusive.'
485
485
486 #-----------------------------------------------------------------------------
486 #-----------------------------------------------------------------------------
487 def get_py_filename(name):
487 def get_py_filename(name):
488 """Return a valid python filename in the current directory.
488 """Return a valid python filename in the current directory.
489
489
490 If the given name is not a file, it adds '.py' and searches again.
490 If the given name is not a file, it adds '.py' and searches again.
491 Raises IOError with an informative message if the file isn't found."""
491 Raises IOError with an informative message if the file isn't found."""
492
492
493 name = os.path.expanduser(name)
493 name = os.path.expanduser(name)
494 if not os.path.isfile(name) and not name.endswith('.py'):
494 if not os.path.isfile(name) and not name.endswith('.py'):
495 name += '.py'
495 name += '.py'
496 if os.path.isfile(name):
496 if os.path.isfile(name):
497 return name
497 return name
498 else:
498 else:
499 raise IOError,'File `%s` not found.' % name
499 raise IOError,'File `%s` not found.' % name
500
500
501 #-----------------------------------------------------------------------------
501 #-----------------------------------------------------------------------------
502 def filefind(fname,alt_dirs = None):
502 def filefind(fname,alt_dirs = None):
503 """Return the given filename either in the current directory, if it
503 """Return the given filename either in the current directory, if it
504 exists, or in a specified list of directories.
504 exists, or in a specified list of directories.
505
505
506 ~ expansion is done on all file and directory names.
506 ~ expansion is done on all file and directory names.
507
507
508 Upon an unsuccessful search, raise an IOError exception."""
508 Upon an unsuccessful search, raise an IOError exception."""
509
509
510 if alt_dirs is None:
510 if alt_dirs is None:
511 try:
511 try:
512 alt_dirs = get_home_dir()
512 alt_dirs = get_home_dir()
513 except HomeDirError:
513 except HomeDirError:
514 alt_dirs = os.getcwd()
514 alt_dirs = os.getcwd()
515 search = [fname] + list_strings(alt_dirs)
515 search = [fname] + list_strings(alt_dirs)
516 search = map(os.path.expanduser,search)
516 search = map(os.path.expanduser,search)
517 #print 'search list for',fname,'list:',search # dbg
517 #print 'search list for',fname,'list:',search # dbg
518 fname = search[0]
518 fname = search[0]
519 if os.path.isfile(fname):
519 if os.path.isfile(fname):
520 return fname
520 return fname
521 for direc in search[1:]:
521 for direc in search[1:]:
522 testname = os.path.join(direc,fname)
522 testname = os.path.join(direc,fname)
523 #print 'testname',testname # dbg
523 #print 'testname',testname # dbg
524 if os.path.isfile(testname):
524 if os.path.isfile(testname):
525 return testname
525 return testname
526 raise IOError,'File' + `fname` + \
526 raise IOError,'File' + `fname` + \
527 ' not found in current or supplied directories:' + `alt_dirs`
527 ' not found in current or supplied directories:' + `alt_dirs`
528
528
529 #----------------------------------------------------------------------------
529 #----------------------------------------------------------------------------
530 def file_read(filename):
530 def file_read(filename):
531 """Read a file and close it. Returns the file source."""
531 """Read a file and close it. Returns the file source."""
532 fobj=open(filename,'r');
532 fobj = open(filename,'r');
533 source = fobj.read();
533 source = fobj.read();
534 fobj.close()
534 fobj.close()
535 return source
535 return source
536
536
537 def file_readlines(filename):
538 """Read a file and close it. Returns the file source using readlines()."""
539 fobj = open(filename,'r');
540 lines = fobj.readlines();
541 fobj.close()
542 return lines
543
537 #----------------------------------------------------------------------------
544 #----------------------------------------------------------------------------
538 def target_outdated(target,deps):
545 def target_outdated(target,deps):
539 """Determine whether a target is out of date.
546 """Determine whether a target is out of date.
540
547
541 target_outdated(target,deps) -> 1/0
548 target_outdated(target,deps) -> 1/0
542
549
543 deps: list of filenames which MUST exist.
550 deps: list of filenames which MUST exist.
544 target: single filename which may or may not exist.
551 target: single filename which may or may not exist.
545
552
546 If target doesn't exist or is older than any file listed in deps, return
553 If target doesn't exist or is older than any file listed in deps, return
547 true, otherwise return false.
554 true, otherwise return false.
548 """
555 """
549 try:
556 try:
550 target_time = os.path.getmtime(target)
557 target_time = os.path.getmtime(target)
551 except os.error:
558 except os.error:
552 return 1
559 return 1
553 for dep in deps:
560 for dep in deps:
554 dep_time = os.path.getmtime(dep)
561 dep_time = os.path.getmtime(dep)
555 if dep_time > target_time:
562 if dep_time > target_time:
556 #print "For target",target,"Dep failed:",dep # dbg
563 #print "For target",target,"Dep failed:",dep # dbg
557 #print "times (dep,tar):",dep_time,target_time # dbg
564 #print "times (dep,tar):",dep_time,target_time # dbg
558 return 1
565 return 1
559 return 0
566 return 0
560
567
561 #-----------------------------------------------------------------------------
568 #-----------------------------------------------------------------------------
562 def target_update(target,deps,cmd):
569 def target_update(target,deps,cmd):
563 """Update a target with a given command given a list of dependencies.
570 """Update a target with a given command given a list of dependencies.
564
571
565 target_update(target,deps,cmd) -> runs cmd if target is outdated.
572 target_update(target,deps,cmd) -> runs cmd if target is outdated.
566
573
567 This is just a wrapper around target_outdated() which calls the given
574 This is just a wrapper around target_outdated() which calls the given
568 command if target is outdated."""
575 command if target is outdated."""
569
576
570 if target_outdated(target,deps):
577 if target_outdated(target,deps):
571 xsys(cmd)
578 xsys(cmd)
572
579
573 #----------------------------------------------------------------------------
580 #----------------------------------------------------------------------------
574 def unquote_ends(istr):
581 def unquote_ends(istr):
575 """Remove a single pair of quotes from the endpoints of a string."""
582 """Remove a single pair of quotes from the endpoints of a string."""
576
583
577 if not istr:
584 if not istr:
578 return istr
585 return istr
579 if (istr[0]=="'" and istr[-1]=="'") or \
586 if (istr[0]=="'" and istr[-1]=="'") or \
580 (istr[0]=='"' and istr[-1]=='"'):
587 (istr[0]=='"' and istr[-1]=='"'):
581 return istr[1:-1]
588 return istr[1:-1]
582 else:
589 else:
583 return istr
590 return istr
584
591
585 #----------------------------------------------------------------------------
592 #----------------------------------------------------------------------------
586 def process_cmdline(argv,names=[],defaults={},usage=''):
593 def process_cmdline(argv,names=[],defaults={},usage=''):
587 """ Process command-line options and arguments.
594 """ Process command-line options and arguments.
588
595
589 Arguments:
596 Arguments:
590
597
591 - argv: list of arguments, typically sys.argv.
598 - argv: list of arguments, typically sys.argv.
592
599
593 - names: list of option names. See DPyGetOpt docs for details on options
600 - names: list of option names. See DPyGetOpt docs for details on options
594 syntax.
601 syntax.
595
602
596 - defaults: dict of default values.
603 - defaults: dict of default values.
597
604
598 - usage: optional usage notice to print if a wrong argument is passed.
605 - usage: optional usage notice to print if a wrong argument is passed.
599
606
600 Return a dict of options and a list of free arguments."""
607 Return a dict of options and a list of free arguments."""
601
608
602 getopt = DPyGetOpt.DPyGetOpt()
609 getopt = DPyGetOpt.DPyGetOpt()
603 getopt.setIgnoreCase(0)
610 getopt.setIgnoreCase(0)
604 getopt.parseConfiguration(names)
611 getopt.parseConfiguration(names)
605
612
606 try:
613 try:
607 getopt.processArguments(argv)
614 getopt.processArguments(argv)
608 except:
615 except:
609 print usage
616 print usage
610 warn(`sys.exc_value`,level=4)
617 warn(`sys.exc_value`,level=4)
611
618
612 defaults.update(getopt.optionValues)
619 defaults.update(getopt.optionValues)
613 args = getopt.freeValues
620 args = getopt.freeValues
614
621
615 return defaults,args
622 return defaults,args
616
623
617 #----------------------------------------------------------------------------
624 #----------------------------------------------------------------------------
618 def optstr2types(ostr):
625 def optstr2types(ostr):
619 """Convert a string of option names to a dict of type mappings.
626 """Convert a string of option names to a dict of type mappings.
620
627
621 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
628 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
622
629
623 This is used to get the types of all the options in a string formatted
630 This is used to get the types of all the options in a string formatted
624 with the conventions of DPyGetOpt. The 'type' None is used for options
631 with the conventions of DPyGetOpt. The 'type' None is used for options
625 which are strings (they need no further conversion). This function's main
632 which are strings (they need no further conversion). This function's main
626 use is to get a typemap for use with read_dict().
633 use is to get a typemap for use with read_dict().
627 """
634 """
628
635
629 typeconv = {None:'',int:'',float:''}
636 typeconv = {None:'',int:'',float:''}
630 typemap = {'s':None,'i':int,'f':float}
637 typemap = {'s':None,'i':int,'f':float}
631 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
638 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
632
639
633 for w in ostr.split():
640 for w in ostr.split():
634 oname,alias,otype = opt_re.match(w).groups()
641 oname,alias,otype = opt_re.match(w).groups()
635 if otype == '' or alias == '!': # simple switches are integers too
642 if otype == '' or alias == '!': # simple switches are integers too
636 otype = 'i'
643 otype = 'i'
637 typeconv[typemap[otype]] += oname + ' '
644 typeconv[typemap[otype]] += oname + ' '
638 return typeconv
645 return typeconv
639
646
640 #----------------------------------------------------------------------------
647 #----------------------------------------------------------------------------
641 def read_dict(filename,type_conv=None,**opt):
648 def read_dict(filename,type_conv=None,**opt):
642
649
643 """Read a dictionary of key=value pairs from an input file, optionally
650 """Read a dictionary of key=value pairs from an input file, optionally
644 performing conversions on the resulting values.
651 performing conversions on the resulting values.
645
652
646 read_dict(filename,type_conv,**opt) -> dict
653 read_dict(filename,type_conv,**opt) -> dict
647
654
648 Only one value per line is accepted, the format should be
655 Only one value per line is accepted, the format should be
649 # optional comments are ignored
656 # optional comments are ignored
650 key value\n
657 key value\n
651
658
652 Args:
659 Args:
653
660
654 - type_conv: A dictionary specifying which keys need to be converted to
661 - type_conv: A dictionary specifying which keys need to be converted to
655 which types. By default all keys are read as strings. This dictionary
662 which types. By default all keys are read as strings. This dictionary
656 should have as its keys valid conversion functions for strings
663 should have as its keys valid conversion functions for strings
657 (int,long,float,complex, or your own). The value for each key
664 (int,long,float,complex, or your own). The value for each key
658 (converter) should be a whitespace separated string containing the names
665 (converter) should be a whitespace separated string containing the names
659 of all the entries in the file to be converted using that function. For
666 of all the entries in the file to be converted using that function. For
660 keys to be left alone, use None as the conversion function (only needed
667 keys to be left alone, use None as the conversion function (only needed
661 with purge=1, see below).
668 with purge=1, see below).
662
669
663 - opt: dictionary with extra options as below (default in parens)
670 - opt: dictionary with extra options as below (default in parens)
664
671
665 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
672 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
666 of the dictionary to be returned. If purge is going to be used, the
673 of the dictionary to be returned. If purge is going to be used, the
667 set of keys to be left as strings also has to be explicitly specified
674 set of keys to be left as strings also has to be explicitly specified
668 using the (non-existent) conversion function None.
675 using the (non-existent) conversion function None.
669
676
670 fs(None): field separator. This is the key/value separator to be used
677 fs(None): field separator. This is the key/value separator to be used
671 when parsing the file. The None default means any whitespace [behavior
678 when parsing the file. The None default means any whitespace [behavior
672 of string.split()].
679 of string.split()].
673
680
674 strip(0): if 1, strip string values of leading/trailinig whitespace.
681 strip(0): if 1, strip string values of leading/trailinig whitespace.
675
682
676 warn(1): warning level if requested keys are not found in file.
683 warn(1): warning level if requested keys are not found in file.
677 - 0: silently ignore.
684 - 0: silently ignore.
678 - 1: inform but proceed.
685 - 1: inform but proceed.
679 - 2: raise KeyError exception.
686 - 2: raise KeyError exception.
680
687
681 no_empty(0): if 1, remove keys with whitespace strings as a value.
688 no_empty(0): if 1, remove keys with whitespace strings as a value.
682
689
683 unique([]): list of keys (or space separated string) which can't be
690 unique([]): list of keys (or space separated string) which can't be
684 repeated. If one such key is found in the file, each new instance
691 repeated. If one such key is found in the file, each new instance
685 overwrites the previous one. For keys not listed here, the behavior is
692 overwrites the previous one. For keys not listed here, the behavior is
686 to make a list of all appearances.
693 to make a list of all appearances.
687
694
688 Example:
695 Example:
689 If the input file test.ini has:
696 If the input file test.ini has:
690 i 3
697 i 3
691 x 4.5
698 x 4.5
692 y 5.5
699 y 5.5
693 s hi ho
700 s hi ho
694 Then:
701 Then:
695
702
696 >>> type_conv={int:'i',float:'x',None:'s'}
703 >>> type_conv={int:'i',float:'x',None:'s'}
697 >>> read_dict('test.ini')
704 >>> read_dict('test.ini')
698 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
705 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
699 >>> read_dict('test.ini',type_conv)
706 >>> read_dict('test.ini',type_conv)
700 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
707 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
701 >>> read_dict('test.ini',type_conv,purge=1)
708 >>> read_dict('test.ini',type_conv,purge=1)
702 {'i': 3, 's': 'hi ho', 'x': 4.5}
709 {'i': 3, 's': 'hi ho', 'x': 4.5}
703 """
710 """
704
711
705 # starting config
712 # starting config
706 opt.setdefault('purge',0)
713 opt.setdefault('purge',0)
707 opt.setdefault('fs',None) # field sep defaults to any whitespace
714 opt.setdefault('fs',None) # field sep defaults to any whitespace
708 opt.setdefault('strip',0)
715 opt.setdefault('strip',0)
709 opt.setdefault('warn',1)
716 opt.setdefault('warn',1)
710 opt.setdefault('no_empty',0)
717 opt.setdefault('no_empty',0)
711 opt.setdefault('unique','')
718 opt.setdefault('unique','')
712 if type(opt['unique']) in StringTypes:
719 if type(opt['unique']) in StringTypes:
713 unique_keys = qw(opt['unique'])
720 unique_keys = qw(opt['unique'])
714 elif type(opt['unique']) in (types.TupleType,types.ListType):
721 elif type(opt['unique']) in (types.TupleType,types.ListType):
715 unique_keys = opt['unique']
722 unique_keys = opt['unique']
716 else:
723 else:
717 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
724 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
718
725
719 dict = {}
726 dict = {}
720 # first read in table of values as strings
727 # first read in table of values as strings
721 file = open(filename,'r')
728 file = open(filename,'r')
722 for line in file.readlines():
729 for line in file.readlines():
723 line = line.strip()
730 line = line.strip()
724 if len(line) and line[0]=='#': continue
731 if len(line) and line[0]=='#': continue
725 if len(line)>0:
732 if len(line)>0:
726 lsplit = line.split(opt['fs'],1)
733 lsplit = line.split(opt['fs'],1)
727 try:
734 try:
728 key,val = lsplit
735 key,val = lsplit
729 except ValueError:
736 except ValueError:
730 key,val = lsplit[0],''
737 key,val = lsplit[0],''
731 key = key.strip()
738 key = key.strip()
732 if opt['strip']: val = val.strip()
739 if opt['strip']: val = val.strip()
733 if val == "''" or val == '""': val = ''
740 if val == "''" or val == '""': val = ''
734 if opt['no_empty'] and (val=='' or val.isspace()):
741 if opt['no_empty'] and (val=='' or val.isspace()):
735 continue
742 continue
736 # if a key is found more than once in the file, build a list
743 # if a key is found more than once in the file, build a list
737 # unless it's in the 'unique' list. In that case, last found in file
744 # unless it's in the 'unique' list. In that case, last found in file
738 # takes precedence. User beware.
745 # takes precedence. User beware.
739 try:
746 try:
740 if dict[key] and key in unique_keys:
747 if dict[key] and key in unique_keys:
741 dict[key] = val
748 dict[key] = val
742 elif type(dict[key]) is types.ListType:
749 elif type(dict[key]) is types.ListType:
743 dict[key].append(val)
750 dict[key].append(val)
744 else:
751 else:
745 dict[key] = [dict[key],val]
752 dict[key] = [dict[key],val]
746 except KeyError:
753 except KeyError:
747 dict[key] = val
754 dict[key] = val
748 # purge if requested
755 # purge if requested
749 if opt['purge']:
756 if opt['purge']:
750 accepted_keys = qwflat(type_conv.values())
757 accepted_keys = qwflat(type_conv.values())
751 for key in dict.keys():
758 for key in dict.keys():
752 if key in accepted_keys: continue
759 if key in accepted_keys: continue
753 del(dict[key])
760 del(dict[key])
754 # now convert if requested
761 # now convert if requested
755 if type_conv==None: return dict
762 if type_conv==None: return dict
756 conversions = type_conv.keys()
763 conversions = type_conv.keys()
757 try: conversions.remove(None)
764 try: conversions.remove(None)
758 except: pass
765 except: pass
759 for convert in conversions:
766 for convert in conversions:
760 for val in qw(type_conv[convert]):
767 for val in qw(type_conv[convert]):
761 try:
768 try:
762 dict[val] = convert(dict[val])
769 dict[val] = convert(dict[val])
763 except KeyError,e:
770 except KeyError,e:
764 if opt['warn'] == 0:
771 if opt['warn'] == 0:
765 pass
772 pass
766 elif opt['warn'] == 1:
773 elif opt['warn'] == 1:
767 print >>sys.stderr, 'Warning: key',val,\
774 print >>sys.stderr, 'Warning: key',val,\
768 'not found in file',filename
775 'not found in file',filename
769 elif opt['warn'] == 2:
776 elif opt['warn'] == 2:
770 raise KeyError,e
777 raise KeyError,e
771 else:
778 else:
772 raise ValueError,'Warning level must be 0,1 or 2'
779 raise ValueError,'Warning level must be 0,1 or 2'
773
780
774 return dict
781 return dict
775
782
776 #----------------------------------------------------------------------------
783 #----------------------------------------------------------------------------
777 def flag_calls(func):
784 def flag_calls(func):
778 """Wrap a function to detect and flag when it gets called.
785 """Wrap a function to detect and flag when it gets called.
779
786
780 This is a decorator which takes a function and wraps it in a function with
787 This is a decorator which takes a function and wraps it in a function with
781 a 'called' attribute. wrapper.called is initialized to False.
788 a 'called' attribute. wrapper.called is initialized to False.
782
789
783 The wrapper.called attribute is set to False right before each call to the
790 The wrapper.called attribute is set to False right before each call to the
784 wrapped function, so if the call fails it remains False. After the call
791 wrapped function, so if the call fails it remains False. After the call
785 completes, wrapper.called is set to True and the output is returned.
792 completes, wrapper.called is set to True and the output is returned.
786
793
787 Testing for truth in wrapper.called allows you to determine if a call to
794 Testing for truth in wrapper.called allows you to determine if a call to
788 func() was attempted and succeeded."""
795 func() was attempted and succeeded."""
789
796
790 def wrapper(*args,**kw):
797 def wrapper(*args,**kw):
791 wrapper.called = False
798 wrapper.called = False
792 out = func(*args,**kw)
799 out = func(*args,**kw)
793 wrapper.called = True
800 wrapper.called = True
794 return out
801 return out
795
802
796 wrapper.called = False
803 wrapper.called = False
797 wrapper.__doc__ = func.__doc__
804 wrapper.__doc__ = func.__doc__
798 return wrapper
805 return wrapper
799
806
800 #----------------------------------------------------------------------------
807 #----------------------------------------------------------------------------
801 class HomeDirError(Error):
808 class HomeDirError(Error):
802 pass
809 pass
803
810
804 def get_home_dir():
811 def get_home_dir():
805 """Return the closest possible equivalent to a 'home' directory.
812 """Return the closest possible equivalent to a 'home' directory.
806
813
807 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
814 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
808
815
809 Currently only Posix and NT are implemented, a HomeDirError exception is
816 Currently only Posix and NT are implemented, a HomeDirError exception is
810 raised for all other OSes. """
817 raised for all other OSes. """
811
818
812 isdir = os.path.isdir
819 isdir = os.path.isdir
813 env = os.environ
820 env = os.environ
814 try:
821 try:
815 homedir = env['HOME']
822 homedir = env['HOME']
816 if not isdir(homedir):
823 if not isdir(homedir):
817 # in case a user stuck some string which does NOT resolve to a
824 # in case a user stuck some string which does NOT resolve to a
818 # valid path, it's as good as if we hadn't foud it
825 # valid path, it's as good as if we hadn't foud it
819 raise KeyError
826 raise KeyError
820 return homedir
827 return homedir
821 except KeyError:
828 except KeyError:
822 if os.name == 'posix':
829 if os.name == 'posix':
823 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
830 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
824 elif os.name == 'nt':
831 elif os.name == 'nt':
825 # For some strange reason, win9x returns 'nt' for os.name.
832 # For some strange reason, win9x returns 'nt' for os.name.
826 try:
833 try:
827 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
834 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
828 if not isdir(homedir):
835 if not isdir(homedir):
829 homedir = os.path.join(env['USERPROFILE'])
836 homedir = os.path.join(env['USERPROFILE'])
830 if not isdir(homedir):
837 if not isdir(homedir):
831 raise HomeDirError
838 raise HomeDirError
832 return homedir
839 return homedir
833 except:
840 except:
834 try:
841 try:
835 # Use the registry to get the 'My Documents' folder.
842 # Use the registry to get the 'My Documents' folder.
836 import _winreg as wreg
843 import _winreg as wreg
837 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
844 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
838 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
845 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
839 homedir = wreg.QueryValueEx(key,'Personal')[0]
846 homedir = wreg.QueryValueEx(key,'Personal')[0]
840 key.Close()
847 key.Close()
841 if not isdir(homedir):
848 if not isdir(homedir):
842 e = ('Invalid "Personal" folder registry key '
849 e = ('Invalid "Personal" folder registry key '
843 'typically "My Documents".\n'
850 'typically "My Documents".\n'
844 'Value: %s\n'
851 'Value: %s\n'
845 'This is not a valid directory on your system.' %
852 'This is not a valid directory on your system.' %
846 homedir)
853 homedir)
847 raise HomeDirError(e)
854 raise HomeDirError(e)
848 return homedir
855 return homedir
849 except HomeDirError:
856 except HomeDirError:
850 raise
857 raise
851 except:
858 except:
852 return 'C:\\'
859 return 'C:\\'
853 elif os.name == 'dos':
860 elif os.name == 'dos':
854 # Desperate, may do absurd things in classic MacOS. May work under DOS.
861 # Desperate, may do absurd things in classic MacOS. May work under DOS.
855 return 'C:\\'
862 return 'C:\\'
856 else:
863 else:
857 raise HomeDirError,'support for your operating system not implemented.'
864 raise HomeDirError,'support for your operating system not implemented.'
858
865
859 #****************************************************************************
866 #****************************************************************************
860 # strings and text
867 # strings and text
861
868
862 class LSString(str):
869 class LSString(str):
863 """String derivative with a special access attributes.
870 """String derivative with a special access attributes.
864
871
865 These are normal strings, but with the special attributes:
872 These are normal strings, but with the special attributes:
866
873
867 .l (or .list) : value as list (split on newlines).
874 .l (or .list) : value as list (split on newlines).
868 .n (or .nlstr): original value (the string itself).
875 .n (or .nlstr): original value (the string itself).
869 .s (or .spstr): value as whitespace-separated string.
876 .s (or .spstr): value as whitespace-separated string.
870
877
871 Any values which require transformations are computed only once and
878 Any values which require transformations are computed only once and
872 cached.
879 cached.
873
880
874 Such strings are very useful to efficiently interact with the shell, which
881 Such strings are very useful to efficiently interact with the shell, which
875 typically only understands whitespace-separated options for commands."""
882 typically only understands whitespace-separated options for commands."""
876
883
877 def get_list(self):
884 def get_list(self):
878 try:
885 try:
879 return self.__list
886 return self.__list
880 except AttributeError:
887 except AttributeError:
881 self.__list = self.split('\n')
888 self.__list = self.split('\n')
882 return self.__list
889 return self.__list
883
890
884 l = list = property(get_list)
891 l = list = property(get_list)
885
892
886 def get_spstr(self):
893 def get_spstr(self):
887 try:
894 try:
888 return self.__spstr
895 return self.__spstr
889 except AttributeError:
896 except AttributeError:
890 self.__spstr = self.replace('\n',' ')
897 self.__spstr = self.replace('\n',' ')
891 return self.__spstr
898 return self.__spstr
892
899
893 s = spstr = property(get_spstr)
900 s = spstr = property(get_spstr)
894
901
895 def get_nlstr(self):
902 def get_nlstr(self):
896 return self
903 return self
897
904
898 n = nlstr = property(get_nlstr)
905 n = nlstr = property(get_nlstr)
899
906
900 def get_paths(self):
907 def get_paths(self):
901 try:
908 try:
902 return self.__paths
909 return self.__paths
903 except AttributeError:
910 except AttributeError:
904 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
911 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
905 return self.__paths
912 return self.__paths
906
913
907 p = paths = property(get_paths)
914 p = paths = property(get_paths)
908
915
909
916
910 #----------------------------------------------------------------------------
917 #----------------------------------------------------------------------------
911 class SList(list):
918 class SList(list):
912 """List derivative with a special access attributes.
919 """List derivative with a special access attributes.
913
920
914 These are normal lists, but with the special attributes:
921 These are normal lists, but with the special attributes:
915
922
916 .l (or .list) : value as list (the list itself).
923 .l (or .list) : value as list (the list itself).
917 .n (or .nlstr): value as a string, joined on newlines.
924 .n (or .nlstr): value as a string, joined on newlines.
918 .s (or .spstr): value as a string, joined on spaces.
925 .s (or .spstr): value as a string, joined on spaces.
919
926
920 Any values which require transformations are computed only once and
927 Any values which require transformations are computed only once and
921 cached."""
928 cached."""
922
929
923 def get_list(self):
930 def get_list(self):
924 return self
931 return self
925
932
926 l = list = property(get_list)
933 l = list = property(get_list)
927
934
928 def get_spstr(self):
935 def get_spstr(self):
929 try:
936 try:
930 return self.__spstr
937 return self.__spstr
931 except AttributeError:
938 except AttributeError:
932 self.__spstr = ' '.join(self)
939 self.__spstr = ' '.join(self)
933 return self.__spstr
940 return self.__spstr
934
941
935 s = spstr = property(get_spstr)
942 s = spstr = property(get_spstr)
936
943
937 def get_nlstr(self):
944 def get_nlstr(self):
938 try:
945 try:
939 return self.__nlstr
946 return self.__nlstr
940 except AttributeError:
947 except AttributeError:
941 self.__nlstr = '\n'.join(self)
948 self.__nlstr = '\n'.join(self)
942 return self.__nlstr
949 return self.__nlstr
943
950
944 n = nlstr = property(get_nlstr)
951 n = nlstr = property(get_nlstr)
945
952
946 def get_paths(self):
953 def get_paths(self):
947 try:
954 try:
948 return self.__paths
955 return self.__paths
949 except AttributeError:
956 except AttributeError:
950 self.__paths = [path(p) for p in self if os.path.exists(p)]
957 self.__paths = [path(p) for p in self if os.path.exists(p)]
951 return self.__paths
958 return self.__paths
952
959
953 p = paths = property(get_paths)
960 p = paths = property(get_paths)
954
961
955 #----------------------------------------------------------------------------
962 #----------------------------------------------------------------------------
956 def esc_quotes(strng):
963 def esc_quotes(strng):
957 """Return the input string with single and double quotes escaped out"""
964 """Return the input string with single and double quotes escaped out"""
958
965
959 return strng.replace('"','\\"').replace("'","\\'")
966 return strng.replace('"','\\"').replace("'","\\'")
960
967
961 #----------------------------------------------------------------------------
968 #----------------------------------------------------------------------------
962 def make_quoted_expr(s):
969 def make_quoted_expr(s):
963 """Return string s in appropriate quotes, using raw string if possible.
970 """Return string s in appropriate quotes, using raw string if possible.
964
971
965 Effectively this turns string: cd \ao\ao\
972 Effectively this turns string: cd \ao\ao\
966 to: r"cd \ao\ao\_"[:-1]
973 to: r"cd \ao\ao\_"[:-1]
967
974
968 Note the use of raw string and padding at the end to allow trailing backslash.
975 Note the use of raw string and padding at the end to allow trailing backslash.
969
976
970 """
977 """
971
978
972 tail = ''
979 tail = ''
973 tailpadding = ''
980 tailpadding = ''
974 raw = ''
981 raw = ''
975 if "\\" in s:
982 if "\\" in s:
976 raw = 'r'
983 raw = 'r'
977 if s.endswith('\\'):
984 if s.endswith('\\'):
978 tail = '[:-1]'
985 tail = '[:-1]'
979 tailpadding = '_'
986 tailpadding = '_'
980 if '"' not in s:
987 if '"' not in s:
981 quote = '"'
988 quote = '"'
982 elif "'" not in s:
989 elif "'" not in s:
983 quote = "'"
990 quote = "'"
984 elif '"""' not in s and not s.endswith('"'):
991 elif '"""' not in s and not s.endswith('"'):
985 quote = '"""'
992 quote = '"""'
986 elif "'''" not in s and not s.endswith("'"):
993 elif "'''" not in s and not s.endswith("'"):
987 quote = "'''"
994 quote = "'''"
988 else:
995 else:
989 # give up, backslash-escaped string will do
996 # give up, backslash-escaped string will do
990 return '"%s"' % esc_quotes(s)
997 return '"%s"' % esc_quotes(s)
991 res = itpl("$raw$quote$s$tailpadding$quote$tail")
998 res = itpl("$raw$quote$s$tailpadding$quote$tail")
992 return res
999 return res
993
1000
994
1001
995 #----------------------------------------------------------------------------
1002 #----------------------------------------------------------------------------
996 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
1003 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
997 """Take multiple lines of input.
1004 """Take multiple lines of input.
998
1005
999 A list with each line of input as a separate element is returned when a
1006 A list with each line of input as a separate element is returned when a
1000 termination string is entered (defaults to a single '.'). Input can also
1007 termination string is entered (defaults to a single '.'). Input can also
1001 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1008 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1002
1009
1003 Lines of input which end in \\ are joined into single entries (and a
1010 Lines of input which end in \\ are joined into single entries (and a
1004 secondary continuation prompt is issued as long as the user terminates
1011 secondary continuation prompt is issued as long as the user terminates
1005 lines with \\). This allows entering very long strings which are still
1012 lines with \\). This allows entering very long strings which are still
1006 meant to be treated as single entities.
1013 meant to be treated as single entities.
1007 """
1014 """
1008
1015
1009 try:
1016 try:
1010 if header:
1017 if header:
1011 header += '\n'
1018 header += '\n'
1012 lines = [raw_input(header + ps1)]
1019 lines = [raw_input(header + ps1)]
1013 except EOFError:
1020 except EOFError:
1014 return []
1021 return []
1015 terminate = [terminate_str]
1022 terminate = [terminate_str]
1016 try:
1023 try:
1017 while lines[-1:] != terminate:
1024 while lines[-1:] != terminate:
1018 new_line = raw_input(ps1)
1025 new_line = raw_input(ps1)
1019 while new_line.endswith('\\'):
1026 while new_line.endswith('\\'):
1020 new_line = new_line[:-1] + raw_input(ps2)
1027 new_line = new_line[:-1] + raw_input(ps2)
1021 lines.append(new_line)
1028 lines.append(new_line)
1022
1029
1023 return lines[:-1] # don't return the termination command
1030 return lines[:-1] # don't return the termination command
1024 except EOFError:
1031 except EOFError:
1025 print
1032 print
1026 return lines
1033 return lines
1027
1034
1028 #----------------------------------------------------------------------------
1035 #----------------------------------------------------------------------------
1029 def raw_input_ext(prompt='', ps2='... '):
1036 def raw_input_ext(prompt='', ps2='... '):
1030 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1037 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1031
1038
1032 line = raw_input(prompt)
1039 line = raw_input(prompt)
1033 while line.endswith('\\'):
1040 while line.endswith('\\'):
1034 line = line[:-1] + raw_input(ps2)
1041 line = line[:-1] + raw_input(ps2)
1035 return line
1042 return line
1036
1043
1037 #----------------------------------------------------------------------------
1044 #----------------------------------------------------------------------------
1038 def ask_yes_no(prompt,default=None):
1045 def ask_yes_no(prompt,default=None):
1039 """Asks a question and returns an integer 1/0 (y/n) answer.
1046 """Asks a question and returns an integer 1/0 (y/n) answer.
1040
1047
1041 If default is given (one of 'y','n'), it is used if the user input is
1048 If default is given (one of 'y','n'), it is used if the user input is
1042 empty. Otherwise the question is repeated until an answer is given.
1049 empty. Otherwise the question is repeated until an answer is given.
1043 If EOF occurs 20 times consecutively, the default answer is assumed,
1050 If EOF occurs 20 times consecutively, the default answer is assumed,
1044 or if there is no default, an exception is raised to prevent infinite
1051 or if there is no default, an exception is raised to prevent infinite
1045 loops.
1052 loops.
1046
1053
1047 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1054 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1048
1055
1049 answers = {'y':True,'n':False,'yes':True,'no':False}
1056 answers = {'y':True,'n':False,'yes':True,'no':False}
1050 ans = None
1057 ans = None
1051 eofs, max_eofs = 0, 20
1058 eofs, max_eofs = 0, 20
1052 while ans not in answers.keys():
1059 while ans not in answers.keys():
1053 try:
1060 try:
1054 ans = raw_input(prompt+' ').lower()
1061 ans = raw_input(prompt+' ').lower()
1055 if not ans: # response was an empty string
1062 if not ans: # response was an empty string
1056 ans = default
1063 ans = default
1057 eofs = 0
1064 eofs = 0
1058 except (EOFError,KeyboardInterrupt):
1065 except (EOFError,KeyboardInterrupt):
1059 eofs = eofs + 1
1066 eofs = eofs + 1
1060 if eofs >= max_eofs:
1067 if eofs >= max_eofs:
1061 if default in answers.keys():
1068 if default in answers.keys():
1062 ans = default
1069 ans = default
1063 else:
1070 else:
1064 raise
1071 raise
1065
1072
1066 return answers[ans]
1073 return answers[ans]
1067
1074
1068 #----------------------------------------------------------------------------
1075 #----------------------------------------------------------------------------
1069 def marquee(txt='',width=78,mark='*'):
1076 def marquee(txt='',width=78,mark='*'):
1070 """Return the input string centered in a 'marquee'."""
1077 """Return the input string centered in a 'marquee'."""
1071 if not txt:
1078 if not txt:
1072 return (mark*width)[:width]
1079 return (mark*width)[:width]
1073 nmark = (width-len(txt)-2)/len(mark)/2
1080 nmark = (width-len(txt)-2)/len(mark)/2
1074 if nmark < 0: nmark =0
1081 if nmark < 0: nmark =0
1075 marks = mark*nmark
1082 marks = mark*nmark
1076 return '%s %s %s' % (marks,txt,marks)
1083 return '%s %s %s' % (marks,txt,marks)
1077
1084
1078 #----------------------------------------------------------------------------
1085 #----------------------------------------------------------------------------
1079 class EvalDict:
1086 class EvalDict:
1080 """
1087 """
1081 Emulate a dict which evaluates its contents in the caller's frame.
1088 Emulate a dict which evaluates its contents in the caller's frame.
1082
1089
1083 Usage:
1090 Usage:
1084 >>>number = 19
1091 >>>number = 19
1085 >>>text = "python"
1092 >>>text = "python"
1086 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1093 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1087 """
1094 """
1088
1095
1089 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1096 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1090 # modified (shorter) version of:
1097 # modified (shorter) version of:
1091 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1098 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1092 # Skip Montanaro (skip@pobox.com).
1099 # Skip Montanaro (skip@pobox.com).
1093
1100
1094 def __getitem__(self, name):
1101 def __getitem__(self, name):
1095 frame = sys._getframe(1)
1102 frame = sys._getframe(1)
1096 return eval(name, frame.f_globals, frame.f_locals)
1103 return eval(name, frame.f_globals, frame.f_locals)
1097
1104
1098 EvalString = EvalDict # for backwards compatibility
1105 EvalString = EvalDict # for backwards compatibility
1099 #----------------------------------------------------------------------------
1106 #----------------------------------------------------------------------------
1100 def qw(words,flat=0,sep=None,maxsplit=-1):
1107 def qw(words,flat=0,sep=None,maxsplit=-1):
1101 """Similar to Perl's qw() operator, but with some more options.
1108 """Similar to Perl's qw() operator, but with some more options.
1102
1109
1103 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1110 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1104
1111
1105 words can also be a list itself, and with flat=1, the output will be
1112 words can also be a list itself, and with flat=1, the output will be
1106 recursively flattened. Examples:
1113 recursively flattened. Examples:
1107
1114
1108 >>> qw('1 2')
1115 >>> qw('1 2')
1109 ['1', '2']
1116 ['1', '2']
1110 >>> qw(['a b','1 2',['m n','p q']])
1117 >>> qw(['a b','1 2',['m n','p q']])
1111 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1118 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1112 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1119 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1113 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1120 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1114
1121
1115 if type(words) in StringTypes:
1122 if type(words) in StringTypes:
1116 return [word.strip() for word in words.split(sep,maxsplit)
1123 return [word.strip() for word in words.split(sep,maxsplit)
1117 if word and not word.isspace() ]
1124 if word and not word.isspace() ]
1118 if flat:
1125 if flat:
1119 return flatten(map(qw,words,[1]*len(words)))
1126 return flatten(map(qw,words,[1]*len(words)))
1120 return map(qw,words)
1127 return map(qw,words)
1121
1128
1122 #----------------------------------------------------------------------------
1129 #----------------------------------------------------------------------------
1123 def qwflat(words,sep=None,maxsplit=-1):
1130 def qwflat(words,sep=None,maxsplit=-1):
1124 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1131 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1125 return qw(words,1,sep,maxsplit)
1132 return qw(words,1,sep,maxsplit)
1126
1133
1127 #----------------------------------------------------------------------------
1134 #----------------------------------------------------------------------------
1128 def qw_lol(indata):
1135 def qw_lol(indata):
1129 """qw_lol('a b') -> [['a','b']],
1136 """qw_lol('a b') -> [['a','b']],
1130 otherwise it's just a call to qw().
1137 otherwise it's just a call to qw().
1131
1138
1132 We need this to make sure the modules_some keys *always* end up as a
1139 We need this to make sure the modules_some keys *always* end up as a
1133 list of lists."""
1140 list of lists."""
1134
1141
1135 if type(indata) in StringTypes:
1142 if type(indata) in StringTypes:
1136 return [qw(indata)]
1143 return [qw(indata)]
1137 else:
1144 else:
1138 return qw(indata)
1145 return qw(indata)
1139
1146
1140 #-----------------------------------------------------------------------------
1147 #-----------------------------------------------------------------------------
1141 def list_strings(arg):
1148 def list_strings(arg):
1142 """Always return a list of strings, given a string or list of strings
1149 """Always return a list of strings, given a string or list of strings
1143 as input."""
1150 as input."""
1144
1151
1145 if type(arg) in StringTypes: return [arg]
1152 if type(arg) in StringTypes: return [arg]
1146 else: return arg
1153 else: return arg
1147
1154
1148 #----------------------------------------------------------------------------
1155 #----------------------------------------------------------------------------
1149 def grep(pat,list,case=1):
1156 def grep(pat,list,case=1):
1150 """Simple minded grep-like function.
1157 """Simple minded grep-like function.
1151 grep(pat,list) returns occurrences of pat in list, None on failure.
1158 grep(pat,list) returns occurrences of pat in list, None on failure.
1152
1159
1153 It only does simple string matching, with no support for regexps. Use the
1160 It only does simple string matching, with no support for regexps. Use the
1154 option case=0 for case-insensitive matching."""
1161 option case=0 for case-insensitive matching."""
1155
1162
1156 # This is pretty crude. At least it should implement copying only references
1163 # This is pretty crude. At least it should implement copying only references
1157 # to the original data in case it's big. Now it copies the data for output.
1164 # to the original data in case it's big. Now it copies the data for output.
1158 out=[]
1165 out=[]
1159 if case:
1166 if case:
1160 for term in list:
1167 for term in list:
1161 if term.find(pat)>-1: out.append(term)
1168 if term.find(pat)>-1: out.append(term)
1162 else:
1169 else:
1163 lpat=pat.lower()
1170 lpat=pat.lower()
1164 for term in list:
1171 for term in list:
1165 if term.lower().find(lpat)>-1: out.append(term)
1172 if term.lower().find(lpat)>-1: out.append(term)
1166
1173
1167 if len(out): return out
1174 if len(out): return out
1168 else: return None
1175 else: return None
1169
1176
1170 #----------------------------------------------------------------------------
1177 #----------------------------------------------------------------------------
1171 def dgrep(pat,*opts):
1178 def dgrep(pat,*opts):
1172 """Return grep() on dir()+dir(__builtins__).
1179 """Return grep() on dir()+dir(__builtins__).
1173
1180
1174 A very common use of grep() when working interactively."""
1181 A very common use of grep() when working interactively."""
1175
1182
1176 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1183 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1177
1184
1178 #----------------------------------------------------------------------------
1185 #----------------------------------------------------------------------------
1179 def idgrep(pat):
1186 def idgrep(pat):
1180 """Case-insensitive dgrep()"""
1187 """Case-insensitive dgrep()"""
1181
1188
1182 return dgrep(pat,0)
1189 return dgrep(pat,0)
1183
1190
1184 #----------------------------------------------------------------------------
1191 #----------------------------------------------------------------------------
1185 def igrep(pat,list):
1192 def igrep(pat,list):
1186 """Synonym for case-insensitive grep."""
1193 """Synonym for case-insensitive grep."""
1187
1194
1188 return grep(pat,list,case=0)
1195 return grep(pat,list,case=0)
1189
1196
1190 #----------------------------------------------------------------------------
1197 #----------------------------------------------------------------------------
1191 def indent(str,nspaces=4,ntabs=0):
1198 def indent(str,nspaces=4,ntabs=0):
1192 """Indent a string a given number of spaces or tabstops.
1199 """Indent a string a given number of spaces or tabstops.
1193
1200
1194 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1201 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1195 """
1202 """
1196 if str is None:
1203 if str is None:
1197 return
1204 return
1198 ind = '\t'*ntabs+' '*nspaces
1205 ind = '\t'*ntabs+' '*nspaces
1199 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1206 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1200 if outstr.endswith(os.linesep+ind):
1207 if outstr.endswith(os.linesep+ind):
1201 return outstr[:-len(ind)]
1208 return outstr[:-len(ind)]
1202 else:
1209 else:
1203 return outstr
1210 return outstr
1204
1211
1205 #-----------------------------------------------------------------------------
1212 #-----------------------------------------------------------------------------
1206 def native_line_ends(filename,backup=1):
1213 def native_line_ends(filename,backup=1):
1207 """Convert (in-place) a file to line-ends native to the current OS.
1214 """Convert (in-place) a file to line-ends native to the current OS.
1208
1215
1209 If the optional backup argument is given as false, no backup of the
1216 If the optional backup argument is given as false, no backup of the
1210 original file is left. """
1217 original file is left. """
1211
1218
1212 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1219 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1213
1220
1214 bak_filename = filename + backup_suffixes[os.name]
1221 bak_filename = filename + backup_suffixes[os.name]
1215
1222
1216 original = open(filename).read()
1223 original = open(filename).read()
1217 shutil.copy2(filename,bak_filename)
1224 shutil.copy2(filename,bak_filename)
1218 try:
1225 try:
1219 new = open(filename,'wb')
1226 new = open(filename,'wb')
1220 new.write(os.linesep.join(original.splitlines()))
1227 new.write(os.linesep.join(original.splitlines()))
1221 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1228 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1222 new.close()
1229 new.close()
1223 except:
1230 except:
1224 os.rename(bak_filename,filename)
1231 os.rename(bak_filename,filename)
1225 if not backup:
1232 if not backup:
1226 try:
1233 try:
1227 os.remove(bak_filename)
1234 os.remove(bak_filename)
1228 except:
1235 except:
1229 pass
1236 pass
1230
1237
1231 #----------------------------------------------------------------------------
1238 #----------------------------------------------------------------------------
1232 def get_pager_cmd(pager_cmd = None):
1239 def get_pager_cmd(pager_cmd = None):
1233 """Return a pager command.
1240 """Return a pager command.
1234
1241
1235 Makes some attempts at finding an OS-correct one."""
1242 Makes some attempts at finding an OS-correct one."""
1236
1243
1237 if os.name == 'posix':
1244 if os.name == 'posix':
1238 default_pager_cmd = 'less -r' # -r for color control sequences
1245 default_pager_cmd = 'less -r' # -r for color control sequences
1239 elif os.name in ['nt','dos']:
1246 elif os.name in ['nt','dos']:
1240 default_pager_cmd = 'type'
1247 default_pager_cmd = 'type'
1241
1248
1242 if pager_cmd is None:
1249 if pager_cmd is None:
1243 try:
1250 try:
1244 pager_cmd = os.environ['PAGER']
1251 pager_cmd = os.environ['PAGER']
1245 except:
1252 except:
1246 pager_cmd = default_pager_cmd
1253 pager_cmd = default_pager_cmd
1247 return pager_cmd
1254 return pager_cmd
1248
1255
1249 #-----------------------------------------------------------------------------
1256 #-----------------------------------------------------------------------------
1250 def get_pager_start(pager,start):
1257 def get_pager_start(pager,start):
1251 """Return the string for paging files with an offset.
1258 """Return the string for paging files with an offset.
1252
1259
1253 This is the '+N' argument which less and more (under Unix) accept.
1260 This is the '+N' argument which less and more (under Unix) accept.
1254 """
1261 """
1255
1262
1256 if pager in ['less','more']:
1263 if pager in ['less','more']:
1257 if start:
1264 if start:
1258 start_string = '+' + str(start)
1265 start_string = '+' + str(start)
1259 else:
1266 else:
1260 start_string = ''
1267 start_string = ''
1261 else:
1268 else:
1262 start_string = ''
1269 start_string = ''
1263 return start_string
1270 return start_string
1264
1271
1265 #----------------------------------------------------------------------------
1272 #----------------------------------------------------------------------------
1266 if os.name == "nt":
1273 if os.name == "nt":
1267 import msvcrt
1274 import msvcrt
1268 def page_more():
1275 def page_more():
1269 """ Smart pausing between pages
1276 """ Smart pausing between pages
1270
1277
1271 @return: True if need print more lines, False if quit
1278 @return: True if need print more lines, False if quit
1272 """
1279 """
1273 Term.cout.write('---Return to continue, q to quit--- ')
1280 Term.cout.write('---Return to continue, q to quit--- ')
1274 ans = msvcrt.getch()
1281 ans = msvcrt.getch()
1275 if ans in ("q", "Q"):
1282 if ans in ("q", "Q"):
1276 result = False
1283 result = False
1277 else:
1284 else:
1278 result = True
1285 result = True
1279 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1286 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1280 return result
1287 return result
1281 else:
1288 else:
1282 def page_more():
1289 def page_more():
1283 ans = raw_input('---Return to continue, q to quit--- ')
1290 ans = raw_input('---Return to continue, q to quit--- ')
1284 if ans.lower().startswith('q'):
1291 if ans.lower().startswith('q'):
1285 return False
1292 return False
1286 else:
1293 else:
1287 return True
1294 return True
1288
1295
1289 esc_re = re.compile(r"(\x1b[^m]+m)")
1296 esc_re = re.compile(r"(\x1b[^m]+m)")
1290
1297
1291 def page_dumb(strng,start=0,screen_lines=25):
1298 def page_dumb(strng,start=0,screen_lines=25):
1292 """Very dumb 'pager' in Python, for when nothing else works.
1299 """Very dumb 'pager' in Python, for when nothing else works.
1293
1300
1294 Only moves forward, same interface as page(), except for pager_cmd and
1301 Only moves forward, same interface as page(), except for pager_cmd and
1295 mode."""
1302 mode."""
1296
1303
1297 out_ln = strng.splitlines()[start:]
1304 out_ln = strng.splitlines()[start:]
1298 screens = chop(out_ln,screen_lines-1)
1305 screens = chop(out_ln,screen_lines-1)
1299 if len(screens) == 1:
1306 if len(screens) == 1:
1300 print >>Term.cout, os.linesep.join(screens[0])
1307 print >>Term.cout, os.linesep.join(screens[0])
1301 else:
1308 else:
1302 last_escape = ""
1309 last_escape = ""
1303 for scr in screens[0:-1]:
1310 for scr in screens[0:-1]:
1304 hunk = os.linesep.join(scr)
1311 hunk = os.linesep.join(scr)
1305 print >>Term.cout, last_escape + hunk
1312 print >>Term.cout, last_escape + hunk
1306 if not page_more():
1313 if not page_more():
1307 return
1314 return
1308 esc_list = esc_re.findall(hunk)
1315 esc_list = esc_re.findall(hunk)
1309 if len(esc_list) > 0:
1316 if len(esc_list) > 0:
1310 last_escape = esc_list[-1]
1317 last_escape = esc_list[-1]
1311 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1318 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1312
1319
1313 #----------------------------------------------------------------------------
1320 #----------------------------------------------------------------------------
1314 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1321 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1315 """Print a string, piping through a pager after a certain length.
1322 """Print a string, piping through a pager after a certain length.
1316
1323
1317 The screen_lines parameter specifies the number of *usable* lines of your
1324 The screen_lines parameter specifies the number of *usable* lines of your
1318 terminal screen (total lines minus lines you need to reserve to show other
1325 terminal screen (total lines minus lines you need to reserve to show other
1319 information).
1326 information).
1320
1327
1321 If you set screen_lines to a number <=0, page() will try to auto-determine
1328 If you set screen_lines to a number <=0, page() will try to auto-determine
1322 your screen size and will only use up to (screen_size+screen_lines) for
1329 your screen size and will only use up to (screen_size+screen_lines) for
1323 printing, paging after that. That is, if you want auto-detection but need
1330 printing, paging after that. That is, if you want auto-detection but need
1324 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1331 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1325 auto-detection without any lines reserved simply use screen_lines = 0.
1332 auto-detection without any lines reserved simply use screen_lines = 0.
1326
1333
1327 If a string won't fit in the allowed lines, it is sent through the
1334 If a string won't fit in the allowed lines, it is sent through the
1328 specified pager command. If none given, look for PAGER in the environment,
1335 specified pager command. If none given, look for PAGER in the environment,
1329 and ultimately default to less.
1336 and ultimately default to less.
1330
1337
1331 If no system pager works, the string is sent through a 'dumb pager'
1338 If no system pager works, the string is sent through a 'dumb pager'
1332 written in python, very simplistic.
1339 written in python, very simplistic.
1333 """
1340 """
1334
1341
1335 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1342 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1336 TERM = os.environ.get('TERM','dumb')
1343 TERM = os.environ.get('TERM','dumb')
1337 if TERM in ['dumb','emacs'] and os.name != 'nt':
1344 if TERM in ['dumb','emacs'] and os.name != 'nt':
1338 print strng
1345 print strng
1339 return
1346 return
1340 # chop off the topmost part of the string we don't want to see
1347 # chop off the topmost part of the string we don't want to see
1341 str_lines = strng.split(os.linesep)[start:]
1348 str_lines = strng.split(os.linesep)[start:]
1342 str_toprint = os.linesep.join(str_lines)
1349 str_toprint = os.linesep.join(str_lines)
1343 num_newlines = len(str_lines)
1350 num_newlines = len(str_lines)
1344 len_str = len(str_toprint)
1351 len_str = len(str_toprint)
1345
1352
1346 # Dumb heuristics to guesstimate number of on-screen lines the string
1353 # Dumb heuristics to guesstimate number of on-screen lines the string
1347 # takes. Very basic, but good enough for docstrings in reasonable
1354 # takes. Very basic, but good enough for docstrings in reasonable
1348 # terminals. If someone later feels like refining it, it's not hard.
1355 # terminals. If someone later feels like refining it, it's not hard.
1349 numlines = max(num_newlines,int(len_str/80)+1)
1356 numlines = max(num_newlines,int(len_str/80)+1)
1350
1357
1351 if os.name == "nt":
1358 if os.name == "nt":
1352 screen_lines_def = get_console_size(defaulty=25)[1]
1359 screen_lines_def = get_console_size(defaulty=25)[1]
1353 else:
1360 else:
1354 screen_lines_def = 25 # default value if we can't auto-determine
1361 screen_lines_def = 25 # default value if we can't auto-determine
1355
1362
1356 # auto-determine screen size
1363 # auto-determine screen size
1357 if screen_lines <= 0:
1364 if screen_lines <= 0:
1358 if TERM=='xterm':
1365 if TERM=='xterm':
1359 try:
1366 try:
1360 import curses
1367 import curses
1361 if hasattr(curses,'initscr'):
1368 if hasattr(curses,'initscr'):
1362 use_curses = 1
1369 use_curses = 1
1363 else:
1370 else:
1364 use_curses = 0
1371 use_curses = 0
1365 except ImportError:
1372 except ImportError:
1366 use_curses = 0
1373 use_curses = 0
1367 else:
1374 else:
1368 # curses causes problems on many terminals other than xterm.
1375 # curses causes problems on many terminals other than xterm.
1369 use_curses = 0
1376 use_curses = 0
1370 if use_curses:
1377 if use_curses:
1371 scr = curses.initscr()
1378 scr = curses.initscr()
1372 screen_lines_real,screen_cols = scr.getmaxyx()
1379 screen_lines_real,screen_cols = scr.getmaxyx()
1373 curses.endwin()
1380 curses.endwin()
1374 screen_lines += screen_lines_real
1381 screen_lines += screen_lines_real
1375 #print '***Screen size:',screen_lines_real,'lines x',\
1382 #print '***Screen size:',screen_lines_real,'lines x',\
1376 #screen_cols,'columns.' # dbg
1383 #screen_cols,'columns.' # dbg
1377 else:
1384 else:
1378 screen_lines += screen_lines_def
1385 screen_lines += screen_lines_def
1379
1386
1380 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1387 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1381 if numlines <= screen_lines :
1388 if numlines <= screen_lines :
1382 #print '*** normal print' # dbg
1389 #print '*** normal print' # dbg
1383 print >>Term.cout, str_toprint
1390 print >>Term.cout, str_toprint
1384 else:
1391 else:
1385 # Try to open pager and default to internal one if that fails.
1392 # Try to open pager and default to internal one if that fails.
1386 # All failure modes are tagged as 'retval=1', to match the return
1393 # All failure modes are tagged as 'retval=1', to match the return
1387 # value of a failed system command. If any intermediate attempt
1394 # value of a failed system command. If any intermediate attempt
1388 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1395 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1389 pager_cmd = get_pager_cmd(pager_cmd)
1396 pager_cmd = get_pager_cmd(pager_cmd)
1390 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1397 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1391 if os.name == 'nt':
1398 if os.name == 'nt':
1392 if pager_cmd.startswith('type'):
1399 if pager_cmd.startswith('type'):
1393 # The default WinXP 'type' command is failing on complex strings.
1400 # The default WinXP 'type' command is failing on complex strings.
1394 retval = 1
1401 retval = 1
1395 else:
1402 else:
1396 tmpname = tempfile.mktemp('.txt')
1403 tmpname = tempfile.mktemp('.txt')
1397 tmpfile = file(tmpname,'wt')
1404 tmpfile = file(tmpname,'wt')
1398 tmpfile.write(strng)
1405 tmpfile.write(strng)
1399 tmpfile.close()
1406 tmpfile.close()
1400 cmd = "%s < %s" % (pager_cmd,tmpname)
1407 cmd = "%s < %s" % (pager_cmd,tmpname)
1401 if os.system(cmd):
1408 if os.system(cmd):
1402 retval = 1
1409 retval = 1
1403 else:
1410 else:
1404 retval = None
1411 retval = None
1405 os.remove(tmpname)
1412 os.remove(tmpname)
1406 else:
1413 else:
1407 try:
1414 try:
1408 retval = None
1415 retval = None
1409 # if I use popen4, things hang. No idea why.
1416 # if I use popen4, things hang. No idea why.
1410 #pager,shell_out = os.popen4(pager_cmd)
1417 #pager,shell_out = os.popen4(pager_cmd)
1411 pager = os.popen(pager_cmd,'w')
1418 pager = os.popen(pager_cmd,'w')
1412 pager.write(strng)
1419 pager.write(strng)
1413 pager.close()
1420 pager.close()
1414 retval = pager.close() # success returns None
1421 retval = pager.close() # success returns None
1415 except IOError,msg: # broken pipe when user quits
1422 except IOError,msg: # broken pipe when user quits
1416 if msg.args == (32,'Broken pipe'):
1423 if msg.args == (32,'Broken pipe'):
1417 retval = None
1424 retval = None
1418 else:
1425 else:
1419 retval = 1
1426 retval = 1
1420 except OSError:
1427 except OSError:
1421 # Other strange problems, sometimes seen in Win2k/cygwin
1428 # Other strange problems, sometimes seen in Win2k/cygwin
1422 retval = 1
1429 retval = 1
1423 if retval is not None:
1430 if retval is not None:
1424 page_dumb(strng,screen_lines=screen_lines)
1431 page_dumb(strng,screen_lines=screen_lines)
1425
1432
1426 #----------------------------------------------------------------------------
1433 #----------------------------------------------------------------------------
1427 def page_file(fname,start = 0, pager_cmd = None):
1434 def page_file(fname,start = 0, pager_cmd = None):
1428 """Page a file, using an optional pager command and starting line.
1435 """Page a file, using an optional pager command and starting line.
1429 """
1436 """
1430
1437
1431 pager_cmd = get_pager_cmd(pager_cmd)
1438 pager_cmd = get_pager_cmd(pager_cmd)
1432 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1439 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1433
1440
1434 try:
1441 try:
1435 if os.environ['TERM'] in ['emacs','dumb']:
1442 if os.environ['TERM'] in ['emacs','dumb']:
1436 raise EnvironmentError
1443 raise EnvironmentError
1437 xsys(pager_cmd + ' ' + fname)
1444 xsys(pager_cmd + ' ' + fname)
1438 except:
1445 except:
1439 try:
1446 try:
1440 if start > 0:
1447 if start > 0:
1441 start -= 1
1448 start -= 1
1442 page(open(fname).read(),start)
1449 page(open(fname).read(),start)
1443 except:
1450 except:
1444 print 'Unable to show file',`fname`
1451 print 'Unable to show file',`fname`
1445
1452
1446 #----------------------------------------------------------------------------
1453 #----------------------------------------------------------------------------
1447 def snip_print(str,width = 75,print_full = 0,header = ''):
1454 def snip_print(str,width = 75,print_full = 0,header = ''):
1448 """Print a string snipping the midsection to fit in width.
1455 """Print a string snipping the midsection to fit in width.
1449
1456
1450 print_full: mode control:
1457 print_full: mode control:
1451 - 0: only snip long strings
1458 - 0: only snip long strings
1452 - 1: send to page() directly.
1459 - 1: send to page() directly.
1453 - 2: snip long strings and ask for full length viewing with page()
1460 - 2: snip long strings and ask for full length viewing with page()
1454 Return 1 if snipping was necessary, 0 otherwise."""
1461 Return 1 if snipping was necessary, 0 otherwise."""
1455
1462
1456 if print_full == 1:
1463 if print_full == 1:
1457 page(header+str)
1464 page(header+str)
1458 return 0
1465 return 0
1459
1466
1460 print header,
1467 print header,
1461 if len(str) < width:
1468 if len(str) < width:
1462 print str
1469 print str
1463 snip = 0
1470 snip = 0
1464 else:
1471 else:
1465 whalf = int((width -5)/2)
1472 whalf = int((width -5)/2)
1466 print str[:whalf] + ' <...> ' + str[-whalf:]
1473 print str[:whalf] + ' <...> ' + str[-whalf:]
1467 snip = 1
1474 snip = 1
1468 if snip and print_full == 2:
1475 if snip and print_full == 2:
1469 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1476 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1470 page(str)
1477 page(str)
1471 return snip
1478 return snip
1472
1479
1473 #****************************************************************************
1480 #****************************************************************************
1474 # lists, dicts and structures
1481 # lists, dicts and structures
1475
1482
1476 def belong(candidates,checklist):
1483 def belong(candidates,checklist):
1477 """Check whether a list of items appear in a given list of options.
1484 """Check whether a list of items appear in a given list of options.
1478
1485
1479 Returns a list of 1 and 0, one for each candidate given."""
1486 Returns a list of 1 and 0, one for each candidate given."""
1480
1487
1481 return [x in checklist for x in candidates]
1488 return [x in checklist for x in candidates]
1482
1489
1483 #----------------------------------------------------------------------------
1490 #----------------------------------------------------------------------------
1484 def uniq_stable(elems):
1491 def uniq_stable(elems):
1485 """uniq_stable(elems) -> list
1492 """uniq_stable(elems) -> list
1486
1493
1487 Return from an iterable, a list of all the unique elements in the input,
1494 Return from an iterable, a list of all the unique elements in the input,
1488 but maintaining the order in which they first appear.
1495 but maintaining the order in which they first appear.
1489
1496
1490 A naive solution to this problem which just makes a dictionary with the
1497 A naive solution to this problem which just makes a dictionary with the
1491 elements as keys fails to respect the stability condition, since
1498 elements as keys fails to respect the stability condition, since
1492 dictionaries are unsorted by nature.
1499 dictionaries are unsorted by nature.
1493
1500
1494 Note: All elements in the input must be valid dictionary keys for this
1501 Note: All elements in the input must be valid dictionary keys for this
1495 routine to work, as it internally uses a dictionary for efficiency
1502 routine to work, as it internally uses a dictionary for efficiency
1496 reasons."""
1503 reasons."""
1497
1504
1498 unique = []
1505 unique = []
1499 unique_dict = {}
1506 unique_dict = {}
1500 for nn in elems:
1507 for nn in elems:
1501 if nn not in unique_dict:
1508 if nn not in unique_dict:
1502 unique.append(nn)
1509 unique.append(nn)
1503 unique_dict[nn] = None
1510 unique_dict[nn] = None
1504 return unique
1511 return unique
1505
1512
1506 #----------------------------------------------------------------------------
1513 #----------------------------------------------------------------------------
1507 class NLprinter:
1514 class NLprinter:
1508 """Print an arbitrarily nested list, indicating index numbers.
1515 """Print an arbitrarily nested list, indicating index numbers.
1509
1516
1510 An instance of this class called nlprint is available and callable as a
1517 An instance of this class called nlprint is available and callable as a
1511 function.
1518 function.
1512
1519
1513 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1520 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1514 and using 'sep' to separate the index from the value. """
1521 and using 'sep' to separate the index from the value. """
1515
1522
1516 def __init__(self):
1523 def __init__(self):
1517 self.depth = 0
1524 self.depth = 0
1518
1525
1519 def __call__(self,lst,pos='',**kw):
1526 def __call__(self,lst,pos='',**kw):
1520 """Prints the nested list numbering levels."""
1527 """Prints the nested list numbering levels."""
1521 kw.setdefault('indent',' ')
1528 kw.setdefault('indent',' ')
1522 kw.setdefault('sep',': ')
1529 kw.setdefault('sep',': ')
1523 kw.setdefault('start',0)
1530 kw.setdefault('start',0)
1524 kw.setdefault('stop',len(lst))
1531 kw.setdefault('stop',len(lst))
1525 # we need to remove start and stop from kw so they don't propagate
1532 # we need to remove start and stop from kw so they don't propagate
1526 # into a recursive call for a nested list.
1533 # into a recursive call for a nested list.
1527 start = kw['start']; del kw['start']
1534 start = kw['start']; del kw['start']
1528 stop = kw['stop']; del kw['stop']
1535 stop = kw['stop']; del kw['stop']
1529 if self.depth == 0 and 'header' in kw.keys():
1536 if self.depth == 0 and 'header' in kw.keys():
1530 print kw['header']
1537 print kw['header']
1531
1538
1532 for idx in range(start,stop):
1539 for idx in range(start,stop):
1533 elem = lst[idx]
1540 elem = lst[idx]
1534 if type(elem)==type([]):
1541 if type(elem)==type([]):
1535 self.depth += 1
1542 self.depth += 1
1536 self.__call__(elem,itpl('$pos$idx,'),**kw)
1543 self.__call__(elem,itpl('$pos$idx,'),**kw)
1537 self.depth -= 1
1544 self.depth -= 1
1538 else:
1545 else:
1539 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1546 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1540
1547
1541 nlprint = NLprinter()
1548 nlprint = NLprinter()
1542 #----------------------------------------------------------------------------
1549 #----------------------------------------------------------------------------
1543 def all_belong(candidates,checklist):
1550 def all_belong(candidates,checklist):
1544 """Check whether a list of items ALL appear in a given list of options.
1551 """Check whether a list of items ALL appear in a given list of options.
1545
1552
1546 Returns a single 1 or 0 value."""
1553 Returns a single 1 or 0 value."""
1547
1554
1548 return 1-(0 in [x in checklist for x in candidates])
1555 return 1-(0 in [x in checklist for x in candidates])
1549
1556
1550 #----------------------------------------------------------------------------
1557 #----------------------------------------------------------------------------
1551 def sort_compare(lst1,lst2,inplace = 1):
1558 def sort_compare(lst1,lst2,inplace = 1):
1552 """Sort and compare two lists.
1559 """Sort and compare two lists.
1553
1560
1554 By default it does it in place, thus modifying the lists. Use inplace = 0
1561 By default it does it in place, thus modifying the lists. Use inplace = 0
1555 to avoid that (at the cost of temporary copy creation)."""
1562 to avoid that (at the cost of temporary copy creation)."""
1556 if not inplace:
1563 if not inplace:
1557 lst1 = lst1[:]
1564 lst1 = lst1[:]
1558 lst2 = lst2[:]
1565 lst2 = lst2[:]
1559 lst1.sort(); lst2.sort()
1566 lst1.sort(); lst2.sort()
1560 return lst1 == lst2
1567 return lst1 == lst2
1561
1568
1562 #----------------------------------------------------------------------------
1569 #----------------------------------------------------------------------------
1563 def mkdict(**kwargs):
1570 def mkdict(**kwargs):
1564 """Return a dict from a keyword list.
1571 """Return a dict from a keyword list.
1565
1572
1566 It's just syntactic sugar for making ditcionary creation more convenient:
1573 It's just syntactic sugar for making ditcionary creation more convenient:
1567 # the standard way
1574 # the standard way
1568 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1575 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1569 # a cleaner way
1576 # a cleaner way
1570 >>>data = dict(red=1, green=2, blue=3)
1577 >>>data = dict(red=1, green=2, blue=3)
1571
1578
1572 If you need more than this, look at the Struct() class."""
1579 If you need more than this, look at the Struct() class."""
1573
1580
1574 return kwargs
1581 return kwargs
1575
1582
1576 #----------------------------------------------------------------------------
1583 #----------------------------------------------------------------------------
1577 def list2dict(lst):
1584 def list2dict(lst):
1578 """Takes a list of (key,value) pairs and turns it into a dict."""
1585 """Takes a list of (key,value) pairs and turns it into a dict."""
1579
1586
1580 dic = {}
1587 dic = {}
1581 for k,v in lst: dic[k] = v
1588 for k,v in lst: dic[k] = v
1582 return dic
1589 return dic
1583
1590
1584 #----------------------------------------------------------------------------
1591 #----------------------------------------------------------------------------
1585 def list2dict2(lst,default=''):
1592 def list2dict2(lst,default=''):
1586 """Takes a list and turns it into a dict.
1593 """Takes a list and turns it into a dict.
1587 Much slower than list2dict, but more versatile. This version can take
1594 Much slower than list2dict, but more versatile. This version can take
1588 lists with sublists of arbitrary length (including sclars)."""
1595 lists with sublists of arbitrary length (including sclars)."""
1589
1596
1590 dic = {}
1597 dic = {}
1591 for elem in lst:
1598 for elem in lst:
1592 if type(elem) in (types.ListType,types.TupleType):
1599 if type(elem) in (types.ListType,types.TupleType):
1593 size = len(elem)
1600 size = len(elem)
1594 if size == 0:
1601 if size == 0:
1595 pass
1602 pass
1596 elif size == 1:
1603 elif size == 1:
1597 dic[elem] = default
1604 dic[elem] = default
1598 else:
1605 else:
1599 k,v = elem[0], elem[1:]
1606 k,v = elem[0], elem[1:]
1600 if len(v) == 1: v = v[0]
1607 if len(v) == 1: v = v[0]
1601 dic[k] = v
1608 dic[k] = v
1602 else:
1609 else:
1603 dic[elem] = default
1610 dic[elem] = default
1604 return dic
1611 return dic
1605
1612
1606 #----------------------------------------------------------------------------
1613 #----------------------------------------------------------------------------
1607 def flatten(seq):
1614 def flatten(seq):
1608 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1615 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1609
1616
1610 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1617 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1611
1618
1612 # if the x=0 isn't made, a *global* variable x is left over after calling
1619 # if the x=0 isn't made, a *global* variable x is left over after calling
1613 # this function, with the value of the last element in the return
1620 # this function, with the value of the last element in the return
1614 # list. This does seem like a bug big time to me.
1621 # list. This does seem like a bug big time to me.
1615
1622
1616 # the problem is fixed with the x=0, which seems to force the creation of
1623 # the problem is fixed with the x=0, which seems to force the creation of
1617 # a local name
1624 # a local name
1618
1625
1619 x = 0
1626 x = 0
1620 return [x for subseq in seq for x in subseq]
1627 return [x for subseq in seq for x in subseq]
1621
1628
1622 #----------------------------------------------------------------------------
1629 #----------------------------------------------------------------------------
1623 def get_slice(seq,start=0,stop=None,step=1):
1630 def get_slice(seq,start=0,stop=None,step=1):
1624 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1631 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1625 if stop == None:
1632 if stop == None:
1626 stop = len(seq)
1633 stop = len(seq)
1627 item = lambda i: seq[i]
1634 item = lambda i: seq[i]
1628 return map(item,xrange(start,stop,step))
1635 return map(item,xrange(start,stop,step))
1629
1636
1630 #----------------------------------------------------------------------------
1637 #----------------------------------------------------------------------------
1631 def chop(seq,size):
1638 def chop(seq,size):
1632 """Chop a sequence into chunks of the given size."""
1639 """Chop a sequence into chunks of the given size."""
1633 chunk = lambda i: seq[i:i+size]
1640 chunk = lambda i: seq[i:i+size]
1634 return map(chunk,xrange(0,len(seq),size))
1641 return map(chunk,xrange(0,len(seq),size))
1635
1642
1636 #----------------------------------------------------------------------------
1643 #----------------------------------------------------------------------------
1637 def with(object, **args):
1644 def with(object, **args):
1638 """Set multiple attributes for an object, similar to Pascal's with.
1645 """Set multiple attributes for an object, similar to Pascal's with.
1639
1646
1640 Example:
1647 Example:
1641 with(jim,
1648 with(jim,
1642 born = 1960,
1649 born = 1960,
1643 haircolour = 'Brown',
1650 haircolour = 'Brown',
1644 eyecolour = 'Green')
1651 eyecolour = 'Green')
1645
1652
1646 Credit: Greg Ewing, in
1653 Credit: Greg Ewing, in
1647 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1654 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1648
1655
1649 object.__dict__.update(args)
1656 object.__dict__.update(args)
1650
1657
1651 #----------------------------------------------------------------------------
1658 #----------------------------------------------------------------------------
1652 def setattr_list(obj,alist,nspace = None):
1659 def setattr_list(obj,alist,nspace = None):
1653 """Set a list of attributes for an object taken from a namespace.
1660 """Set a list of attributes for an object taken from a namespace.
1654
1661
1655 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1662 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1656 alist with their values taken from nspace, which must be a dict (something
1663 alist with their values taken from nspace, which must be a dict (something
1657 like locals() will often do) If nspace isn't given, locals() of the
1664 like locals() will often do) If nspace isn't given, locals() of the
1658 *caller* is used, so in most cases you can omit it.
1665 *caller* is used, so in most cases you can omit it.
1659
1666
1660 Note that alist can be given as a string, which will be automatically
1667 Note that alist can be given as a string, which will be automatically
1661 split into a list on whitespace. If given as a list, it must be a list of
1668 split into a list on whitespace. If given as a list, it must be a list of
1662 *strings* (the variable names themselves), not of variables."""
1669 *strings* (the variable names themselves), not of variables."""
1663
1670
1664 # this grabs the local variables from the *previous* call frame -- that is
1671 # this grabs the local variables from the *previous* call frame -- that is
1665 # the locals from the function that called setattr_list().
1672 # the locals from the function that called setattr_list().
1666 # - snipped from weave.inline()
1673 # - snipped from weave.inline()
1667 if nspace is None:
1674 if nspace is None:
1668 call_frame = sys._getframe().f_back
1675 call_frame = sys._getframe().f_back
1669 nspace = call_frame.f_locals
1676 nspace = call_frame.f_locals
1670
1677
1671 if type(alist) in StringTypes:
1678 if type(alist) in StringTypes:
1672 alist = alist.split()
1679 alist = alist.split()
1673 for attr in alist:
1680 for attr in alist:
1674 val = eval(attr,nspace)
1681 val = eval(attr,nspace)
1675 setattr(obj,attr,val)
1682 setattr(obj,attr,val)
1676
1683
1677 #----------------------------------------------------------------------------
1684 #----------------------------------------------------------------------------
1678 def getattr_list(obj,alist,*args):
1685 def getattr_list(obj,alist,*args):
1679 """getattr_list(obj,alist[, default]) -> attribute list.
1686 """getattr_list(obj,alist[, default]) -> attribute list.
1680
1687
1681 Get a list of named attributes for an object. When a default argument is
1688 Get a list of named attributes for an object. When a default argument is
1682 given, it is returned when the attribute doesn't exist; without it, an
1689 given, it is returned when the attribute doesn't exist; without it, an
1683 exception is raised in that case.
1690 exception is raised in that case.
1684
1691
1685 Note that alist can be given as a string, which will be automatically
1692 Note that alist can be given as a string, which will be automatically
1686 split into a list on whitespace. If given as a list, it must be a list of
1693 split into a list on whitespace. If given as a list, it must be a list of
1687 *strings* (the variable names themselves), not of variables."""
1694 *strings* (the variable names themselves), not of variables."""
1688
1695
1689 if type(alist) in StringTypes:
1696 if type(alist) in StringTypes:
1690 alist = alist.split()
1697 alist = alist.split()
1691 if args:
1698 if args:
1692 if len(args)==1:
1699 if len(args)==1:
1693 default = args[0]
1700 default = args[0]
1694 return map(lambda attr: getattr(obj,attr,default),alist)
1701 return map(lambda attr: getattr(obj,attr,default),alist)
1695 else:
1702 else:
1696 raise ValueError,'getattr_list() takes only one optional argument'
1703 raise ValueError,'getattr_list() takes only one optional argument'
1697 else:
1704 else:
1698 return map(lambda attr: getattr(obj,attr),alist)
1705 return map(lambda attr: getattr(obj,attr),alist)
1699
1706
1700 #----------------------------------------------------------------------------
1707 #----------------------------------------------------------------------------
1701 def map_method(method,object_list,*argseq,**kw):
1708 def map_method(method,object_list,*argseq,**kw):
1702 """map_method(method,object_list,*args,**kw) -> list
1709 """map_method(method,object_list,*args,**kw) -> list
1703
1710
1704 Return a list of the results of applying the methods to the items of the
1711 Return a list of the results of applying the methods to the items of the
1705 argument sequence(s). If more than one sequence is given, the method is
1712 argument sequence(s). If more than one sequence is given, the method is
1706 called with an argument list consisting of the corresponding item of each
1713 called with an argument list consisting of the corresponding item of each
1707 sequence. All sequences must be of the same length.
1714 sequence. All sequences must be of the same length.
1708
1715
1709 Keyword arguments are passed verbatim to all objects called.
1716 Keyword arguments are passed verbatim to all objects called.
1710
1717
1711 This is Python code, so it's not nearly as fast as the builtin map()."""
1718 This is Python code, so it's not nearly as fast as the builtin map()."""
1712
1719
1713 out_list = []
1720 out_list = []
1714 idx = 0
1721 idx = 0
1715 for object in object_list:
1722 for object in object_list:
1716 try:
1723 try:
1717 handler = getattr(object, method)
1724 handler = getattr(object, method)
1718 except AttributeError:
1725 except AttributeError:
1719 out_list.append(None)
1726 out_list.append(None)
1720 else:
1727 else:
1721 if argseq:
1728 if argseq:
1722 args = map(lambda lst:lst[idx],argseq)
1729 args = map(lambda lst:lst[idx],argseq)
1723 #print 'ob',object,'hand',handler,'ar',args # dbg
1730 #print 'ob',object,'hand',handler,'ar',args # dbg
1724 out_list.append(handler(args,**kw))
1731 out_list.append(handler(args,**kw))
1725 else:
1732 else:
1726 out_list.append(handler(**kw))
1733 out_list.append(handler(**kw))
1727 idx += 1
1734 idx += 1
1728 return out_list
1735 return out_list
1729
1736
1730 #----------------------------------------------------------------------------
1737 #----------------------------------------------------------------------------
1731 def import_fail_info(mod_name,fns=None):
1738 def import_fail_info(mod_name,fns=None):
1732 """Inform load failure for a module."""
1739 """Inform load failure for a module."""
1733
1740
1734 if fns == None:
1741 if fns == None:
1735 warn("Loading of %s failed.\n" % (mod_name,))
1742 warn("Loading of %s failed.\n" % (mod_name,))
1736 else:
1743 else:
1737 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1744 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1738
1745
1739 #----------------------------------------------------------------------------
1746 #----------------------------------------------------------------------------
1740 # Proposed popitem() extension, written as a method
1747 # Proposed popitem() extension, written as a method
1741
1748
1742 class NotGiven: pass
1749 class NotGiven: pass
1743
1750
1744 def popkey(dct,key,default=NotGiven):
1751 def popkey(dct,key,default=NotGiven):
1745 """Return dct[key] and delete dct[key].
1752 """Return dct[key] and delete dct[key].
1746
1753
1747 If default is given, return it if dct[key] doesn't exist, otherwise raise
1754 If default is given, return it if dct[key] doesn't exist, otherwise raise
1748 KeyError. """
1755 KeyError. """
1749
1756
1750 try:
1757 try:
1751 val = dct[key]
1758 val = dct[key]
1752 except KeyError:
1759 except KeyError:
1753 if default is NotGiven:
1760 if default is NotGiven:
1754 raise
1761 raise
1755 else:
1762 else:
1756 return default
1763 return default
1757 else:
1764 else:
1758 del dct[key]
1765 del dct[key]
1759 return val
1766 return val
1760 #*************************** end of file <genutils.py> **********************
1767 #*************************** end of file <genutils.py> **********************
1761
1768
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