##// END OF EJS Templates
- Fix unicode bug in %psearch reported by Stefan.
fperez -
Show More

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

@@ -1,3101 +1,3109 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 2187 2007-03-30 04:56:40Z fperez $"""
4 $Id: Magic.py 2190 2007-03-30 18:35:46Z 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 # cProfile was added in Python2.5
39 # cProfile was added in Python2.5
40 try:
40 try:
41 import cProfile as profile
41 import cProfile as profile
42 import pstats
42 import pstats
43 except ImportError:
43 except ImportError:
44 # profile isn't bundled by default in Debian for license reasons
44 # profile isn't bundled by default in Debian for license reasons
45 try:
45 try:
46 import profile,pstats
46 import profile,pstats
47 except ImportError:
47 except ImportError:
48 profile = pstats = None
48 profile = pstats = None
49
49
50 # Homebrewed
50 # Homebrewed
51 import IPython
51 import IPython
52 from IPython import Debugger, OInspect, wildcard
52 from IPython import Debugger, OInspect, wildcard
53 from IPython.FakeModule import FakeModule
53 from IPython.FakeModule import FakeModule
54 from IPython.Itpl import Itpl, itpl, printpl,itplns
54 from IPython.Itpl import Itpl, itpl, printpl,itplns
55 from IPython.PyColorize import Parser
55 from IPython.PyColorize import Parser
56 from IPython.ipstruct import Struct
56 from IPython.ipstruct import Struct
57 from IPython.macro import Macro
57 from IPython.macro import Macro
58 from IPython.genutils import *
58 from IPython.genutils import *
59 from IPython import platutils
59 from IPython import platutils
60
60
61 #***************************************************************************
61 #***************************************************************************
62 # Utility functions
62 # Utility functions
63 def on_off(tag):
63 def on_off(tag):
64 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
64 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
65 return ['OFF','ON'][tag]
65 return ['OFF','ON'][tag]
66
66
67 class Bunch: pass
67 class Bunch: pass
68
68
69 #***************************************************************************
69 #***************************************************************************
70 # Main class implementing Magic functionality
70 # Main class implementing Magic functionality
71 class Magic:
71 class Magic:
72 """Magic functions for InteractiveShell.
72 """Magic functions for InteractiveShell.
73
73
74 Shell functions which can be reached as %function_name. All magic
74 Shell functions which can be reached as %function_name. All magic
75 functions should accept a string, which they can parse for their own
75 functions should accept a string, which they can parse for their own
76 needs. This can make some functions easier to type, eg `%cd ../`
76 needs. This can make some functions easier to type, eg `%cd ../`
77 vs. `%cd("../")`
77 vs. `%cd("../")`
78
78
79 ALL definitions MUST begin with the prefix magic_. The user won't need it
79 ALL definitions MUST begin with the prefix magic_. The user won't need it
80 at the command line, but it is is needed in the definition. """
80 at the command line, but it is is needed in the definition. """
81
81
82 # class globals
82 # class globals
83 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
83 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
84 'Automagic is ON, % prefix NOT needed for magic functions.']
84 'Automagic is ON, % prefix NOT needed for magic functions.']
85
85
86 #......................................................................
86 #......................................................................
87 # some utility functions
87 # some utility functions
88
88
89 def __init__(self,shell):
89 def __init__(self,shell):
90
90
91 self.options_table = {}
91 self.options_table = {}
92 if profile is None:
92 if profile is None:
93 self.magic_prun = self.profile_missing_notice
93 self.magic_prun = self.profile_missing_notice
94 self.shell = shell
94 self.shell = shell
95
95
96 # namespace for holding state we may need
96 # namespace for holding state we may need
97 self._magic_state = Bunch()
97 self._magic_state = Bunch()
98
98
99 def profile_missing_notice(self, *args, **kwargs):
99 def profile_missing_notice(self, *args, **kwargs):
100 error("""\
100 error("""\
101 The profile module could not be found. If you are a Debian user,
101 The profile module could not be found. If you are a Debian user,
102 it has been removed from the standard Debian package because of its non-free
102 it has been removed from the standard Debian package because of its non-free
103 license. To use profiling, please install"python2.3-profiler" from non-free.""")
103 license. To use profiling, please install"python2.3-profiler" from non-free.""")
104
104
105 def default_option(self,fn,optstr):
105 def default_option(self,fn,optstr):
106 """Make an entry in the options_table for fn, with value optstr"""
106 """Make an entry in the options_table for fn, with value optstr"""
107
107
108 if fn not in self.lsmagic():
108 if fn not in self.lsmagic():
109 error("%s is not a magic function" % fn)
109 error("%s is not a magic function" % fn)
110 self.options_table[fn] = optstr
110 self.options_table[fn] = optstr
111
111
112 def lsmagic(self):
112 def lsmagic(self):
113 """Return a list of currently available magic functions.
113 """Return a list of currently available magic functions.
114
114
115 Gives a list of the bare names after mangling (['ls','cd', ...], not
115 Gives a list of the bare names after mangling (['ls','cd', ...], not
116 ['magic_ls','magic_cd',...]"""
116 ['magic_ls','magic_cd',...]"""
117
117
118 # FIXME. This needs a cleanup, in the way the magics list is built.
118 # FIXME. This needs a cleanup, in the way the magics list is built.
119
119
120 # magics in class definition
120 # magics in class definition
121 class_magic = lambda fn: fn.startswith('magic_') and \
121 class_magic = lambda fn: fn.startswith('magic_') and \
122 callable(Magic.__dict__[fn])
122 callable(Magic.__dict__[fn])
123 # in instance namespace (run-time user additions)
123 # in instance namespace (run-time user additions)
124 inst_magic = lambda fn: fn.startswith('magic_') and \
124 inst_magic = lambda fn: fn.startswith('magic_') and \
125 callable(self.__dict__[fn])
125 callable(self.__dict__[fn])
126 # and bound magics by user (so they can access self):
126 # and bound magics by user (so they can access self):
127 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
127 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
128 callable(self.__class__.__dict__[fn])
128 callable(self.__class__.__dict__[fn])
129 magics = filter(class_magic,Magic.__dict__.keys()) + \
129 magics = filter(class_magic,Magic.__dict__.keys()) + \
130 filter(inst_magic,self.__dict__.keys()) + \
130 filter(inst_magic,self.__dict__.keys()) + \
131 filter(inst_bound_magic,self.__class__.__dict__.keys())
131 filter(inst_bound_magic,self.__class__.__dict__.keys())
132 out = []
132 out = []
133 for fn in magics:
133 for fn in magics:
134 out.append(fn.replace('magic_','',1))
134 out.append(fn.replace('magic_','',1))
135 out.sort()
135 out.sort()
136 return out
136 return out
137
137
138 def extract_input_slices(self,slices,raw=False):
138 def extract_input_slices(self,slices,raw=False):
139 """Return as a string a set of input history slices.
139 """Return as a string a set of input history slices.
140
140
141 Inputs:
141 Inputs:
142
142
143 - slices: the set of slices is given as a list of strings (like
143 - slices: the set of slices is given as a list of strings (like
144 ['1','4:8','9'], since this function is for use by magic functions
144 ['1','4:8','9'], since this function is for use by magic functions
145 which get their arguments as strings.
145 which get their arguments as strings.
146
146
147 Optional inputs:
147 Optional inputs:
148
148
149 - raw(False): by default, the processed input is used. If this is
149 - raw(False): by default, the processed input is used. If this is
150 true, the raw input history is used instead.
150 true, the raw input history is used instead.
151
151
152 Note that slices can be called with two notations:
152 Note that slices can be called with two notations:
153
153
154 N:M -> standard python form, means including items N...(M-1).
154 N:M -> standard python form, means including items N...(M-1).
155
155
156 N-M -> include items N..M (closed endpoint)."""
156 N-M -> include items N..M (closed endpoint)."""
157
157
158 if raw:
158 if raw:
159 hist = self.shell.input_hist_raw
159 hist = self.shell.input_hist_raw
160 else:
160 else:
161 hist = self.shell.input_hist
161 hist = self.shell.input_hist
162
162
163 cmds = []
163 cmds = []
164 for chunk in slices:
164 for chunk in slices:
165 if ':' in chunk:
165 if ':' in chunk:
166 ini,fin = map(int,chunk.split(':'))
166 ini,fin = map(int,chunk.split(':'))
167 elif '-' in chunk:
167 elif '-' in chunk:
168 ini,fin = map(int,chunk.split('-'))
168 ini,fin = map(int,chunk.split('-'))
169 fin += 1
169 fin += 1
170 else:
170 else:
171 ini = int(chunk)
171 ini = int(chunk)
172 fin = ini+1
172 fin = ini+1
173 cmds.append(hist[ini:fin])
173 cmds.append(hist[ini:fin])
174 return cmds
174 return cmds
175
175
176 def _ofind(self, oname, namespaces=None):
176 def _ofind(self, oname, namespaces=None):
177 """Find an object in the available namespaces.
177 """Find an object in the available namespaces.
178
178
179 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
179 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
180
180
181 Has special code to detect magic functions.
181 Has special code to detect magic functions.
182 """
182 """
183
183
184 oname = oname.strip()
184 oname = oname.strip()
185
185
186 alias_ns = None
186 alias_ns = None
187 if namespaces is None:
187 if namespaces is None:
188 # Namespaces to search in:
188 # Namespaces to search in:
189 # Put them in a list. The order is important so that we
189 # Put them in a list. The order is important so that we
190 # find things in the same order that Python finds them.
190 # find things in the same order that Python finds them.
191 namespaces = [ ('Interactive', self.shell.user_ns),
191 namespaces = [ ('Interactive', self.shell.user_ns),
192 ('IPython internal', self.shell.internal_ns),
192 ('IPython internal', self.shell.internal_ns),
193 ('Python builtin', __builtin__.__dict__),
193 ('Python builtin', __builtin__.__dict__),
194 ('Alias', self.shell.alias_table),
194 ('Alias', self.shell.alias_table),
195 ]
195 ]
196 alias_ns = self.shell.alias_table
196 alias_ns = self.shell.alias_table
197
197
198 # initialize results to 'null'
198 # initialize results to 'null'
199 found = 0; obj = None; ospace = None; ds = None;
199 found = 0; obj = None; ospace = None; ds = None;
200 ismagic = 0; isalias = 0; parent = None
200 ismagic = 0; isalias = 0; parent = None
201
201
202 # Look for the given name by splitting it in parts. If the head is
202 # Look for the given name by splitting it in parts. If the head is
203 # found, then we look for all the remaining parts as members, and only
203 # found, then we look for all the remaining parts as members, and only
204 # declare success if we can find them all.
204 # declare success if we can find them all.
205 oname_parts = oname.split('.')
205 oname_parts = oname.split('.')
206 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
206 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
207 for nsname,ns in namespaces:
207 for nsname,ns in namespaces:
208 try:
208 try:
209 obj = ns[oname_head]
209 obj = ns[oname_head]
210 except KeyError:
210 except KeyError:
211 continue
211 continue
212 else:
212 else:
213 #print 'oname_rest:', oname_rest # dbg
213 #print 'oname_rest:', oname_rest # dbg
214 for part in oname_rest:
214 for part in oname_rest:
215 try:
215 try:
216 parent = obj
216 parent = obj
217 obj = getattr(obj,part)
217 obj = getattr(obj,part)
218 except:
218 except:
219 # Blanket except b/c some badly implemented objects
219 # Blanket except b/c some badly implemented objects
220 # allow __getattr__ to raise exceptions other than
220 # allow __getattr__ to raise exceptions other than
221 # AttributeError, which then crashes IPython.
221 # AttributeError, which then crashes IPython.
222 break
222 break
223 else:
223 else:
224 # If we finish the for loop (no break), we got all members
224 # If we finish the for loop (no break), we got all members
225 found = 1
225 found = 1
226 ospace = nsname
226 ospace = nsname
227 if ns == alias_ns:
227 if ns == alias_ns:
228 isalias = 1
228 isalias = 1
229 break # namespace loop
229 break # namespace loop
230
230
231 # Try to see if it's magic
231 # Try to see if it's magic
232 if not found:
232 if not found:
233 if oname.startswith(self.shell.ESC_MAGIC):
233 if oname.startswith(self.shell.ESC_MAGIC):
234 oname = oname[1:]
234 oname = oname[1:]
235 obj = getattr(self,'magic_'+oname,None)
235 obj = getattr(self,'magic_'+oname,None)
236 if obj is not None:
236 if obj is not None:
237 found = 1
237 found = 1
238 ospace = 'IPython internal'
238 ospace = 'IPython internal'
239 ismagic = 1
239 ismagic = 1
240
240
241 # Last try: special-case some literals like '', [], {}, etc:
241 # Last try: special-case some literals like '', [], {}, etc:
242 if not found and oname_head in ["''",'""','[]','{}','()']:
242 if not found and oname_head in ["''",'""','[]','{}','()']:
243 obj = eval(oname_head)
243 obj = eval(oname_head)
244 found = 1
244 found = 1
245 ospace = 'Interactive'
245 ospace = 'Interactive'
246
246
247 return {'found':found, 'obj':obj, 'namespace':ospace,
247 return {'found':found, 'obj':obj, 'namespace':ospace,
248 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
248 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
249
249
250 def arg_err(self,func):
250 def arg_err(self,func):
251 """Print docstring if incorrect arguments were passed"""
251 """Print docstring if incorrect arguments were passed"""
252 print 'Error in arguments:'
252 print 'Error in arguments:'
253 print OInspect.getdoc(func)
253 print OInspect.getdoc(func)
254
254
255 def format_latex(self,strng):
255 def format_latex(self,strng):
256 """Format a string for latex inclusion."""
256 """Format a string for latex inclusion."""
257
257
258 # Characters that need to be escaped for latex:
258 # Characters that need to be escaped for latex:
259 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
259 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
260 # Magic command names as headers:
260 # Magic command names as headers:
261 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
261 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
262 re.MULTILINE)
262 re.MULTILINE)
263 # Magic commands
263 # Magic commands
264 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
264 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
265 re.MULTILINE)
265 re.MULTILINE)
266 # Paragraph continue
266 # Paragraph continue
267 par_re = re.compile(r'\\$',re.MULTILINE)
267 par_re = re.compile(r'\\$',re.MULTILINE)
268
268
269 # The "\n" symbol
269 # The "\n" symbol
270 newline_re = re.compile(r'\\n')
270 newline_re = re.compile(r'\\n')
271
271
272 # Now build the string for output:
272 # Now build the string for output:
273 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
273 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
274 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
274 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
275 strng)
275 strng)
276 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
276 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
277 strng = par_re.sub(r'\\\\',strng)
277 strng = par_re.sub(r'\\\\',strng)
278 strng = escape_re.sub(r'\\\1',strng)
278 strng = escape_re.sub(r'\\\1',strng)
279 strng = newline_re.sub(r'\\textbackslash{}n',strng)
279 strng = newline_re.sub(r'\\textbackslash{}n',strng)
280 return strng
280 return strng
281
281
282 def format_screen(self,strng):
282 def format_screen(self,strng):
283 """Format a string for screen printing.
283 """Format a string for screen printing.
284
284
285 This removes some latex-type format codes."""
285 This removes some latex-type format codes."""
286 # Paragraph continue
286 # Paragraph continue
287 par_re = re.compile(r'\\$',re.MULTILINE)
287 par_re = re.compile(r'\\$',re.MULTILINE)
288 strng = par_re.sub('',strng)
288 strng = par_re.sub('',strng)
289 return strng
289 return strng
290
290
291 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
291 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
292 """Parse options passed to an argument string.
292 """Parse options passed to an argument string.
293
293
294 The interface is similar to that of getopt(), but it returns back a
294 The interface is similar to that of getopt(), but it returns back a
295 Struct with the options as keys and the stripped argument string still
295 Struct with the options as keys and the stripped argument string still
296 as a string.
296 as a string.
297
297
298 arg_str is quoted as a true sys.argv vector by using shlex.split.
298 arg_str is quoted as a true sys.argv vector by using shlex.split.
299 This allows us to easily expand variables, glob files, quote
299 This allows us to easily expand variables, glob files, quote
300 arguments, etc.
300 arguments, etc.
301
301
302 Options:
302 Options:
303 -mode: default 'string'. If given as 'list', the argument string is
303 -mode: default 'string'. If given as 'list', the argument string is
304 returned as a list (split on whitespace) instead of a string.
304 returned as a list (split on whitespace) instead of a string.
305
305
306 -list_all: put all option values in lists. Normally only options
306 -list_all: put all option values in lists. Normally only options
307 appearing more than once are put in a list.
307 appearing more than once are put in a list.
308
308
309 -posix (True): whether to split the input line in POSIX mode or not,
309 -posix (True): whether to split the input line in POSIX mode or not,
310 as per the conventions outlined in the shlex module from the
310 as per the conventions outlined in the shlex module from the
311 standard library."""
311 standard library."""
312
312
313 # inject default options at the beginning of the input line
313 # inject default options at the beginning of the input line
314 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
314 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
315 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
315 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
316
316
317 mode = kw.get('mode','string')
317 mode = kw.get('mode','string')
318 if mode not in ['string','list']:
318 if mode not in ['string','list']:
319 raise ValueError,'incorrect mode given: %s' % mode
319 raise ValueError,'incorrect mode given: %s' % mode
320 # Get options
320 # Get options
321 list_all = kw.get('list_all',0)
321 list_all = kw.get('list_all',0)
322 posix = kw.get('posix',True)
322 posix = kw.get('posix',True)
323
323
324 # Check if we have more than one argument to warrant extra processing:
324 # Check if we have more than one argument to warrant extra processing:
325 odict = {} # Dictionary with options
325 odict = {} # Dictionary with options
326 args = arg_str.split()
326 args = arg_str.split()
327 if len(args) >= 1:
327 if len(args) >= 1:
328 # If the list of inputs only has 0 or 1 thing in it, there's no
328 # If the list of inputs only has 0 or 1 thing in it, there's no
329 # need to look for options
329 # need to look for options
330 argv = arg_split(arg_str,posix)
330 argv = arg_split(arg_str,posix)
331 # Do regular option processing
331 # Do regular option processing
332 try:
332 try:
333 opts,args = getopt(argv,opt_str,*long_opts)
333 opts,args = getopt(argv,opt_str,*long_opts)
334 except GetoptError,e:
334 except GetoptError,e:
335 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
335 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
336 " ".join(long_opts)))
336 " ".join(long_opts)))
337 for o,a in opts:
337 for o,a in opts:
338 if o.startswith('--'):
338 if o.startswith('--'):
339 o = o[2:]
339 o = o[2:]
340 else:
340 else:
341 o = o[1:]
341 o = o[1:]
342 try:
342 try:
343 odict[o].append(a)
343 odict[o].append(a)
344 except AttributeError:
344 except AttributeError:
345 odict[o] = [odict[o],a]
345 odict[o] = [odict[o],a]
346 except KeyError:
346 except KeyError:
347 if list_all:
347 if list_all:
348 odict[o] = [a]
348 odict[o] = [a]
349 else:
349 else:
350 odict[o] = a
350 odict[o] = a
351
351
352 # Prepare opts,args for return
352 # Prepare opts,args for return
353 opts = Struct(odict)
353 opts = Struct(odict)
354 if mode == 'string':
354 if mode == 'string':
355 args = ' '.join(args)
355 args = ' '.join(args)
356
356
357 return opts,args
357 return opts,args
358
358
359 #......................................................................
359 #......................................................................
360 # And now the actual magic functions
360 # And now the actual magic functions
361
361
362 # Functions for IPython shell work (vars,funcs, config, etc)
362 # Functions for IPython shell work (vars,funcs, config, etc)
363 def magic_lsmagic(self, parameter_s = ''):
363 def magic_lsmagic(self, parameter_s = ''):
364 """List currently available magic functions."""
364 """List currently available magic functions."""
365 mesc = self.shell.ESC_MAGIC
365 mesc = self.shell.ESC_MAGIC
366 print 'Available magic functions:\n'+mesc+\
366 print 'Available magic functions:\n'+mesc+\
367 (' '+mesc).join(self.lsmagic())
367 (' '+mesc).join(self.lsmagic())
368 print '\n' + Magic.auto_status[self.shell.rc.automagic]
368 print '\n' + Magic.auto_status[self.shell.rc.automagic]
369 return None
369 return None
370
370
371 def magic_magic(self, parameter_s = ''):
371 def magic_magic(self, parameter_s = ''):
372 """Print information about the magic function system."""
372 """Print information about the magic function system."""
373
373
374 mode = ''
374 mode = ''
375 try:
375 try:
376 if parameter_s.split()[0] == '-latex':
376 if parameter_s.split()[0] == '-latex':
377 mode = 'latex'
377 mode = 'latex'
378 if parameter_s.split()[0] == '-brief':
378 if parameter_s.split()[0] == '-brief':
379 mode = 'brief'
379 mode = 'brief'
380 except:
380 except:
381 pass
381 pass
382
382
383 magic_docs = []
383 magic_docs = []
384 for fname in self.lsmagic():
384 for fname in self.lsmagic():
385 mname = 'magic_' + fname
385 mname = 'magic_' + fname
386 for space in (Magic,self,self.__class__):
386 for space in (Magic,self,self.__class__):
387 try:
387 try:
388 fn = space.__dict__[mname]
388 fn = space.__dict__[mname]
389 except KeyError:
389 except KeyError:
390 pass
390 pass
391 else:
391 else:
392 break
392 break
393 if mode == 'brief':
393 if mode == 'brief':
394 # only first line
394 # only first line
395 fndoc = fn.__doc__.split('\n',1)[0]
395 fndoc = fn.__doc__.split('\n',1)[0]
396 else:
396 else:
397 fndoc = fn.__doc__
397 fndoc = fn.__doc__
398
398
399 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
399 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
400 fname,fndoc))
400 fname,fndoc))
401 magic_docs = ''.join(magic_docs)
401 magic_docs = ''.join(magic_docs)
402
402
403 if mode == 'latex':
403 if mode == 'latex':
404 print self.format_latex(magic_docs)
404 print self.format_latex(magic_docs)
405 return
405 return
406 else:
406 else:
407 magic_docs = self.format_screen(magic_docs)
407 magic_docs = self.format_screen(magic_docs)
408 if mode == 'brief':
408 if mode == 'brief':
409 return magic_docs
409 return magic_docs
410
410
411 outmsg = """
411 outmsg = """
412 IPython's 'magic' functions
412 IPython's 'magic' functions
413 ===========================
413 ===========================
414
414
415 The magic function system provides a series of functions which allow you to
415 The magic function system provides a series of functions which allow you to
416 control the behavior of IPython itself, plus a lot of system-type
416 control the behavior of IPython itself, plus a lot of system-type
417 features. All these functions are prefixed with a % character, but parameters
417 features. All these functions are prefixed with a % character, but parameters
418 are given without parentheses or quotes.
418 are given without parentheses or quotes.
419
419
420 NOTE: If you have 'automagic' enabled (via the command line option or with the
420 NOTE: If you have 'automagic' enabled (via the command line option or with the
421 %automagic function), you don't need to type in the % explicitly. By default,
421 %automagic function), you don't need to type in the % explicitly. By default,
422 IPython ships with automagic on, so you should only rarely need the % escape.
422 IPython ships with automagic on, so you should only rarely need the % escape.
423
423
424 Example: typing '%cd mydir' (without the quotes) changes you working directory
424 Example: typing '%cd mydir' (without the quotes) changes you working directory
425 to 'mydir', if it exists.
425 to 'mydir', if it exists.
426
426
427 You can define your own magic functions to extend the system. See the supplied
427 You can define your own magic functions to extend the system. See the supplied
428 ipythonrc and example-magic.py files for details (in your ipython
428 ipythonrc and example-magic.py files for details (in your ipython
429 configuration directory, typically $HOME/.ipython/).
429 configuration directory, typically $HOME/.ipython/).
430
430
431 You can also define your own aliased names for magic functions. In your
431 You can also define your own aliased names for magic functions. In your
432 ipythonrc file, placing a line like:
432 ipythonrc file, placing a line like:
433
433
434 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
434 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
435
435
436 will define %pf as a new name for %profile.
436 will define %pf as a new name for %profile.
437
437
438 You can also call magics in code using the ipmagic() function, which IPython
438 You can also call magics in code using the ipmagic() function, which IPython
439 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
439 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
440
440
441 For a list of the available magic functions, use %lsmagic. For a description
441 For a list of the available magic functions, use %lsmagic. For a description
442 of any of them, type %magic_name?, e.g. '%cd?'.
442 of any of them, type %magic_name?, e.g. '%cd?'.
443
443
444 Currently the magic system has the following functions:\n"""
444 Currently the magic system has the following functions:\n"""
445
445
446 mesc = self.shell.ESC_MAGIC
446 mesc = self.shell.ESC_MAGIC
447 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
447 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
448 "\n\n%s%s\n\n%s" % (outmsg,
448 "\n\n%s%s\n\n%s" % (outmsg,
449 magic_docs,mesc,mesc,
449 magic_docs,mesc,mesc,
450 (' '+mesc).join(self.lsmagic()),
450 (' '+mesc).join(self.lsmagic()),
451 Magic.auto_status[self.shell.rc.automagic] ) )
451 Magic.auto_status[self.shell.rc.automagic] ) )
452
452
453 page(outmsg,screen_lines=self.shell.rc.screen_length)
453 page(outmsg,screen_lines=self.shell.rc.screen_length)
454
454
455 def magic_automagic(self, parameter_s = ''):
455 def magic_automagic(self, parameter_s = ''):
456 """Make magic functions callable without having to type the initial %.
456 """Make magic functions callable without having to type the initial %.
457
457
458 Without argumentsl toggles on/off (when off, you must call it as
458 Without argumentsl toggles on/off (when off, you must call it as
459 %automagic, of course). With arguments it sets the value, and you can
459 %automagic, of course). With arguments it sets the value, and you can
460 use any of (case insensitive):
460 use any of (case insensitive):
461
461
462 - on,1,True: to activate
462 - on,1,True: to activate
463
463
464 - off,0,False: to deactivate.
464 - off,0,False: to deactivate.
465
465
466 Note that magic functions have lowest priority, so if there's a
466 Note that magic functions have lowest priority, so if there's a
467 variable whose name collides with that of a magic fn, automagic won't
467 variable whose name collides with that of a magic fn, automagic won't
468 work for that function (you get the variable instead). However, if you
468 work for that function (you get the variable instead). However, if you
469 delete the variable (del var), the previously shadowed magic function
469 delete the variable (del var), the previously shadowed magic function
470 becomes visible to automagic again."""
470 becomes visible to automagic again."""
471
471
472 rc = self.shell.rc
472 rc = self.shell.rc
473 arg = parameter_s.lower()
473 arg = parameter_s.lower()
474 if parameter_s in ('on','1','true'):
474 if parameter_s in ('on','1','true'):
475 rc.automagic = True
475 rc.automagic = True
476 elif parameter_s in ('off','0','false'):
476 elif parameter_s in ('off','0','false'):
477 rc.automagic = False
477 rc.automagic = False
478 else:
478 else:
479 rc.automagic = not rc.automagic
479 rc.automagic = not rc.automagic
480 print '\n' + Magic.auto_status[rc.automagic]
480 print '\n' + Magic.auto_status[rc.automagic]
481
481
482 def magic_autocall(self, parameter_s = ''):
482 def magic_autocall(self, parameter_s = ''):
483 """Make functions callable without having to type parentheses.
483 """Make functions callable without having to type parentheses.
484
484
485 Usage:
485 Usage:
486
486
487 %autocall [mode]
487 %autocall [mode]
488
488
489 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
489 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
490 value is toggled on and off (remembering the previous state)."""
490 value is toggled on and off (remembering the previous state)."""
491
491
492 rc = self.shell.rc
492 rc = self.shell.rc
493
493
494 if parameter_s:
494 if parameter_s:
495 arg = int(parameter_s)
495 arg = int(parameter_s)
496 else:
496 else:
497 arg = 'toggle'
497 arg = 'toggle'
498
498
499 if not arg in (0,1,2,'toggle'):
499 if not arg in (0,1,2,'toggle'):
500 error('Valid modes: (0->Off, 1->Smart, 2->Full')
500 error('Valid modes: (0->Off, 1->Smart, 2->Full')
501 return
501 return
502
502
503 if arg in (0,1,2):
503 if arg in (0,1,2):
504 rc.autocall = arg
504 rc.autocall = arg
505 else: # toggle
505 else: # toggle
506 if rc.autocall:
506 if rc.autocall:
507 self._magic_state.autocall_save = rc.autocall
507 self._magic_state.autocall_save = rc.autocall
508 rc.autocall = 0
508 rc.autocall = 0
509 else:
509 else:
510 try:
510 try:
511 rc.autocall = self._magic_state.autocall_save
511 rc.autocall = self._magic_state.autocall_save
512 except AttributeError:
512 except AttributeError:
513 rc.autocall = self._magic_state.autocall_save = 1
513 rc.autocall = self._magic_state.autocall_save = 1
514
514
515 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
515 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
516
516
517 def magic_autoindent(self, parameter_s = ''):
517 def magic_autoindent(self, parameter_s = ''):
518 """Toggle autoindent on/off (if available)."""
518 """Toggle autoindent on/off (if available)."""
519
519
520 self.shell.set_autoindent()
520 self.shell.set_autoindent()
521 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
521 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
522
522
523 def magic_system_verbose(self, parameter_s = ''):
523 def magic_system_verbose(self, parameter_s = ''):
524 """Set verbose printing of system calls.
524 """Set verbose printing of system calls.
525
525
526 If called without an argument, act as a toggle"""
526 If called without an argument, act as a toggle"""
527
527
528 if parameter_s:
528 if parameter_s:
529 val = bool(eval(parameter_s))
529 val = bool(eval(parameter_s))
530 else:
530 else:
531 val = None
531 val = None
532
532
533 self.shell.rc_set_toggle('system_verbose',val)
533 self.shell.rc_set_toggle('system_verbose',val)
534 print "System verbose printing is:",\
534 print "System verbose printing is:",\
535 ['OFF','ON'][self.shell.rc.system_verbose]
535 ['OFF','ON'][self.shell.rc.system_verbose]
536
536
537 def magic_history(self, parameter_s = ''):
537 def magic_history(self, parameter_s = ''):
538 """Print input history (_i<n> variables), with most recent last.
538 """Print input history (_i<n> variables), with most recent last.
539
539
540 %history -> print at most 40 inputs (some may be multi-line)\\
540 %history -> print at most 40 inputs (some may be multi-line)\\
541 %history n -> print at most n inputs\\
541 %history n -> print at most n inputs\\
542 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
542 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
543
543
544 Each input's number <n> is shown, and is accessible as the
544 Each input's number <n> is shown, and is accessible as the
545 automatically generated variable _i<n>. Multi-line statements are
545 automatically generated variable _i<n>. Multi-line statements are
546 printed starting at a new line for easy copy/paste.
546 printed starting at a new line for easy copy/paste.
547
547
548
548
549 Options:
549 Options:
550
550
551 -n: do NOT print line numbers. This is useful if you want to get a
551 -n: do NOT print line numbers. This is useful if you want to get a
552 printout of many lines which can be directly pasted into a text
552 printout of many lines which can be directly pasted into a text
553 editor.
553 editor.
554
554
555 This feature is only available if numbered prompts are in use.
555 This feature is only available if numbered prompts are in use.
556
556
557 -r: print the 'raw' history. IPython filters your input and
557 -r: print the 'raw' history. IPython filters your input and
558 converts it all into valid Python source before executing it (things
558 converts it all into valid Python source before executing it (things
559 like magics or aliases are turned into function calls, for
559 like magics or aliases are turned into function calls, for
560 example). With this option, you'll see the unfiltered history
560 example). With this option, you'll see the unfiltered history
561 instead of the filtered version: '%cd /' will be seen as '%cd /'
561 instead of the filtered version: '%cd /' will be seen as '%cd /'
562 instead of '_ip.magic("%cd /")'.
562 instead of '_ip.magic("%cd /")'.
563 """
563 """
564
564
565 shell = self.shell
565 shell = self.shell
566 if not shell.outputcache.do_full_cache:
566 if not shell.outputcache.do_full_cache:
567 print 'This feature is only available if numbered prompts are in use.'
567 print 'This feature is only available if numbered prompts are in use.'
568 return
568 return
569 opts,args = self.parse_options(parameter_s,'nr',mode='list')
569 opts,args = self.parse_options(parameter_s,'nr',mode='list')
570
570
571 if opts.has_key('r'):
571 if opts.has_key('r'):
572 input_hist = shell.input_hist_raw
572 input_hist = shell.input_hist_raw
573 else:
573 else:
574 input_hist = shell.input_hist
574 input_hist = shell.input_hist
575
575
576 default_length = 40
576 default_length = 40
577 if len(args) == 0:
577 if len(args) == 0:
578 final = len(input_hist)
578 final = len(input_hist)
579 init = max(1,final-default_length)
579 init = max(1,final-default_length)
580 elif len(args) == 1:
580 elif len(args) == 1:
581 final = len(input_hist)
581 final = len(input_hist)
582 init = max(1,final-int(args[0]))
582 init = max(1,final-int(args[0]))
583 elif len(args) == 2:
583 elif len(args) == 2:
584 init,final = map(int,args)
584 init,final = map(int,args)
585 else:
585 else:
586 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
586 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
587 print self.magic_hist.__doc__
587 print self.magic_hist.__doc__
588 return
588 return
589 width = len(str(final))
589 width = len(str(final))
590 line_sep = ['','\n']
590 line_sep = ['','\n']
591 print_nums = not opts.has_key('n')
591 print_nums = not opts.has_key('n')
592 for in_num in range(init,final):
592 for in_num in range(init,final):
593 inline = input_hist[in_num]
593 inline = input_hist[in_num]
594 multiline = int(inline.count('\n') > 1)
594 multiline = int(inline.count('\n') > 1)
595 if print_nums:
595 if print_nums:
596 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
596 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
597 print inline,
597 print inline,
598
598
599 def magic_hist(self, parameter_s=''):
599 def magic_hist(self, parameter_s=''):
600 """Alternate name for %history."""
600 """Alternate name for %history."""
601 return self.magic_history(parameter_s)
601 return self.magic_history(parameter_s)
602
602
603 def magic_p(self, parameter_s=''):
603 def magic_p(self, parameter_s=''):
604 """Just a short alias for Python's 'print'."""
604 """Just a short alias for Python's 'print'."""
605 exec 'print ' + parameter_s in self.shell.user_ns
605 exec 'print ' + parameter_s in self.shell.user_ns
606
606
607 def magic_r(self, parameter_s=''):
607 def magic_r(self, parameter_s=''):
608 """Repeat previous input.
608 """Repeat previous input.
609
609
610 If given an argument, repeats the previous command which starts with
610 If given an argument, repeats the previous command which starts with
611 the same string, otherwise it just repeats the previous input.
611 the same string, otherwise it just repeats the previous input.
612
612
613 Shell escaped commands (with ! as first character) are not recognized
613 Shell escaped commands (with ! as first character) are not recognized
614 by this system, only pure python code and magic commands.
614 by this system, only pure python code and magic commands.
615 """
615 """
616
616
617 start = parameter_s.strip()
617 start = parameter_s.strip()
618 esc_magic = self.shell.ESC_MAGIC
618 esc_magic = self.shell.ESC_MAGIC
619 # Identify magic commands even if automagic is on (which means
619 # Identify magic commands even if automagic is on (which means
620 # the in-memory version is different from that typed by the user).
620 # the in-memory version is different from that typed by the user).
621 if self.shell.rc.automagic:
621 if self.shell.rc.automagic:
622 start_magic = esc_magic+start
622 start_magic = esc_magic+start
623 else:
623 else:
624 start_magic = start
624 start_magic = start
625 # Look through the input history in reverse
625 # Look through the input history in reverse
626 for n in range(len(self.shell.input_hist)-2,0,-1):
626 for n in range(len(self.shell.input_hist)-2,0,-1):
627 input = self.shell.input_hist[n]
627 input = self.shell.input_hist[n]
628 # skip plain 'r' lines so we don't recurse to infinity
628 # skip plain 'r' lines so we don't recurse to infinity
629 if input != '_ip.magic("r")\n' and \
629 if input != '_ip.magic("r")\n' and \
630 (input.startswith(start) or input.startswith(start_magic)):
630 (input.startswith(start) or input.startswith(start_magic)):
631 #print 'match',`input` # dbg
631 #print 'match',`input` # dbg
632 print 'Executing:',input,
632 print 'Executing:',input,
633 self.shell.runlines(input)
633 self.shell.runlines(input)
634 return
634 return
635 print 'No previous input matching `%s` found.' % start
635 print 'No previous input matching `%s` found.' % start
636
636
637 def magic_page(self, parameter_s=''):
637 def magic_page(self, parameter_s=''):
638 """Pretty print the object and display it through a pager.
638 """Pretty print the object and display it through a pager.
639
639
640 %page [options] OBJECT
640 %page [options] OBJECT
641
641
642 If no object is given, use _ (last output).
642 If no object is given, use _ (last output).
643
643
644 Options:
644 Options:
645
645
646 -r: page str(object), don't pretty-print it."""
646 -r: page str(object), don't pretty-print it."""
647
647
648 # After a function contributed by Olivier Aubert, slightly modified.
648 # After a function contributed by Olivier Aubert, slightly modified.
649
649
650 # Process options/args
650 # Process options/args
651 opts,args = self.parse_options(parameter_s,'r')
651 opts,args = self.parse_options(parameter_s,'r')
652 raw = 'r' in opts
652 raw = 'r' in opts
653
653
654 oname = args and args or '_'
654 oname = args and args or '_'
655 info = self._ofind(oname)
655 info = self._ofind(oname)
656 if info['found']:
656 if info['found']:
657 txt = (raw and str or pformat)( info['obj'] )
657 txt = (raw and str or pformat)( info['obj'] )
658 page(txt)
658 page(txt)
659 else:
659 else:
660 print 'Object `%s` not found' % oname
660 print 'Object `%s` not found' % oname
661
661
662 def magic_profile(self, parameter_s=''):
662 def magic_profile(self, parameter_s=''):
663 """Print your currently active IPyhton profile."""
663 """Print your currently active IPyhton profile."""
664 if self.shell.rc.profile:
664 if self.shell.rc.profile:
665 printpl('Current IPython profile: $self.shell.rc.profile.')
665 printpl('Current IPython profile: $self.shell.rc.profile.')
666 else:
666 else:
667 print 'No profile active.'
667 print 'No profile active.'
668
668
669 def _inspect(self,meth,oname,namespaces=None,**kw):
669 def _inspect(self,meth,oname,namespaces=None,**kw):
670 """Generic interface to the inspector system.
670 """Generic interface to the inspector system.
671
671
672 This function is meant to be called by pdef, pdoc & friends."""
672 This function is meant to be called by pdef, pdoc & friends."""
673
673
674 #oname = oname.strip()
675 #print '1- oname: <%r>' % oname # dbg
674 try:
676 try:
675 oname = oname.strip().encode('ascii')
677 oname = oname.strip().encode('ascii')
678 #print '2- oname: <%r>' % oname # dbg
676 except UnicodeEncodeError:
679 except UnicodeEncodeError:
677 print 'Python identifiers can only contain ascii characters.'
680 print 'Python identifiers can only contain ascii characters.'
678 return 'not found'
681 return 'not found'
679
682
680 info = Struct(self._ofind(oname, namespaces))
683 info = Struct(self._ofind(oname, namespaces))
681
684
682 if info.found:
685 if info.found:
683 # Get the docstring of the class property if it exists.
686 # Get the docstring of the class property if it exists.
684 path = oname.split('.')
687 path = oname.split('.')
685 root = '.'.join(path[:-1])
688 root = '.'.join(path[:-1])
686 if info.parent is not None:
689 if info.parent is not None:
687 try:
690 try:
688 target = getattr(info.parent, '__class__')
691 target = getattr(info.parent, '__class__')
689 # The object belongs to a class instance.
692 # The object belongs to a class instance.
690 try:
693 try:
691 target = getattr(target, path[-1])
694 target = getattr(target, path[-1])
692 # The class defines the object.
695 # The class defines the object.
693 if isinstance(target, property):
696 if isinstance(target, property):
694 oname = root + '.__class__.' + path[-1]
697 oname = root + '.__class__.' + path[-1]
695 info = Struct(self._ofind(oname))
698 info = Struct(self._ofind(oname))
696 except AttributeError: pass
699 except AttributeError: pass
697 except AttributeError: pass
700 except AttributeError: pass
698
701
699 pmethod = getattr(self.shell.inspector,meth)
702 pmethod = getattr(self.shell.inspector,meth)
700 formatter = info.ismagic and self.format_screen or None
703 formatter = info.ismagic and self.format_screen or None
701 if meth == 'pdoc':
704 if meth == 'pdoc':
702 pmethod(info.obj,oname,formatter)
705 pmethod(info.obj,oname,formatter)
703 elif meth == 'pinfo':
706 elif meth == 'pinfo':
704 pmethod(info.obj,oname,formatter,info,**kw)
707 pmethod(info.obj,oname,formatter,info,**kw)
705 else:
708 else:
706 pmethod(info.obj,oname)
709 pmethod(info.obj,oname)
707 else:
710 else:
708 print 'Object `%s` not found.' % oname
711 print 'Object `%s` not found.' % oname
709 return 'not found' # so callers can take other action
712 return 'not found' # so callers can take other action
710
713
711 def magic_pdef(self, parameter_s='', namespaces=None):
714 def magic_pdef(self, parameter_s='', namespaces=None):
712 """Print the definition header for any callable object.
715 """Print the definition header for any callable object.
713
716
714 If the object is a class, print the constructor information."""
717 If the object is a class, print the constructor information."""
715 self._inspect('pdef',parameter_s, namespaces)
718 self._inspect('pdef',parameter_s, namespaces)
716
719
717 def magic_pdoc(self, parameter_s='', namespaces=None):
720 def magic_pdoc(self, parameter_s='', namespaces=None):
718 """Print the docstring for an object.
721 """Print the docstring for an object.
719
722
720 If the given object is a class, it will print both the class and the
723 If the given object is a class, it will print both the class and the
721 constructor docstrings."""
724 constructor docstrings."""
722 self._inspect('pdoc',parameter_s, namespaces)
725 self._inspect('pdoc',parameter_s, namespaces)
723
726
724 def magic_psource(self, parameter_s='', namespaces=None):
727 def magic_psource(self, parameter_s='', namespaces=None):
725 """Print (or run through pager) the source code for an object."""
728 """Print (or run through pager) the source code for an object."""
726 self._inspect('psource',parameter_s, namespaces)
729 self._inspect('psource',parameter_s, namespaces)
727
730
728 def magic_pfile(self, parameter_s=''):
731 def magic_pfile(self, parameter_s=''):
729 """Print (or run through pager) the file where an object is defined.
732 """Print (or run through pager) the file where an object is defined.
730
733
731 The file opens at the line where the object definition begins. IPython
734 The file opens at the line where the object definition begins. IPython
732 will honor the environment variable PAGER if set, and otherwise will
735 will honor the environment variable PAGER if set, and otherwise will
733 do its best to print the file in a convenient form.
736 do its best to print the file in a convenient form.
734
737
735 If the given argument is not an object currently defined, IPython will
738 If the given argument is not an object currently defined, IPython will
736 try to interpret it as a filename (automatically adding a .py extension
739 try to interpret it as a filename (automatically adding a .py extension
737 if needed). You can thus use %pfile as a syntax highlighting code
740 if needed). You can thus use %pfile as a syntax highlighting code
738 viewer."""
741 viewer."""
739
742
740 # first interpret argument as an object name
743 # first interpret argument as an object name
741 out = self._inspect('pfile',parameter_s)
744 out = self._inspect('pfile',parameter_s)
742 # if not, try the input as a filename
745 # if not, try the input as a filename
743 if out == 'not found':
746 if out == 'not found':
744 try:
747 try:
745 filename = get_py_filename(parameter_s)
748 filename = get_py_filename(parameter_s)
746 except IOError,msg:
749 except IOError,msg:
747 print msg
750 print msg
748 return
751 return
749 page(self.shell.inspector.format(file(filename).read()))
752 page(self.shell.inspector.format(file(filename).read()))
750
753
751 def magic_pinfo(self, parameter_s='', namespaces=None):
754 def magic_pinfo(self, parameter_s='', namespaces=None):
752 """Provide detailed information about an object.
755 """Provide detailed information about an object.
753
756
754 '%pinfo object' is just a synonym for object? or ?object."""
757 '%pinfo object' is just a synonym for object? or ?object."""
755
758
756 #print 'pinfo par: <%s>' % parameter_s # dbg
759 #print 'pinfo par: <%s>' % parameter_s # dbg
757
760
758 # detail_level: 0 -> obj? , 1 -> obj??
761 # detail_level: 0 -> obj? , 1 -> obj??
759 detail_level = 0
762 detail_level = 0
760 # We need to detect if we got called as 'pinfo pinfo foo', which can
763 # We need to detect if we got called as 'pinfo pinfo foo', which can
761 # happen if the user types 'pinfo foo?' at the cmd line.
764 # happen if the user types 'pinfo foo?' at the cmd line.
762 pinfo,qmark1,oname,qmark2 = \
765 pinfo,qmark1,oname,qmark2 = \
763 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
766 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
764 if pinfo or qmark1 or qmark2:
767 if pinfo or qmark1 or qmark2:
765 detail_level = 1
768 detail_level = 1
766 if "*" in oname:
769 if "*" in oname:
767 self.magic_psearch(oname)
770 self.magic_psearch(oname)
768 else:
771 else:
769 self._inspect('pinfo', oname, detail_level=detail_level,
772 self._inspect('pinfo', oname, detail_level=detail_level,
770 namespaces=namespaces)
773 namespaces=namespaces)
771
774
772 def magic_psearch(self, parameter_s=''):
775 def magic_psearch(self, parameter_s=''):
773 """Search for object in namespaces by wildcard.
776 """Search for object in namespaces by wildcard.
774
777
775 %psearch [options] PATTERN [OBJECT TYPE]
778 %psearch [options] PATTERN [OBJECT TYPE]
776
779
777 Note: ? can be used as a synonym for %psearch, at the beginning or at
780 Note: ? can be used as a synonym for %psearch, at the beginning or at
778 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
781 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
779 rest of the command line must be unchanged (options come first), so
782 rest of the command line must be unchanged (options come first), so
780 for example the following forms are equivalent
783 for example the following forms are equivalent
781
784
782 %psearch -i a* function
785 %psearch -i a* function
783 -i a* function?
786 -i a* function?
784 ?-i a* function
787 ?-i a* function
785
788
786 Arguments:
789 Arguments:
787
790
788 PATTERN
791 PATTERN
789
792
790 where PATTERN is a string containing * as a wildcard similar to its
793 where PATTERN is a string containing * as a wildcard similar to its
791 use in a shell. The pattern is matched in all namespaces on the
794 use in a shell. The pattern is matched in all namespaces on the
792 search path. By default objects starting with a single _ are not
795 search path. By default objects starting with a single _ are not
793 matched, many IPython generated objects have a single
796 matched, many IPython generated objects have a single
794 underscore. The default is case insensitive matching. Matching is
797 underscore. The default is case insensitive matching. Matching is
795 also done on the attributes of objects and not only on the objects
798 also done on the attributes of objects and not only on the objects
796 in a module.
799 in a module.
797
800
798 [OBJECT TYPE]
801 [OBJECT TYPE]
799
802
800 Is the name of a python type from the types module. The name is
803 Is the name of a python type from the types module. The name is
801 given in lowercase without the ending type, ex. StringType is
804 given in lowercase without the ending type, ex. StringType is
802 written string. By adding a type here only objects matching the
805 written string. By adding a type here only objects matching the
803 given type are matched. Using all here makes the pattern match all
806 given type are matched. Using all here makes the pattern match all
804 types (this is the default).
807 types (this is the default).
805
808
806 Options:
809 Options:
807
810
808 -a: makes the pattern match even objects whose names start with a
811 -a: makes the pattern match even objects whose names start with a
809 single underscore. These names are normally ommitted from the
812 single underscore. These names are normally ommitted from the
810 search.
813 search.
811
814
812 -i/-c: make the pattern case insensitive/sensitive. If neither of
815 -i/-c: make the pattern case insensitive/sensitive. If neither of
813 these options is given, the default is read from your ipythonrc
816 these options is given, the default is read from your ipythonrc
814 file. The option name which sets this value is
817 file. The option name which sets this value is
815 'wildcards_case_sensitive'. If this option is not specified in your
818 'wildcards_case_sensitive'. If this option is not specified in your
816 ipythonrc file, IPython's internal default is to do a case sensitive
819 ipythonrc file, IPython's internal default is to do a case sensitive
817 search.
820 search.
818
821
819 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
822 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
820 specifiy can be searched in any of the following namespaces:
823 specifiy can be searched in any of the following namespaces:
821 'builtin', 'user', 'user_global','internal', 'alias', where
824 'builtin', 'user', 'user_global','internal', 'alias', where
822 'builtin' and 'user' are the search defaults. Note that you should
825 'builtin' and 'user' are the search defaults. Note that you should
823 not use quotes when specifying namespaces.
826 not use quotes when specifying namespaces.
824
827
825 'Builtin' contains the python module builtin, 'user' contains all
828 'Builtin' contains the python module builtin, 'user' contains all
826 user data, 'alias' only contain the shell aliases and no python
829 user data, 'alias' only contain the shell aliases and no python
827 objects, 'internal' contains objects used by IPython. The
830 objects, 'internal' contains objects used by IPython. The
828 'user_global' namespace is only used by embedded IPython instances,
831 'user_global' namespace is only used by embedded IPython instances,
829 and it contains module-level globals. You can add namespaces to the
832 and it contains module-level globals. You can add namespaces to the
830 search with -s or exclude them with -e (these options can be given
833 search with -s or exclude them with -e (these options can be given
831 more than once).
834 more than once).
832
835
833 Examples:
836 Examples:
834
837
835 %psearch a* -> objects beginning with an a
838 %psearch a* -> objects beginning with an a
836 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
839 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
837 %psearch a* function -> all functions beginning with an a
840 %psearch a* function -> all functions beginning with an a
838 %psearch re.e* -> objects beginning with an e in module re
841 %psearch re.e* -> objects beginning with an e in module re
839 %psearch r*.e* -> objects that start with e in modules starting in r
842 %psearch r*.e* -> objects that start with e in modules starting in r
840 %psearch r*.* string -> all strings in modules beginning with r
843 %psearch r*.* string -> all strings in modules beginning with r
841
844
842 Case sensitve search:
845 Case sensitve search:
843
846
844 %psearch -c a* list all object beginning with lower case a
847 %psearch -c a* list all object beginning with lower case a
845
848
846 Show objects beginning with a single _:
849 Show objects beginning with a single _:
847
850
848 %psearch -a _* list objects beginning with a single underscore"""
851 %psearch -a _* list objects beginning with a single underscore"""
852 try:
853 parameter_s = parameter_s.encode('ascii')
854 except UnicodeEncodeError:
855 print 'Python identifiers can only contain ascii characters.'
856 return
849
857
850 # default namespaces to be searched
858 # default namespaces to be searched
851 def_search = ['user','builtin']
859 def_search = ['user','builtin']
852
860
853 # Process options/args
861 # Process options/args
854 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
862 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
855 opt = opts.get
863 opt = opts.get
856 shell = self.shell
864 shell = self.shell
857 psearch = shell.inspector.psearch
865 psearch = shell.inspector.psearch
858
866
859 # select case options
867 # select case options
860 if opts.has_key('i'):
868 if opts.has_key('i'):
861 ignore_case = True
869 ignore_case = True
862 elif opts.has_key('c'):
870 elif opts.has_key('c'):
863 ignore_case = False
871 ignore_case = False
864 else:
872 else:
865 ignore_case = not shell.rc.wildcards_case_sensitive
873 ignore_case = not shell.rc.wildcards_case_sensitive
866
874
867 # Build list of namespaces to search from user options
875 # Build list of namespaces to search from user options
868 def_search.extend(opt('s',[]))
876 def_search.extend(opt('s',[]))
869 ns_exclude = ns_exclude=opt('e',[])
877 ns_exclude = ns_exclude=opt('e',[])
870 ns_search = [nm for nm in def_search if nm not in ns_exclude]
878 ns_search = [nm for nm in def_search if nm not in ns_exclude]
871
879
872 # Call the actual search
880 # Call the actual search
873 try:
881 try:
874 psearch(args,shell.ns_table,ns_search,
882 psearch(args,shell.ns_table,ns_search,
875 show_all=opt('a'),ignore_case=ignore_case)
883 show_all=opt('a'),ignore_case=ignore_case)
876 except:
884 except:
877 shell.showtraceback()
885 shell.showtraceback()
878
886
879 def magic_who_ls(self, parameter_s=''):
887 def magic_who_ls(self, parameter_s=''):
880 """Return a sorted list of all interactive variables.
888 """Return a sorted list of all interactive variables.
881
889
882 If arguments are given, only variables of types matching these
890 If arguments are given, only variables of types matching these
883 arguments are returned."""
891 arguments are returned."""
884
892
885 user_ns = self.shell.user_ns
893 user_ns = self.shell.user_ns
886 internal_ns = self.shell.internal_ns
894 internal_ns = self.shell.internal_ns
887 user_config_ns = self.shell.user_config_ns
895 user_config_ns = self.shell.user_config_ns
888 out = []
896 out = []
889 typelist = parameter_s.split()
897 typelist = parameter_s.split()
890
898
891 for i in user_ns:
899 for i in user_ns:
892 if not (i.startswith('_') or i.startswith('_i')) \
900 if not (i.startswith('_') or i.startswith('_i')) \
893 and not (i in internal_ns or i in user_config_ns):
901 and not (i in internal_ns or i in user_config_ns):
894 if typelist:
902 if typelist:
895 if type(user_ns[i]).__name__ in typelist:
903 if type(user_ns[i]).__name__ in typelist:
896 out.append(i)
904 out.append(i)
897 else:
905 else:
898 out.append(i)
906 out.append(i)
899 out.sort()
907 out.sort()
900 return out
908 return out
901
909
902 def magic_who(self, parameter_s=''):
910 def magic_who(self, parameter_s=''):
903 """Print all interactive variables, with some minimal formatting.
911 """Print all interactive variables, with some minimal formatting.
904
912
905 If any arguments are given, only variables whose type matches one of
913 If any arguments are given, only variables whose type matches one of
906 these are printed. For example:
914 these are printed. For example:
907
915
908 %who function str
916 %who function str
909
917
910 will only list functions and strings, excluding all other types of
918 will only list functions and strings, excluding all other types of
911 variables. To find the proper type names, simply use type(var) at a
919 variables. To find the proper type names, simply use type(var) at a
912 command line to see how python prints type names. For example:
920 command line to see how python prints type names. For example:
913
921
914 In [1]: type('hello')\\
922 In [1]: type('hello')\\
915 Out[1]: <type 'str'>
923 Out[1]: <type 'str'>
916
924
917 indicates that the type name for strings is 'str'.
925 indicates that the type name for strings is 'str'.
918
926
919 %who always excludes executed names loaded through your configuration
927 %who always excludes executed names loaded through your configuration
920 file and things which are internal to IPython.
928 file and things which are internal to IPython.
921
929
922 This is deliberate, as typically you may load many modules and the
930 This is deliberate, as typically you may load many modules and the
923 purpose of %who is to show you only what you've manually defined."""
931 purpose of %who is to show you only what you've manually defined."""
924
932
925 varlist = self.magic_who_ls(parameter_s)
933 varlist = self.magic_who_ls(parameter_s)
926 if not varlist:
934 if not varlist:
927 print 'Interactive namespace is empty.'
935 print 'Interactive namespace is empty.'
928 return
936 return
929
937
930 # if we have variables, move on...
938 # if we have variables, move on...
931
939
932 # stupid flushing problem: when prompts have no separators, stdout is
940 # stupid flushing problem: when prompts have no separators, stdout is
933 # getting lost. I'm starting to think this is a python bug. I'm having
941 # getting lost. I'm starting to think this is a python bug. I'm having
934 # to force a flush with a print because even a sys.stdout.flush
942 # to force a flush with a print because even a sys.stdout.flush
935 # doesn't seem to do anything!
943 # doesn't seem to do anything!
936
944
937 count = 0
945 count = 0
938 for i in varlist:
946 for i in varlist:
939 print i+'\t',
947 print i+'\t',
940 count += 1
948 count += 1
941 if count > 8:
949 if count > 8:
942 count = 0
950 count = 0
943 print
951 print
944 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
952 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
945
953
946 print # well, this does force a flush at the expense of an extra \n
954 print # well, this does force a flush at the expense of an extra \n
947
955
948 def magic_whos(self, parameter_s=''):
956 def magic_whos(self, parameter_s=''):
949 """Like %who, but gives some extra information about each variable.
957 """Like %who, but gives some extra information about each variable.
950
958
951 The same type filtering of %who can be applied here.
959 The same type filtering of %who can be applied here.
952
960
953 For all variables, the type is printed. Additionally it prints:
961 For all variables, the type is printed. Additionally it prints:
954
962
955 - For {},[],(): their length.
963 - For {},[],(): their length.
956
964
957 - For Numeric arrays, a summary with shape, number of elements,
965 - For Numeric arrays, a summary with shape, number of elements,
958 typecode and size in memory.
966 typecode and size in memory.
959
967
960 - Everything else: a string representation, snipping their middle if
968 - Everything else: a string representation, snipping their middle if
961 too long."""
969 too long."""
962
970
963 varnames = self.magic_who_ls(parameter_s)
971 varnames = self.magic_who_ls(parameter_s)
964 if not varnames:
972 if not varnames:
965 print 'Interactive namespace is empty.'
973 print 'Interactive namespace is empty.'
966 return
974 return
967
975
968 # if we have variables, move on...
976 # if we have variables, move on...
969
977
970 # for these types, show len() instead of data:
978 # for these types, show len() instead of data:
971 seq_types = [types.DictType,types.ListType,types.TupleType]
979 seq_types = [types.DictType,types.ListType,types.TupleType]
972
980
973 # for Numeric arrays, display summary info
981 # for Numeric arrays, display summary info
974 try:
982 try:
975 import Numeric
983 import Numeric
976 except ImportError:
984 except ImportError:
977 array_type = None
985 array_type = None
978 else:
986 else:
979 array_type = Numeric.ArrayType.__name__
987 array_type = Numeric.ArrayType.__name__
980
988
981 # Find all variable names and types so we can figure out column sizes
989 # Find all variable names and types so we can figure out column sizes
982
990
983 def get_vars(i):
991 def get_vars(i):
984 return self.shell.user_ns[i]
992 return self.shell.user_ns[i]
985
993
986 # some types are well known and can be shorter
994 # some types are well known and can be shorter
987 abbrevs = {'IPython.macro.Macro' : 'Macro'}
995 abbrevs = {'IPython.macro.Macro' : 'Macro'}
988 def type_name(v):
996 def type_name(v):
989 tn = type(v).__name__
997 tn = type(v).__name__
990 return abbrevs.get(tn,tn)
998 return abbrevs.get(tn,tn)
991
999
992 varlist = map(get_vars,varnames)
1000 varlist = map(get_vars,varnames)
993
1001
994 typelist = []
1002 typelist = []
995 for vv in varlist:
1003 for vv in varlist:
996 tt = type_name(vv)
1004 tt = type_name(vv)
997
1005
998 if tt=='instance':
1006 if tt=='instance':
999 typelist.append( abbrevs.get(str(vv.__class__),str(vv.__class__)))
1007 typelist.append( abbrevs.get(str(vv.__class__),str(vv.__class__)))
1000 else:
1008 else:
1001 typelist.append(tt)
1009 typelist.append(tt)
1002
1010
1003 # column labels and # of spaces as separator
1011 # column labels and # of spaces as separator
1004 varlabel = 'Variable'
1012 varlabel = 'Variable'
1005 typelabel = 'Type'
1013 typelabel = 'Type'
1006 datalabel = 'Data/Info'
1014 datalabel = 'Data/Info'
1007 colsep = 3
1015 colsep = 3
1008 # variable format strings
1016 # variable format strings
1009 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1017 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1010 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1018 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1011 aformat = "%s: %s elems, type `%s`, %s bytes"
1019 aformat = "%s: %s elems, type `%s`, %s bytes"
1012 # find the size of the columns to format the output nicely
1020 # find the size of the columns to format the output nicely
1013 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1021 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1014 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1022 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1015 # table header
1023 # table header
1016 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1024 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1017 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1025 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1018 # and the table itself
1026 # and the table itself
1019 kb = 1024
1027 kb = 1024
1020 Mb = 1048576 # kb**2
1028 Mb = 1048576 # kb**2
1021 for vname,var,vtype in zip(varnames,varlist,typelist):
1029 for vname,var,vtype in zip(varnames,varlist,typelist):
1022 print itpl(vformat),
1030 print itpl(vformat),
1023 if vtype in seq_types:
1031 if vtype in seq_types:
1024 print len(var)
1032 print len(var)
1025 elif vtype==array_type:
1033 elif vtype==array_type:
1026 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1034 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1027 vsize = Numeric.size(var)
1035 vsize = Numeric.size(var)
1028 vbytes = vsize*var.itemsize()
1036 vbytes = vsize*var.itemsize()
1029 if vbytes < 100000:
1037 if vbytes < 100000:
1030 print aformat % (vshape,vsize,var.typecode(),vbytes)
1038 print aformat % (vshape,vsize,var.typecode(),vbytes)
1031 else:
1039 else:
1032 print aformat % (vshape,vsize,var.typecode(),vbytes),
1040 print aformat % (vshape,vsize,var.typecode(),vbytes),
1033 if vbytes < Mb:
1041 if vbytes < Mb:
1034 print '(%s kb)' % (vbytes/kb,)
1042 print '(%s kb)' % (vbytes/kb,)
1035 else:
1043 else:
1036 print '(%s Mb)' % (vbytes/Mb,)
1044 print '(%s Mb)' % (vbytes/Mb,)
1037 else:
1045 else:
1038 vstr = str(var).replace('\n','\\n')
1046 vstr = str(var).replace('\n','\\n')
1039 if len(vstr) < 50:
1047 if len(vstr) < 50:
1040 print vstr
1048 print vstr
1041 else:
1049 else:
1042 printpl(vfmt_short)
1050 printpl(vfmt_short)
1043
1051
1044 def magic_reset(self, parameter_s=''):
1052 def magic_reset(self, parameter_s=''):
1045 """Resets the namespace by removing all names defined by the user.
1053 """Resets the namespace by removing all names defined by the user.
1046
1054
1047 Input/Output history are left around in case you need them."""
1055 Input/Output history are left around in case you need them."""
1048
1056
1049 ans = self.shell.ask_yes_no(
1057 ans = self.shell.ask_yes_no(
1050 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1058 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1051 if not ans:
1059 if not ans:
1052 print 'Nothing done.'
1060 print 'Nothing done.'
1053 return
1061 return
1054 user_ns = self.shell.user_ns
1062 user_ns = self.shell.user_ns
1055 for i in self.magic_who_ls():
1063 for i in self.magic_who_ls():
1056 del(user_ns[i])
1064 del(user_ns[i])
1057
1065
1058 def magic_logstart(self,parameter_s=''):
1066 def magic_logstart(self,parameter_s=''):
1059 """Start logging anywhere in a session.
1067 """Start logging anywhere in a session.
1060
1068
1061 %logstart [-o|-r|-t] [log_name [log_mode]]
1069 %logstart [-o|-r|-t] [log_name [log_mode]]
1062
1070
1063 If no name is given, it defaults to a file named 'ipython_log.py' in your
1071 If no name is given, it defaults to a file named 'ipython_log.py' in your
1064 current directory, in 'rotate' mode (see below).
1072 current directory, in 'rotate' mode (see below).
1065
1073
1066 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1074 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1067 history up to that point and then continues logging.
1075 history up to that point and then continues logging.
1068
1076
1069 %logstart takes a second optional parameter: logging mode. This can be one
1077 %logstart takes a second optional parameter: logging mode. This can be one
1070 of (note that the modes are given unquoted):\\
1078 of (note that the modes are given unquoted):\\
1071 append: well, that says it.\\
1079 append: well, that says it.\\
1072 backup: rename (if exists) to name~ and start name.\\
1080 backup: rename (if exists) to name~ and start name.\\
1073 global: single logfile in your home dir, appended to.\\
1081 global: single logfile in your home dir, appended to.\\
1074 over : overwrite existing log.\\
1082 over : overwrite existing log.\\
1075 rotate: create rotating logs name.1~, name.2~, etc.
1083 rotate: create rotating logs name.1~, name.2~, etc.
1076
1084
1077 Options:
1085 Options:
1078
1086
1079 -o: log also IPython's output. In this mode, all commands which
1087 -o: log also IPython's output. In this mode, all commands which
1080 generate an Out[NN] prompt are recorded to the logfile, right after
1088 generate an Out[NN] prompt are recorded to the logfile, right after
1081 their corresponding input line. The output lines are always
1089 their corresponding input line. The output lines are always
1082 prepended with a '#[Out]# ' marker, so that the log remains valid
1090 prepended with a '#[Out]# ' marker, so that the log remains valid
1083 Python code.
1091 Python code.
1084
1092
1085 Since this marker is always the same, filtering only the output from
1093 Since this marker is always the same, filtering only the output from
1086 a log is very easy, using for example a simple awk call:
1094 a log is very easy, using for example a simple awk call:
1087
1095
1088 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1096 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1089
1097
1090 -r: log 'raw' input. Normally, IPython's logs contain the processed
1098 -r: log 'raw' input. Normally, IPython's logs contain the processed
1091 input, so that user lines are logged in their final form, converted
1099 input, so that user lines are logged in their final form, converted
1092 into valid Python. For example, %Exit is logged as
1100 into valid Python. For example, %Exit is logged as
1093 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1101 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1094 exactly as typed, with no transformations applied.
1102 exactly as typed, with no transformations applied.
1095
1103
1096 -t: put timestamps before each input line logged (these are put in
1104 -t: put timestamps before each input line logged (these are put in
1097 comments)."""
1105 comments)."""
1098
1106
1099 opts,par = self.parse_options(parameter_s,'ort')
1107 opts,par = self.parse_options(parameter_s,'ort')
1100 log_output = 'o' in opts
1108 log_output = 'o' in opts
1101 log_raw_input = 'r' in opts
1109 log_raw_input = 'r' in opts
1102 timestamp = 't' in opts
1110 timestamp = 't' in opts
1103
1111
1104 rc = self.shell.rc
1112 rc = self.shell.rc
1105 logger = self.shell.logger
1113 logger = self.shell.logger
1106
1114
1107 # if no args are given, the defaults set in the logger constructor by
1115 # if no args are given, the defaults set in the logger constructor by
1108 # ipytohn remain valid
1116 # ipytohn remain valid
1109 if par:
1117 if par:
1110 try:
1118 try:
1111 logfname,logmode = par.split()
1119 logfname,logmode = par.split()
1112 except:
1120 except:
1113 logfname = par
1121 logfname = par
1114 logmode = 'backup'
1122 logmode = 'backup'
1115 else:
1123 else:
1116 logfname = logger.logfname
1124 logfname = logger.logfname
1117 logmode = logger.logmode
1125 logmode = logger.logmode
1118 # put logfname into rc struct as if it had been called on the command
1126 # put logfname into rc struct as if it had been called on the command
1119 # line, so it ends up saved in the log header Save it in case we need
1127 # line, so it ends up saved in the log header Save it in case we need
1120 # to restore it...
1128 # to restore it...
1121 old_logfile = rc.opts.get('logfile','')
1129 old_logfile = rc.opts.get('logfile','')
1122 if logfname:
1130 if logfname:
1123 logfname = os.path.expanduser(logfname)
1131 logfname = os.path.expanduser(logfname)
1124 rc.opts.logfile = logfname
1132 rc.opts.logfile = logfname
1125 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1133 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1126 try:
1134 try:
1127 started = logger.logstart(logfname,loghead,logmode,
1135 started = logger.logstart(logfname,loghead,logmode,
1128 log_output,timestamp,log_raw_input)
1136 log_output,timestamp,log_raw_input)
1129 except:
1137 except:
1130 rc.opts.logfile = old_logfile
1138 rc.opts.logfile = old_logfile
1131 warn("Couldn't start log: %s" % sys.exc_info()[1])
1139 warn("Couldn't start log: %s" % sys.exc_info()[1])
1132 else:
1140 else:
1133 # log input history up to this point, optionally interleaving
1141 # log input history up to this point, optionally interleaving
1134 # output if requested
1142 # output if requested
1135
1143
1136 if timestamp:
1144 if timestamp:
1137 # disable timestamping for the previous history, since we've
1145 # disable timestamping for the previous history, since we've
1138 # lost those already (no time machine here).
1146 # lost those already (no time machine here).
1139 logger.timestamp = False
1147 logger.timestamp = False
1140
1148
1141 if log_raw_input:
1149 if log_raw_input:
1142 input_hist = self.shell.input_hist_raw
1150 input_hist = self.shell.input_hist_raw
1143 else:
1151 else:
1144 input_hist = self.shell.input_hist
1152 input_hist = self.shell.input_hist
1145
1153
1146 if log_output:
1154 if log_output:
1147 log_write = logger.log_write
1155 log_write = logger.log_write
1148 output_hist = self.shell.output_hist
1156 output_hist = self.shell.output_hist
1149 for n in range(1,len(input_hist)-1):
1157 for n in range(1,len(input_hist)-1):
1150 log_write(input_hist[n].rstrip())
1158 log_write(input_hist[n].rstrip())
1151 if n in output_hist:
1159 if n in output_hist:
1152 log_write(repr(output_hist[n]),'output')
1160 log_write(repr(output_hist[n]),'output')
1153 else:
1161 else:
1154 logger.log_write(input_hist[1:])
1162 logger.log_write(input_hist[1:])
1155 if timestamp:
1163 if timestamp:
1156 # re-enable timestamping
1164 # re-enable timestamping
1157 logger.timestamp = True
1165 logger.timestamp = True
1158
1166
1159 print ('Activating auto-logging. '
1167 print ('Activating auto-logging. '
1160 'Current session state plus future input saved.')
1168 'Current session state plus future input saved.')
1161 logger.logstate()
1169 logger.logstate()
1162
1170
1163 def magic_logoff(self,parameter_s=''):
1171 def magic_logoff(self,parameter_s=''):
1164 """Temporarily stop logging.
1172 """Temporarily stop logging.
1165
1173
1166 You must have previously started logging."""
1174 You must have previously started logging."""
1167 self.shell.logger.switch_log(0)
1175 self.shell.logger.switch_log(0)
1168
1176
1169 def magic_logon(self,parameter_s=''):
1177 def magic_logon(self,parameter_s=''):
1170 """Restart logging.
1178 """Restart logging.
1171
1179
1172 This function is for restarting logging which you've temporarily
1180 This function is for restarting logging which you've temporarily
1173 stopped with %logoff. For starting logging for the first time, you
1181 stopped with %logoff. For starting logging for the first time, you
1174 must use the %logstart function, which allows you to specify an
1182 must use the %logstart function, which allows you to specify an
1175 optional log filename."""
1183 optional log filename."""
1176
1184
1177 self.shell.logger.switch_log(1)
1185 self.shell.logger.switch_log(1)
1178
1186
1179 def magic_logstate(self,parameter_s=''):
1187 def magic_logstate(self,parameter_s=''):
1180 """Print the status of the logging system."""
1188 """Print the status of the logging system."""
1181
1189
1182 self.shell.logger.logstate()
1190 self.shell.logger.logstate()
1183
1191
1184 def magic_pdb(self, parameter_s=''):
1192 def magic_pdb(self, parameter_s=''):
1185 """Control the automatic calling of the pdb interactive debugger.
1193 """Control the automatic calling of the pdb interactive debugger.
1186
1194
1187 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1195 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1188 argument it works as a toggle.
1196 argument it works as a toggle.
1189
1197
1190 When an exception is triggered, IPython can optionally call the
1198 When an exception is triggered, IPython can optionally call the
1191 interactive pdb debugger after the traceback printout. %pdb toggles
1199 interactive pdb debugger after the traceback printout. %pdb toggles
1192 this feature on and off.
1200 this feature on and off.
1193
1201
1194 The initial state of this feature is set in your ipythonrc
1202 The initial state of this feature is set in your ipythonrc
1195 configuration file (the variable is called 'pdb').
1203 configuration file (the variable is called 'pdb').
1196
1204
1197 If you want to just activate the debugger AFTER an exception has fired,
1205 If you want to just activate the debugger AFTER an exception has fired,
1198 without having to type '%pdb on' and rerunning your code, you can use
1206 without having to type '%pdb on' and rerunning your code, you can use
1199 the %debug magic."""
1207 the %debug magic."""
1200
1208
1201 par = parameter_s.strip().lower()
1209 par = parameter_s.strip().lower()
1202
1210
1203 if par:
1211 if par:
1204 try:
1212 try:
1205 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1213 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1206 except KeyError:
1214 except KeyError:
1207 print ('Incorrect argument. Use on/1, off/0, '
1215 print ('Incorrect argument. Use on/1, off/0, '
1208 'or nothing for a toggle.')
1216 'or nothing for a toggle.')
1209 return
1217 return
1210 else:
1218 else:
1211 # toggle
1219 # toggle
1212 new_pdb = not self.shell.call_pdb
1220 new_pdb = not self.shell.call_pdb
1213
1221
1214 # set on the shell
1222 # set on the shell
1215 self.shell.call_pdb = new_pdb
1223 self.shell.call_pdb = new_pdb
1216 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1224 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1217
1225
1218 def magic_debug(self, parameter_s=''):
1226 def magic_debug(self, parameter_s=''):
1219 """Activate the interactive debugger in post-mortem mode.
1227 """Activate the interactive debugger in post-mortem mode.
1220
1228
1221 If an exception has just occurred, this lets you inspect its stack
1229 If an exception has just occurred, this lets you inspect its stack
1222 frames interactively. Note that this will always work only on the last
1230 frames interactively. Note that this will always work only on the last
1223 traceback that occurred, so you must call this quickly after an
1231 traceback that occurred, so you must call this quickly after an
1224 exception that you wish to inspect has fired, because if another one
1232 exception that you wish to inspect has fired, because if another one
1225 occurs, it clobbers the previous one.
1233 occurs, it clobbers the previous one.
1226
1234
1227 If you want IPython to automatically do this on every exception, see
1235 If you want IPython to automatically do this on every exception, see
1228 the %pdb magic for more details.
1236 the %pdb magic for more details.
1229 """
1237 """
1230
1238
1231 self.shell.debugger(force=True)
1239 self.shell.debugger(force=True)
1232
1240
1233 def magic_prun(self, parameter_s ='',user_mode=1,
1241 def magic_prun(self, parameter_s ='',user_mode=1,
1234 opts=None,arg_lst=None,prog_ns=None):
1242 opts=None,arg_lst=None,prog_ns=None):
1235
1243
1236 """Run a statement through the python code profiler.
1244 """Run a statement through the python code profiler.
1237
1245
1238 Usage:\\
1246 Usage:\\
1239 %prun [options] statement
1247 %prun [options] statement
1240
1248
1241 The given statement (which doesn't require quote marks) is run via the
1249 The given statement (which doesn't require quote marks) is run via the
1242 python profiler in a manner similar to the profile.run() function.
1250 python profiler in a manner similar to the profile.run() function.
1243 Namespaces are internally managed to work correctly; profile.run
1251 Namespaces are internally managed to work correctly; profile.run
1244 cannot be used in IPython because it makes certain assumptions about
1252 cannot be used in IPython because it makes certain assumptions about
1245 namespaces which do not hold under IPython.
1253 namespaces which do not hold under IPython.
1246
1254
1247 Options:
1255 Options:
1248
1256
1249 -l <limit>: you can place restrictions on what or how much of the
1257 -l <limit>: you can place restrictions on what or how much of the
1250 profile gets printed. The limit value can be:
1258 profile gets printed. The limit value can be:
1251
1259
1252 * A string: only information for function names containing this string
1260 * A string: only information for function names containing this string
1253 is printed.
1261 is printed.
1254
1262
1255 * An integer: only these many lines are printed.
1263 * An integer: only these many lines are printed.
1256
1264
1257 * A float (between 0 and 1): this fraction of the report is printed
1265 * A float (between 0 and 1): this fraction of the report is printed
1258 (for example, use a limit of 0.4 to see the topmost 40% only).
1266 (for example, use a limit of 0.4 to see the topmost 40% only).
1259
1267
1260 You can combine several limits with repeated use of the option. For
1268 You can combine several limits with repeated use of the option. For
1261 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1269 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1262 information about class constructors.
1270 information about class constructors.
1263
1271
1264 -r: return the pstats.Stats object generated by the profiling. This
1272 -r: return the pstats.Stats object generated by the profiling. This
1265 object has all the information about the profile in it, and you can
1273 object has all the information about the profile in it, and you can
1266 later use it for further analysis or in other functions.
1274 later use it for further analysis or in other functions.
1267
1275
1268 -s <key>: sort profile by given key. You can provide more than one key
1276 -s <key>: sort profile by given key. You can provide more than one key
1269 by using the option several times: '-s key1 -s key2 -s key3...'. The
1277 by using the option several times: '-s key1 -s key2 -s key3...'. The
1270 default sorting key is 'time'.
1278 default sorting key is 'time'.
1271
1279
1272 The following is copied verbatim from the profile documentation
1280 The following is copied verbatim from the profile documentation
1273 referenced below:
1281 referenced below:
1274
1282
1275 When more than one key is provided, additional keys are used as
1283 When more than one key is provided, additional keys are used as
1276 secondary criteria when the there is equality in all keys selected
1284 secondary criteria when the there is equality in all keys selected
1277 before them.
1285 before them.
1278
1286
1279 Abbreviations can be used for any key names, as long as the
1287 Abbreviations can be used for any key names, as long as the
1280 abbreviation is unambiguous. The following are the keys currently
1288 abbreviation is unambiguous. The following are the keys currently
1281 defined:
1289 defined:
1282
1290
1283 Valid Arg Meaning\\
1291 Valid Arg Meaning\\
1284 "calls" call count\\
1292 "calls" call count\\
1285 "cumulative" cumulative time\\
1293 "cumulative" cumulative time\\
1286 "file" file name\\
1294 "file" file name\\
1287 "module" file name\\
1295 "module" file name\\
1288 "pcalls" primitive call count\\
1296 "pcalls" primitive call count\\
1289 "line" line number\\
1297 "line" line number\\
1290 "name" function name\\
1298 "name" function name\\
1291 "nfl" name/file/line\\
1299 "nfl" name/file/line\\
1292 "stdname" standard name\\
1300 "stdname" standard name\\
1293 "time" internal time
1301 "time" internal time
1294
1302
1295 Note that all sorts on statistics are in descending order (placing
1303 Note that all sorts on statistics are in descending order (placing
1296 most time consuming items first), where as name, file, and line number
1304 most time consuming items first), where as name, file, and line number
1297 searches are in ascending order (i.e., alphabetical). The subtle
1305 searches are in ascending order (i.e., alphabetical). The subtle
1298 distinction between "nfl" and "stdname" is that the standard name is a
1306 distinction between "nfl" and "stdname" is that the standard name is a
1299 sort of the name as printed, which means that the embedded line
1307 sort of the name as printed, which means that the embedded line
1300 numbers get compared in an odd way. For example, lines 3, 20, and 40
1308 numbers get compared in an odd way. For example, lines 3, 20, and 40
1301 would (if the file names were the same) appear in the string order
1309 would (if the file names were the same) appear in the string order
1302 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1310 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1303 line numbers. In fact, sort_stats("nfl") is the same as
1311 line numbers. In fact, sort_stats("nfl") is the same as
1304 sort_stats("name", "file", "line").
1312 sort_stats("name", "file", "line").
1305
1313
1306 -T <filename>: save profile results as shown on screen to a text
1314 -T <filename>: save profile results as shown on screen to a text
1307 file. The profile is still shown on screen.
1315 file. The profile is still shown on screen.
1308
1316
1309 -D <filename>: save (via dump_stats) profile statistics to given
1317 -D <filename>: save (via dump_stats) profile statistics to given
1310 filename. This data is in a format understod by the pstats module, and
1318 filename. This data is in a format understod by the pstats module, and
1311 is generated by a call to the dump_stats() method of profile
1319 is generated by a call to the dump_stats() method of profile
1312 objects. The profile is still shown on screen.
1320 objects. The profile is still shown on screen.
1313
1321
1314 If you want to run complete programs under the profiler's control, use
1322 If you want to run complete programs under the profiler's control, use
1315 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1323 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1316 contains profiler specific options as described here.
1324 contains profiler specific options as described here.
1317
1325
1318 You can read the complete documentation for the profile module with:\\
1326 You can read the complete documentation for the profile module with:\\
1319 In [1]: import profile; profile.help() """
1327 In [1]: import profile; profile.help() """
1320
1328
1321 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1329 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1322 # protect user quote marks
1330 # protect user quote marks
1323 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1331 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1324
1332
1325 if user_mode: # regular user call
1333 if user_mode: # regular user call
1326 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1334 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1327 list_all=1)
1335 list_all=1)
1328 namespace = self.shell.user_ns
1336 namespace = self.shell.user_ns
1329 else: # called to run a program by %run -p
1337 else: # called to run a program by %run -p
1330 try:
1338 try:
1331 filename = get_py_filename(arg_lst[0])
1339 filename = get_py_filename(arg_lst[0])
1332 except IOError,msg:
1340 except IOError,msg:
1333 error(msg)
1341 error(msg)
1334 return
1342 return
1335
1343
1336 arg_str = 'execfile(filename,prog_ns)'
1344 arg_str = 'execfile(filename,prog_ns)'
1337 namespace = locals()
1345 namespace = locals()
1338
1346
1339 opts.merge(opts_def)
1347 opts.merge(opts_def)
1340
1348
1341 prof = profile.Profile()
1349 prof = profile.Profile()
1342 try:
1350 try:
1343 prof = prof.runctx(arg_str,namespace,namespace)
1351 prof = prof.runctx(arg_str,namespace,namespace)
1344 sys_exit = ''
1352 sys_exit = ''
1345 except SystemExit:
1353 except SystemExit:
1346 sys_exit = """*** SystemExit exception caught in code being profiled."""
1354 sys_exit = """*** SystemExit exception caught in code being profiled."""
1347
1355
1348 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1356 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1349
1357
1350 lims = opts.l
1358 lims = opts.l
1351 if lims:
1359 if lims:
1352 lims = [] # rebuild lims with ints/floats/strings
1360 lims = [] # rebuild lims with ints/floats/strings
1353 for lim in opts.l:
1361 for lim in opts.l:
1354 try:
1362 try:
1355 lims.append(int(lim))
1363 lims.append(int(lim))
1356 except ValueError:
1364 except ValueError:
1357 try:
1365 try:
1358 lims.append(float(lim))
1366 lims.append(float(lim))
1359 except ValueError:
1367 except ValueError:
1360 lims.append(lim)
1368 lims.append(lim)
1361
1369
1362 # Trap output.
1370 # Trap output.
1363 stdout_trap = StringIO()
1371 stdout_trap = StringIO()
1364
1372
1365 if hasattr(stats,'stream'):
1373 if hasattr(stats,'stream'):
1366 # In newer versions of python, the stats object has a 'stream'
1374 # In newer versions of python, the stats object has a 'stream'
1367 # attribute to write into.
1375 # attribute to write into.
1368 stats.stream = stdout_trap
1376 stats.stream = stdout_trap
1369 stats.print_stats(*lims)
1377 stats.print_stats(*lims)
1370 else:
1378 else:
1371 # For older versions, we manually redirect stdout during printing
1379 # For older versions, we manually redirect stdout during printing
1372 sys_stdout = sys.stdout
1380 sys_stdout = sys.stdout
1373 try:
1381 try:
1374 sys.stdout = stdout_trap
1382 sys.stdout = stdout_trap
1375 stats.print_stats(*lims)
1383 stats.print_stats(*lims)
1376 finally:
1384 finally:
1377 sys.stdout = sys_stdout
1385 sys.stdout = sys_stdout
1378
1386
1379 output = stdout_trap.getvalue()
1387 output = stdout_trap.getvalue()
1380 output = output.rstrip()
1388 output = output.rstrip()
1381
1389
1382 page(output,screen_lines=self.shell.rc.screen_length)
1390 page(output,screen_lines=self.shell.rc.screen_length)
1383 print sys_exit,
1391 print sys_exit,
1384
1392
1385 dump_file = opts.D[0]
1393 dump_file = opts.D[0]
1386 text_file = opts.T[0]
1394 text_file = opts.T[0]
1387 if dump_file:
1395 if dump_file:
1388 prof.dump_stats(dump_file)
1396 prof.dump_stats(dump_file)
1389 print '\n*** Profile stats marshalled to file',\
1397 print '\n*** Profile stats marshalled to file',\
1390 `dump_file`+'.',sys_exit
1398 `dump_file`+'.',sys_exit
1391 if text_file:
1399 if text_file:
1392 pfile = file(text_file,'w')
1400 pfile = file(text_file,'w')
1393 pfile.write(output)
1401 pfile.write(output)
1394 pfile.close()
1402 pfile.close()
1395 print '\n*** Profile printout saved to text file',\
1403 print '\n*** Profile printout saved to text file',\
1396 `text_file`+'.',sys_exit
1404 `text_file`+'.',sys_exit
1397
1405
1398 if opts.has_key('r'):
1406 if opts.has_key('r'):
1399 return stats
1407 return stats
1400 else:
1408 else:
1401 return None
1409 return None
1402
1410
1403 def magic_run(self, parameter_s ='',runner=None):
1411 def magic_run(self, parameter_s ='',runner=None):
1404 """Run the named file inside IPython as a program.
1412 """Run the named file inside IPython as a program.
1405
1413
1406 Usage:\\
1414 Usage:\\
1407 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1415 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1408
1416
1409 Parameters after the filename are passed as command-line arguments to
1417 Parameters after the filename are passed as command-line arguments to
1410 the program (put in sys.argv). Then, control returns to IPython's
1418 the program (put in sys.argv). Then, control returns to IPython's
1411 prompt.
1419 prompt.
1412
1420
1413 This is similar to running at a system prompt:\\
1421 This is similar to running at a system prompt:\\
1414 $ python file args\\
1422 $ python file args\\
1415 but with the advantage of giving you IPython's tracebacks, and of
1423 but with the advantage of giving you IPython's tracebacks, and of
1416 loading all variables into your interactive namespace for further use
1424 loading all variables into your interactive namespace for further use
1417 (unless -p is used, see below).
1425 (unless -p is used, see below).
1418
1426
1419 The file is executed in a namespace initially consisting only of
1427 The file is executed in a namespace initially consisting only of
1420 __name__=='__main__' and sys.argv constructed as indicated. It thus
1428 __name__=='__main__' and sys.argv constructed as indicated. It thus
1421 sees its environment as if it were being run as a stand-alone
1429 sees its environment as if it were being run as a stand-alone
1422 program. But after execution, the IPython interactive namespace gets
1430 program. But after execution, the IPython interactive namespace gets
1423 updated with all variables defined in the program (except for __name__
1431 updated with all variables defined in the program (except for __name__
1424 and sys.argv). This allows for very convenient loading of code for
1432 and sys.argv). This allows for very convenient loading of code for
1425 interactive work, while giving each program a 'clean sheet' to run in.
1433 interactive work, while giving each program a 'clean sheet' to run in.
1426
1434
1427 Options:
1435 Options:
1428
1436
1429 -n: __name__ is NOT set to '__main__', but to the running file's name
1437 -n: __name__ is NOT set to '__main__', but to the running file's name
1430 without extension (as python does under import). This allows running
1438 without extension (as python does under import). This allows running
1431 scripts and reloading the definitions in them without calling code
1439 scripts and reloading the definitions in them without calling code
1432 protected by an ' if __name__ == "__main__" ' clause.
1440 protected by an ' if __name__ == "__main__" ' clause.
1433
1441
1434 -i: run the file in IPython's namespace instead of an empty one. This
1442 -i: run the file in IPython's namespace instead of an empty one. This
1435 is useful if you are experimenting with code written in a text editor
1443 is useful if you are experimenting with code written in a text editor
1436 which depends on variables defined interactively.
1444 which depends on variables defined interactively.
1437
1445
1438 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1446 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1439 being run. This is particularly useful if IPython is being used to
1447 being run. This is particularly useful if IPython is being used to
1440 run unittests, which always exit with a sys.exit() call. In such
1448 run unittests, which always exit with a sys.exit() call. In such
1441 cases you are interested in the output of the test results, not in
1449 cases you are interested in the output of the test results, not in
1442 seeing a traceback of the unittest module.
1450 seeing a traceback of the unittest module.
1443
1451
1444 -t: print timing information at the end of the run. IPython will give
1452 -t: print timing information at the end of the run. IPython will give
1445 you an estimated CPU time consumption for your script, which under
1453 you an estimated CPU time consumption for your script, which under
1446 Unix uses the resource module to avoid the wraparound problems of
1454 Unix uses the resource module to avoid the wraparound problems of
1447 time.clock(). Under Unix, an estimate of time spent on system tasks
1455 time.clock(). Under Unix, an estimate of time spent on system tasks
1448 is also given (for Windows platforms this is reported as 0.0).
1456 is also given (for Windows platforms this is reported as 0.0).
1449
1457
1450 If -t is given, an additional -N<N> option can be given, where <N>
1458 If -t is given, an additional -N<N> option can be given, where <N>
1451 must be an integer indicating how many times you want the script to
1459 must be an integer indicating how many times you want the script to
1452 run. The final timing report will include total and per run results.
1460 run. The final timing report will include total and per run results.
1453
1461
1454 For example (testing the script uniq_stable.py):
1462 For example (testing the script uniq_stable.py):
1455
1463
1456 In [1]: run -t uniq_stable
1464 In [1]: run -t uniq_stable
1457
1465
1458 IPython CPU timings (estimated):\\
1466 IPython CPU timings (estimated):\\
1459 User : 0.19597 s.\\
1467 User : 0.19597 s.\\
1460 System: 0.0 s.\\
1468 System: 0.0 s.\\
1461
1469
1462 In [2]: run -t -N5 uniq_stable
1470 In [2]: run -t -N5 uniq_stable
1463
1471
1464 IPython CPU timings (estimated):\\
1472 IPython CPU timings (estimated):\\
1465 Total runs performed: 5\\
1473 Total runs performed: 5\\
1466 Times : Total Per run\\
1474 Times : Total Per run\\
1467 User : 0.910862 s, 0.1821724 s.\\
1475 User : 0.910862 s, 0.1821724 s.\\
1468 System: 0.0 s, 0.0 s.
1476 System: 0.0 s, 0.0 s.
1469
1477
1470 -d: run your program under the control of pdb, the Python debugger.
1478 -d: run your program under the control of pdb, the Python debugger.
1471 This allows you to execute your program step by step, watch variables,
1479 This allows you to execute your program step by step, watch variables,
1472 etc. Internally, what IPython does is similar to calling:
1480 etc. Internally, what IPython does is similar to calling:
1473
1481
1474 pdb.run('execfile("YOURFILENAME")')
1482 pdb.run('execfile("YOURFILENAME")')
1475
1483
1476 with a breakpoint set on line 1 of your file. You can change the line
1484 with a breakpoint set on line 1 of your file. You can change the line
1477 number for this automatic breakpoint to be <N> by using the -bN option
1485 number for this automatic breakpoint to be <N> by using the -bN option
1478 (where N must be an integer). For example:
1486 (where N must be an integer). For example:
1479
1487
1480 %run -d -b40 myscript
1488 %run -d -b40 myscript
1481
1489
1482 will set the first breakpoint at line 40 in myscript.py. Note that
1490 will set the first breakpoint at line 40 in myscript.py. Note that
1483 the first breakpoint must be set on a line which actually does
1491 the first breakpoint must be set on a line which actually does
1484 something (not a comment or docstring) for it to stop execution.
1492 something (not a comment or docstring) for it to stop execution.
1485
1493
1486 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1494 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1487 first enter 'c' (without qoutes) to start execution up to the first
1495 first enter 'c' (without qoutes) to start execution up to the first
1488 breakpoint.
1496 breakpoint.
1489
1497
1490 Entering 'help' gives information about the use of the debugger. You
1498 Entering 'help' gives information about the use of the debugger. You
1491 can easily see pdb's full documentation with "import pdb;pdb.help()"
1499 can easily see pdb's full documentation with "import pdb;pdb.help()"
1492 at a prompt.
1500 at a prompt.
1493
1501
1494 -p: run program under the control of the Python profiler module (which
1502 -p: run program under the control of the Python profiler module (which
1495 prints a detailed report of execution times, function calls, etc).
1503 prints a detailed report of execution times, function calls, etc).
1496
1504
1497 You can pass other options after -p which affect the behavior of the
1505 You can pass other options after -p which affect the behavior of the
1498 profiler itself. See the docs for %prun for details.
1506 profiler itself. See the docs for %prun for details.
1499
1507
1500 In this mode, the program's variables do NOT propagate back to the
1508 In this mode, the program's variables do NOT propagate back to the
1501 IPython interactive namespace (because they remain in the namespace
1509 IPython interactive namespace (because they remain in the namespace
1502 where the profiler executes them).
1510 where the profiler executes them).
1503
1511
1504 Internally this triggers a call to %prun, see its documentation for
1512 Internally this triggers a call to %prun, see its documentation for
1505 details on the options available specifically for profiling.
1513 details on the options available specifically for profiling.
1506
1514
1507 There is one special usage for which the text above doesn't apply:
1515 There is one special usage for which the text above doesn't apply:
1508 if the filename ends with .ipy, the file is run as ipython script,
1516 if the filename ends with .ipy, the file is run as ipython script,
1509 just as if the commands were written on IPython prompt.
1517 just as if the commands were written on IPython prompt.
1510 """
1518 """
1511
1519
1512 # get arguments and set sys.argv for program to be run.
1520 # get arguments and set sys.argv for program to be run.
1513 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1521 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1514 mode='list',list_all=1)
1522 mode='list',list_all=1)
1515
1523
1516 try:
1524 try:
1517 filename = get_py_filename(arg_lst[0])
1525 filename = get_py_filename(arg_lst[0])
1518 except IndexError:
1526 except IndexError:
1519 warn('you must provide at least a filename.')
1527 warn('you must provide at least a filename.')
1520 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1528 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1521 return
1529 return
1522 except IOError,msg:
1530 except IOError,msg:
1523 error(msg)
1531 error(msg)
1524 return
1532 return
1525
1533
1526 if filename.lower().endswith('.ipy'):
1534 if filename.lower().endswith('.ipy'):
1527 self.api.runlines(open(filename).read())
1535 self.api.runlines(open(filename).read())
1528 return
1536 return
1529
1537
1530 # Control the response to exit() calls made by the script being run
1538 # Control the response to exit() calls made by the script being run
1531 exit_ignore = opts.has_key('e')
1539 exit_ignore = opts.has_key('e')
1532
1540
1533 # Make sure that the running script gets a proper sys.argv as if it
1541 # Make sure that the running script gets a proper sys.argv as if it
1534 # were run from a system shell.
1542 # were run from a system shell.
1535 save_argv = sys.argv # save it for later restoring
1543 save_argv = sys.argv # save it for later restoring
1536 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1544 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1537
1545
1538 if opts.has_key('i'):
1546 if opts.has_key('i'):
1539 prog_ns = self.shell.user_ns
1547 prog_ns = self.shell.user_ns
1540 __name__save = self.shell.user_ns['__name__']
1548 __name__save = self.shell.user_ns['__name__']
1541 prog_ns['__name__'] = '__main__'
1549 prog_ns['__name__'] = '__main__'
1542 else:
1550 else:
1543 if opts.has_key('n'):
1551 if opts.has_key('n'):
1544 name = os.path.splitext(os.path.basename(filename))[0]
1552 name = os.path.splitext(os.path.basename(filename))[0]
1545 else:
1553 else:
1546 name = '__main__'
1554 name = '__main__'
1547 prog_ns = {'__name__':name}
1555 prog_ns = {'__name__':name}
1548
1556
1549 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1557 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1550 # set the __file__ global in the script's namespace
1558 # set the __file__ global in the script's namespace
1551 prog_ns['__file__'] = filename
1559 prog_ns['__file__'] = filename
1552
1560
1553 # pickle fix. See iplib for an explanation. But we need to make sure
1561 # pickle fix. See iplib for an explanation. But we need to make sure
1554 # that, if we overwrite __main__, we replace it at the end
1562 # that, if we overwrite __main__, we replace it at the end
1555 if prog_ns['__name__'] == '__main__':
1563 if prog_ns['__name__'] == '__main__':
1556 restore_main = sys.modules['__main__']
1564 restore_main = sys.modules['__main__']
1557 else:
1565 else:
1558 restore_main = False
1566 restore_main = False
1559
1567
1560 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1568 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1561
1569
1562 stats = None
1570 stats = None
1563 try:
1571 try:
1564 if self.shell.has_readline:
1572 if self.shell.has_readline:
1565 self.shell.savehist()
1573 self.shell.savehist()
1566
1574
1567 if opts.has_key('p'):
1575 if opts.has_key('p'):
1568 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1576 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1569 else:
1577 else:
1570 if opts.has_key('d'):
1578 if opts.has_key('d'):
1571 deb = Debugger.Pdb(self.shell.rc.colors)
1579 deb = Debugger.Pdb(self.shell.rc.colors)
1572 # reset Breakpoint state, which is moronically kept
1580 # reset Breakpoint state, which is moronically kept
1573 # in a class
1581 # in a class
1574 bdb.Breakpoint.next = 1
1582 bdb.Breakpoint.next = 1
1575 bdb.Breakpoint.bplist = {}
1583 bdb.Breakpoint.bplist = {}
1576 bdb.Breakpoint.bpbynumber = [None]
1584 bdb.Breakpoint.bpbynumber = [None]
1577 # Set an initial breakpoint to stop execution
1585 # Set an initial breakpoint to stop execution
1578 maxtries = 10
1586 maxtries = 10
1579 bp = int(opts.get('b',[1])[0])
1587 bp = int(opts.get('b',[1])[0])
1580 checkline = deb.checkline(filename,bp)
1588 checkline = deb.checkline(filename,bp)
1581 if not checkline:
1589 if not checkline:
1582 for bp in range(bp+1,bp+maxtries+1):
1590 for bp in range(bp+1,bp+maxtries+1):
1583 if deb.checkline(filename,bp):
1591 if deb.checkline(filename,bp):
1584 break
1592 break
1585 else:
1593 else:
1586 msg = ("\nI failed to find a valid line to set "
1594 msg = ("\nI failed to find a valid line to set "
1587 "a breakpoint\n"
1595 "a breakpoint\n"
1588 "after trying up to line: %s.\n"
1596 "after trying up to line: %s.\n"
1589 "Please set a valid breakpoint manually "
1597 "Please set a valid breakpoint manually "
1590 "with the -b option." % bp)
1598 "with the -b option." % bp)
1591 error(msg)
1599 error(msg)
1592 return
1600 return
1593 # if we find a good linenumber, set the breakpoint
1601 # if we find a good linenumber, set the breakpoint
1594 deb.do_break('%s:%s' % (filename,bp))
1602 deb.do_break('%s:%s' % (filename,bp))
1595 # Start file run
1603 # Start file run
1596 print "NOTE: Enter 'c' at the",
1604 print "NOTE: Enter 'c' at the",
1597 print "%s prompt to start your script." % deb.prompt
1605 print "%s prompt to start your script." % deb.prompt
1598 try:
1606 try:
1599 deb.run('execfile("%s")' % filename,prog_ns)
1607 deb.run('execfile("%s")' % filename,prog_ns)
1600
1608
1601 except:
1609 except:
1602 etype, value, tb = sys.exc_info()
1610 etype, value, tb = sys.exc_info()
1603 # Skip three frames in the traceback: the %run one,
1611 # Skip three frames in the traceback: the %run one,
1604 # one inside bdb.py, and the command-line typed by the
1612 # one inside bdb.py, and the command-line typed by the
1605 # user (run by exec in pdb itself).
1613 # user (run by exec in pdb itself).
1606 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1614 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1607 else:
1615 else:
1608 if runner is None:
1616 if runner is None:
1609 runner = self.shell.safe_execfile
1617 runner = self.shell.safe_execfile
1610 if opts.has_key('t'):
1618 if opts.has_key('t'):
1611 try:
1619 try:
1612 nruns = int(opts['N'][0])
1620 nruns = int(opts['N'][0])
1613 if nruns < 1:
1621 if nruns < 1:
1614 error('Number of runs must be >=1')
1622 error('Number of runs must be >=1')
1615 return
1623 return
1616 except (KeyError):
1624 except (KeyError):
1617 nruns = 1
1625 nruns = 1
1618 if nruns == 1:
1626 if nruns == 1:
1619 t0 = clock2()
1627 t0 = clock2()
1620 runner(filename,prog_ns,prog_ns,
1628 runner(filename,prog_ns,prog_ns,
1621 exit_ignore=exit_ignore)
1629 exit_ignore=exit_ignore)
1622 t1 = clock2()
1630 t1 = clock2()
1623 t_usr = t1[0]-t0[0]
1631 t_usr = t1[0]-t0[0]
1624 t_sys = t1[1]-t1[1]
1632 t_sys = t1[1]-t1[1]
1625 print "\nIPython CPU timings (estimated):"
1633 print "\nIPython CPU timings (estimated):"
1626 print " User : %10s s." % t_usr
1634 print " User : %10s s." % t_usr
1627 print " System: %10s s." % t_sys
1635 print " System: %10s s." % t_sys
1628 else:
1636 else:
1629 runs = range(nruns)
1637 runs = range(nruns)
1630 t0 = clock2()
1638 t0 = clock2()
1631 for nr in runs:
1639 for nr in runs:
1632 runner(filename,prog_ns,prog_ns,
1640 runner(filename,prog_ns,prog_ns,
1633 exit_ignore=exit_ignore)
1641 exit_ignore=exit_ignore)
1634 t1 = clock2()
1642 t1 = clock2()
1635 t_usr = t1[0]-t0[0]
1643 t_usr = t1[0]-t0[0]
1636 t_sys = t1[1]-t1[1]
1644 t_sys = t1[1]-t1[1]
1637 print "\nIPython CPU timings (estimated):"
1645 print "\nIPython CPU timings (estimated):"
1638 print "Total runs performed:",nruns
1646 print "Total runs performed:",nruns
1639 print " Times : %10s %10s" % ('Total','Per run')
1647 print " Times : %10s %10s" % ('Total','Per run')
1640 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1648 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1641 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1649 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1642
1650
1643 else:
1651 else:
1644 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1652 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1645 if opts.has_key('i'):
1653 if opts.has_key('i'):
1646 self.shell.user_ns['__name__'] = __name__save
1654 self.shell.user_ns['__name__'] = __name__save
1647 else:
1655 else:
1648 # update IPython interactive namespace
1656 # update IPython interactive namespace
1649 del prog_ns['__name__']
1657 del prog_ns['__name__']
1650 self.shell.user_ns.update(prog_ns)
1658 self.shell.user_ns.update(prog_ns)
1651 finally:
1659 finally:
1652 sys.argv = save_argv
1660 sys.argv = save_argv
1653 if restore_main:
1661 if restore_main:
1654 sys.modules['__main__'] = restore_main
1662 sys.modules['__main__'] = restore_main
1655 if self.shell.has_readline:
1663 if self.shell.has_readline:
1656 self.shell.readline.read_history_file(self.shell.histfile)
1664 self.shell.readline.read_history_file(self.shell.histfile)
1657
1665
1658 return stats
1666 return stats
1659
1667
1660 def magic_runlog(self, parameter_s =''):
1668 def magic_runlog(self, parameter_s =''):
1661 """Run files as logs.
1669 """Run files as logs.
1662
1670
1663 Usage:\\
1671 Usage:\\
1664 %runlog file1 file2 ...
1672 %runlog file1 file2 ...
1665
1673
1666 Run the named files (treating them as log files) in sequence inside
1674 Run the named files (treating them as log files) in sequence inside
1667 the interpreter, and return to the prompt. This is much slower than
1675 the interpreter, and return to the prompt. This is much slower than
1668 %run because each line is executed in a try/except block, but it
1676 %run because each line is executed in a try/except block, but it
1669 allows running files with syntax errors in them.
1677 allows running files with syntax errors in them.
1670
1678
1671 Normally IPython will guess when a file is one of its own logfiles, so
1679 Normally IPython will guess when a file is one of its own logfiles, so
1672 you can typically use %run even for logs. This shorthand allows you to
1680 you can typically use %run even for logs. This shorthand allows you to
1673 force any file to be treated as a log file."""
1681 force any file to be treated as a log file."""
1674
1682
1675 for f in parameter_s.split():
1683 for f in parameter_s.split():
1676 self.shell.safe_execfile(f,self.shell.user_ns,
1684 self.shell.safe_execfile(f,self.shell.user_ns,
1677 self.shell.user_ns,islog=1)
1685 self.shell.user_ns,islog=1)
1678
1686
1679 def magic_timeit(self, parameter_s =''):
1687 def magic_timeit(self, parameter_s =''):
1680 """Time execution of a Python statement or expression
1688 """Time execution of a Python statement or expression
1681
1689
1682 Usage:\\
1690 Usage:\\
1683 %timeit [-n<N> -r<R> [-t|-c]] statement
1691 %timeit [-n<N> -r<R> [-t|-c]] statement
1684
1692
1685 Time execution of a Python statement or expression using the timeit
1693 Time execution of a Python statement or expression using the timeit
1686 module.
1694 module.
1687
1695
1688 Options:
1696 Options:
1689 -n<N>: execute the given statement <N> times in a loop. If this value
1697 -n<N>: execute the given statement <N> times in a loop. If this value
1690 is not given, a fitting value is chosen.
1698 is not given, a fitting value is chosen.
1691
1699
1692 -r<R>: repeat the loop iteration <R> times and take the best result.
1700 -r<R>: repeat the loop iteration <R> times and take the best result.
1693 Default: 3
1701 Default: 3
1694
1702
1695 -t: use time.time to measure the time, which is the default on Unix.
1703 -t: use time.time to measure the time, which is the default on Unix.
1696 This function measures wall time.
1704 This function measures wall time.
1697
1705
1698 -c: use time.clock to measure the time, which is the default on
1706 -c: use time.clock to measure the time, which is the default on
1699 Windows and measures wall time. On Unix, resource.getrusage is used
1707 Windows and measures wall time. On Unix, resource.getrusage is used
1700 instead and returns the CPU user time.
1708 instead and returns the CPU user time.
1701
1709
1702 -p<P>: use a precision of <P> digits to display the timing result.
1710 -p<P>: use a precision of <P> digits to display the timing result.
1703 Default: 3
1711 Default: 3
1704
1712
1705
1713
1706 Examples:\\
1714 Examples:\\
1707 In [1]: %timeit pass
1715 In [1]: %timeit pass
1708 10000000 loops, best of 3: 53.3 ns per loop
1716 10000000 loops, best of 3: 53.3 ns per loop
1709
1717
1710 In [2]: u = None
1718 In [2]: u = None
1711
1719
1712 In [3]: %timeit u is None
1720 In [3]: %timeit u is None
1713 10000000 loops, best of 3: 184 ns per loop
1721 10000000 loops, best of 3: 184 ns per loop
1714
1722
1715 In [4]: %timeit -r 4 u == None
1723 In [4]: %timeit -r 4 u == None
1716 1000000 loops, best of 4: 242 ns per loop
1724 1000000 loops, best of 4: 242 ns per loop
1717
1725
1718 In [5]: import time
1726 In [5]: import time
1719
1727
1720 In [6]: %timeit -n1 time.sleep(2)
1728 In [6]: %timeit -n1 time.sleep(2)
1721 1 loops, best of 3: 2 s per loop
1729 1 loops, best of 3: 2 s per loop
1722
1730
1723
1731
1724 The times reported by %timeit will be slightly higher than those
1732 The times reported by %timeit will be slightly higher than those
1725 reported by the timeit.py script when variables are accessed. This is
1733 reported by the timeit.py script when variables are accessed. This is
1726 due to the fact that %timeit executes the statement in the namespace
1734 due to the fact that %timeit executes the statement in the namespace
1727 of the shell, compared with timeit.py, which uses a single setup
1735 of the shell, compared with timeit.py, which uses a single setup
1728 statement to import function or create variables. Generally, the bias
1736 statement to import function or create variables. Generally, the bias
1729 does not matter as long as results from timeit.py are not mixed with
1737 does not matter as long as results from timeit.py are not mixed with
1730 those from %timeit."""
1738 those from %timeit."""
1731
1739
1732 import timeit
1740 import timeit
1733 import math
1741 import math
1734
1742
1735 units = ["s", "ms", "\xc2\xb5s", "ns"]
1743 units = ["s", "ms", "\xc2\xb5s", "ns"]
1736 scaling = [1, 1e3, 1e6, 1e9]
1744 scaling = [1, 1e3, 1e6, 1e9]
1737
1745
1738 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1746 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1739 posix=False)
1747 posix=False)
1740 if stmt == "":
1748 if stmt == "":
1741 return
1749 return
1742 timefunc = timeit.default_timer
1750 timefunc = timeit.default_timer
1743 number = int(getattr(opts, "n", 0))
1751 number = int(getattr(opts, "n", 0))
1744 repeat = int(getattr(opts, "r", timeit.default_repeat))
1752 repeat = int(getattr(opts, "r", timeit.default_repeat))
1745 precision = int(getattr(opts, "p", 3))
1753 precision = int(getattr(opts, "p", 3))
1746 if hasattr(opts, "t"):
1754 if hasattr(opts, "t"):
1747 timefunc = time.time
1755 timefunc = time.time
1748 if hasattr(opts, "c"):
1756 if hasattr(opts, "c"):
1749 timefunc = clock
1757 timefunc = clock
1750
1758
1751 timer = timeit.Timer(timer=timefunc)
1759 timer = timeit.Timer(timer=timefunc)
1752 # this code has tight coupling to the inner workings of timeit.Timer,
1760 # this code has tight coupling to the inner workings of timeit.Timer,
1753 # but is there a better way to achieve that the code stmt has access
1761 # but is there a better way to achieve that the code stmt has access
1754 # to the shell namespace?
1762 # to the shell namespace?
1755
1763
1756 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1764 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1757 'setup': "pass"}
1765 'setup': "pass"}
1758 code = compile(src, "<magic-timeit>", "exec")
1766 code = compile(src, "<magic-timeit>", "exec")
1759 ns = {}
1767 ns = {}
1760 exec code in self.shell.user_ns, ns
1768 exec code in self.shell.user_ns, ns
1761 timer.inner = ns["inner"]
1769 timer.inner = ns["inner"]
1762
1770
1763 if number == 0:
1771 if number == 0:
1764 # determine number so that 0.2 <= total time < 2.0
1772 # determine number so that 0.2 <= total time < 2.0
1765 number = 1
1773 number = 1
1766 for i in range(1, 10):
1774 for i in range(1, 10):
1767 number *= 10
1775 number *= 10
1768 if timer.timeit(number) >= 0.2:
1776 if timer.timeit(number) >= 0.2:
1769 break
1777 break
1770
1778
1771 best = min(timer.repeat(repeat, number)) / number
1779 best = min(timer.repeat(repeat, number)) / number
1772
1780
1773 if best > 0.0:
1781 if best > 0.0:
1774 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1782 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1775 else:
1783 else:
1776 order = 3
1784 order = 3
1777 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1785 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1778 precision,
1786 precision,
1779 best * scaling[order],
1787 best * scaling[order],
1780 units[order])
1788 units[order])
1781
1789
1782 def magic_time(self,parameter_s = ''):
1790 def magic_time(self,parameter_s = ''):
1783 """Time execution of a Python statement or expression.
1791 """Time execution of a Python statement or expression.
1784
1792
1785 The CPU and wall clock times are printed, and the value of the
1793 The CPU and wall clock times are printed, and the value of the
1786 expression (if any) is returned. Note that under Win32, system time
1794 expression (if any) is returned. Note that under Win32, system time
1787 is always reported as 0, since it can not be measured.
1795 is always reported as 0, since it can not be measured.
1788
1796
1789 This function provides very basic timing functionality. In Python
1797 This function provides very basic timing functionality. In Python
1790 2.3, the timeit module offers more control and sophistication, so this
1798 2.3, the timeit module offers more control and sophistication, so this
1791 could be rewritten to use it (patches welcome).
1799 could be rewritten to use it (patches welcome).
1792
1800
1793 Some examples:
1801 Some examples:
1794
1802
1795 In [1]: time 2**128
1803 In [1]: time 2**128
1796 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1804 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1797 Wall time: 0.00
1805 Wall time: 0.00
1798 Out[1]: 340282366920938463463374607431768211456L
1806 Out[1]: 340282366920938463463374607431768211456L
1799
1807
1800 In [2]: n = 1000000
1808 In [2]: n = 1000000
1801
1809
1802 In [3]: time sum(range(n))
1810 In [3]: time sum(range(n))
1803 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1811 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1804 Wall time: 1.37
1812 Wall time: 1.37
1805 Out[3]: 499999500000L
1813 Out[3]: 499999500000L
1806
1814
1807 In [4]: time print 'hello world'
1815 In [4]: time print 'hello world'
1808 hello world
1816 hello world
1809 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1817 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1810 Wall time: 0.00
1818 Wall time: 0.00
1811 """
1819 """
1812
1820
1813 # fail immediately if the given expression can't be compiled
1821 # fail immediately if the given expression can't be compiled
1814 try:
1822 try:
1815 mode = 'eval'
1823 mode = 'eval'
1816 code = compile(parameter_s,'<timed eval>',mode)
1824 code = compile(parameter_s,'<timed eval>',mode)
1817 except SyntaxError:
1825 except SyntaxError:
1818 mode = 'exec'
1826 mode = 'exec'
1819 code = compile(parameter_s,'<timed exec>',mode)
1827 code = compile(parameter_s,'<timed exec>',mode)
1820 # skew measurement as little as possible
1828 # skew measurement as little as possible
1821 glob = self.shell.user_ns
1829 glob = self.shell.user_ns
1822 clk = clock2
1830 clk = clock2
1823 wtime = time.time
1831 wtime = time.time
1824 # time execution
1832 # time execution
1825 wall_st = wtime()
1833 wall_st = wtime()
1826 if mode=='eval':
1834 if mode=='eval':
1827 st = clk()
1835 st = clk()
1828 out = eval(code,glob)
1836 out = eval(code,glob)
1829 end = clk()
1837 end = clk()
1830 else:
1838 else:
1831 st = clk()
1839 st = clk()
1832 exec code in glob
1840 exec code in glob
1833 end = clk()
1841 end = clk()
1834 out = None
1842 out = None
1835 wall_end = wtime()
1843 wall_end = wtime()
1836 # Compute actual times and report
1844 # Compute actual times and report
1837 wall_time = wall_end-wall_st
1845 wall_time = wall_end-wall_st
1838 cpu_user = end[0]-st[0]
1846 cpu_user = end[0]-st[0]
1839 cpu_sys = end[1]-st[1]
1847 cpu_sys = end[1]-st[1]
1840 cpu_tot = cpu_user+cpu_sys
1848 cpu_tot = cpu_user+cpu_sys
1841 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1849 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1842 (cpu_user,cpu_sys,cpu_tot)
1850 (cpu_user,cpu_sys,cpu_tot)
1843 print "Wall time: %.2f" % wall_time
1851 print "Wall time: %.2f" % wall_time
1844 return out
1852 return out
1845
1853
1846 def magic_macro(self,parameter_s = ''):
1854 def magic_macro(self,parameter_s = ''):
1847 """Define a set of input lines as a macro for future re-execution.
1855 """Define a set of input lines as a macro for future re-execution.
1848
1856
1849 Usage:\\
1857 Usage:\\
1850 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1858 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1851
1859
1852 Options:
1860 Options:
1853
1861
1854 -r: use 'raw' input. By default, the 'processed' history is used,
1862 -r: use 'raw' input. By default, the 'processed' history is used,
1855 so that magics are loaded in their transformed version to valid
1863 so that magics are loaded in their transformed version to valid
1856 Python. If this option is given, the raw input as typed as the
1864 Python. If this option is given, the raw input as typed as the
1857 command line is used instead.
1865 command line is used instead.
1858
1866
1859 This will define a global variable called `name` which is a string
1867 This will define a global variable called `name` which is a string
1860 made of joining the slices and lines you specify (n1,n2,... numbers
1868 made of joining the slices and lines you specify (n1,n2,... numbers
1861 above) from your input history into a single string. This variable
1869 above) from your input history into a single string. This variable
1862 acts like an automatic function which re-executes those lines as if
1870 acts like an automatic function which re-executes those lines as if
1863 you had typed them. You just type 'name' at the prompt and the code
1871 you had typed them. You just type 'name' at the prompt and the code
1864 executes.
1872 executes.
1865
1873
1866 The notation for indicating number ranges is: n1-n2 means 'use line
1874 The notation for indicating number ranges is: n1-n2 means 'use line
1867 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1875 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1868 using the lines numbered 5,6 and 7.
1876 using the lines numbered 5,6 and 7.
1869
1877
1870 Note: as a 'hidden' feature, you can also use traditional python slice
1878 Note: as a 'hidden' feature, you can also use traditional python slice
1871 notation, where N:M means numbers N through M-1.
1879 notation, where N:M means numbers N through M-1.
1872
1880
1873 For example, if your history contains (%hist prints it):
1881 For example, if your history contains (%hist prints it):
1874
1882
1875 44: x=1\\
1883 44: x=1\\
1876 45: y=3\\
1884 45: y=3\\
1877 46: z=x+y\\
1885 46: z=x+y\\
1878 47: print x\\
1886 47: print x\\
1879 48: a=5\\
1887 48: a=5\\
1880 49: print 'x',x,'y',y\\
1888 49: print 'x',x,'y',y\\
1881
1889
1882 you can create a macro with lines 44 through 47 (included) and line 49
1890 you can create a macro with lines 44 through 47 (included) and line 49
1883 called my_macro with:
1891 called my_macro with:
1884
1892
1885 In [51]: %macro my_macro 44-47 49
1893 In [51]: %macro my_macro 44-47 49
1886
1894
1887 Now, typing `my_macro` (without quotes) will re-execute all this code
1895 Now, typing `my_macro` (without quotes) will re-execute all this code
1888 in one pass.
1896 in one pass.
1889
1897
1890 You don't need to give the line-numbers in order, and any given line
1898 You don't need to give the line-numbers in order, and any given line
1891 number can appear multiple times. You can assemble macros with any
1899 number can appear multiple times. You can assemble macros with any
1892 lines from your input history in any order.
1900 lines from your input history in any order.
1893
1901
1894 The macro is a simple object which holds its value in an attribute,
1902 The macro is a simple object which holds its value in an attribute,
1895 but IPython's display system checks for macros and executes them as
1903 but IPython's display system checks for macros and executes them as
1896 code instead of printing them when you type their name.
1904 code instead of printing them when you type their name.
1897
1905
1898 You can view a macro's contents by explicitly printing it with:
1906 You can view a macro's contents by explicitly printing it with:
1899
1907
1900 'print macro_name'.
1908 'print macro_name'.
1901
1909
1902 For one-off cases which DON'T contain magic function calls in them you
1910 For one-off cases which DON'T contain magic function calls in them you
1903 can obtain similar results by explicitly executing slices from your
1911 can obtain similar results by explicitly executing slices from your
1904 input history with:
1912 input history with:
1905
1913
1906 In [60]: exec In[44:48]+In[49]"""
1914 In [60]: exec In[44:48]+In[49]"""
1907
1915
1908 opts,args = self.parse_options(parameter_s,'r',mode='list')
1916 opts,args = self.parse_options(parameter_s,'r',mode='list')
1909 name,ranges = args[0], args[1:]
1917 name,ranges = args[0], args[1:]
1910 #print 'rng',ranges # dbg
1918 #print 'rng',ranges # dbg
1911 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1919 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1912 macro = Macro(lines)
1920 macro = Macro(lines)
1913 self.shell.user_ns.update({name:macro})
1921 self.shell.user_ns.update({name:macro})
1914 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1922 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1915 print 'Macro contents:'
1923 print 'Macro contents:'
1916 print macro,
1924 print macro,
1917
1925
1918 def magic_save(self,parameter_s = ''):
1926 def magic_save(self,parameter_s = ''):
1919 """Save a set of lines to a given filename.
1927 """Save a set of lines to a given filename.
1920
1928
1921 Usage:\\
1929 Usage:\\
1922 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1930 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1923
1931
1924 Options:
1932 Options:
1925
1933
1926 -r: use 'raw' input. By default, the 'processed' history is used,
1934 -r: use 'raw' input. By default, the 'processed' history is used,
1927 so that magics are loaded in their transformed version to valid
1935 so that magics are loaded in their transformed version to valid
1928 Python. If this option is given, the raw input as typed as the
1936 Python. If this option is given, the raw input as typed as the
1929 command line is used instead.
1937 command line is used instead.
1930
1938
1931 This function uses the same syntax as %macro for line extraction, but
1939 This function uses the same syntax as %macro for line extraction, but
1932 instead of creating a macro it saves the resulting string to the
1940 instead of creating a macro it saves the resulting string to the
1933 filename you specify.
1941 filename you specify.
1934
1942
1935 It adds a '.py' extension to the file if you don't do so yourself, and
1943 It adds a '.py' extension to the file if you don't do so yourself, and
1936 it asks for confirmation before overwriting existing files."""
1944 it asks for confirmation before overwriting existing files."""
1937
1945
1938 opts,args = self.parse_options(parameter_s,'r',mode='list')
1946 opts,args = self.parse_options(parameter_s,'r',mode='list')
1939 fname,ranges = args[0], args[1:]
1947 fname,ranges = args[0], args[1:]
1940 if not fname.endswith('.py'):
1948 if not fname.endswith('.py'):
1941 fname += '.py'
1949 fname += '.py'
1942 if os.path.isfile(fname):
1950 if os.path.isfile(fname):
1943 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1951 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1944 if ans.lower() not in ['y','yes']:
1952 if ans.lower() not in ['y','yes']:
1945 print 'Operation cancelled.'
1953 print 'Operation cancelled.'
1946 return
1954 return
1947 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1955 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1948 f = file(fname,'w')
1956 f = file(fname,'w')
1949 f.write(cmds)
1957 f.write(cmds)
1950 f.close()
1958 f.close()
1951 print 'The following commands were written to file `%s`:' % fname
1959 print 'The following commands were written to file `%s`:' % fname
1952 print cmds
1960 print cmds
1953
1961
1954 def _edit_macro(self,mname,macro):
1962 def _edit_macro(self,mname,macro):
1955 """open an editor with the macro data in a file"""
1963 """open an editor with the macro data in a file"""
1956 filename = self.shell.mktempfile(macro.value)
1964 filename = self.shell.mktempfile(macro.value)
1957 self.shell.hooks.editor(filename)
1965 self.shell.hooks.editor(filename)
1958
1966
1959 # and make a new macro object, to replace the old one
1967 # and make a new macro object, to replace the old one
1960 mfile = open(filename)
1968 mfile = open(filename)
1961 mvalue = mfile.read()
1969 mvalue = mfile.read()
1962 mfile.close()
1970 mfile.close()
1963 self.shell.user_ns[mname] = Macro(mvalue)
1971 self.shell.user_ns[mname] = Macro(mvalue)
1964
1972
1965 def magic_ed(self,parameter_s=''):
1973 def magic_ed(self,parameter_s=''):
1966 """Alias to %edit."""
1974 """Alias to %edit."""
1967 return self.magic_edit(parameter_s)
1975 return self.magic_edit(parameter_s)
1968
1976
1969 def magic_edit(self,parameter_s='',last_call=['','']):
1977 def magic_edit(self,parameter_s='',last_call=['','']):
1970 """Bring up an editor and execute the resulting code.
1978 """Bring up an editor and execute the resulting code.
1971
1979
1972 Usage:
1980 Usage:
1973 %edit [options] [args]
1981 %edit [options] [args]
1974
1982
1975 %edit runs IPython's editor hook. The default version of this hook is
1983 %edit runs IPython's editor hook. The default version of this hook is
1976 set to call the __IPYTHON__.rc.editor command. This is read from your
1984 set to call the __IPYTHON__.rc.editor command. This is read from your
1977 environment variable $EDITOR. If this isn't found, it will default to
1985 environment variable $EDITOR. If this isn't found, it will default to
1978 vi under Linux/Unix and to notepad under Windows. See the end of this
1986 vi under Linux/Unix and to notepad under Windows. See the end of this
1979 docstring for how to change the editor hook.
1987 docstring for how to change the editor hook.
1980
1988
1981 You can also set the value of this editor via the command line option
1989 You can also set the value of this editor via the command line option
1982 '-editor' or in your ipythonrc file. This is useful if you wish to use
1990 '-editor' or in your ipythonrc file. This is useful if you wish to use
1983 specifically for IPython an editor different from your typical default
1991 specifically for IPython an editor different from your typical default
1984 (and for Windows users who typically don't set environment variables).
1992 (and for Windows users who typically don't set environment variables).
1985
1993
1986 This command allows you to conveniently edit multi-line code right in
1994 This command allows you to conveniently edit multi-line code right in
1987 your IPython session.
1995 your IPython session.
1988
1996
1989 If called without arguments, %edit opens up an empty editor with a
1997 If called without arguments, %edit opens up an empty editor with a
1990 temporary file and will execute the contents of this file when you
1998 temporary file and will execute the contents of this file when you
1991 close it (don't forget to save it!).
1999 close it (don't forget to save it!).
1992
2000
1993
2001
1994 Options:
2002 Options:
1995
2003
1996 -n <number>: open the editor at a specified line number. By default,
2004 -n <number>: open the editor at a specified line number. By default,
1997 the IPython editor hook uses the unix syntax 'editor +N filename', but
2005 the IPython editor hook uses the unix syntax 'editor +N filename', but
1998 you can configure this by providing your own modified hook if your
2006 you can configure this by providing your own modified hook if your
1999 favorite editor supports line-number specifications with a different
2007 favorite editor supports line-number specifications with a different
2000 syntax.
2008 syntax.
2001
2009
2002 -p: this will call the editor with the same data as the previous time
2010 -p: this will call the editor with the same data as the previous time
2003 it was used, regardless of how long ago (in your current session) it
2011 it was used, regardless of how long ago (in your current session) it
2004 was.
2012 was.
2005
2013
2006 -r: use 'raw' input. This option only applies to input taken from the
2014 -r: use 'raw' input. This option only applies to input taken from the
2007 user's history. By default, the 'processed' history is used, so that
2015 user's history. By default, the 'processed' history is used, so that
2008 magics are loaded in their transformed version to valid Python. If
2016 magics are loaded in their transformed version to valid Python. If
2009 this option is given, the raw input as typed as the command line is
2017 this option is given, the raw input as typed as the command line is
2010 used instead. When you exit the editor, it will be executed by
2018 used instead. When you exit the editor, it will be executed by
2011 IPython's own processor.
2019 IPython's own processor.
2012
2020
2013 -x: do not execute the edited code immediately upon exit. This is
2021 -x: do not execute the edited code immediately upon exit. This is
2014 mainly useful if you are editing programs which need to be called with
2022 mainly useful if you are editing programs which need to be called with
2015 command line arguments, which you can then do using %run.
2023 command line arguments, which you can then do using %run.
2016
2024
2017
2025
2018 Arguments:
2026 Arguments:
2019
2027
2020 If arguments are given, the following possibilites exist:
2028 If arguments are given, the following possibilites exist:
2021
2029
2022 - The arguments are numbers or pairs of colon-separated numbers (like
2030 - The arguments are numbers or pairs of colon-separated numbers (like
2023 1 4:8 9). These are interpreted as lines of previous input to be
2031 1 4:8 9). These are interpreted as lines of previous input to be
2024 loaded into the editor. The syntax is the same of the %macro command.
2032 loaded into the editor. The syntax is the same of the %macro command.
2025
2033
2026 - If the argument doesn't start with a number, it is evaluated as a
2034 - If the argument doesn't start with a number, it is evaluated as a
2027 variable and its contents loaded into the editor. You can thus edit
2035 variable and its contents loaded into the editor. You can thus edit
2028 any string which contains python code (including the result of
2036 any string which contains python code (including the result of
2029 previous edits).
2037 previous edits).
2030
2038
2031 - If the argument is the name of an object (other than a string),
2039 - If the argument is the name of an object (other than a string),
2032 IPython will try to locate the file where it was defined and open the
2040 IPython will try to locate the file where it was defined and open the
2033 editor at the point where it is defined. You can use `%edit function`
2041 editor at the point where it is defined. You can use `%edit function`
2034 to load an editor exactly at the point where 'function' is defined,
2042 to load an editor exactly at the point where 'function' is defined,
2035 edit it and have the file be executed automatically.
2043 edit it and have the file be executed automatically.
2036
2044
2037 If the object is a macro (see %macro for details), this opens up your
2045 If the object is a macro (see %macro for details), this opens up your
2038 specified editor with a temporary file containing the macro's data.
2046 specified editor with a temporary file containing the macro's data.
2039 Upon exit, the macro is reloaded with the contents of the file.
2047 Upon exit, the macro is reloaded with the contents of the file.
2040
2048
2041 Note: opening at an exact line is only supported under Unix, and some
2049 Note: opening at an exact line is only supported under Unix, and some
2042 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2050 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2043 '+NUMBER' parameter necessary for this feature. Good editors like
2051 '+NUMBER' parameter necessary for this feature. Good editors like
2044 (X)Emacs, vi, jed, pico and joe all do.
2052 (X)Emacs, vi, jed, pico and joe all do.
2045
2053
2046 - If the argument is not found as a variable, IPython will look for a
2054 - If the argument is not found as a variable, IPython will look for a
2047 file with that name (adding .py if necessary) and load it into the
2055 file with that name (adding .py if necessary) and load it into the
2048 editor. It will execute its contents with execfile() when you exit,
2056 editor. It will execute its contents with execfile() when you exit,
2049 loading any code in the file into your interactive namespace.
2057 loading any code in the file into your interactive namespace.
2050
2058
2051 After executing your code, %edit will return as output the code you
2059 After executing your code, %edit will return as output the code you
2052 typed in the editor (except when it was an existing file). This way
2060 typed in the editor (except when it was an existing file). This way
2053 you can reload the code in further invocations of %edit as a variable,
2061 you can reload the code in further invocations of %edit as a variable,
2054 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2062 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2055 the output.
2063 the output.
2056
2064
2057 Note that %edit is also available through the alias %ed.
2065 Note that %edit is also available through the alias %ed.
2058
2066
2059 This is an example of creating a simple function inside the editor and
2067 This is an example of creating a simple function inside the editor and
2060 then modifying it. First, start up the editor:
2068 then modifying it. First, start up the editor:
2061
2069
2062 In [1]: ed\\
2070 In [1]: ed\\
2063 Editing... done. Executing edited code...\\
2071 Editing... done. Executing edited code...\\
2064 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
2072 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
2065
2073
2066 We can then call the function foo():
2074 We can then call the function foo():
2067
2075
2068 In [2]: foo()\\
2076 In [2]: foo()\\
2069 foo() was defined in an editing session
2077 foo() was defined in an editing session
2070
2078
2071 Now we edit foo. IPython automatically loads the editor with the
2079 Now we edit foo. IPython automatically loads the editor with the
2072 (temporary) file where foo() was previously defined:
2080 (temporary) file where foo() was previously defined:
2073
2081
2074 In [3]: ed foo\\
2082 In [3]: ed foo\\
2075 Editing... done. Executing edited code...
2083 Editing... done. Executing edited code...
2076
2084
2077 And if we call foo() again we get the modified version:
2085 And if we call foo() again we get the modified version:
2078
2086
2079 In [4]: foo()\\
2087 In [4]: foo()\\
2080 foo() has now been changed!
2088 foo() has now been changed!
2081
2089
2082 Here is an example of how to edit a code snippet successive
2090 Here is an example of how to edit a code snippet successive
2083 times. First we call the editor:
2091 times. First we call the editor:
2084
2092
2085 In [8]: ed\\
2093 In [8]: ed\\
2086 Editing... done. Executing edited code...\\
2094 Editing... done. Executing edited code...\\
2087 hello\\
2095 hello\\
2088 Out[8]: "print 'hello'\\n"
2096 Out[8]: "print 'hello'\\n"
2089
2097
2090 Now we call it again with the previous output (stored in _):
2098 Now we call it again with the previous output (stored in _):
2091
2099
2092 In [9]: ed _\\
2100 In [9]: ed _\\
2093 Editing... done. Executing edited code...\\
2101 Editing... done. Executing edited code...\\
2094 hello world\\
2102 hello world\\
2095 Out[9]: "print 'hello world'\\n"
2103 Out[9]: "print 'hello world'\\n"
2096
2104
2097 Now we call it with the output #8 (stored in _8, also as Out[8]):
2105 Now we call it with the output #8 (stored in _8, also as Out[8]):
2098
2106
2099 In [10]: ed _8\\
2107 In [10]: ed _8\\
2100 Editing... done. Executing edited code...\\
2108 Editing... done. Executing edited code...\\
2101 hello again\\
2109 hello again\\
2102 Out[10]: "print 'hello again'\\n"
2110 Out[10]: "print 'hello again'\\n"
2103
2111
2104
2112
2105 Changing the default editor hook:
2113 Changing the default editor hook:
2106
2114
2107 If you wish to write your own editor hook, you can put it in a
2115 If you wish to write your own editor hook, you can put it in a
2108 configuration file which you load at startup time. The default hook
2116 configuration file which you load at startup time. The default hook
2109 is defined in the IPython.hooks module, and you can use that as a
2117 is defined in the IPython.hooks module, and you can use that as a
2110 starting example for further modifications. That file also has
2118 starting example for further modifications. That file also has
2111 general instructions on how to set a new hook for use once you've
2119 general instructions on how to set a new hook for use once you've
2112 defined it."""
2120 defined it."""
2113
2121
2114 # FIXME: This function has become a convoluted mess. It needs a
2122 # FIXME: This function has become a convoluted mess. It needs a
2115 # ground-up rewrite with clean, simple logic.
2123 # ground-up rewrite with clean, simple logic.
2116
2124
2117 def make_filename(arg):
2125 def make_filename(arg):
2118 "Make a filename from the given args"
2126 "Make a filename from the given args"
2119 try:
2127 try:
2120 filename = get_py_filename(arg)
2128 filename = get_py_filename(arg)
2121 except IOError:
2129 except IOError:
2122 if args.endswith('.py'):
2130 if args.endswith('.py'):
2123 filename = arg
2131 filename = arg
2124 else:
2132 else:
2125 filename = None
2133 filename = None
2126 return filename
2134 return filename
2127
2135
2128 # custom exceptions
2136 # custom exceptions
2129 class DataIsObject(Exception): pass
2137 class DataIsObject(Exception): pass
2130
2138
2131 opts,args = self.parse_options(parameter_s,'prxn:')
2139 opts,args = self.parse_options(parameter_s,'prxn:')
2132 # Set a few locals from the options for convenience:
2140 # Set a few locals from the options for convenience:
2133 opts_p = opts.has_key('p')
2141 opts_p = opts.has_key('p')
2134 opts_r = opts.has_key('r')
2142 opts_r = opts.has_key('r')
2135
2143
2136 # Default line number value
2144 # Default line number value
2137 lineno = opts.get('n',None)
2145 lineno = opts.get('n',None)
2138
2146
2139 if opts_p:
2147 if opts_p:
2140 args = '_%s' % last_call[0]
2148 args = '_%s' % last_call[0]
2141 if not self.shell.user_ns.has_key(args):
2149 if not self.shell.user_ns.has_key(args):
2142 args = last_call[1]
2150 args = last_call[1]
2143
2151
2144 # use last_call to remember the state of the previous call, but don't
2152 # use last_call to remember the state of the previous call, but don't
2145 # let it be clobbered by successive '-p' calls.
2153 # let it be clobbered by successive '-p' calls.
2146 try:
2154 try:
2147 last_call[0] = self.shell.outputcache.prompt_count
2155 last_call[0] = self.shell.outputcache.prompt_count
2148 if not opts_p:
2156 if not opts_p:
2149 last_call[1] = parameter_s
2157 last_call[1] = parameter_s
2150 except:
2158 except:
2151 pass
2159 pass
2152
2160
2153 # by default this is done with temp files, except when the given
2161 # by default this is done with temp files, except when the given
2154 # arg is a filename
2162 # arg is a filename
2155 use_temp = 1
2163 use_temp = 1
2156
2164
2157 if re.match(r'\d',args):
2165 if re.match(r'\d',args):
2158 # Mode where user specifies ranges of lines, like in %macro.
2166 # Mode where user specifies ranges of lines, like in %macro.
2159 # This means that you can't edit files whose names begin with
2167 # This means that you can't edit files whose names begin with
2160 # numbers this way. Tough.
2168 # numbers this way. Tough.
2161 ranges = args.split()
2169 ranges = args.split()
2162 data = ''.join(self.extract_input_slices(ranges,opts_r))
2170 data = ''.join(self.extract_input_slices(ranges,opts_r))
2163 elif args.endswith('.py'):
2171 elif args.endswith('.py'):
2164 filename = make_filename(args)
2172 filename = make_filename(args)
2165 data = ''
2173 data = ''
2166 use_temp = 0
2174 use_temp = 0
2167 elif args:
2175 elif args:
2168 try:
2176 try:
2169 # Load the parameter given as a variable. If not a string,
2177 # Load the parameter given as a variable. If not a string,
2170 # process it as an object instead (below)
2178 # process it as an object instead (below)
2171
2179
2172 #print '*** args',args,'type',type(args) # dbg
2180 #print '*** args',args,'type',type(args) # dbg
2173 data = eval(args,self.shell.user_ns)
2181 data = eval(args,self.shell.user_ns)
2174 if not type(data) in StringTypes:
2182 if not type(data) in StringTypes:
2175 raise DataIsObject
2183 raise DataIsObject
2176
2184
2177 except (NameError,SyntaxError):
2185 except (NameError,SyntaxError):
2178 # given argument is not a variable, try as a filename
2186 # given argument is not a variable, try as a filename
2179 filename = make_filename(args)
2187 filename = make_filename(args)
2180 if filename is None:
2188 if filename is None:
2181 warn("Argument given (%s) can't be found as a variable "
2189 warn("Argument given (%s) can't be found as a variable "
2182 "or as a filename." % args)
2190 "or as a filename." % args)
2183 return
2191 return
2184
2192
2185 data = ''
2193 data = ''
2186 use_temp = 0
2194 use_temp = 0
2187 except DataIsObject:
2195 except DataIsObject:
2188
2196
2189 # macros have a special edit function
2197 # macros have a special edit function
2190 if isinstance(data,Macro):
2198 if isinstance(data,Macro):
2191 self._edit_macro(args,data)
2199 self._edit_macro(args,data)
2192 return
2200 return
2193
2201
2194 # For objects, try to edit the file where they are defined
2202 # For objects, try to edit the file where they are defined
2195 try:
2203 try:
2196 filename = inspect.getabsfile(data)
2204 filename = inspect.getabsfile(data)
2197 datafile = 1
2205 datafile = 1
2198 except TypeError:
2206 except TypeError:
2199 filename = make_filename(args)
2207 filename = make_filename(args)
2200 datafile = 1
2208 datafile = 1
2201 warn('Could not find file where `%s` is defined.\n'
2209 warn('Could not find file where `%s` is defined.\n'
2202 'Opening a file named `%s`' % (args,filename))
2210 'Opening a file named `%s`' % (args,filename))
2203 # Now, make sure we can actually read the source (if it was in
2211 # Now, make sure we can actually read the source (if it was in
2204 # a temp file it's gone by now).
2212 # a temp file it's gone by now).
2205 if datafile:
2213 if datafile:
2206 try:
2214 try:
2207 if lineno is None:
2215 if lineno is None:
2208 lineno = inspect.getsourcelines(data)[1]
2216 lineno = inspect.getsourcelines(data)[1]
2209 except IOError:
2217 except IOError:
2210 filename = make_filename(args)
2218 filename = make_filename(args)
2211 if filename is None:
2219 if filename is None:
2212 warn('The file `%s` where `%s` was defined cannot '
2220 warn('The file `%s` where `%s` was defined cannot '
2213 'be read.' % (filename,data))
2221 'be read.' % (filename,data))
2214 return
2222 return
2215 use_temp = 0
2223 use_temp = 0
2216 else:
2224 else:
2217 data = ''
2225 data = ''
2218
2226
2219 if use_temp:
2227 if use_temp:
2220 filename = self.shell.mktempfile(data)
2228 filename = self.shell.mktempfile(data)
2221 print 'IPython will make a temporary file named:',filename
2229 print 'IPython will make a temporary file named:',filename
2222
2230
2223 # do actual editing here
2231 # do actual editing here
2224 print 'Editing...',
2232 print 'Editing...',
2225 sys.stdout.flush()
2233 sys.stdout.flush()
2226 self.shell.hooks.editor(filename,lineno)
2234 self.shell.hooks.editor(filename,lineno)
2227 if opts.has_key('x'): # -x prevents actual execution
2235 if opts.has_key('x'): # -x prevents actual execution
2228 print
2236 print
2229 else:
2237 else:
2230 print 'done. Executing edited code...'
2238 print 'done. Executing edited code...'
2231 if opts_r:
2239 if opts_r:
2232 self.shell.runlines(file_read(filename))
2240 self.shell.runlines(file_read(filename))
2233 else:
2241 else:
2234 self.shell.safe_execfile(filename,self.shell.user_ns)
2242 self.shell.safe_execfile(filename,self.shell.user_ns)
2235 if use_temp:
2243 if use_temp:
2236 try:
2244 try:
2237 return open(filename).read()
2245 return open(filename).read()
2238 except IOError,msg:
2246 except IOError,msg:
2239 if msg.filename == filename:
2247 if msg.filename == filename:
2240 warn('File not found. Did you forget to save?')
2248 warn('File not found. Did you forget to save?')
2241 return
2249 return
2242 else:
2250 else:
2243 self.shell.showtraceback()
2251 self.shell.showtraceback()
2244
2252
2245 def magic_xmode(self,parameter_s = ''):
2253 def magic_xmode(self,parameter_s = ''):
2246 """Switch modes for the exception handlers.
2254 """Switch modes for the exception handlers.
2247
2255
2248 Valid modes: Plain, Context and Verbose.
2256 Valid modes: Plain, Context and Verbose.
2249
2257
2250 If called without arguments, acts as a toggle."""
2258 If called without arguments, acts as a toggle."""
2251
2259
2252 def xmode_switch_err(name):
2260 def xmode_switch_err(name):
2253 warn('Error changing %s exception modes.\n%s' %
2261 warn('Error changing %s exception modes.\n%s' %
2254 (name,sys.exc_info()[1]))
2262 (name,sys.exc_info()[1]))
2255
2263
2256 shell = self.shell
2264 shell = self.shell
2257 new_mode = parameter_s.strip().capitalize()
2265 new_mode = parameter_s.strip().capitalize()
2258 try:
2266 try:
2259 shell.InteractiveTB.set_mode(mode=new_mode)
2267 shell.InteractiveTB.set_mode(mode=new_mode)
2260 print 'Exception reporting mode:',shell.InteractiveTB.mode
2268 print 'Exception reporting mode:',shell.InteractiveTB.mode
2261 except:
2269 except:
2262 xmode_switch_err('user')
2270 xmode_switch_err('user')
2263
2271
2264 # threaded shells use a special handler in sys.excepthook
2272 # threaded shells use a special handler in sys.excepthook
2265 if shell.isthreaded:
2273 if shell.isthreaded:
2266 try:
2274 try:
2267 shell.sys_excepthook.set_mode(mode=new_mode)
2275 shell.sys_excepthook.set_mode(mode=new_mode)
2268 except:
2276 except:
2269 xmode_switch_err('threaded')
2277 xmode_switch_err('threaded')
2270
2278
2271 def magic_colors(self,parameter_s = ''):
2279 def magic_colors(self,parameter_s = ''):
2272 """Switch color scheme for prompts, info system and exception handlers.
2280 """Switch color scheme for prompts, info system and exception handlers.
2273
2281
2274 Currently implemented schemes: NoColor, Linux, LightBG.
2282 Currently implemented schemes: NoColor, Linux, LightBG.
2275
2283
2276 Color scheme names are not case-sensitive."""
2284 Color scheme names are not case-sensitive."""
2277
2285
2278 def color_switch_err(name):
2286 def color_switch_err(name):
2279 warn('Error changing %s color schemes.\n%s' %
2287 warn('Error changing %s color schemes.\n%s' %
2280 (name,sys.exc_info()[1]))
2288 (name,sys.exc_info()[1]))
2281
2289
2282
2290
2283 new_scheme = parameter_s.strip()
2291 new_scheme = parameter_s.strip()
2284 if not new_scheme:
2292 if not new_scheme:
2285 print 'You must specify a color scheme.'
2293 print 'You must specify a color scheme.'
2286 return
2294 return
2287 import IPython.rlineimpl as readline
2295 import IPython.rlineimpl as readline
2288 if not readline.have_readline:
2296 if not readline.have_readline:
2289 msg = """\
2297 msg = """\
2290 Proper color support under MS Windows requires the pyreadline library.
2298 Proper color support under MS Windows requires the pyreadline library.
2291 You can find it at:
2299 You can find it at:
2292 http://ipython.scipy.org/moin/PyReadline/Intro
2300 http://ipython.scipy.org/moin/PyReadline/Intro
2293 Gary's readline needs the ctypes module, from:
2301 Gary's readline needs the ctypes module, from:
2294 http://starship.python.net/crew/theller/ctypes
2302 http://starship.python.net/crew/theller/ctypes
2295 (Note that ctypes is already part of Python versions 2.5 and newer).
2303 (Note that ctypes is already part of Python versions 2.5 and newer).
2296
2304
2297 Defaulting color scheme to 'NoColor'"""
2305 Defaulting color scheme to 'NoColor'"""
2298 new_scheme = 'NoColor'
2306 new_scheme = 'NoColor'
2299 warn(msg)
2307 warn(msg)
2300 # local shortcut
2308 # local shortcut
2301 shell = self.shell
2309 shell = self.shell
2302
2310
2303 # Set prompt colors
2311 # Set prompt colors
2304 try:
2312 try:
2305 shell.outputcache.set_colors(new_scheme)
2313 shell.outputcache.set_colors(new_scheme)
2306 except:
2314 except:
2307 color_switch_err('prompt')
2315 color_switch_err('prompt')
2308 else:
2316 else:
2309 shell.rc.colors = \
2317 shell.rc.colors = \
2310 shell.outputcache.color_table.active_scheme_name
2318 shell.outputcache.color_table.active_scheme_name
2311 # Set exception colors
2319 # Set exception colors
2312 try:
2320 try:
2313 shell.InteractiveTB.set_colors(scheme = new_scheme)
2321 shell.InteractiveTB.set_colors(scheme = new_scheme)
2314 shell.SyntaxTB.set_colors(scheme = new_scheme)
2322 shell.SyntaxTB.set_colors(scheme = new_scheme)
2315 except:
2323 except:
2316 color_switch_err('exception')
2324 color_switch_err('exception')
2317
2325
2318 # threaded shells use a verbose traceback in sys.excepthook
2326 # threaded shells use a verbose traceback in sys.excepthook
2319 if shell.isthreaded:
2327 if shell.isthreaded:
2320 try:
2328 try:
2321 shell.sys_excepthook.set_colors(scheme=new_scheme)
2329 shell.sys_excepthook.set_colors(scheme=new_scheme)
2322 except:
2330 except:
2323 color_switch_err('system exception handler')
2331 color_switch_err('system exception handler')
2324
2332
2325 # Set info (for 'object?') colors
2333 # Set info (for 'object?') colors
2326 if shell.rc.color_info:
2334 if shell.rc.color_info:
2327 try:
2335 try:
2328 shell.inspector.set_active_scheme(new_scheme)
2336 shell.inspector.set_active_scheme(new_scheme)
2329 except:
2337 except:
2330 color_switch_err('object inspector')
2338 color_switch_err('object inspector')
2331 else:
2339 else:
2332 shell.inspector.set_active_scheme('NoColor')
2340 shell.inspector.set_active_scheme('NoColor')
2333
2341
2334 def magic_color_info(self,parameter_s = ''):
2342 def magic_color_info(self,parameter_s = ''):
2335 """Toggle color_info.
2343 """Toggle color_info.
2336
2344
2337 The color_info configuration parameter controls whether colors are
2345 The color_info configuration parameter controls whether colors are
2338 used for displaying object details (by things like %psource, %pfile or
2346 used for displaying object details (by things like %psource, %pfile or
2339 the '?' system). This function toggles this value with each call.
2347 the '?' system). This function toggles this value with each call.
2340
2348
2341 Note that unless you have a fairly recent pager (less works better
2349 Note that unless you have a fairly recent pager (less works better
2342 than more) in your system, using colored object information displays
2350 than more) in your system, using colored object information displays
2343 will not work properly. Test it and see."""
2351 will not work properly. Test it and see."""
2344
2352
2345 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2353 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2346 self.magic_colors(self.shell.rc.colors)
2354 self.magic_colors(self.shell.rc.colors)
2347 print 'Object introspection functions have now coloring:',
2355 print 'Object introspection functions have now coloring:',
2348 print ['OFF','ON'][self.shell.rc.color_info]
2356 print ['OFF','ON'][self.shell.rc.color_info]
2349
2357
2350 def magic_Pprint(self, parameter_s=''):
2358 def magic_Pprint(self, parameter_s=''):
2351 """Toggle pretty printing on/off."""
2359 """Toggle pretty printing on/off."""
2352
2360
2353 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2361 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2354 print 'Pretty printing has been turned', \
2362 print 'Pretty printing has been turned', \
2355 ['OFF','ON'][self.shell.rc.pprint]
2363 ['OFF','ON'][self.shell.rc.pprint]
2356
2364
2357 def magic_exit(self, parameter_s=''):
2365 def magic_exit(self, parameter_s=''):
2358 """Exit IPython, confirming if configured to do so.
2366 """Exit IPython, confirming if configured to do so.
2359
2367
2360 You can configure whether IPython asks for confirmation upon exit by
2368 You can configure whether IPython asks for confirmation upon exit by
2361 setting the confirm_exit flag in the ipythonrc file."""
2369 setting the confirm_exit flag in the ipythonrc file."""
2362
2370
2363 self.shell.exit()
2371 self.shell.exit()
2364
2372
2365 def magic_quit(self, parameter_s=''):
2373 def magic_quit(self, parameter_s=''):
2366 """Exit IPython, confirming if configured to do so (like %exit)"""
2374 """Exit IPython, confirming if configured to do so (like %exit)"""
2367
2375
2368 self.shell.exit()
2376 self.shell.exit()
2369
2377
2370 def magic_Exit(self, parameter_s=''):
2378 def magic_Exit(self, parameter_s=''):
2371 """Exit IPython without confirmation."""
2379 """Exit IPython without confirmation."""
2372
2380
2373 self.shell.exit_now = True
2381 self.shell.exit_now = True
2374
2382
2375 def magic_Quit(self, parameter_s=''):
2383 def magic_Quit(self, parameter_s=''):
2376 """Exit IPython without confirmation (like %Exit)."""
2384 """Exit IPython without confirmation (like %Exit)."""
2377
2385
2378 self.shell.exit_now = True
2386 self.shell.exit_now = True
2379
2387
2380 #......................................................................
2388 #......................................................................
2381 # Functions to implement unix shell-type things
2389 # Functions to implement unix shell-type things
2382
2390
2383 def magic_alias(self, parameter_s = ''):
2391 def magic_alias(self, parameter_s = ''):
2384 """Define an alias for a system command.
2392 """Define an alias for a system command.
2385
2393
2386 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2394 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2387
2395
2388 Then, typing 'alias_name params' will execute the system command 'cmd
2396 Then, typing 'alias_name params' will execute the system command 'cmd
2389 params' (from your underlying operating system).
2397 params' (from your underlying operating system).
2390
2398
2391 Aliases have lower precedence than magic functions and Python normal
2399 Aliases have lower precedence than magic functions and Python normal
2392 variables, so if 'foo' is both a Python variable and an alias, the
2400 variables, so if 'foo' is both a Python variable and an alias, the
2393 alias can not be executed until 'del foo' removes the Python variable.
2401 alias can not be executed until 'del foo' removes the Python variable.
2394
2402
2395 You can use the %l specifier in an alias definition to represent the
2403 You can use the %l specifier in an alias definition to represent the
2396 whole line when the alias is called. For example:
2404 whole line when the alias is called. For example:
2397
2405
2398 In [2]: alias all echo "Input in brackets: <%l>"\\
2406 In [2]: alias all echo "Input in brackets: <%l>"\\
2399 In [3]: all hello world\\
2407 In [3]: all hello world\\
2400 Input in brackets: <hello world>
2408 Input in brackets: <hello world>
2401
2409
2402 You can also define aliases with parameters using %s specifiers (one
2410 You can also define aliases with parameters using %s specifiers (one
2403 per parameter):
2411 per parameter):
2404
2412
2405 In [1]: alias parts echo first %s second %s\\
2413 In [1]: alias parts echo first %s second %s\\
2406 In [2]: %parts A B\\
2414 In [2]: %parts A B\\
2407 first A second B\\
2415 first A second B\\
2408 In [3]: %parts A\\
2416 In [3]: %parts A\\
2409 Incorrect number of arguments: 2 expected.\\
2417 Incorrect number of arguments: 2 expected.\\
2410 parts is an alias to: 'echo first %s second %s'
2418 parts is an alias to: 'echo first %s second %s'
2411
2419
2412 Note that %l and %s are mutually exclusive. You can only use one or
2420 Note that %l and %s are mutually exclusive. You can only use one or
2413 the other in your aliases.
2421 the other in your aliases.
2414
2422
2415 Aliases expand Python variables just like system calls using ! or !!
2423 Aliases expand Python variables just like system calls using ! or !!
2416 do: all expressions prefixed with '$' get expanded. For details of
2424 do: all expressions prefixed with '$' get expanded. For details of
2417 the semantic rules, see PEP-215:
2425 the semantic rules, see PEP-215:
2418 http://www.python.org/peps/pep-0215.html. This is the library used by
2426 http://www.python.org/peps/pep-0215.html. This is the library used by
2419 IPython for variable expansion. If you want to access a true shell
2427 IPython for variable expansion. If you want to access a true shell
2420 variable, an extra $ is necessary to prevent its expansion by IPython:
2428 variable, an extra $ is necessary to prevent its expansion by IPython:
2421
2429
2422 In [6]: alias show echo\\
2430 In [6]: alias show echo\\
2423 In [7]: PATH='A Python string'\\
2431 In [7]: PATH='A Python string'\\
2424 In [8]: show $PATH\\
2432 In [8]: show $PATH\\
2425 A Python string\\
2433 A Python string\\
2426 In [9]: show $$PATH\\
2434 In [9]: show $$PATH\\
2427 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2435 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2428
2436
2429 You can use the alias facility to acess all of $PATH. See the %rehash
2437 You can use the alias facility to acess all of $PATH. See the %rehash
2430 and %rehashx functions, which automatically create aliases for the
2438 and %rehashx functions, which automatically create aliases for the
2431 contents of your $PATH.
2439 contents of your $PATH.
2432
2440
2433 If called with no parameters, %alias prints the current alias table."""
2441 If called with no parameters, %alias prints the current alias table."""
2434
2442
2435 par = parameter_s.strip()
2443 par = parameter_s.strip()
2436 if not par:
2444 if not par:
2437 stored = self.db.get('stored_aliases', {} )
2445 stored = self.db.get('stored_aliases', {} )
2438 atab = self.shell.alias_table
2446 atab = self.shell.alias_table
2439 aliases = atab.keys()
2447 aliases = atab.keys()
2440 aliases.sort()
2448 aliases.sort()
2441 res = []
2449 res = []
2442 showlast = []
2450 showlast = []
2443 for alias in aliases:
2451 for alias in aliases:
2444 tgt = atab[alias][1]
2452 tgt = atab[alias][1]
2445 # 'interesting' aliases
2453 # 'interesting' aliases
2446 if (alias in stored or
2454 if (alias in stored or
2447 alias != os.path.splitext(tgt)[0] or
2455 alias != os.path.splitext(tgt)[0] or
2448 ' ' in tgt):
2456 ' ' in tgt):
2449 showlast.append((alias, tgt))
2457 showlast.append((alias, tgt))
2450 else:
2458 else:
2451 res.append((alias, tgt ))
2459 res.append((alias, tgt ))
2452
2460
2453 # show most interesting aliases last
2461 # show most interesting aliases last
2454 res.extend(showlast)
2462 res.extend(showlast)
2455 print "Total number of aliases:",len(aliases)
2463 print "Total number of aliases:",len(aliases)
2456 return res
2464 return res
2457 try:
2465 try:
2458 alias,cmd = par.split(None,1)
2466 alias,cmd = par.split(None,1)
2459 except:
2467 except:
2460 print OInspect.getdoc(self.magic_alias)
2468 print OInspect.getdoc(self.magic_alias)
2461 else:
2469 else:
2462 nargs = cmd.count('%s')
2470 nargs = cmd.count('%s')
2463 if nargs>0 and cmd.find('%l')>=0:
2471 if nargs>0 and cmd.find('%l')>=0:
2464 error('The %s and %l specifiers are mutually exclusive '
2472 error('The %s and %l specifiers are mutually exclusive '
2465 'in alias definitions.')
2473 'in alias definitions.')
2466 else: # all looks OK
2474 else: # all looks OK
2467 self.shell.alias_table[alias] = (nargs,cmd)
2475 self.shell.alias_table[alias] = (nargs,cmd)
2468 self.shell.alias_table_validate(verbose=0)
2476 self.shell.alias_table_validate(verbose=0)
2469 # end magic_alias
2477 # end magic_alias
2470
2478
2471 def magic_unalias(self, parameter_s = ''):
2479 def magic_unalias(self, parameter_s = ''):
2472 """Remove an alias"""
2480 """Remove an alias"""
2473
2481
2474 aname = parameter_s.strip()
2482 aname = parameter_s.strip()
2475 if aname in self.shell.alias_table:
2483 if aname in self.shell.alias_table:
2476 del self.shell.alias_table[aname]
2484 del self.shell.alias_table[aname]
2477 stored = self.db.get('stored_aliases', {} )
2485 stored = self.db.get('stored_aliases', {} )
2478 if aname in stored:
2486 if aname in stored:
2479 print "Removing %stored alias",aname
2487 print "Removing %stored alias",aname
2480 del stored[aname]
2488 del stored[aname]
2481 self.db['stored_aliases'] = stored
2489 self.db['stored_aliases'] = stored
2482
2490
2483 def magic_rehash(self, parameter_s = ''):
2491 def magic_rehash(self, parameter_s = ''):
2484 """Update the alias table with all entries in $PATH.
2492 """Update the alias table with all entries in $PATH.
2485
2493
2486 This version does no checks on execute permissions or whether the
2494 This version does no checks on execute permissions or whether the
2487 contents of $PATH are truly files (instead of directories or something
2495 contents of $PATH are truly files (instead of directories or something
2488 else). For such a safer (but slower) version, use %rehashx."""
2496 else). For such a safer (but slower) version, use %rehashx."""
2489
2497
2490 # This function (and rehashx) manipulate the alias_table directly
2498 # This function (and rehashx) manipulate the alias_table directly
2491 # rather than calling magic_alias, for speed reasons. A rehash on a
2499 # rather than calling magic_alias, for speed reasons. A rehash on a
2492 # typical Linux box involves several thousand entries, so efficiency
2500 # typical Linux box involves several thousand entries, so efficiency
2493 # here is a top concern.
2501 # here is a top concern.
2494
2502
2495 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2503 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2496 alias_table = self.shell.alias_table
2504 alias_table = self.shell.alias_table
2497 for pdir in path:
2505 for pdir in path:
2498 for ff in os.listdir(pdir):
2506 for ff in os.listdir(pdir):
2499 # each entry in the alias table must be (N,name), where
2507 # each entry in the alias table must be (N,name), where
2500 # N is the number of positional arguments of the alias.
2508 # N is the number of positional arguments of the alias.
2501 alias_table[ff] = (0,ff)
2509 alias_table[ff] = (0,ff)
2502 # Make sure the alias table doesn't contain keywords or builtins
2510 # Make sure the alias table doesn't contain keywords or builtins
2503 self.shell.alias_table_validate()
2511 self.shell.alias_table_validate()
2504 # Call again init_auto_alias() so we get 'rm -i' and other modified
2512 # Call again init_auto_alias() so we get 'rm -i' and other modified
2505 # aliases since %rehash will probably clobber them
2513 # aliases since %rehash will probably clobber them
2506 self.shell.init_auto_alias()
2514 self.shell.init_auto_alias()
2507
2515
2508 def magic_rehashx(self, parameter_s = ''):
2516 def magic_rehashx(self, parameter_s = ''):
2509 """Update the alias table with all executable files in $PATH.
2517 """Update the alias table with all executable files in $PATH.
2510
2518
2511 This version explicitly checks that every entry in $PATH is a file
2519 This version explicitly checks that every entry in $PATH is a file
2512 with execute access (os.X_OK), so it is much slower than %rehash.
2520 with execute access (os.X_OK), so it is much slower than %rehash.
2513
2521
2514 Under Windows, it checks executability as a match agains a
2522 Under Windows, it checks executability as a match agains a
2515 '|'-separated string of extensions, stored in the IPython config
2523 '|'-separated string of extensions, stored in the IPython config
2516 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2524 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2517
2525
2518 path = [os.path.abspath(os.path.expanduser(p)) for p in
2526 path = [os.path.abspath(os.path.expanduser(p)) for p in
2519 os.environ['PATH'].split(os.pathsep)]
2527 os.environ['PATH'].split(os.pathsep)]
2520 path = filter(os.path.isdir,path)
2528 path = filter(os.path.isdir,path)
2521
2529
2522 alias_table = self.shell.alias_table
2530 alias_table = self.shell.alias_table
2523 syscmdlist = []
2531 syscmdlist = []
2524 if os.name == 'posix':
2532 if os.name == 'posix':
2525 isexec = lambda fname:os.path.isfile(fname) and \
2533 isexec = lambda fname:os.path.isfile(fname) and \
2526 os.access(fname,os.X_OK)
2534 os.access(fname,os.X_OK)
2527 else:
2535 else:
2528
2536
2529 try:
2537 try:
2530 winext = os.environ['pathext'].replace(';','|').replace('.','')
2538 winext = os.environ['pathext'].replace(';','|').replace('.','')
2531 except KeyError:
2539 except KeyError:
2532 winext = 'exe|com|bat|py'
2540 winext = 'exe|com|bat|py'
2533 if 'py' not in winext:
2541 if 'py' not in winext:
2534 winext += '|py'
2542 winext += '|py'
2535 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2543 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2536 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2544 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2537 savedir = os.getcwd()
2545 savedir = os.getcwd()
2538 try:
2546 try:
2539 # write the whole loop for posix/Windows so we don't have an if in
2547 # write the whole loop for posix/Windows so we don't have an if in
2540 # the innermost part
2548 # the innermost part
2541 if os.name == 'posix':
2549 if os.name == 'posix':
2542 for pdir in path:
2550 for pdir in path:
2543 os.chdir(pdir)
2551 os.chdir(pdir)
2544 for ff in os.listdir(pdir):
2552 for ff in os.listdir(pdir):
2545 if isexec(ff) and ff not in self.shell.no_alias:
2553 if isexec(ff) and ff not in self.shell.no_alias:
2546 # each entry in the alias table must be (N,name),
2554 # each entry in the alias table must be (N,name),
2547 # where N is the number of positional arguments of the
2555 # where N is the number of positional arguments of the
2548 # alias.
2556 # alias.
2549 alias_table[ff] = (0,ff)
2557 alias_table[ff] = (0,ff)
2550 syscmdlist.append(ff)
2558 syscmdlist.append(ff)
2551 else:
2559 else:
2552 for pdir in path:
2560 for pdir in path:
2553 os.chdir(pdir)
2561 os.chdir(pdir)
2554 for ff in os.listdir(pdir):
2562 for ff in os.listdir(pdir):
2555 base, ext = os.path.splitext(ff)
2563 base, ext = os.path.splitext(ff)
2556 if isexec(ff) and base not in self.shell.no_alias:
2564 if isexec(ff) and base not in self.shell.no_alias:
2557 if ext.lower() == '.exe':
2565 if ext.lower() == '.exe':
2558 ff = base
2566 ff = base
2559 alias_table[base] = (0,ff)
2567 alias_table[base] = (0,ff)
2560 syscmdlist.append(ff)
2568 syscmdlist.append(ff)
2561 # Make sure the alias table doesn't contain keywords or builtins
2569 # Make sure the alias table doesn't contain keywords or builtins
2562 self.shell.alias_table_validate()
2570 self.shell.alias_table_validate()
2563 # Call again init_auto_alias() so we get 'rm -i' and other
2571 # Call again init_auto_alias() so we get 'rm -i' and other
2564 # modified aliases since %rehashx will probably clobber them
2572 # modified aliases since %rehashx will probably clobber them
2565 self.shell.init_auto_alias()
2573 self.shell.init_auto_alias()
2566 db = self.getapi().db
2574 db = self.getapi().db
2567 db['syscmdlist'] = syscmdlist
2575 db['syscmdlist'] = syscmdlist
2568 finally:
2576 finally:
2569 os.chdir(savedir)
2577 os.chdir(savedir)
2570
2578
2571 def magic_pwd(self, parameter_s = ''):
2579 def magic_pwd(self, parameter_s = ''):
2572 """Return the current working directory path."""
2580 """Return the current working directory path."""
2573 return os.getcwd()
2581 return os.getcwd()
2574
2582
2575 def magic_cd(self, parameter_s=''):
2583 def magic_cd(self, parameter_s=''):
2576 """Change the current working directory.
2584 """Change the current working directory.
2577
2585
2578 This command automatically maintains an internal list of directories
2586 This command automatically maintains an internal list of directories
2579 you visit during your IPython session, in the variable _dh. The
2587 you visit during your IPython session, in the variable _dh. The
2580 command %dhist shows this history nicely formatted. You can also
2588 command %dhist shows this history nicely formatted. You can also
2581 do 'cd -<tab>' to see directory history conveniently.
2589 do 'cd -<tab>' to see directory history conveniently.
2582
2590
2583 Usage:
2591 Usage:
2584
2592
2585 cd 'dir': changes to directory 'dir'.
2593 cd 'dir': changes to directory 'dir'.
2586
2594
2587 cd -: changes to the last visited directory.
2595 cd -: changes to the last visited directory.
2588
2596
2589 cd -<n>: changes to the n-th directory in the directory history.
2597 cd -<n>: changes to the n-th directory in the directory history.
2590
2598
2591 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2599 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2592 (note: cd <bookmark_name> is enough if there is no
2600 (note: cd <bookmark_name> is enough if there is no
2593 directory <bookmark_name>, but a bookmark with the name exists.)
2601 directory <bookmark_name>, but a bookmark with the name exists.)
2594 'cd -b <tab>' allows you to tab-complete bookmark names.
2602 'cd -b <tab>' allows you to tab-complete bookmark names.
2595
2603
2596 Options:
2604 Options:
2597
2605
2598 -q: quiet. Do not print the working directory after the cd command is
2606 -q: quiet. Do not print the working directory after the cd command is
2599 executed. By default IPython's cd command does print this directory,
2607 executed. By default IPython's cd command does print this directory,
2600 since the default prompts do not display path information.
2608 since the default prompts do not display path information.
2601
2609
2602 Note that !cd doesn't work for this purpose because the shell where
2610 Note that !cd doesn't work for this purpose because the shell where
2603 !command runs is immediately discarded after executing 'command'."""
2611 !command runs is immediately discarded after executing 'command'."""
2604
2612
2605 parameter_s = parameter_s.strip()
2613 parameter_s = parameter_s.strip()
2606 #bkms = self.shell.persist.get("bookmarks",{})
2614 #bkms = self.shell.persist.get("bookmarks",{})
2607
2615
2608 numcd = re.match(r'(-)(\d+)$',parameter_s)
2616 numcd = re.match(r'(-)(\d+)$',parameter_s)
2609 # jump in directory history by number
2617 # jump in directory history by number
2610 if numcd:
2618 if numcd:
2611 nn = int(numcd.group(2))
2619 nn = int(numcd.group(2))
2612 try:
2620 try:
2613 ps = self.shell.user_ns['_dh'][nn]
2621 ps = self.shell.user_ns['_dh'][nn]
2614 except IndexError:
2622 except IndexError:
2615 print 'The requested directory does not exist in history.'
2623 print 'The requested directory does not exist in history.'
2616 return
2624 return
2617 else:
2625 else:
2618 opts = {}
2626 opts = {}
2619 else:
2627 else:
2620 #turn all non-space-escaping backslashes to slashes,
2628 #turn all non-space-escaping backslashes to slashes,
2621 # for c:\windows\directory\names\
2629 # for c:\windows\directory\names\
2622 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2630 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2623 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2631 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2624 # jump to previous
2632 # jump to previous
2625 if ps == '-':
2633 if ps == '-':
2626 try:
2634 try:
2627 ps = self.shell.user_ns['_dh'][-2]
2635 ps = self.shell.user_ns['_dh'][-2]
2628 except IndexError:
2636 except IndexError:
2629 print 'No previous directory to change to.'
2637 print 'No previous directory to change to.'
2630 return
2638 return
2631 # jump to bookmark if needed
2639 # jump to bookmark if needed
2632 else:
2640 else:
2633 if not os.path.isdir(ps) or opts.has_key('b'):
2641 if not os.path.isdir(ps) or opts.has_key('b'):
2634 bkms = self.db.get('bookmarks', {})
2642 bkms = self.db.get('bookmarks', {})
2635
2643
2636 if bkms.has_key(ps):
2644 if bkms.has_key(ps):
2637 target = bkms[ps]
2645 target = bkms[ps]
2638 print '(bookmark:%s) -> %s' % (ps,target)
2646 print '(bookmark:%s) -> %s' % (ps,target)
2639 ps = target
2647 ps = target
2640 else:
2648 else:
2641 if opts.has_key('b'):
2649 if opts.has_key('b'):
2642 error("Bookmark '%s' not found. "
2650 error("Bookmark '%s' not found. "
2643 "Use '%%bookmark -l' to see your bookmarks." % ps)
2651 "Use '%%bookmark -l' to see your bookmarks." % ps)
2644 return
2652 return
2645
2653
2646 # at this point ps should point to the target dir
2654 # at this point ps should point to the target dir
2647 if ps:
2655 if ps:
2648 try:
2656 try:
2649 os.chdir(os.path.expanduser(ps))
2657 os.chdir(os.path.expanduser(ps))
2650 if self.shell.rc.term_title:
2658 if self.shell.rc.term_title:
2651 #print 'set term title:',self.shell.rc.term_title # dbg
2659 #print 'set term title:',self.shell.rc.term_title # dbg
2652 ttitle = ("IPy:" + (
2660 ttitle = ("IPy:" + (
2653 os.getcwd() == '/' and '/' or \
2661 os.getcwd() == '/' and '/' or \
2654 os.path.basename(os.getcwd())))
2662 os.path.basename(os.getcwd())))
2655 platutils.set_term_title(ttitle)
2663 platutils.set_term_title(ttitle)
2656 except OSError:
2664 except OSError:
2657 print sys.exc_info()[1]
2665 print sys.exc_info()[1]
2658 else:
2666 else:
2659 self.shell.user_ns['_dh'].append(os.getcwd())
2667 self.shell.user_ns['_dh'].append(os.getcwd())
2660 else:
2668 else:
2661 os.chdir(self.shell.home_dir)
2669 os.chdir(self.shell.home_dir)
2662 if self.shell.rc.term_title:
2670 if self.shell.rc.term_title:
2663 platutils.set_term_title("IPy:~")
2671 platutils.set_term_title("IPy:~")
2664 self.shell.user_ns['_dh'].append(os.getcwd())
2672 self.shell.user_ns['_dh'].append(os.getcwd())
2665 if not 'q' in opts:
2673 if not 'q' in opts:
2666 print self.shell.user_ns['_dh'][-1]
2674 print self.shell.user_ns['_dh'][-1]
2667
2675
2668 def magic_dhist(self, parameter_s=''):
2676 def magic_dhist(self, parameter_s=''):
2669 """Print your history of visited directories.
2677 """Print your history of visited directories.
2670
2678
2671 %dhist -> print full history\\
2679 %dhist -> print full history\\
2672 %dhist n -> print last n entries only\\
2680 %dhist n -> print last n entries only\\
2673 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2681 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2674
2682
2675 This history is automatically maintained by the %cd command, and
2683 This history is automatically maintained by the %cd command, and
2676 always available as the global list variable _dh. You can use %cd -<n>
2684 always available as the global list variable _dh. You can use %cd -<n>
2677 to go to directory number <n>."""
2685 to go to directory number <n>."""
2678
2686
2679 dh = self.shell.user_ns['_dh']
2687 dh = self.shell.user_ns['_dh']
2680 if parameter_s:
2688 if parameter_s:
2681 try:
2689 try:
2682 args = map(int,parameter_s.split())
2690 args = map(int,parameter_s.split())
2683 except:
2691 except:
2684 self.arg_err(Magic.magic_dhist)
2692 self.arg_err(Magic.magic_dhist)
2685 return
2693 return
2686 if len(args) == 1:
2694 if len(args) == 1:
2687 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2695 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2688 elif len(args) == 2:
2696 elif len(args) == 2:
2689 ini,fin = args
2697 ini,fin = args
2690 else:
2698 else:
2691 self.arg_err(Magic.magic_dhist)
2699 self.arg_err(Magic.magic_dhist)
2692 return
2700 return
2693 else:
2701 else:
2694 ini,fin = 0,len(dh)
2702 ini,fin = 0,len(dh)
2695 nlprint(dh,
2703 nlprint(dh,
2696 header = 'Directory history (kept in _dh)',
2704 header = 'Directory history (kept in _dh)',
2697 start=ini,stop=fin)
2705 start=ini,stop=fin)
2698
2706
2699 def magic_env(self, parameter_s=''):
2707 def magic_env(self, parameter_s=''):
2700 """List environment variables."""
2708 """List environment variables."""
2701
2709
2702 return os.environ.data
2710 return os.environ.data
2703
2711
2704 def magic_pushd(self, parameter_s=''):
2712 def magic_pushd(self, parameter_s=''):
2705 """Place the current dir on stack and change directory.
2713 """Place the current dir on stack and change directory.
2706
2714
2707 Usage:\\
2715 Usage:\\
2708 %pushd ['dirname']
2716 %pushd ['dirname']
2709
2717
2710 %pushd with no arguments does a %pushd to your home directory.
2718 %pushd with no arguments does a %pushd to your home directory.
2711 """
2719 """
2712 if parameter_s == '': parameter_s = '~'
2720 if parameter_s == '': parameter_s = '~'
2713 dir_s = self.shell.dir_stack
2721 dir_s = self.shell.dir_stack
2714 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2722 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2715 os.path.expanduser(self.shell.dir_stack[0]):
2723 os.path.expanduser(self.shell.dir_stack[0]):
2716 try:
2724 try:
2717 self.magic_cd(parameter_s)
2725 self.magic_cd(parameter_s)
2718 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2726 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2719 self.magic_dirs()
2727 self.magic_dirs()
2720 except:
2728 except:
2721 print 'Invalid directory'
2729 print 'Invalid directory'
2722 else:
2730 else:
2723 print 'You are already there!'
2731 print 'You are already there!'
2724
2732
2725 def magic_popd(self, parameter_s=''):
2733 def magic_popd(self, parameter_s=''):
2726 """Change to directory popped off the top of the stack.
2734 """Change to directory popped off the top of the stack.
2727 """
2735 """
2728 if len (self.shell.dir_stack) > 1:
2736 if len (self.shell.dir_stack) > 1:
2729 self.shell.dir_stack.pop(0)
2737 self.shell.dir_stack.pop(0)
2730 self.magic_cd(self.shell.dir_stack[0])
2738 self.magic_cd(self.shell.dir_stack[0])
2731 print self.shell.dir_stack[0]
2739 print self.shell.dir_stack[0]
2732 else:
2740 else:
2733 print "You can't remove the starting directory from the stack:",\
2741 print "You can't remove the starting directory from the stack:",\
2734 self.shell.dir_stack
2742 self.shell.dir_stack
2735
2743
2736 def magic_dirs(self, parameter_s=''):
2744 def magic_dirs(self, parameter_s=''):
2737 """Return the current directory stack."""
2745 """Return the current directory stack."""
2738
2746
2739 return self.shell.dir_stack[:]
2747 return self.shell.dir_stack[:]
2740
2748
2741 def magic_sc(self, parameter_s=''):
2749 def magic_sc(self, parameter_s=''):
2742 """Shell capture - execute a shell command and capture its output.
2750 """Shell capture - execute a shell command and capture its output.
2743
2751
2744 DEPRECATED. Suboptimal, retained for backwards compatibility.
2752 DEPRECATED. Suboptimal, retained for backwards compatibility.
2745
2753
2746 You should use the form 'var = !command' instead. Example:
2754 You should use the form 'var = !command' instead. Example:
2747
2755
2748 "%sc -l myfiles = ls ~" should now be written as
2756 "%sc -l myfiles = ls ~" should now be written as
2749
2757
2750 "myfiles = !ls ~"
2758 "myfiles = !ls ~"
2751
2759
2752 myfiles.s, myfiles.l and myfiles.n still apply as documented
2760 myfiles.s, myfiles.l and myfiles.n still apply as documented
2753 below.
2761 below.
2754
2762
2755 --
2763 --
2756 %sc [options] varname=command
2764 %sc [options] varname=command
2757
2765
2758 IPython will run the given command using commands.getoutput(), and
2766 IPython will run the given command using commands.getoutput(), and
2759 will then update the user's interactive namespace with a variable
2767 will then update the user's interactive namespace with a variable
2760 called varname, containing the value of the call. Your command can
2768 called varname, containing the value of the call. Your command can
2761 contain shell wildcards, pipes, etc.
2769 contain shell wildcards, pipes, etc.
2762
2770
2763 The '=' sign in the syntax is mandatory, and the variable name you
2771 The '=' sign in the syntax is mandatory, and the variable name you
2764 supply must follow Python's standard conventions for valid names.
2772 supply must follow Python's standard conventions for valid names.
2765
2773
2766 (A special format without variable name exists for internal use)
2774 (A special format without variable name exists for internal use)
2767
2775
2768 Options:
2776 Options:
2769
2777
2770 -l: list output. Split the output on newlines into a list before
2778 -l: list output. Split the output on newlines into a list before
2771 assigning it to the given variable. By default the output is stored
2779 assigning it to the given variable. By default the output is stored
2772 as a single string.
2780 as a single string.
2773
2781
2774 -v: verbose. Print the contents of the variable.
2782 -v: verbose. Print the contents of the variable.
2775
2783
2776 In most cases you should not need to split as a list, because the
2784 In most cases you should not need to split as a list, because the
2777 returned value is a special type of string which can automatically
2785 returned value is a special type of string which can automatically
2778 provide its contents either as a list (split on newlines) or as a
2786 provide its contents either as a list (split on newlines) or as a
2779 space-separated string. These are convenient, respectively, either
2787 space-separated string. These are convenient, respectively, either
2780 for sequential processing or to be passed to a shell command.
2788 for sequential processing or to be passed to a shell command.
2781
2789
2782 For example:
2790 For example:
2783
2791
2784 # Capture into variable a
2792 # Capture into variable a
2785 In [9]: sc a=ls *py
2793 In [9]: sc a=ls *py
2786
2794
2787 # a is a string with embedded newlines
2795 # a is a string with embedded newlines
2788 In [10]: a
2796 In [10]: a
2789 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2797 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2790
2798
2791 # which can be seen as a list:
2799 # which can be seen as a list:
2792 In [11]: a.l
2800 In [11]: a.l
2793 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2801 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2794
2802
2795 # or as a whitespace-separated string:
2803 # or as a whitespace-separated string:
2796 In [12]: a.s
2804 In [12]: a.s
2797 Out[12]: 'setup.py win32_manual_post_install.py'
2805 Out[12]: 'setup.py win32_manual_post_install.py'
2798
2806
2799 # a.s is useful to pass as a single command line:
2807 # a.s is useful to pass as a single command line:
2800 In [13]: !wc -l $a.s
2808 In [13]: !wc -l $a.s
2801 146 setup.py
2809 146 setup.py
2802 130 win32_manual_post_install.py
2810 130 win32_manual_post_install.py
2803 276 total
2811 276 total
2804
2812
2805 # while the list form is useful to loop over:
2813 # while the list form is useful to loop over:
2806 In [14]: for f in a.l:
2814 In [14]: for f in a.l:
2807 ....: !wc -l $f
2815 ....: !wc -l $f
2808 ....:
2816 ....:
2809 146 setup.py
2817 146 setup.py
2810 130 win32_manual_post_install.py
2818 130 win32_manual_post_install.py
2811
2819
2812 Similiarly, the lists returned by the -l option are also special, in
2820 Similiarly, the lists returned by the -l option are also special, in
2813 the sense that you can equally invoke the .s attribute on them to
2821 the sense that you can equally invoke the .s attribute on them to
2814 automatically get a whitespace-separated string from their contents:
2822 automatically get a whitespace-separated string from their contents:
2815
2823
2816 In [1]: sc -l b=ls *py
2824 In [1]: sc -l b=ls *py
2817
2825
2818 In [2]: b
2826 In [2]: b
2819 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2827 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2820
2828
2821 In [3]: b.s
2829 In [3]: b.s
2822 Out[3]: 'setup.py win32_manual_post_install.py'
2830 Out[3]: 'setup.py win32_manual_post_install.py'
2823
2831
2824 In summary, both the lists and strings used for ouptut capture have
2832 In summary, both the lists and strings used for ouptut capture have
2825 the following special attributes:
2833 the following special attributes:
2826
2834
2827 .l (or .list) : value as list.
2835 .l (or .list) : value as list.
2828 .n (or .nlstr): value as newline-separated string.
2836 .n (or .nlstr): value as newline-separated string.
2829 .s (or .spstr): value as space-separated string.
2837 .s (or .spstr): value as space-separated string.
2830 """
2838 """
2831
2839
2832 opts,args = self.parse_options(parameter_s,'lv')
2840 opts,args = self.parse_options(parameter_s,'lv')
2833 # Try to get a variable name and command to run
2841 # Try to get a variable name and command to run
2834 try:
2842 try:
2835 # the variable name must be obtained from the parse_options
2843 # the variable name must be obtained from the parse_options
2836 # output, which uses shlex.split to strip options out.
2844 # output, which uses shlex.split to strip options out.
2837 var,_ = args.split('=',1)
2845 var,_ = args.split('=',1)
2838 var = var.strip()
2846 var = var.strip()
2839 # But the the command has to be extracted from the original input
2847 # But the the command has to be extracted from the original input
2840 # parameter_s, not on what parse_options returns, to avoid the
2848 # parameter_s, not on what parse_options returns, to avoid the
2841 # quote stripping which shlex.split performs on it.
2849 # quote stripping which shlex.split performs on it.
2842 _,cmd = parameter_s.split('=',1)
2850 _,cmd = parameter_s.split('=',1)
2843 except ValueError:
2851 except ValueError:
2844 var,cmd = '',''
2852 var,cmd = '',''
2845 # If all looks ok, proceed
2853 # If all looks ok, proceed
2846 out,err = self.shell.getoutputerror(cmd)
2854 out,err = self.shell.getoutputerror(cmd)
2847 if err:
2855 if err:
2848 print >> Term.cerr,err
2856 print >> Term.cerr,err
2849 if opts.has_key('l'):
2857 if opts.has_key('l'):
2850 out = SList(out.split('\n'))
2858 out = SList(out.split('\n'))
2851 else:
2859 else:
2852 out = LSString(out)
2860 out = LSString(out)
2853 if opts.has_key('v'):
2861 if opts.has_key('v'):
2854 print '%s ==\n%s' % (var,pformat(out))
2862 print '%s ==\n%s' % (var,pformat(out))
2855 if var:
2863 if var:
2856 self.shell.user_ns.update({var:out})
2864 self.shell.user_ns.update({var:out})
2857 else:
2865 else:
2858 return out
2866 return out
2859
2867
2860 def magic_sx(self, parameter_s=''):
2868 def magic_sx(self, parameter_s=''):
2861 """Shell execute - run a shell command and capture its output.
2869 """Shell execute - run a shell command and capture its output.
2862
2870
2863 %sx command
2871 %sx command
2864
2872
2865 IPython will run the given command using commands.getoutput(), and
2873 IPython will run the given command using commands.getoutput(), and
2866 return the result formatted as a list (split on '\\n'). Since the
2874 return the result formatted as a list (split on '\\n'). Since the
2867 output is _returned_, it will be stored in ipython's regular output
2875 output is _returned_, it will be stored in ipython's regular output
2868 cache Out[N] and in the '_N' automatic variables.
2876 cache Out[N] and in the '_N' automatic variables.
2869
2877
2870 Notes:
2878 Notes:
2871
2879
2872 1) If an input line begins with '!!', then %sx is automatically
2880 1) If an input line begins with '!!', then %sx is automatically
2873 invoked. That is, while:
2881 invoked. That is, while:
2874 !ls
2882 !ls
2875 causes ipython to simply issue system('ls'), typing
2883 causes ipython to simply issue system('ls'), typing
2876 !!ls
2884 !!ls
2877 is a shorthand equivalent to:
2885 is a shorthand equivalent to:
2878 %sx ls
2886 %sx ls
2879
2887
2880 2) %sx differs from %sc in that %sx automatically splits into a list,
2888 2) %sx differs from %sc in that %sx automatically splits into a list,
2881 like '%sc -l'. The reason for this is to make it as easy as possible
2889 like '%sc -l'. The reason for this is to make it as easy as possible
2882 to process line-oriented shell output via further python commands.
2890 to process line-oriented shell output via further python commands.
2883 %sc is meant to provide much finer control, but requires more
2891 %sc is meant to provide much finer control, but requires more
2884 typing.
2892 typing.
2885
2893
2886 3) Just like %sc -l, this is a list with special attributes:
2894 3) Just like %sc -l, this is a list with special attributes:
2887
2895
2888 .l (or .list) : value as list.
2896 .l (or .list) : value as list.
2889 .n (or .nlstr): value as newline-separated string.
2897 .n (or .nlstr): value as newline-separated string.
2890 .s (or .spstr): value as whitespace-separated string.
2898 .s (or .spstr): value as whitespace-separated string.
2891
2899
2892 This is very useful when trying to use such lists as arguments to
2900 This is very useful when trying to use such lists as arguments to
2893 system commands."""
2901 system commands."""
2894
2902
2895 if parameter_s:
2903 if parameter_s:
2896 out,err = self.shell.getoutputerror(parameter_s)
2904 out,err = self.shell.getoutputerror(parameter_s)
2897 if err:
2905 if err:
2898 print >> Term.cerr,err
2906 print >> Term.cerr,err
2899 return SList(out.split('\n'))
2907 return SList(out.split('\n'))
2900
2908
2901 def magic_bg(self, parameter_s=''):
2909 def magic_bg(self, parameter_s=''):
2902 """Run a job in the background, in a separate thread.
2910 """Run a job in the background, in a separate thread.
2903
2911
2904 For example,
2912 For example,
2905
2913
2906 %bg myfunc(x,y,z=1)
2914 %bg myfunc(x,y,z=1)
2907
2915
2908 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2916 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2909 execution starts, a message will be printed indicating the job
2917 execution starts, a message will be printed indicating the job
2910 number. If your job number is 5, you can use
2918 number. If your job number is 5, you can use
2911
2919
2912 myvar = jobs.result(5) or myvar = jobs[5].result
2920 myvar = jobs.result(5) or myvar = jobs[5].result
2913
2921
2914 to assign this result to variable 'myvar'.
2922 to assign this result to variable 'myvar'.
2915
2923
2916 IPython has a job manager, accessible via the 'jobs' object. You can
2924 IPython has a job manager, accessible via the 'jobs' object. You can
2917 type jobs? to get more information about it, and use jobs.<TAB> to see
2925 type jobs? to get more information about it, and use jobs.<TAB> to see
2918 its attributes. All attributes not starting with an underscore are
2926 its attributes. All attributes not starting with an underscore are
2919 meant for public use.
2927 meant for public use.
2920
2928
2921 In particular, look at the jobs.new() method, which is used to create
2929 In particular, look at the jobs.new() method, which is used to create
2922 new jobs. This magic %bg function is just a convenience wrapper
2930 new jobs. This magic %bg function is just a convenience wrapper
2923 around jobs.new(), for expression-based jobs. If you want to create a
2931 around jobs.new(), for expression-based jobs. If you want to create a
2924 new job with an explicit function object and arguments, you must call
2932 new job with an explicit function object and arguments, you must call
2925 jobs.new() directly.
2933 jobs.new() directly.
2926
2934
2927 The jobs.new docstring also describes in detail several important
2935 The jobs.new docstring also describes in detail several important
2928 caveats associated with a thread-based model for background job
2936 caveats associated with a thread-based model for background job
2929 execution. Type jobs.new? for details.
2937 execution. Type jobs.new? for details.
2930
2938
2931 You can check the status of all jobs with jobs.status().
2939 You can check the status of all jobs with jobs.status().
2932
2940
2933 The jobs variable is set by IPython into the Python builtin namespace.
2941 The jobs variable is set by IPython into the Python builtin namespace.
2934 If you ever declare a variable named 'jobs', you will shadow this
2942 If you ever declare a variable named 'jobs', you will shadow this
2935 name. You can either delete your global jobs variable to regain
2943 name. You can either delete your global jobs variable to regain
2936 access to the job manager, or make a new name and assign it manually
2944 access to the job manager, or make a new name and assign it manually
2937 to the manager (stored in IPython's namespace). For example, to
2945 to the manager (stored in IPython's namespace). For example, to
2938 assign the job manager to the Jobs name, use:
2946 assign the job manager to the Jobs name, use:
2939
2947
2940 Jobs = __builtins__.jobs"""
2948 Jobs = __builtins__.jobs"""
2941
2949
2942 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2950 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2943
2951
2944
2952
2945 def magic_bookmark(self, parameter_s=''):
2953 def magic_bookmark(self, parameter_s=''):
2946 """Manage IPython's bookmark system.
2954 """Manage IPython's bookmark system.
2947
2955
2948 %bookmark <name> - set bookmark to current dir
2956 %bookmark <name> - set bookmark to current dir
2949 %bookmark <name> <dir> - set bookmark to <dir>
2957 %bookmark <name> <dir> - set bookmark to <dir>
2950 %bookmark -l - list all bookmarks
2958 %bookmark -l - list all bookmarks
2951 %bookmark -d <name> - remove bookmark
2959 %bookmark -d <name> - remove bookmark
2952 %bookmark -r - remove all bookmarks
2960 %bookmark -r - remove all bookmarks
2953
2961
2954 You can later on access a bookmarked folder with:
2962 You can later on access a bookmarked folder with:
2955 %cd -b <name>
2963 %cd -b <name>
2956 or simply '%cd <name>' if there is no directory called <name> AND
2964 or simply '%cd <name>' if there is no directory called <name> AND
2957 there is such a bookmark defined.
2965 there is such a bookmark defined.
2958
2966
2959 Your bookmarks persist through IPython sessions, but they are
2967 Your bookmarks persist through IPython sessions, but they are
2960 associated with each profile."""
2968 associated with each profile."""
2961
2969
2962 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2970 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2963 if len(args) > 2:
2971 if len(args) > 2:
2964 error('You can only give at most two arguments')
2972 error('You can only give at most two arguments')
2965 return
2973 return
2966
2974
2967 bkms = self.db.get('bookmarks',{})
2975 bkms = self.db.get('bookmarks',{})
2968
2976
2969 if opts.has_key('d'):
2977 if opts.has_key('d'):
2970 try:
2978 try:
2971 todel = args[0]
2979 todel = args[0]
2972 except IndexError:
2980 except IndexError:
2973 error('You must provide a bookmark to delete')
2981 error('You must provide a bookmark to delete')
2974 else:
2982 else:
2975 try:
2983 try:
2976 del bkms[todel]
2984 del bkms[todel]
2977 except:
2985 except:
2978 error("Can't delete bookmark '%s'" % todel)
2986 error("Can't delete bookmark '%s'" % todel)
2979 elif opts.has_key('r'):
2987 elif opts.has_key('r'):
2980 bkms = {}
2988 bkms = {}
2981 elif opts.has_key('l'):
2989 elif opts.has_key('l'):
2982 bks = bkms.keys()
2990 bks = bkms.keys()
2983 bks.sort()
2991 bks.sort()
2984 if bks:
2992 if bks:
2985 size = max(map(len,bks))
2993 size = max(map(len,bks))
2986 else:
2994 else:
2987 size = 0
2995 size = 0
2988 fmt = '%-'+str(size)+'s -> %s'
2996 fmt = '%-'+str(size)+'s -> %s'
2989 print 'Current bookmarks:'
2997 print 'Current bookmarks:'
2990 for bk in bks:
2998 for bk in bks:
2991 print fmt % (bk,bkms[bk])
2999 print fmt % (bk,bkms[bk])
2992 else:
3000 else:
2993 if not args:
3001 if not args:
2994 error("You must specify the bookmark name")
3002 error("You must specify the bookmark name")
2995 elif len(args)==1:
3003 elif len(args)==1:
2996 bkms[args[0]] = os.getcwd()
3004 bkms[args[0]] = os.getcwd()
2997 elif len(args)==2:
3005 elif len(args)==2:
2998 bkms[args[0]] = args[1]
3006 bkms[args[0]] = args[1]
2999 self.db['bookmarks'] = bkms
3007 self.db['bookmarks'] = bkms
3000
3008
3001 def magic_pycat(self, parameter_s=''):
3009 def magic_pycat(self, parameter_s=''):
3002 """Show a syntax-highlighted file through a pager.
3010 """Show a syntax-highlighted file through a pager.
3003
3011
3004 This magic is similar to the cat utility, but it will assume the file
3012 This magic is similar to the cat utility, but it will assume the file
3005 to be Python source and will show it with syntax highlighting. """
3013 to be Python source and will show it with syntax highlighting. """
3006
3014
3007 try:
3015 try:
3008 filename = get_py_filename(parameter_s)
3016 filename = get_py_filename(parameter_s)
3009 cont = file_read(filename)
3017 cont = file_read(filename)
3010 except IOError:
3018 except IOError:
3011 try:
3019 try:
3012 cont = eval(parameter_s,self.user_ns)
3020 cont = eval(parameter_s,self.user_ns)
3013 except NameError:
3021 except NameError:
3014 cont = None
3022 cont = None
3015 if cont is None:
3023 if cont is None:
3016 print "Error: no such file or variable"
3024 print "Error: no such file or variable"
3017 return
3025 return
3018
3026
3019 page(self.shell.pycolorize(cont),
3027 page(self.shell.pycolorize(cont),
3020 screen_lines=self.shell.rc.screen_length)
3028 screen_lines=self.shell.rc.screen_length)
3021
3029
3022 def magic_cpaste(self, parameter_s=''):
3030 def magic_cpaste(self, parameter_s=''):
3023 """Allows you to paste & execute a pre-formatted code block from clipboard
3031 """Allows you to paste & execute a pre-formatted code block from clipboard
3024
3032
3025 You must terminate the block with '--' (two minus-signs) alone on the
3033 You must terminate the block with '--' (two minus-signs) alone on the
3026 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3034 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3027 is the new sentinel for this operation)
3035 is the new sentinel for this operation)
3028
3036
3029 The block is dedented prior to execution to enable execution of
3037 The block is dedented prior to execution to enable execution of
3030 method definitions. '>' characters at the beginning of a line is
3038 method definitions. '>' characters at the beginning of a line is
3031 ignored, to allow pasting directly from e-mails. The executed block
3039 ignored, to allow pasting directly from e-mails. The executed block
3032 is also assigned to variable named 'pasted_block' for later editing
3040 is also assigned to variable named 'pasted_block' for later editing
3033 with '%edit pasted_block'.
3041 with '%edit pasted_block'.
3034
3042
3035 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3043 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3036 This assigns the pasted block to variable 'foo' as string, without
3044 This assigns the pasted block to variable 'foo' as string, without
3037 dedenting or executing it.
3045 dedenting or executing it.
3038
3046
3039 Do not be alarmed by garbled output on Windows (it's a readline bug).
3047 Do not be alarmed by garbled output on Windows (it's a readline bug).
3040 Just press enter and type -- (and press enter again) and the block
3048 Just press enter and type -- (and press enter again) and the block
3041 will be what was just pasted.
3049 will be what was just pasted.
3042
3050
3043 IPython statements (magics, shell escapes) are not supported (yet).
3051 IPython statements (magics, shell escapes) are not supported (yet).
3044 """
3052 """
3045 opts,args = self.parse_options(parameter_s,'s:',mode='string')
3053 opts,args = self.parse_options(parameter_s,'s:',mode='string')
3046 par = args.strip()
3054 par = args.strip()
3047 sentinel = opts.get('s','--')
3055 sentinel = opts.get('s','--')
3048
3056
3049 from IPython import iplib
3057 from IPython import iplib
3050 lines = []
3058 lines = []
3051 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3059 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3052 while 1:
3060 while 1:
3053 l = iplib.raw_input_original(':')
3061 l = iplib.raw_input_original(':')
3054 if l ==sentinel:
3062 if l ==sentinel:
3055 break
3063 break
3056 lines.append(l.lstrip('>'))
3064 lines.append(l.lstrip('>'))
3057 block = "\n".join(lines) + '\n'
3065 block = "\n".join(lines) + '\n'
3058 #print "block:\n",block
3066 #print "block:\n",block
3059 if not par:
3067 if not par:
3060 b = textwrap.dedent(block)
3068 b = textwrap.dedent(block)
3061 exec b in self.user_ns
3069 exec b in self.user_ns
3062 self.user_ns['pasted_block'] = b
3070 self.user_ns['pasted_block'] = b
3063 else:
3071 else:
3064 self.user_ns[par] = block
3072 self.user_ns[par] = block
3065 print "Block assigned to '%s'" % par
3073 print "Block assigned to '%s'" % par
3066
3074
3067 def magic_quickref(self,arg):
3075 def magic_quickref(self,arg):
3068 """ Show a quick reference sheet """
3076 """ Show a quick reference sheet """
3069 import IPython.usage
3077 import IPython.usage
3070 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3078 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3071
3079
3072 page(qr)
3080 page(qr)
3073
3081
3074 def magic_upgrade(self,arg):
3082 def magic_upgrade(self,arg):
3075 """ Upgrade your IPython installation
3083 """ Upgrade your IPython installation
3076
3084
3077 This will copy the config files that don't yet exist in your
3085 This will copy the config files that don't yet exist in your
3078 ipython dir from the system config dir. Use this after upgrading
3086 ipython dir from the system config dir. Use this after upgrading
3079 IPython if you don't wish to delete your .ipython dir.
3087 IPython if you don't wish to delete your .ipython dir.
3080
3088
3081 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3089 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3082 new users)
3090 new users)
3083
3091
3084 """
3092 """
3085 ip = self.getapi()
3093 ip = self.getapi()
3086 ipinstallation = path(IPython.__file__).dirname()
3094 ipinstallation = path(IPython.__file__).dirname()
3087 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3095 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3088 src_config = ipinstallation / 'UserConfig'
3096 src_config = ipinstallation / 'UserConfig'
3089 userdir = path(ip.options.ipythondir)
3097 userdir = path(ip.options.ipythondir)
3090 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3098 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3091 print ">",cmd
3099 print ">",cmd
3092 shell(cmd)
3100 shell(cmd)
3093 if arg == '-nolegacy':
3101 if arg == '-nolegacy':
3094 legacy = userdir.files('ipythonrc*')
3102 legacy = userdir.files('ipythonrc*')
3095 print "Nuking legacy files:",legacy
3103 print "Nuking legacy files:",legacy
3096
3104
3097 [p.remove() for p in legacy]
3105 [p.remove() for p in legacy]
3098 suffix = (sys.platform == 'win32' and '.ini' or '')
3106 suffix = (sys.platform == 'win32' and '.ini' or '')
3099 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3107 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3100
3108
3101 # end Magic
3109 # end Magic
@@ -1,1756 +1,1763 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 2154 2007-03-19 00:10:07Z fperez $"""
8 $Id: genutils.py 2190 2007-03-30 18:35:46Z 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 IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>' % Release.authors['Fernando']
18 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __license__ = Release.license
19 __license__ = Release.license
20
20
21 #****************************************************************************
21 #****************************************************************************
22 # required modules from the Python standard library
22 # required modules from the Python standard library
23 import __main__
23 import __main__
24 import commands
24 import commands
25 import os
25 import os
26 import re
26 import re
27 import shlex
27 import shlex
28 import shutil
28 import shutil
29 import sys
29 import sys
30 import tempfile
30 import tempfile
31 import time
31 import time
32 import types
32 import types
33 import warnings
33 import warnings
34
34
35 # Other IPython utilities
35 # Other IPython utilities
36 from IPython.Itpl import Itpl,itpl,printpl
36 from IPython.Itpl import Itpl,itpl,printpl
37 from IPython import DPyGetOpt
37 from IPython import DPyGetOpt
38 from path import path
38 from path import path
39 if os.name == "nt":
39 if os.name == "nt":
40 from IPython.winconsole import get_console_size
40 from IPython.winconsole import get_console_size
41
41
42 #****************************************************************************
42 #****************************************************************************
43 # Exceptions
43 # Exceptions
44 class Error(Exception):
44 class Error(Exception):
45 """Base class for exceptions in this module."""
45 """Base class for exceptions in this module."""
46 pass
46 pass
47
47
48 #----------------------------------------------------------------------------
48 #----------------------------------------------------------------------------
49 class IOStream:
49 class IOStream:
50 def __init__(self,stream,fallback):
50 def __init__(self,stream,fallback):
51 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
51 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
52 stream = fallback
52 stream = fallback
53 self.stream = stream
53 self.stream = stream
54 self._swrite = stream.write
54 self._swrite = stream.write
55 self.flush = stream.flush
55 self.flush = stream.flush
56
56
57 def write(self,data):
57 def write(self,data):
58 try:
58 try:
59 self._swrite(data)
59 self._swrite(data)
60 except:
60 except:
61 try:
61 try:
62 # print handles some unicode issues which may trip a plain
62 # print handles some unicode issues which may trip a plain
63 # write() call. Attempt to emulate write() by using a
63 # write() call. Attempt to emulate write() by using a
64 # trailing comma
64 # trailing comma
65 print >> self.stream, data,
65 print >> self.stream, data,
66 except:
66 except:
67 # if we get here, something is seriously broken.
67 # if we get here, something is seriously broken.
68 print >> sys.stderr, \
68 print >> sys.stderr, \
69 'ERROR - failed to write data to stream:', self.stream
69 'ERROR - failed to write data to stream:', self.stream
70
70
71 def close(self):
71 def close(self):
72 pass
72 pass
73
73
74
74
75 class IOTerm:
75 class IOTerm:
76 """ Term holds the file or file-like objects for handling I/O operations.
76 """ Term holds the file or file-like objects for handling I/O operations.
77
77
78 These are normally just sys.stdin, sys.stdout and sys.stderr but for
78 These are normally just sys.stdin, sys.stdout and sys.stderr but for
79 Windows they can can replaced to allow editing the strings before they are
79 Windows they can can replaced to allow editing the strings before they are
80 displayed."""
80 displayed."""
81
81
82 # In the future, having IPython channel all its I/O operations through
82 # In the future, having IPython channel all its I/O operations through
83 # this class will make it easier to embed it into other environments which
83 # this class will make it easier to embed it into other environments which
84 # are not a normal terminal (such as a GUI-based shell)
84 # are not a normal terminal (such as a GUI-based shell)
85 def __init__(self,cin=None,cout=None,cerr=None):
85 def __init__(self,cin=None,cout=None,cerr=None):
86 self.cin = IOStream(cin,sys.stdin)
86 self.cin = IOStream(cin,sys.stdin)
87 self.cout = IOStream(cout,sys.stdout)
87 self.cout = IOStream(cout,sys.stdout)
88 self.cerr = IOStream(cerr,sys.stderr)
88 self.cerr = IOStream(cerr,sys.stderr)
89
89
90 # Global variable to be used for all I/O
90 # Global variable to be used for all I/O
91 Term = IOTerm()
91 Term = IOTerm()
92
92
93 import IPython.rlineimpl as readline
93 import IPython.rlineimpl as readline
94 # Remake Term to use the readline i/o facilities
94 # Remake Term to use the readline i/o facilities
95 if sys.platform == 'win32' and readline.have_readline:
95 if sys.platform == 'win32' and readline.have_readline:
96
96
97 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
97 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
98
98
99
99
100 #****************************************************************************
100 #****************************************************************************
101 # Generic warning/error printer, used by everything else
101 # Generic warning/error printer, used by everything else
102 def warn(msg,level=2,exit_val=1):
102 def warn(msg,level=2,exit_val=1):
103 """Standard warning printer. Gives formatting consistency.
103 """Standard warning printer. Gives formatting consistency.
104
104
105 Output is sent to Term.cerr (sys.stderr by default).
105 Output is sent to Term.cerr (sys.stderr by default).
106
106
107 Options:
107 Options:
108
108
109 -level(2): allows finer control:
109 -level(2): allows finer control:
110 0 -> Do nothing, dummy function.
110 0 -> Do nothing, dummy function.
111 1 -> Print message.
111 1 -> Print message.
112 2 -> Print 'WARNING:' + message. (Default level).
112 2 -> Print 'WARNING:' + message. (Default level).
113 3 -> Print 'ERROR:' + message.
113 3 -> Print 'ERROR:' + message.
114 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
114 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
115
115
116 -exit_val (1): exit value returned by sys.exit() for a level 4
116 -exit_val (1): exit value returned by sys.exit() for a level 4
117 warning. Ignored for all other levels."""
117 warning. Ignored for all other levels."""
118
118
119 if level>0:
119 if level>0:
120 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
120 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
121 print >> Term.cerr, '%s%s' % (header[level],msg)
121 print >> Term.cerr, '%s%s' % (header[level],msg)
122 if level == 4:
122 if level == 4:
123 print >> Term.cerr,'Exiting.\n'
123 print >> Term.cerr,'Exiting.\n'
124 sys.exit(exit_val)
124 sys.exit(exit_val)
125
125
126 def info(msg):
126 def info(msg):
127 """Equivalent to warn(msg,level=1)."""
127 """Equivalent to warn(msg,level=1)."""
128
128
129 warn(msg,level=1)
129 warn(msg,level=1)
130
130
131 def error(msg):
131 def error(msg):
132 """Equivalent to warn(msg,level=3)."""
132 """Equivalent to warn(msg,level=3)."""
133
133
134 warn(msg,level=3)
134 warn(msg,level=3)
135
135
136 def fatal(msg,exit_val=1):
136 def fatal(msg,exit_val=1):
137 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
137 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
138
138
139 warn(msg,exit_val=exit_val,level=4)
139 warn(msg,exit_val=exit_val,level=4)
140
140
141 #---------------------------------------------------------------------------
141 #---------------------------------------------------------------------------
142 # Debugging routines
142 # Debugging routines
143 #
143 #
144 def debugx(expr,pre_msg=''):
144 def debugx(expr,pre_msg=''):
145 """Print the value of an expression from the caller's frame.
145 """Print the value of an expression from the caller's frame.
146
146
147 Takes an expression, evaluates it in the caller's frame and prints both
147 Takes an expression, evaluates it in the caller's frame and prints both
148 the given expression and the resulting value (as well as a debug mark
148 the given expression and the resulting value (as well as a debug mark
149 indicating the name of the calling function. The input must be of a form
149 indicating the name of the calling function. The input must be of a form
150 suitable for eval().
150 suitable for eval().
151
151
152 An optional message can be passed, which will be prepended to the printed
152 An optional message can be passed, which will be prepended to the printed
153 expr->value pair."""
153 expr->value pair."""
154
154
155 cf = sys._getframe(1)
155 cf = sys._getframe(1)
156 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
156 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
157 eval(expr,cf.f_globals,cf.f_locals))
157 eval(expr,cf.f_globals,cf.f_locals))
158
158
159 # deactivate it by uncommenting the following line, which makes it a no-op
159 # deactivate it by uncommenting the following line, which makes it a no-op
160 #def debugx(expr,pre_msg=''): pass
160 #def debugx(expr,pre_msg=''): pass
161
161
162 #----------------------------------------------------------------------------
162 #----------------------------------------------------------------------------
163 StringTypes = types.StringTypes
163 StringTypes = types.StringTypes
164
164
165 # Basic timing functionality
165 # Basic timing functionality
166
166
167 # If possible (Unix), use the resource module instead of time.clock()
167 # If possible (Unix), use the resource module instead of time.clock()
168 try:
168 try:
169 import resource
169 import resource
170 def clocku():
170 def clocku():
171 """clocku() -> floating point number
171 """clocku() -> floating point number
172
172
173 Return the *USER* CPU time in seconds since the start of the process.
173 Return the *USER* CPU time in seconds since the start of the process.
174 This is done via a call to resource.getrusage, so it avoids the
174 This is done via a call to resource.getrusage, so it avoids the
175 wraparound problems in time.clock()."""
175 wraparound problems in time.clock()."""
176
176
177 return resource.getrusage(resource.RUSAGE_SELF)[0]
177 return resource.getrusage(resource.RUSAGE_SELF)[0]
178
178
179 def clocks():
179 def clocks():
180 """clocks() -> floating point number
180 """clocks() -> floating point number
181
181
182 Return the *SYSTEM* CPU time in seconds since the start of the process.
182 Return the *SYSTEM* CPU time in seconds since the start of the process.
183 This is done via a call to resource.getrusage, so it avoids the
183 This is done via a call to resource.getrusage, so it avoids the
184 wraparound problems in time.clock()."""
184 wraparound problems in time.clock()."""
185
185
186 return resource.getrusage(resource.RUSAGE_SELF)[1]
186 return resource.getrusage(resource.RUSAGE_SELF)[1]
187
187
188 def clock():
188 def clock():
189 """clock() -> floating point number
189 """clock() -> floating point number
190
190
191 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
191 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
192 the process. This is done via a call to resource.getrusage, so it
192 the process. This is done via a call to resource.getrusage, so it
193 avoids the wraparound problems in time.clock()."""
193 avoids the wraparound problems in time.clock()."""
194
194
195 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
195 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
196 return u+s
196 return u+s
197
197
198 def clock2():
198 def clock2():
199 """clock2() -> (t_user,t_system)
199 """clock2() -> (t_user,t_system)
200
200
201 Similar to clock(), but return a tuple of user/system times."""
201 Similar to clock(), but return a tuple of user/system times."""
202 return resource.getrusage(resource.RUSAGE_SELF)[:2]
202 return resource.getrusage(resource.RUSAGE_SELF)[:2]
203
203
204 except ImportError:
204 except ImportError:
205 # There is no distinction of user/system time under windows, so we just use
205 # There is no distinction of user/system time under windows, so we just use
206 # time.clock() for everything...
206 # time.clock() for everything...
207 clocku = clocks = clock = time.clock
207 clocku = clocks = clock = time.clock
208 def clock2():
208 def clock2():
209 """Under windows, system CPU time can't be measured.
209 """Under windows, system CPU time can't be measured.
210
210
211 This just returns clock() and zero."""
211 This just returns clock() and zero."""
212 return time.clock(),0.0
212 return time.clock(),0.0
213
213
214 def timings_out(reps,func,*args,**kw):
214 def timings_out(reps,func,*args,**kw):
215 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
215 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
216
216
217 Execute a function reps times, return a tuple with the elapsed total
217 Execute a function reps times, return a tuple with the elapsed total
218 CPU time in seconds, the time per call and the function's output.
218 CPU time in seconds, the time per call and the function's output.
219
219
220 Under Unix, the return value is the sum of user+system time consumed by
220 Under Unix, the return value is the sum of user+system time consumed by
221 the process, computed via the resource module. This prevents problems
221 the process, computed via the resource module. This prevents problems
222 related to the wraparound effect which the time.clock() function has.
222 related to the wraparound effect which the time.clock() function has.
223
223
224 Under Windows the return value is in wall clock seconds. See the
224 Under Windows the return value is in wall clock seconds. See the
225 documentation for the time module for more details."""
225 documentation for the time module for more details."""
226
226
227 reps = int(reps)
227 reps = int(reps)
228 assert reps >=1, 'reps must be >= 1'
228 assert reps >=1, 'reps must be >= 1'
229 if reps==1:
229 if reps==1:
230 start = clock()
230 start = clock()
231 out = func(*args,**kw)
231 out = func(*args,**kw)
232 tot_time = clock()-start
232 tot_time = clock()-start
233 else:
233 else:
234 rng = xrange(reps-1) # the last time is executed separately to store output
234 rng = xrange(reps-1) # the last time is executed separately to store output
235 start = clock()
235 start = clock()
236 for dummy in rng: func(*args,**kw)
236 for dummy in rng: func(*args,**kw)
237 out = func(*args,**kw) # one last time
237 out = func(*args,**kw) # one last time
238 tot_time = clock()-start
238 tot_time = clock()-start
239 av_time = tot_time / reps
239 av_time = tot_time / reps
240 return tot_time,av_time,out
240 return tot_time,av_time,out
241
241
242 def timings(reps,func,*args,**kw):
242 def timings(reps,func,*args,**kw):
243 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
243 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
244
244
245 Execute a function reps times, return a tuple with the elapsed total CPU
245 Execute a function reps times, return a tuple with the elapsed total CPU
246 time in seconds and the time per call. These are just the first two values
246 time in seconds and the time per call. These are just the first two values
247 in timings_out()."""
247 in timings_out()."""
248
248
249 return timings_out(reps,func,*args,**kw)[0:2]
249 return timings_out(reps,func,*args,**kw)[0:2]
250
250
251 def timing(func,*args,**kw):
251 def timing(func,*args,**kw):
252 """timing(func,*args,**kw) -> t_total
252 """timing(func,*args,**kw) -> t_total
253
253
254 Execute a function once, return the elapsed total CPU time in
254 Execute a function once, return the elapsed total CPU time in
255 seconds. This is just the first value in timings_out()."""
255 seconds. This is just the first value in timings_out()."""
256
256
257 return timings_out(1,func,*args,**kw)[0]
257 return timings_out(1,func,*args,**kw)[0]
258
258
259 #****************************************************************************
259 #****************************************************************************
260 # file and system
260 # file and system
261
261
262 def arg_split(s,posix=False):
262 def arg_split(s,posix=False):
263 """Split a command line's arguments in a shell-like manner.
263 """Split a command line's arguments in a shell-like manner.
264
264
265 This is a modified version of the standard library's shlex.split()
265 This is a modified version of the standard library's shlex.split()
266 function, but with a default of posix=False for splitting, so that quotes
266 function, but with a default of posix=False for splitting, so that quotes
267 in inputs are respected."""
267 in inputs are respected."""
268
268
269 # XXX - there may be unicode-related problems here!!! I'm not sure that
270 # shlex is truly unicode-safe, so it might be necessary to do
271 #
272 # s = s.encode(sys.stdin.encoding)
273 #
274 # first, to ensure that shlex gets a normal string. Input from anyone who
275 # knows more about unicode and shlex than I would be good to have here...
269 lex = shlex.shlex(s, posix=posix)
276 lex = shlex.shlex(s, posix=posix)
270 lex.whitespace_split = True
277 lex.whitespace_split = True
271 return list(lex)
278 return list(lex)
272
279
273 def system(cmd,verbose=0,debug=0,header=''):
280 def system(cmd,verbose=0,debug=0,header=''):
274 """Execute a system command, return its exit status.
281 """Execute a system command, return its exit status.
275
282
276 Options:
283 Options:
277
284
278 - verbose (0): print the command to be executed.
285 - verbose (0): print the command to be executed.
279
286
280 - debug (0): only print, do not actually execute.
287 - debug (0): only print, do not actually execute.
281
288
282 - header (''): Header to print on screen prior to the executed command (it
289 - header (''): Header to print on screen prior to the executed command (it
283 is only prepended to the command, no newlines are added).
290 is only prepended to the command, no newlines are added).
284
291
285 Note: a stateful version of this function is available through the
292 Note: a stateful version of this function is available through the
286 SystemExec class."""
293 SystemExec class."""
287
294
288 stat = 0
295 stat = 0
289 if verbose or debug: print header+cmd
296 if verbose or debug: print header+cmd
290 sys.stdout.flush()
297 sys.stdout.flush()
291 if not debug: stat = os.system(cmd)
298 if not debug: stat = os.system(cmd)
292 return stat
299 return stat
293
300
294 # This function is used by ipython in a lot of places to make system calls.
301 # This function is used by ipython in a lot of places to make system calls.
295 # We need it to be slightly different under win32, due to the vagaries of
302 # We need it to be slightly different under win32, due to the vagaries of
296 # 'network shares'. A win32 override is below.
303 # 'network shares'. A win32 override is below.
297
304
298 def shell(cmd,verbose=0,debug=0,header=''):
305 def shell(cmd,verbose=0,debug=0,header=''):
299 """Execute a command in the system shell, always return None.
306 """Execute a command in the system shell, always return None.
300
307
301 Options:
308 Options:
302
309
303 - verbose (0): print the command to be executed.
310 - verbose (0): print the command to be executed.
304
311
305 - debug (0): only print, do not actually execute.
312 - debug (0): only print, do not actually execute.
306
313
307 - header (''): Header to print on screen prior to the executed command (it
314 - header (''): Header to print on screen prior to the executed command (it
308 is only prepended to the command, no newlines are added).
315 is only prepended to the command, no newlines are added).
309
316
310 Note: this is similar to genutils.system(), but it returns None so it can
317 Note: this is similar to genutils.system(), but it returns None so it can
311 be conveniently used in interactive loops without getting the return value
318 be conveniently used in interactive loops without getting the return value
312 (typically 0) printed many times."""
319 (typically 0) printed many times."""
313
320
314 stat = 0
321 stat = 0
315 if verbose or debug: print header+cmd
322 if verbose or debug: print header+cmd
316 # flush stdout so we don't mangle python's buffering
323 # flush stdout so we don't mangle python's buffering
317 sys.stdout.flush()
324 sys.stdout.flush()
318 if not debug:
325 if not debug:
319 os.system(cmd)
326 os.system(cmd)
320
327
321 # override shell() for win32 to deal with network shares
328 # override shell() for win32 to deal with network shares
322 if os.name in ('nt','dos'):
329 if os.name in ('nt','dos'):
323
330
324 shell_ori = shell
331 shell_ori = shell
325
332
326 def shell(cmd,verbose=0,debug=0,header=''):
333 def shell(cmd,verbose=0,debug=0,header=''):
327 if os.getcwd().startswith(r"\\"):
334 if os.getcwd().startswith(r"\\"):
328 path = os.getcwd()
335 path = os.getcwd()
329 # change to c drive (cannot be on UNC-share when issuing os.system,
336 # change to c drive (cannot be on UNC-share when issuing os.system,
330 # as cmd.exe cannot handle UNC addresses)
337 # as cmd.exe cannot handle UNC addresses)
331 os.chdir("c:")
338 os.chdir("c:")
332 # issue pushd to the UNC-share and then run the command
339 # issue pushd to the UNC-share and then run the command
333 try:
340 try:
334 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
341 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
335 finally:
342 finally:
336 os.chdir(path)
343 os.chdir(path)
337 else:
344 else:
338 shell_ori(cmd,verbose,debug,header)
345 shell_ori(cmd,verbose,debug,header)
339
346
340 shell.__doc__ = shell_ori.__doc__
347 shell.__doc__ = shell_ori.__doc__
341
348
342 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
349 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
343 """Dummy substitute for perl's backquotes.
350 """Dummy substitute for perl's backquotes.
344
351
345 Executes a command and returns the output.
352 Executes a command and returns the output.
346
353
347 Accepts the same arguments as system(), plus:
354 Accepts the same arguments as system(), plus:
348
355
349 - split(0): if true, the output is returned as a list split on newlines.
356 - split(0): if true, the output is returned as a list split on newlines.
350
357
351 Note: a stateful version of this function is available through the
358 Note: a stateful version of this function is available through the
352 SystemExec class.
359 SystemExec class.
353
360
354 This is pretty much deprecated and rarely used,
361 This is pretty much deprecated and rarely used,
355 genutils.getoutputerror may be what you need.
362 genutils.getoutputerror may be what you need.
356
363
357 """
364 """
358
365
359 if verbose or debug: print header+cmd
366 if verbose or debug: print header+cmd
360 if not debug:
367 if not debug:
361 output = os.popen(cmd).read()
368 output = os.popen(cmd).read()
362 # stipping last \n is here for backwards compat.
369 # stipping last \n is here for backwards compat.
363 if output.endswith('\n'):
370 if output.endswith('\n'):
364 output = output[:-1]
371 output = output[:-1]
365 if split:
372 if split:
366 return output.split('\n')
373 return output.split('\n')
367 else:
374 else:
368 return output
375 return output
369
376
370 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
377 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
371 """Return (standard output,standard error) of executing cmd in a shell.
378 """Return (standard output,standard error) of executing cmd in a shell.
372
379
373 Accepts the same arguments as system(), plus:
380 Accepts the same arguments as system(), plus:
374
381
375 - split(0): if true, each of stdout/err is returned as a list split on
382 - split(0): if true, each of stdout/err is returned as a list split on
376 newlines.
383 newlines.
377
384
378 Note: a stateful version of this function is available through the
385 Note: a stateful version of this function is available through the
379 SystemExec class."""
386 SystemExec class."""
380
387
381 if verbose or debug: print header+cmd
388 if verbose or debug: print header+cmd
382 if not cmd:
389 if not cmd:
383 if split:
390 if split:
384 return [],[]
391 return [],[]
385 else:
392 else:
386 return '',''
393 return '',''
387 if not debug:
394 if not debug:
388 pin,pout,perr = os.popen3(cmd)
395 pin,pout,perr = os.popen3(cmd)
389 tout = pout.read().rstrip()
396 tout = pout.read().rstrip()
390 terr = perr.read().rstrip()
397 terr = perr.read().rstrip()
391 pin.close()
398 pin.close()
392 pout.close()
399 pout.close()
393 perr.close()
400 perr.close()
394 if split:
401 if split:
395 return tout.split('\n'),terr.split('\n')
402 return tout.split('\n'),terr.split('\n')
396 else:
403 else:
397 return tout,terr
404 return tout,terr
398
405
399 # for compatibility with older naming conventions
406 # for compatibility with older naming conventions
400 xsys = system
407 xsys = system
401 bq = getoutput
408 bq = getoutput
402
409
403 class SystemExec:
410 class SystemExec:
404 """Access the system and getoutput functions through a stateful interface.
411 """Access the system and getoutput functions through a stateful interface.
405
412
406 Note: here we refer to the system and getoutput functions from this
413 Note: here we refer to the system and getoutput functions from this
407 library, not the ones from the standard python library.
414 library, not the ones from the standard python library.
408
415
409 This class offers the system and getoutput functions as methods, but the
416 This class offers the system and getoutput functions as methods, but the
410 verbose, debug and header parameters can be set for the instance (at
417 verbose, debug and header parameters can be set for the instance (at
411 creation time or later) so that they don't need to be specified on each
418 creation time or later) so that they don't need to be specified on each
412 call.
419 call.
413
420
414 For efficiency reasons, there's no way to override the parameters on a
421 For efficiency reasons, there's no way to override the parameters on a
415 per-call basis other than by setting instance attributes. If you need
422 per-call basis other than by setting instance attributes. If you need
416 local overrides, it's best to directly call system() or getoutput().
423 local overrides, it's best to directly call system() or getoutput().
417
424
418 The following names are provided as alternate options:
425 The following names are provided as alternate options:
419 - xsys: alias to system
426 - xsys: alias to system
420 - bq: alias to getoutput
427 - bq: alias to getoutput
421
428
422 An instance can then be created as:
429 An instance can then be created as:
423 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
430 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
424
431
425 And used as:
432 And used as:
426 >>> sysexec.xsys('pwd')
433 >>> sysexec.xsys('pwd')
427 >>> dirlist = sysexec.bq('ls -l')
434 >>> dirlist = sysexec.bq('ls -l')
428 """
435 """
429
436
430 def __init__(self,verbose=0,debug=0,header='',split=0):
437 def __init__(self,verbose=0,debug=0,header='',split=0):
431 """Specify the instance's values for verbose, debug and header."""
438 """Specify the instance's values for verbose, debug and header."""
432 setattr_list(self,'verbose debug header split')
439 setattr_list(self,'verbose debug header split')
433
440
434 def system(self,cmd):
441 def system(self,cmd):
435 """Stateful interface to system(), with the same keyword parameters."""
442 """Stateful interface to system(), with the same keyword parameters."""
436
443
437 system(cmd,self.verbose,self.debug,self.header)
444 system(cmd,self.verbose,self.debug,self.header)
438
445
439 def shell(self,cmd):
446 def shell(self,cmd):
440 """Stateful interface to shell(), with the same keyword parameters."""
447 """Stateful interface to shell(), with the same keyword parameters."""
441
448
442 shell(cmd,self.verbose,self.debug,self.header)
449 shell(cmd,self.verbose,self.debug,self.header)
443
450
444 xsys = system # alias
451 xsys = system # alias
445
452
446 def getoutput(self,cmd):
453 def getoutput(self,cmd):
447 """Stateful interface to getoutput()."""
454 """Stateful interface to getoutput()."""
448
455
449 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
456 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
450
457
451 def getoutputerror(self,cmd):
458 def getoutputerror(self,cmd):
452 """Stateful interface to getoutputerror()."""
459 """Stateful interface to getoutputerror()."""
453
460
454 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
461 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
455
462
456 bq = getoutput # alias
463 bq = getoutput # alias
457
464
458 #-----------------------------------------------------------------------------
465 #-----------------------------------------------------------------------------
459 def mutex_opts(dict,ex_op):
466 def mutex_opts(dict,ex_op):
460 """Check for presence of mutually exclusive keys in a dict.
467 """Check for presence of mutually exclusive keys in a dict.
461
468
462 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
469 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
463 for op1,op2 in ex_op:
470 for op1,op2 in ex_op:
464 if op1 in dict and op2 in dict:
471 if op1 in dict and op2 in dict:
465 raise ValueError,'\n*** ERROR in Arguments *** '\
472 raise ValueError,'\n*** ERROR in Arguments *** '\
466 'Options '+op1+' and '+op2+' are mutually exclusive.'
473 'Options '+op1+' and '+op2+' are mutually exclusive.'
467
474
468 #-----------------------------------------------------------------------------
475 #-----------------------------------------------------------------------------
469 def get_py_filename(name):
476 def get_py_filename(name):
470 """Return a valid python filename in the current directory.
477 """Return a valid python filename in the current directory.
471
478
472 If the given name is not a file, it adds '.py' and searches again.
479 If the given name is not a file, it adds '.py' and searches again.
473 Raises IOError with an informative message if the file isn't found."""
480 Raises IOError with an informative message if the file isn't found."""
474
481
475 name = os.path.expanduser(name)
482 name = os.path.expanduser(name)
476 if not os.path.isfile(name) and not name.endswith('.py'):
483 if not os.path.isfile(name) and not name.endswith('.py'):
477 name += '.py'
484 name += '.py'
478 if os.path.isfile(name):
485 if os.path.isfile(name):
479 return name
486 return name
480 else:
487 else:
481 raise IOError,'File `%s` not found.' % name
488 raise IOError,'File `%s` not found.' % name
482
489
483 #-----------------------------------------------------------------------------
490 #-----------------------------------------------------------------------------
484 def filefind(fname,alt_dirs = None):
491 def filefind(fname,alt_dirs = None):
485 """Return the given filename either in the current directory, if it
492 """Return the given filename either in the current directory, if it
486 exists, or in a specified list of directories.
493 exists, or in a specified list of directories.
487
494
488 ~ expansion is done on all file and directory names.
495 ~ expansion is done on all file and directory names.
489
496
490 Upon an unsuccessful search, raise an IOError exception."""
497 Upon an unsuccessful search, raise an IOError exception."""
491
498
492 if alt_dirs is None:
499 if alt_dirs is None:
493 try:
500 try:
494 alt_dirs = get_home_dir()
501 alt_dirs = get_home_dir()
495 except HomeDirError:
502 except HomeDirError:
496 alt_dirs = os.getcwd()
503 alt_dirs = os.getcwd()
497 search = [fname] + list_strings(alt_dirs)
504 search = [fname] + list_strings(alt_dirs)
498 search = map(os.path.expanduser,search)
505 search = map(os.path.expanduser,search)
499 #print 'search list for',fname,'list:',search # dbg
506 #print 'search list for',fname,'list:',search # dbg
500 fname = search[0]
507 fname = search[0]
501 if os.path.isfile(fname):
508 if os.path.isfile(fname):
502 return fname
509 return fname
503 for direc in search[1:]:
510 for direc in search[1:]:
504 testname = os.path.join(direc,fname)
511 testname = os.path.join(direc,fname)
505 #print 'testname',testname # dbg
512 #print 'testname',testname # dbg
506 if os.path.isfile(testname):
513 if os.path.isfile(testname):
507 return testname
514 return testname
508 raise IOError,'File' + `fname` + \
515 raise IOError,'File' + `fname` + \
509 ' not found in current or supplied directories:' + `alt_dirs`
516 ' not found in current or supplied directories:' + `alt_dirs`
510
517
511 #----------------------------------------------------------------------------
518 #----------------------------------------------------------------------------
512 def file_read(filename):
519 def file_read(filename):
513 """Read a file and close it. Returns the file source."""
520 """Read a file and close it. Returns the file source."""
514 fobj = open(filename,'r');
521 fobj = open(filename,'r');
515 source = fobj.read();
522 source = fobj.read();
516 fobj.close()
523 fobj.close()
517 return source
524 return source
518
525
519 def file_readlines(filename):
526 def file_readlines(filename):
520 """Read a file and close it. Returns the file source using readlines()."""
527 """Read a file and close it. Returns the file source using readlines()."""
521 fobj = open(filename,'r');
528 fobj = open(filename,'r');
522 lines = fobj.readlines();
529 lines = fobj.readlines();
523 fobj.close()
530 fobj.close()
524 return lines
531 return lines
525
532
526 #----------------------------------------------------------------------------
533 #----------------------------------------------------------------------------
527 def target_outdated(target,deps):
534 def target_outdated(target,deps):
528 """Determine whether a target is out of date.
535 """Determine whether a target is out of date.
529
536
530 target_outdated(target,deps) -> 1/0
537 target_outdated(target,deps) -> 1/0
531
538
532 deps: list of filenames which MUST exist.
539 deps: list of filenames which MUST exist.
533 target: single filename which may or may not exist.
540 target: single filename which may or may not exist.
534
541
535 If target doesn't exist or is older than any file listed in deps, return
542 If target doesn't exist or is older than any file listed in deps, return
536 true, otherwise return false.
543 true, otherwise return false.
537 """
544 """
538 try:
545 try:
539 target_time = os.path.getmtime(target)
546 target_time = os.path.getmtime(target)
540 except os.error:
547 except os.error:
541 return 1
548 return 1
542 for dep in deps:
549 for dep in deps:
543 dep_time = os.path.getmtime(dep)
550 dep_time = os.path.getmtime(dep)
544 if dep_time > target_time:
551 if dep_time > target_time:
545 #print "For target",target,"Dep failed:",dep # dbg
552 #print "For target",target,"Dep failed:",dep # dbg
546 #print "times (dep,tar):",dep_time,target_time # dbg
553 #print "times (dep,tar):",dep_time,target_time # dbg
547 return 1
554 return 1
548 return 0
555 return 0
549
556
550 #-----------------------------------------------------------------------------
557 #-----------------------------------------------------------------------------
551 def target_update(target,deps,cmd):
558 def target_update(target,deps,cmd):
552 """Update a target with a given command given a list of dependencies.
559 """Update a target with a given command given a list of dependencies.
553
560
554 target_update(target,deps,cmd) -> runs cmd if target is outdated.
561 target_update(target,deps,cmd) -> runs cmd if target is outdated.
555
562
556 This is just a wrapper around target_outdated() which calls the given
563 This is just a wrapper around target_outdated() which calls the given
557 command if target is outdated."""
564 command if target is outdated."""
558
565
559 if target_outdated(target,deps):
566 if target_outdated(target,deps):
560 xsys(cmd)
567 xsys(cmd)
561
568
562 #----------------------------------------------------------------------------
569 #----------------------------------------------------------------------------
563 def unquote_ends(istr):
570 def unquote_ends(istr):
564 """Remove a single pair of quotes from the endpoints of a string."""
571 """Remove a single pair of quotes from the endpoints of a string."""
565
572
566 if not istr:
573 if not istr:
567 return istr
574 return istr
568 if (istr[0]=="'" and istr[-1]=="'") or \
575 if (istr[0]=="'" and istr[-1]=="'") or \
569 (istr[0]=='"' and istr[-1]=='"'):
576 (istr[0]=='"' and istr[-1]=='"'):
570 return istr[1:-1]
577 return istr[1:-1]
571 else:
578 else:
572 return istr
579 return istr
573
580
574 #----------------------------------------------------------------------------
581 #----------------------------------------------------------------------------
575 def process_cmdline(argv,names=[],defaults={},usage=''):
582 def process_cmdline(argv,names=[],defaults={},usage=''):
576 """ Process command-line options and arguments.
583 """ Process command-line options and arguments.
577
584
578 Arguments:
585 Arguments:
579
586
580 - argv: list of arguments, typically sys.argv.
587 - argv: list of arguments, typically sys.argv.
581
588
582 - names: list of option names. See DPyGetOpt docs for details on options
589 - names: list of option names. See DPyGetOpt docs for details on options
583 syntax.
590 syntax.
584
591
585 - defaults: dict of default values.
592 - defaults: dict of default values.
586
593
587 - usage: optional usage notice to print if a wrong argument is passed.
594 - usage: optional usage notice to print if a wrong argument is passed.
588
595
589 Return a dict of options and a list of free arguments."""
596 Return a dict of options and a list of free arguments."""
590
597
591 getopt = DPyGetOpt.DPyGetOpt()
598 getopt = DPyGetOpt.DPyGetOpt()
592 getopt.setIgnoreCase(0)
599 getopt.setIgnoreCase(0)
593 getopt.parseConfiguration(names)
600 getopt.parseConfiguration(names)
594
601
595 try:
602 try:
596 getopt.processArguments(argv)
603 getopt.processArguments(argv)
597 except:
604 except:
598 print usage
605 print usage
599 warn(`sys.exc_value`,level=4)
606 warn(`sys.exc_value`,level=4)
600
607
601 defaults.update(getopt.optionValues)
608 defaults.update(getopt.optionValues)
602 args = getopt.freeValues
609 args = getopt.freeValues
603
610
604 return defaults,args
611 return defaults,args
605
612
606 #----------------------------------------------------------------------------
613 #----------------------------------------------------------------------------
607 def optstr2types(ostr):
614 def optstr2types(ostr):
608 """Convert a string of option names to a dict of type mappings.
615 """Convert a string of option names to a dict of type mappings.
609
616
610 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
617 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
611
618
612 This is used to get the types of all the options in a string formatted
619 This is used to get the types of all the options in a string formatted
613 with the conventions of DPyGetOpt. The 'type' None is used for options
620 with the conventions of DPyGetOpt. The 'type' None is used for options
614 which are strings (they need no further conversion). This function's main
621 which are strings (they need no further conversion). This function's main
615 use is to get a typemap for use with read_dict().
622 use is to get a typemap for use with read_dict().
616 """
623 """
617
624
618 typeconv = {None:'',int:'',float:''}
625 typeconv = {None:'',int:'',float:''}
619 typemap = {'s':None,'i':int,'f':float}
626 typemap = {'s':None,'i':int,'f':float}
620 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
627 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
621
628
622 for w in ostr.split():
629 for w in ostr.split():
623 oname,alias,otype = opt_re.match(w).groups()
630 oname,alias,otype = opt_re.match(w).groups()
624 if otype == '' or alias == '!': # simple switches are integers too
631 if otype == '' or alias == '!': # simple switches are integers too
625 otype = 'i'
632 otype = 'i'
626 typeconv[typemap[otype]] += oname + ' '
633 typeconv[typemap[otype]] += oname + ' '
627 return typeconv
634 return typeconv
628
635
629 #----------------------------------------------------------------------------
636 #----------------------------------------------------------------------------
630 def read_dict(filename,type_conv=None,**opt):
637 def read_dict(filename,type_conv=None,**opt):
631
638
632 """Read a dictionary of key=value pairs from an input file, optionally
639 """Read a dictionary of key=value pairs from an input file, optionally
633 performing conversions on the resulting values.
640 performing conversions on the resulting values.
634
641
635 read_dict(filename,type_conv,**opt) -> dict
642 read_dict(filename,type_conv,**opt) -> dict
636
643
637 Only one value per line is accepted, the format should be
644 Only one value per line is accepted, the format should be
638 # optional comments are ignored
645 # optional comments are ignored
639 key value\n
646 key value\n
640
647
641 Args:
648 Args:
642
649
643 - type_conv: A dictionary specifying which keys need to be converted to
650 - type_conv: A dictionary specifying which keys need to be converted to
644 which types. By default all keys are read as strings. This dictionary
651 which types. By default all keys are read as strings. This dictionary
645 should have as its keys valid conversion functions for strings
652 should have as its keys valid conversion functions for strings
646 (int,long,float,complex, or your own). The value for each key
653 (int,long,float,complex, or your own). The value for each key
647 (converter) should be a whitespace separated string containing the names
654 (converter) should be a whitespace separated string containing the names
648 of all the entries in the file to be converted using that function. For
655 of all the entries in the file to be converted using that function. For
649 keys to be left alone, use None as the conversion function (only needed
656 keys to be left alone, use None as the conversion function (only needed
650 with purge=1, see below).
657 with purge=1, see below).
651
658
652 - opt: dictionary with extra options as below (default in parens)
659 - opt: dictionary with extra options as below (default in parens)
653
660
654 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
661 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
655 of the dictionary to be returned. If purge is going to be used, the
662 of the dictionary to be returned. If purge is going to be used, the
656 set of keys to be left as strings also has to be explicitly specified
663 set of keys to be left as strings also has to be explicitly specified
657 using the (non-existent) conversion function None.
664 using the (non-existent) conversion function None.
658
665
659 fs(None): field separator. This is the key/value separator to be used
666 fs(None): field separator. This is the key/value separator to be used
660 when parsing the file. The None default means any whitespace [behavior
667 when parsing the file. The None default means any whitespace [behavior
661 of string.split()].
668 of string.split()].
662
669
663 strip(0): if 1, strip string values of leading/trailinig whitespace.
670 strip(0): if 1, strip string values of leading/trailinig whitespace.
664
671
665 warn(1): warning level if requested keys are not found in file.
672 warn(1): warning level if requested keys are not found in file.
666 - 0: silently ignore.
673 - 0: silently ignore.
667 - 1: inform but proceed.
674 - 1: inform but proceed.
668 - 2: raise KeyError exception.
675 - 2: raise KeyError exception.
669
676
670 no_empty(0): if 1, remove keys with whitespace strings as a value.
677 no_empty(0): if 1, remove keys with whitespace strings as a value.
671
678
672 unique([]): list of keys (or space separated string) which can't be
679 unique([]): list of keys (or space separated string) which can't be
673 repeated. If one such key is found in the file, each new instance
680 repeated. If one such key is found in the file, each new instance
674 overwrites the previous one. For keys not listed here, the behavior is
681 overwrites the previous one. For keys not listed here, the behavior is
675 to make a list of all appearances.
682 to make a list of all appearances.
676
683
677 Example:
684 Example:
678 If the input file test.ini has:
685 If the input file test.ini has:
679 i 3
686 i 3
680 x 4.5
687 x 4.5
681 y 5.5
688 y 5.5
682 s hi ho
689 s hi ho
683 Then:
690 Then:
684
691
685 >>> type_conv={int:'i',float:'x',None:'s'}
692 >>> type_conv={int:'i',float:'x',None:'s'}
686 >>> read_dict('test.ini')
693 >>> read_dict('test.ini')
687 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
694 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
688 >>> read_dict('test.ini',type_conv)
695 >>> read_dict('test.ini',type_conv)
689 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
696 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
690 >>> read_dict('test.ini',type_conv,purge=1)
697 >>> read_dict('test.ini',type_conv,purge=1)
691 {'i': 3, 's': 'hi ho', 'x': 4.5}
698 {'i': 3, 's': 'hi ho', 'x': 4.5}
692 """
699 """
693
700
694 # starting config
701 # starting config
695 opt.setdefault('purge',0)
702 opt.setdefault('purge',0)
696 opt.setdefault('fs',None) # field sep defaults to any whitespace
703 opt.setdefault('fs',None) # field sep defaults to any whitespace
697 opt.setdefault('strip',0)
704 opt.setdefault('strip',0)
698 opt.setdefault('warn',1)
705 opt.setdefault('warn',1)
699 opt.setdefault('no_empty',0)
706 opt.setdefault('no_empty',0)
700 opt.setdefault('unique','')
707 opt.setdefault('unique','')
701 if type(opt['unique']) in StringTypes:
708 if type(opt['unique']) in StringTypes:
702 unique_keys = qw(opt['unique'])
709 unique_keys = qw(opt['unique'])
703 elif type(opt['unique']) in (types.TupleType,types.ListType):
710 elif type(opt['unique']) in (types.TupleType,types.ListType):
704 unique_keys = opt['unique']
711 unique_keys = opt['unique']
705 else:
712 else:
706 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
713 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
707
714
708 dict = {}
715 dict = {}
709 # first read in table of values as strings
716 # first read in table of values as strings
710 file = open(filename,'r')
717 file = open(filename,'r')
711 for line in file.readlines():
718 for line in file.readlines():
712 line = line.strip()
719 line = line.strip()
713 if len(line) and line[0]=='#': continue
720 if len(line) and line[0]=='#': continue
714 if len(line)>0:
721 if len(line)>0:
715 lsplit = line.split(opt['fs'],1)
722 lsplit = line.split(opt['fs'],1)
716 try:
723 try:
717 key,val = lsplit
724 key,val = lsplit
718 except ValueError:
725 except ValueError:
719 key,val = lsplit[0],''
726 key,val = lsplit[0],''
720 key = key.strip()
727 key = key.strip()
721 if opt['strip']: val = val.strip()
728 if opt['strip']: val = val.strip()
722 if val == "''" or val == '""': val = ''
729 if val == "''" or val == '""': val = ''
723 if opt['no_empty'] and (val=='' or val.isspace()):
730 if opt['no_empty'] and (val=='' or val.isspace()):
724 continue
731 continue
725 # if a key is found more than once in the file, build a list
732 # if a key is found more than once in the file, build a list
726 # unless it's in the 'unique' list. In that case, last found in file
733 # unless it's in the 'unique' list. In that case, last found in file
727 # takes precedence. User beware.
734 # takes precedence. User beware.
728 try:
735 try:
729 if dict[key] and key in unique_keys:
736 if dict[key] and key in unique_keys:
730 dict[key] = val
737 dict[key] = val
731 elif type(dict[key]) is types.ListType:
738 elif type(dict[key]) is types.ListType:
732 dict[key].append(val)
739 dict[key].append(val)
733 else:
740 else:
734 dict[key] = [dict[key],val]
741 dict[key] = [dict[key],val]
735 except KeyError:
742 except KeyError:
736 dict[key] = val
743 dict[key] = val
737 # purge if requested
744 # purge if requested
738 if opt['purge']:
745 if opt['purge']:
739 accepted_keys = qwflat(type_conv.values())
746 accepted_keys = qwflat(type_conv.values())
740 for key in dict.keys():
747 for key in dict.keys():
741 if key in accepted_keys: continue
748 if key in accepted_keys: continue
742 del(dict[key])
749 del(dict[key])
743 # now convert if requested
750 # now convert if requested
744 if type_conv==None: return dict
751 if type_conv==None: return dict
745 conversions = type_conv.keys()
752 conversions = type_conv.keys()
746 try: conversions.remove(None)
753 try: conversions.remove(None)
747 except: pass
754 except: pass
748 for convert in conversions:
755 for convert in conversions:
749 for val in qw(type_conv[convert]):
756 for val in qw(type_conv[convert]):
750 try:
757 try:
751 dict[val] = convert(dict[val])
758 dict[val] = convert(dict[val])
752 except KeyError,e:
759 except KeyError,e:
753 if opt['warn'] == 0:
760 if opt['warn'] == 0:
754 pass
761 pass
755 elif opt['warn'] == 1:
762 elif opt['warn'] == 1:
756 print >>sys.stderr, 'Warning: key',val,\
763 print >>sys.stderr, 'Warning: key',val,\
757 'not found in file',filename
764 'not found in file',filename
758 elif opt['warn'] == 2:
765 elif opt['warn'] == 2:
759 raise KeyError,e
766 raise KeyError,e
760 else:
767 else:
761 raise ValueError,'Warning level must be 0,1 or 2'
768 raise ValueError,'Warning level must be 0,1 or 2'
762
769
763 return dict
770 return dict
764
771
765 #----------------------------------------------------------------------------
772 #----------------------------------------------------------------------------
766 def flag_calls(func):
773 def flag_calls(func):
767 """Wrap a function to detect and flag when it gets called.
774 """Wrap a function to detect and flag when it gets called.
768
775
769 This is a decorator which takes a function and wraps it in a function with
776 This is a decorator which takes a function and wraps it in a function with
770 a 'called' attribute. wrapper.called is initialized to False.
777 a 'called' attribute. wrapper.called is initialized to False.
771
778
772 The wrapper.called attribute is set to False right before each call to the
779 The wrapper.called attribute is set to False right before each call to the
773 wrapped function, so if the call fails it remains False. After the call
780 wrapped function, so if the call fails it remains False. After the call
774 completes, wrapper.called is set to True and the output is returned.
781 completes, wrapper.called is set to True and the output is returned.
775
782
776 Testing for truth in wrapper.called allows you to determine if a call to
783 Testing for truth in wrapper.called allows you to determine if a call to
777 func() was attempted and succeeded."""
784 func() was attempted and succeeded."""
778
785
779 def wrapper(*args,**kw):
786 def wrapper(*args,**kw):
780 wrapper.called = False
787 wrapper.called = False
781 out = func(*args,**kw)
788 out = func(*args,**kw)
782 wrapper.called = True
789 wrapper.called = True
783 return out
790 return out
784
791
785 wrapper.called = False
792 wrapper.called = False
786 wrapper.__doc__ = func.__doc__
793 wrapper.__doc__ = func.__doc__
787 return wrapper
794 return wrapper
788
795
789 #----------------------------------------------------------------------------
796 #----------------------------------------------------------------------------
790 class HomeDirError(Error):
797 class HomeDirError(Error):
791 pass
798 pass
792
799
793 def get_home_dir():
800 def get_home_dir():
794 """Return the closest possible equivalent to a 'home' directory.
801 """Return the closest possible equivalent to a 'home' directory.
795
802
796 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
803 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
797
804
798 Currently only Posix and NT are implemented, a HomeDirError exception is
805 Currently only Posix and NT are implemented, a HomeDirError exception is
799 raised for all other OSes. """
806 raised for all other OSes. """
800
807
801 isdir = os.path.isdir
808 isdir = os.path.isdir
802 env = os.environ
809 env = os.environ
803 try:
810 try:
804 homedir = env['HOME']
811 homedir = env['HOME']
805 if not isdir(homedir):
812 if not isdir(homedir):
806 # in case a user stuck some string which does NOT resolve to a
813 # in case a user stuck some string which does NOT resolve to a
807 # valid path, it's as good as if we hadn't foud it
814 # valid path, it's as good as if we hadn't foud it
808 raise KeyError
815 raise KeyError
809 return homedir
816 return homedir
810 except KeyError:
817 except KeyError:
811 if os.name == 'posix':
818 if os.name == 'posix':
812 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
819 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
813 elif os.name == 'nt':
820 elif os.name == 'nt':
814 # For some strange reason, win9x returns 'nt' for os.name.
821 # For some strange reason, win9x returns 'nt' for os.name.
815 try:
822 try:
816 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
823 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
817 if not isdir(homedir):
824 if not isdir(homedir):
818 homedir = os.path.join(env['USERPROFILE'])
825 homedir = os.path.join(env['USERPROFILE'])
819 if not isdir(homedir):
826 if not isdir(homedir):
820 raise HomeDirError
827 raise HomeDirError
821 return homedir
828 return homedir
822 except:
829 except:
823 try:
830 try:
824 # Use the registry to get the 'My Documents' folder.
831 # Use the registry to get the 'My Documents' folder.
825 import _winreg as wreg
832 import _winreg as wreg
826 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
833 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
827 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
834 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
828 homedir = wreg.QueryValueEx(key,'Personal')[0]
835 homedir = wreg.QueryValueEx(key,'Personal')[0]
829 key.Close()
836 key.Close()
830 if not isdir(homedir):
837 if not isdir(homedir):
831 e = ('Invalid "Personal" folder registry key '
838 e = ('Invalid "Personal" folder registry key '
832 'typically "My Documents".\n'
839 'typically "My Documents".\n'
833 'Value: %s\n'
840 'Value: %s\n'
834 'This is not a valid directory on your system.' %
841 'This is not a valid directory on your system.' %
835 homedir)
842 homedir)
836 raise HomeDirError(e)
843 raise HomeDirError(e)
837 return homedir
844 return homedir
838 except HomeDirError:
845 except HomeDirError:
839 raise
846 raise
840 except:
847 except:
841 return 'C:\\'
848 return 'C:\\'
842 elif os.name == 'dos':
849 elif os.name == 'dos':
843 # Desperate, may do absurd things in classic MacOS. May work under DOS.
850 # Desperate, may do absurd things in classic MacOS. May work under DOS.
844 return 'C:\\'
851 return 'C:\\'
845 else:
852 else:
846 raise HomeDirError,'support for your operating system not implemented.'
853 raise HomeDirError,'support for your operating system not implemented.'
847
854
848 #****************************************************************************
855 #****************************************************************************
849 # strings and text
856 # strings and text
850
857
851 class LSString(str):
858 class LSString(str):
852 """String derivative with a special access attributes.
859 """String derivative with a special access attributes.
853
860
854 These are normal strings, but with the special attributes:
861 These are normal strings, but with the special attributes:
855
862
856 .l (or .list) : value as list (split on newlines).
863 .l (or .list) : value as list (split on newlines).
857 .n (or .nlstr): original value (the string itself).
864 .n (or .nlstr): original value (the string itself).
858 .s (or .spstr): value as whitespace-separated string.
865 .s (or .spstr): value as whitespace-separated string.
859
866
860 Any values which require transformations are computed only once and
867 Any values which require transformations are computed only once and
861 cached.
868 cached.
862
869
863 Such strings are very useful to efficiently interact with the shell, which
870 Such strings are very useful to efficiently interact with the shell, which
864 typically only understands whitespace-separated options for commands."""
871 typically only understands whitespace-separated options for commands."""
865
872
866 def get_list(self):
873 def get_list(self):
867 try:
874 try:
868 return self.__list
875 return self.__list
869 except AttributeError:
876 except AttributeError:
870 self.__list = self.split('\n')
877 self.__list = self.split('\n')
871 return self.__list
878 return self.__list
872
879
873 l = list = property(get_list)
880 l = list = property(get_list)
874
881
875 def get_spstr(self):
882 def get_spstr(self):
876 try:
883 try:
877 return self.__spstr
884 return self.__spstr
878 except AttributeError:
885 except AttributeError:
879 self.__spstr = self.replace('\n',' ')
886 self.__spstr = self.replace('\n',' ')
880 return self.__spstr
887 return self.__spstr
881
888
882 s = spstr = property(get_spstr)
889 s = spstr = property(get_spstr)
883
890
884 def get_nlstr(self):
891 def get_nlstr(self):
885 return self
892 return self
886
893
887 n = nlstr = property(get_nlstr)
894 n = nlstr = property(get_nlstr)
888
895
889 def get_paths(self):
896 def get_paths(self):
890 try:
897 try:
891 return self.__paths
898 return self.__paths
892 except AttributeError:
899 except AttributeError:
893 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
900 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
894 return self.__paths
901 return self.__paths
895
902
896 p = paths = property(get_paths)
903 p = paths = property(get_paths)
897
904
898
905
899 #----------------------------------------------------------------------------
906 #----------------------------------------------------------------------------
900 class SList(list):
907 class SList(list):
901 """List derivative with a special access attributes.
908 """List derivative with a special access attributes.
902
909
903 These are normal lists, but with the special attributes:
910 These are normal lists, but with the special attributes:
904
911
905 .l (or .list) : value as list (the list itself).
912 .l (or .list) : value as list (the list itself).
906 .n (or .nlstr): value as a string, joined on newlines.
913 .n (or .nlstr): value as a string, joined on newlines.
907 .s (or .spstr): value as a string, joined on spaces.
914 .s (or .spstr): value as a string, joined on spaces.
908
915
909 Any values which require transformations are computed only once and
916 Any values which require transformations are computed only once and
910 cached."""
917 cached."""
911
918
912 def get_list(self):
919 def get_list(self):
913 return self
920 return self
914
921
915 l = list = property(get_list)
922 l = list = property(get_list)
916
923
917 def get_spstr(self):
924 def get_spstr(self):
918 try:
925 try:
919 return self.__spstr
926 return self.__spstr
920 except AttributeError:
927 except AttributeError:
921 self.__spstr = ' '.join(self)
928 self.__spstr = ' '.join(self)
922 return self.__spstr
929 return self.__spstr
923
930
924 s = spstr = property(get_spstr)
931 s = spstr = property(get_spstr)
925
932
926 def get_nlstr(self):
933 def get_nlstr(self):
927 try:
934 try:
928 return self.__nlstr
935 return self.__nlstr
929 except AttributeError:
936 except AttributeError:
930 self.__nlstr = '\n'.join(self)
937 self.__nlstr = '\n'.join(self)
931 return self.__nlstr
938 return self.__nlstr
932
939
933 n = nlstr = property(get_nlstr)
940 n = nlstr = property(get_nlstr)
934
941
935 def get_paths(self):
942 def get_paths(self):
936 try:
943 try:
937 return self.__paths
944 return self.__paths
938 except AttributeError:
945 except AttributeError:
939 self.__paths = [path(p) for p in self if os.path.exists(p)]
946 self.__paths = [path(p) for p in self if os.path.exists(p)]
940 return self.__paths
947 return self.__paths
941
948
942 p = paths = property(get_paths)
949 p = paths = property(get_paths)
943
950
944 #----------------------------------------------------------------------------
951 #----------------------------------------------------------------------------
945 def esc_quotes(strng):
952 def esc_quotes(strng):
946 """Return the input string with single and double quotes escaped out"""
953 """Return the input string with single and double quotes escaped out"""
947
954
948 return strng.replace('"','\\"').replace("'","\\'")
955 return strng.replace('"','\\"').replace("'","\\'")
949
956
950 #----------------------------------------------------------------------------
957 #----------------------------------------------------------------------------
951 def make_quoted_expr(s):
958 def make_quoted_expr(s):
952 """Return string s in appropriate quotes, using raw string if possible.
959 """Return string s in appropriate quotes, using raw string if possible.
953
960
954 Effectively this turns string: cd \ao\ao\
961 Effectively this turns string: cd \ao\ao\
955 to: r"cd \ao\ao\_"[:-1]
962 to: r"cd \ao\ao\_"[:-1]
956
963
957 Note the use of raw string and padding at the end to allow trailing backslash.
964 Note the use of raw string and padding at the end to allow trailing backslash.
958
965
959 """
966 """
960
967
961 tail = ''
968 tail = ''
962 tailpadding = ''
969 tailpadding = ''
963 raw = ''
970 raw = ''
964 if "\\" in s:
971 if "\\" in s:
965 raw = 'r'
972 raw = 'r'
966 if s.endswith('\\'):
973 if s.endswith('\\'):
967 tail = '[:-1]'
974 tail = '[:-1]'
968 tailpadding = '_'
975 tailpadding = '_'
969 if '"' not in s:
976 if '"' not in s:
970 quote = '"'
977 quote = '"'
971 elif "'" not in s:
978 elif "'" not in s:
972 quote = "'"
979 quote = "'"
973 elif '"""' not in s and not s.endswith('"'):
980 elif '"""' not in s and not s.endswith('"'):
974 quote = '"""'
981 quote = '"""'
975 elif "'''" not in s and not s.endswith("'"):
982 elif "'''" not in s and not s.endswith("'"):
976 quote = "'''"
983 quote = "'''"
977 else:
984 else:
978 # give up, backslash-escaped string will do
985 # give up, backslash-escaped string will do
979 return '"%s"' % esc_quotes(s)
986 return '"%s"' % esc_quotes(s)
980 res = itpl("$raw$quote$s$tailpadding$quote$tail")
987 res = itpl("$raw$quote$s$tailpadding$quote$tail")
981 return res
988 return res
982
989
983
990
984 #----------------------------------------------------------------------------
991 #----------------------------------------------------------------------------
985 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
992 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
986 """Take multiple lines of input.
993 """Take multiple lines of input.
987
994
988 A list with each line of input as a separate element is returned when a
995 A list with each line of input as a separate element is returned when a
989 termination string is entered (defaults to a single '.'). Input can also
996 termination string is entered (defaults to a single '.'). Input can also
990 terminate via EOF (^D in Unix, ^Z-RET in Windows).
997 terminate via EOF (^D in Unix, ^Z-RET in Windows).
991
998
992 Lines of input which end in \\ are joined into single entries (and a
999 Lines of input which end in \\ are joined into single entries (and a
993 secondary continuation prompt is issued as long as the user terminates
1000 secondary continuation prompt is issued as long as the user terminates
994 lines with \\). This allows entering very long strings which are still
1001 lines with \\). This allows entering very long strings which are still
995 meant to be treated as single entities.
1002 meant to be treated as single entities.
996 """
1003 """
997
1004
998 try:
1005 try:
999 if header:
1006 if header:
1000 header += '\n'
1007 header += '\n'
1001 lines = [raw_input(header + ps1)]
1008 lines = [raw_input(header + ps1)]
1002 except EOFError:
1009 except EOFError:
1003 return []
1010 return []
1004 terminate = [terminate_str]
1011 terminate = [terminate_str]
1005 try:
1012 try:
1006 while lines[-1:] != terminate:
1013 while lines[-1:] != terminate:
1007 new_line = raw_input(ps1)
1014 new_line = raw_input(ps1)
1008 while new_line.endswith('\\'):
1015 while new_line.endswith('\\'):
1009 new_line = new_line[:-1] + raw_input(ps2)
1016 new_line = new_line[:-1] + raw_input(ps2)
1010 lines.append(new_line)
1017 lines.append(new_line)
1011
1018
1012 return lines[:-1] # don't return the termination command
1019 return lines[:-1] # don't return the termination command
1013 except EOFError:
1020 except EOFError:
1014 print
1021 print
1015 return lines
1022 return lines
1016
1023
1017 #----------------------------------------------------------------------------
1024 #----------------------------------------------------------------------------
1018 def raw_input_ext(prompt='', ps2='... '):
1025 def raw_input_ext(prompt='', ps2='... '):
1019 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1026 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1020
1027
1021 line = raw_input(prompt)
1028 line = raw_input(prompt)
1022 while line.endswith('\\'):
1029 while line.endswith('\\'):
1023 line = line[:-1] + raw_input(ps2)
1030 line = line[:-1] + raw_input(ps2)
1024 return line
1031 return line
1025
1032
1026 #----------------------------------------------------------------------------
1033 #----------------------------------------------------------------------------
1027 def ask_yes_no(prompt,default=None):
1034 def ask_yes_no(prompt,default=None):
1028 """Asks a question and returns an integer 1/0 (y/n) answer.
1035 """Asks a question and returns an integer 1/0 (y/n) answer.
1029
1036
1030 If default is given (one of 'y','n'), it is used if the user input is
1037 If default is given (one of 'y','n'), it is used if the user input is
1031 empty. Otherwise the question is repeated until an answer is given.
1038 empty. Otherwise the question is repeated until an answer is given.
1032
1039
1033 An EOF is treated as the default answer. If there is no default, an
1040 An EOF is treated as the default answer. If there is no default, an
1034 exception is raised to prevent infinite loops.
1041 exception is raised to prevent infinite loops.
1035
1042
1036 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1043 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1037
1044
1038 answers = {'y':True,'n':False,'yes':True,'no':False}
1045 answers = {'y':True,'n':False,'yes':True,'no':False}
1039 ans = None
1046 ans = None
1040 while ans not in answers.keys():
1047 while ans not in answers.keys():
1041 try:
1048 try:
1042 ans = raw_input(prompt+' ').lower()
1049 ans = raw_input(prompt+' ').lower()
1043 if not ans: # response was an empty string
1050 if not ans: # response was an empty string
1044 ans = default
1051 ans = default
1045 except KeyboardInterrupt:
1052 except KeyboardInterrupt:
1046 pass
1053 pass
1047 except EOFError:
1054 except EOFError:
1048 if default in answers.keys():
1055 if default in answers.keys():
1049 ans = default
1056 ans = default
1050 print
1057 print
1051 else:
1058 else:
1052 raise
1059 raise
1053
1060
1054 return answers[ans]
1061 return answers[ans]
1055
1062
1056 #----------------------------------------------------------------------------
1063 #----------------------------------------------------------------------------
1057 def marquee(txt='',width=78,mark='*'):
1064 def marquee(txt='',width=78,mark='*'):
1058 """Return the input string centered in a 'marquee'."""
1065 """Return the input string centered in a 'marquee'."""
1059 if not txt:
1066 if not txt:
1060 return (mark*width)[:width]
1067 return (mark*width)[:width]
1061 nmark = (width-len(txt)-2)/len(mark)/2
1068 nmark = (width-len(txt)-2)/len(mark)/2
1062 if nmark < 0: nmark =0
1069 if nmark < 0: nmark =0
1063 marks = mark*nmark
1070 marks = mark*nmark
1064 return '%s %s %s' % (marks,txt,marks)
1071 return '%s %s %s' % (marks,txt,marks)
1065
1072
1066 #----------------------------------------------------------------------------
1073 #----------------------------------------------------------------------------
1067 class EvalDict:
1074 class EvalDict:
1068 """
1075 """
1069 Emulate a dict which evaluates its contents in the caller's frame.
1076 Emulate a dict which evaluates its contents in the caller's frame.
1070
1077
1071 Usage:
1078 Usage:
1072 >>>number = 19
1079 >>>number = 19
1073 >>>text = "python"
1080 >>>text = "python"
1074 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1081 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1075 """
1082 """
1076
1083
1077 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1084 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1078 # modified (shorter) version of:
1085 # modified (shorter) version of:
1079 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1086 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1080 # Skip Montanaro (skip@pobox.com).
1087 # Skip Montanaro (skip@pobox.com).
1081
1088
1082 def __getitem__(self, name):
1089 def __getitem__(self, name):
1083 frame = sys._getframe(1)
1090 frame = sys._getframe(1)
1084 return eval(name, frame.f_globals, frame.f_locals)
1091 return eval(name, frame.f_globals, frame.f_locals)
1085
1092
1086 EvalString = EvalDict # for backwards compatibility
1093 EvalString = EvalDict # for backwards compatibility
1087 #----------------------------------------------------------------------------
1094 #----------------------------------------------------------------------------
1088 def qw(words,flat=0,sep=None,maxsplit=-1):
1095 def qw(words,flat=0,sep=None,maxsplit=-1):
1089 """Similar to Perl's qw() operator, but with some more options.
1096 """Similar to Perl's qw() operator, but with some more options.
1090
1097
1091 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1098 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1092
1099
1093 words can also be a list itself, and with flat=1, the output will be
1100 words can also be a list itself, and with flat=1, the output will be
1094 recursively flattened. Examples:
1101 recursively flattened. Examples:
1095
1102
1096 >>> qw('1 2')
1103 >>> qw('1 2')
1097 ['1', '2']
1104 ['1', '2']
1098 >>> qw(['a b','1 2',['m n','p q']])
1105 >>> qw(['a b','1 2',['m n','p q']])
1099 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1106 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1100 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1107 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1101 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1108 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1102
1109
1103 if type(words) in StringTypes:
1110 if type(words) in StringTypes:
1104 return [word.strip() for word in words.split(sep,maxsplit)
1111 return [word.strip() for word in words.split(sep,maxsplit)
1105 if word and not word.isspace() ]
1112 if word and not word.isspace() ]
1106 if flat:
1113 if flat:
1107 return flatten(map(qw,words,[1]*len(words)))
1114 return flatten(map(qw,words,[1]*len(words)))
1108 return map(qw,words)
1115 return map(qw,words)
1109
1116
1110 #----------------------------------------------------------------------------
1117 #----------------------------------------------------------------------------
1111 def qwflat(words,sep=None,maxsplit=-1):
1118 def qwflat(words,sep=None,maxsplit=-1):
1112 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1119 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1113 return qw(words,1,sep,maxsplit)
1120 return qw(words,1,sep,maxsplit)
1114
1121
1115 #----------------------------------------------------------------------------
1122 #----------------------------------------------------------------------------
1116 def qw_lol(indata):
1123 def qw_lol(indata):
1117 """qw_lol('a b') -> [['a','b']],
1124 """qw_lol('a b') -> [['a','b']],
1118 otherwise it's just a call to qw().
1125 otherwise it's just a call to qw().
1119
1126
1120 We need this to make sure the modules_some keys *always* end up as a
1127 We need this to make sure the modules_some keys *always* end up as a
1121 list of lists."""
1128 list of lists."""
1122
1129
1123 if type(indata) in StringTypes:
1130 if type(indata) in StringTypes:
1124 return [qw(indata)]
1131 return [qw(indata)]
1125 else:
1132 else:
1126 return qw(indata)
1133 return qw(indata)
1127
1134
1128 #-----------------------------------------------------------------------------
1135 #-----------------------------------------------------------------------------
1129 def list_strings(arg):
1136 def list_strings(arg):
1130 """Always return a list of strings, given a string or list of strings
1137 """Always return a list of strings, given a string or list of strings
1131 as input."""
1138 as input."""
1132
1139
1133 if type(arg) in StringTypes: return [arg]
1140 if type(arg) in StringTypes: return [arg]
1134 else: return arg
1141 else: return arg
1135
1142
1136 #----------------------------------------------------------------------------
1143 #----------------------------------------------------------------------------
1137 def grep(pat,list,case=1):
1144 def grep(pat,list,case=1):
1138 """Simple minded grep-like function.
1145 """Simple minded grep-like function.
1139 grep(pat,list) returns occurrences of pat in list, None on failure.
1146 grep(pat,list) returns occurrences of pat in list, None on failure.
1140
1147
1141 It only does simple string matching, with no support for regexps. Use the
1148 It only does simple string matching, with no support for regexps. Use the
1142 option case=0 for case-insensitive matching."""
1149 option case=0 for case-insensitive matching."""
1143
1150
1144 # This is pretty crude. At least it should implement copying only references
1151 # This is pretty crude. At least it should implement copying only references
1145 # to the original data in case it's big. Now it copies the data for output.
1152 # to the original data in case it's big. Now it copies the data for output.
1146 out=[]
1153 out=[]
1147 if case:
1154 if case:
1148 for term in list:
1155 for term in list:
1149 if term.find(pat)>-1: out.append(term)
1156 if term.find(pat)>-1: out.append(term)
1150 else:
1157 else:
1151 lpat=pat.lower()
1158 lpat=pat.lower()
1152 for term in list:
1159 for term in list:
1153 if term.lower().find(lpat)>-1: out.append(term)
1160 if term.lower().find(lpat)>-1: out.append(term)
1154
1161
1155 if len(out): return out
1162 if len(out): return out
1156 else: return None
1163 else: return None
1157
1164
1158 #----------------------------------------------------------------------------
1165 #----------------------------------------------------------------------------
1159 def dgrep(pat,*opts):
1166 def dgrep(pat,*opts):
1160 """Return grep() on dir()+dir(__builtins__).
1167 """Return grep() on dir()+dir(__builtins__).
1161
1168
1162 A very common use of grep() when working interactively."""
1169 A very common use of grep() when working interactively."""
1163
1170
1164 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1171 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1165
1172
1166 #----------------------------------------------------------------------------
1173 #----------------------------------------------------------------------------
1167 def idgrep(pat):
1174 def idgrep(pat):
1168 """Case-insensitive dgrep()"""
1175 """Case-insensitive dgrep()"""
1169
1176
1170 return dgrep(pat,0)
1177 return dgrep(pat,0)
1171
1178
1172 #----------------------------------------------------------------------------
1179 #----------------------------------------------------------------------------
1173 def igrep(pat,list):
1180 def igrep(pat,list):
1174 """Synonym for case-insensitive grep."""
1181 """Synonym for case-insensitive grep."""
1175
1182
1176 return grep(pat,list,case=0)
1183 return grep(pat,list,case=0)
1177
1184
1178 #----------------------------------------------------------------------------
1185 #----------------------------------------------------------------------------
1179 def indent(str,nspaces=4,ntabs=0):
1186 def indent(str,nspaces=4,ntabs=0):
1180 """Indent a string a given number of spaces or tabstops.
1187 """Indent a string a given number of spaces or tabstops.
1181
1188
1182 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1189 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1183 """
1190 """
1184 if str is None:
1191 if str is None:
1185 return
1192 return
1186 ind = '\t'*ntabs+' '*nspaces
1193 ind = '\t'*ntabs+' '*nspaces
1187 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1194 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1188 if outstr.endswith(os.linesep+ind):
1195 if outstr.endswith(os.linesep+ind):
1189 return outstr[:-len(ind)]
1196 return outstr[:-len(ind)]
1190 else:
1197 else:
1191 return outstr
1198 return outstr
1192
1199
1193 #-----------------------------------------------------------------------------
1200 #-----------------------------------------------------------------------------
1194 def native_line_ends(filename,backup=1):
1201 def native_line_ends(filename,backup=1):
1195 """Convert (in-place) a file to line-ends native to the current OS.
1202 """Convert (in-place) a file to line-ends native to the current OS.
1196
1203
1197 If the optional backup argument is given as false, no backup of the
1204 If the optional backup argument is given as false, no backup of the
1198 original file is left. """
1205 original file is left. """
1199
1206
1200 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1207 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1201
1208
1202 bak_filename = filename + backup_suffixes[os.name]
1209 bak_filename = filename + backup_suffixes[os.name]
1203
1210
1204 original = open(filename).read()
1211 original = open(filename).read()
1205 shutil.copy2(filename,bak_filename)
1212 shutil.copy2(filename,bak_filename)
1206 try:
1213 try:
1207 new = open(filename,'wb')
1214 new = open(filename,'wb')
1208 new.write(os.linesep.join(original.splitlines()))
1215 new.write(os.linesep.join(original.splitlines()))
1209 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1216 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1210 new.close()
1217 new.close()
1211 except:
1218 except:
1212 os.rename(bak_filename,filename)
1219 os.rename(bak_filename,filename)
1213 if not backup:
1220 if not backup:
1214 try:
1221 try:
1215 os.remove(bak_filename)
1222 os.remove(bak_filename)
1216 except:
1223 except:
1217 pass
1224 pass
1218
1225
1219 #----------------------------------------------------------------------------
1226 #----------------------------------------------------------------------------
1220 def get_pager_cmd(pager_cmd = None):
1227 def get_pager_cmd(pager_cmd = None):
1221 """Return a pager command.
1228 """Return a pager command.
1222
1229
1223 Makes some attempts at finding an OS-correct one."""
1230 Makes some attempts at finding an OS-correct one."""
1224
1231
1225 if os.name == 'posix':
1232 if os.name == 'posix':
1226 default_pager_cmd = 'less -r' # -r for color control sequences
1233 default_pager_cmd = 'less -r' # -r for color control sequences
1227 elif os.name in ['nt','dos']:
1234 elif os.name in ['nt','dos']:
1228 default_pager_cmd = 'type'
1235 default_pager_cmd = 'type'
1229
1236
1230 if pager_cmd is None:
1237 if pager_cmd is None:
1231 try:
1238 try:
1232 pager_cmd = os.environ['PAGER']
1239 pager_cmd = os.environ['PAGER']
1233 except:
1240 except:
1234 pager_cmd = default_pager_cmd
1241 pager_cmd = default_pager_cmd
1235 return pager_cmd
1242 return pager_cmd
1236
1243
1237 #-----------------------------------------------------------------------------
1244 #-----------------------------------------------------------------------------
1238 def get_pager_start(pager,start):
1245 def get_pager_start(pager,start):
1239 """Return the string for paging files with an offset.
1246 """Return the string for paging files with an offset.
1240
1247
1241 This is the '+N' argument which less and more (under Unix) accept.
1248 This is the '+N' argument which less and more (under Unix) accept.
1242 """
1249 """
1243
1250
1244 if pager in ['less','more']:
1251 if pager in ['less','more']:
1245 if start:
1252 if start:
1246 start_string = '+' + str(start)
1253 start_string = '+' + str(start)
1247 else:
1254 else:
1248 start_string = ''
1255 start_string = ''
1249 else:
1256 else:
1250 start_string = ''
1257 start_string = ''
1251 return start_string
1258 return start_string
1252
1259
1253 #----------------------------------------------------------------------------
1260 #----------------------------------------------------------------------------
1254 # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch()
1261 # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch()
1255 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
1262 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
1256 import msvcrt
1263 import msvcrt
1257 def page_more():
1264 def page_more():
1258 """ Smart pausing between pages
1265 """ Smart pausing between pages
1259
1266
1260 @return: True if need print more lines, False if quit
1267 @return: True if need print more lines, False if quit
1261 """
1268 """
1262 Term.cout.write('---Return to continue, q to quit--- ')
1269 Term.cout.write('---Return to continue, q to quit--- ')
1263 ans = msvcrt.getch()
1270 ans = msvcrt.getch()
1264 if ans in ("q", "Q"):
1271 if ans in ("q", "Q"):
1265 result = False
1272 result = False
1266 else:
1273 else:
1267 result = True
1274 result = True
1268 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1275 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1269 return result
1276 return result
1270 else:
1277 else:
1271 def page_more():
1278 def page_more():
1272 ans = raw_input('---Return to continue, q to quit--- ')
1279 ans = raw_input('---Return to continue, q to quit--- ')
1273 if ans.lower().startswith('q'):
1280 if ans.lower().startswith('q'):
1274 return False
1281 return False
1275 else:
1282 else:
1276 return True
1283 return True
1277
1284
1278 esc_re = re.compile(r"(\x1b[^m]+m)")
1285 esc_re = re.compile(r"(\x1b[^m]+m)")
1279
1286
1280 def page_dumb(strng,start=0,screen_lines=25):
1287 def page_dumb(strng,start=0,screen_lines=25):
1281 """Very dumb 'pager' in Python, for when nothing else works.
1288 """Very dumb 'pager' in Python, for when nothing else works.
1282
1289
1283 Only moves forward, same interface as page(), except for pager_cmd and
1290 Only moves forward, same interface as page(), except for pager_cmd and
1284 mode."""
1291 mode."""
1285
1292
1286 out_ln = strng.splitlines()[start:]
1293 out_ln = strng.splitlines()[start:]
1287 screens = chop(out_ln,screen_lines-1)
1294 screens = chop(out_ln,screen_lines-1)
1288 if len(screens) == 1:
1295 if len(screens) == 1:
1289 print >>Term.cout, os.linesep.join(screens[0])
1296 print >>Term.cout, os.linesep.join(screens[0])
1290 else:
1297 else:
1291 last_escape = ""
1298 last_escape = ""
1292 for scr in screens[0:-1]:
1299 for scr in screens[0:-1]:
1293 hunk = os.linesep.join(scr)
1300 hunk = os.linesep.join(scr)
1294 print >>Term.cout, last_escape + hunk
1301 print >>Term.cout, last_escape + hunk
1295 if not page_more():
1302 if not page_more():
1296 return
1303 return
1297 esc_list = esc_re.findall(hunk)
1304 esc_list = esc_re.findall(hunk)
1298 if len(esc_list) > 0:
1305 if len(esc_list) > 0:
1299 last_escape = esc_list[-1]
1306 last_escape = esc_list[-1]
1300 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1307 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1301
1308
1302 #----------------------------------------------------------------------------
1309 #----------------------------------------------------------------------------
1303 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1310 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1304 """Print a string, piping through a pager after a certain length.
1311 """Print a string, piping through a pager after a certain length.
1305
1312
1306 The screen_lines parameter specifies the number of *usable* lines of your
1313 The screen_lines parameter specifies the number of *usable* lines of your
1307 terminal screen (total lines minus lines you need to reserve to show other
1314 terminal screen (total lines minus lines you need to reserve to show other
1308 information).
1315 information).
1309
1316
1310 If you set screen_lines to a number <=0, page() will try to auto-determine
1317 If you set screen_lines to a number <=0, page() will try to auto-determine
1311 your screen size and will only use up to (screen_size+screen_lines) for
1318 your screen size and will only use up to (screen_size+screen_lines) for
1312 printing, paging after that. That is, if you want auto-detection but need
1319 printing, paging after that. That is, if you want auto-detection but need
1313 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1320 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1314 auto-detection without any lines reserved simply use screen_lines = 0.
1321 auto-detection without any lines reserved simply use screen_lines = 0.
1315
1322
1316 If a string won't fit in the allowed lines, it is sent through the
1323 If a string won't fit in the allowed lines, it is sent through the
1317 specified pager command. If none given, look for PAGER in the environment,
1324 specified pager command. If none given, look for PAGER in the environment,
1318 and ultimately default to less.
1325 and ultimately default to less.
1319
1326
1320 If no system pager works, the string is sent through a 'dumb pager'
1327 If no system pager works, the string is sent through a 'dumb pager'
1321 written in python, very simplistic.
1328 written in python, very simplistic.
1322 """
1329 """
1323
1330
1324 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1331 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1325 TERM = os.environ.get('TERM','dumb')
1332 TERM = os.environ.get('TERM','dumb')
1326 if TERM in ['dumb','emacs'] and os.name != 'nt':
1333 if TERM in ['dumb','emacs'] and os.name != 'nt':
1327 print strng
1334 print strng
1328 return
1335 return
1329 # chop off the topmost part of the string we don't want to see
1336 # chop off the topmost part of the string we don't want to see
1330 str_lines = strng.split(os.linesep)[start:]
1337 str_lines = strng.split(os.linesep)[start:]
1331 str_toprint = os.linesep.join(str_lines)
1338 str_toprint = os.linesep.join(str_lines)
1332 num_newlines = len(str_lines)
1339 num_newlines = len(str_lines)
1333 len_str = len(str_toprint)
1340 len_str = len(str_toprint)
1334
1341
1335 # Dumb heuristics to guesstimate number of on-screen lines the string
1342 # Dumb heuristics to guesstimate number of on-screen lines the string
1336 # takes. Very basic, but good enough for docstrings in reasonable
1343 # takes. Very basic, but good enough for docstrings in reasonable
1337 # terminals. If someone later feels like refining it, it's not hard.
1344 # terminals. If someone later feels like refining it, it's not hard.
1338 numlines = max(num_newlines,int(len_str/80)+1)
1345 numlines = max(num_newlines,int(len_str/80)+1)
1339
1346
1340 if os.name == "nt":
1347 if os.name == "nt":
1341 screen_lines_def = get_console_size(defaulty=25)[1]
1348 screen_lines_def = get_console_size(defaulty=25)[1]
1342 else:
1349 else:
1343 screen_lines_def = 25 # default value if we can't auto-determine
1350 screen_lines_def = 25 # default value if we can't auto-determine
1344
1351
1345 # auto-determine screen size
1352 # auto-determine screen size
1346 if screen_lines <= 0:
1353 if screen_lines <= 0:
1347 if TERM=='xterm':
1354 if TERM=='xterm':
1348 try:
1355 try:
1349 import curses
1356 import curses
1350 if hasattr(curses,'initscr'):
1357 if hasattr(curses,'initscr'):
1351 use_curses = 1
1358 use_curses = 1
1352 else:
1359 else:
1353 use_curses = 0
1360 use_curses = 0
1354 except ImportError:
1361 except ImportError:
1355 use_curses = 0
1362 use_curses = 0
1356 else:
1363 else:
1357 # curses causes problems on many terminals other than xterm.
1364 # curses causes problems on many terminals other than xterm.
1358 use_curses = 0
1365 use_curses = 0
1359 if use_curses:
1366 if use_curses:
1360 scr = curses.initscr()
1367 scr = curses.initscr()
1361 screen_lines_real,screen_cols = scr.getmaxyx()
1368 screen_lines_real,screen_cols = scr.getmaxyx()
1362 curses.endwin()
1369 curses.endwin()
1363 screen_lines += screen_lines_real
1370 screen_lines += screen_lines_real
1364 #print '***Screen size:',screen_lines_real,'lines x',\
1371 #print '***Screen size:',screen_lines_real,'lines x',\
1365 #screen_cols,'columns.' # dbg
1372 #screen_cols,'columns.' # dbg
1366 else:
1373 else:
1367 screen_lines += screen_lines_def
1374 screen_lines += screen_lines_def
1368
1375
1369 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1376 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1370 if numlines <= screen_lines :
1377 if numlines <= screen_lines :
1371 #print '*** normal print' # dbg
1378 #print '*** normal print' # dbg
1372 print >>Term.cout, str_toprint
1379 print >>Term.cout, str_toprint
1373 else:
1380 else:
1374 # Try to open pager and default to internal one if that fails.
1381 # Try to open pager and default to internal one if that fails.
1375 # All failure modes are tagged as 'retval=1', to match the return
1382 # All failure modes are tagged as 'retval=1', to match the return
1376 # value of a failed system command. If any intermediate attempt
1383 # value of a failed system command. If any intermediate attempt
1377 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1384 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1378 pager_cmd = get_pager_cmd(pager_cmd)
1385 pager_cmd = get_pager_cmd(pager_cmd)
1379 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1386 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1380 if os.name == 'nt':
1387 if os.name == 'nt':
1381 if pager_cmd.startswith('type'):
1388 if pager_cmd.startswith('type'):
1382 # The default WinXP 'type' command is failing on complex strings.
1389 # The default WinXP 'type' command is failing on complex strings.
1383 retval = 1
1390 retval = 1
1384 else:
1391 else:
1385 tmpname = tempfile.mktemp('.txt')
1392 tmpname = tempfile.mktemp('.txt')
1386 tmpfile = file(tmpname,'wt')
1393 tmpfile = file(tmpname,'wt')
1387 tmpfile.write(strng)
1394 tmpfile.write(strng)
1388 tmpfile.close()
1395 tmpfile.close()
1389 cmd = "%s < %s" % (pager_cmd,tmpname)
1396 cmd = "%s < %s" % (pager_cmd,tmpname)
1390 if os.system(cmd):
1397 if os.system(cmd):
1391 retval = 1
1398 retval = 1
1392 else:
1399 else:
1393 retval = None
1400 retval = None
1394 os.remove(tmpname)
1401 os.remove(tmpname)
1395 else:
1402 else:
1396 try:
1403 try:
1397 retval = None
1404 retval = None
1398 # if I use popen4, things hang. No idea why.
1405 # if I use popen4, things hang. No idea why.
1399 #pager,shell_out = os.popen4(pager_cmd)
1406 #pager,shell_out = os.popen4(pager_cmd)
1400 pager = os.popen(pager_cmd,'w')
1407 pager = os.popen(pager_cmd,'w')
1401 pager.write(strng)
1408 pager.write(strng)
1402 pager.close()
1409 pager.close()
1403 retval = pager.close() # success returns None
1410 retval = pager.close() # success returns None
1404 except IOError,msg: # broken pipe when user quits
1411 except IOError,msg: # broken pipe when user quits
1405 if msg.args == (32,'Broken pipe'):
1412 if msg.args == (32,'Broken pipe'):
1406 retval = None
1413 retval = None
1407 else:
1414 else:
1408 retval = 1
1415 retval = 1
1409 except OSError:
1416 except OSError:
1410 # Other strange problems, sometimes seen in Win2k/cygwin
1417 # Other strange problems, sometimes seen in Win2k/cygwin
1411 retval = 1
1418 retval = 1
1412 if retval is not None:
1419 if retval is not None:
1413 page_dumb(strng,screen_lines=screen_lines)
1420 page_dumb(strng,screen_lines=screen_lines)
1414
1421
1415 #----------------------------------------------------------------------------
1422 #----------------------------------------------------------------------------
1416 def page_file(fname,start = 0, pager_cmd = None):
1423 def page_file(fname,start = 0, pager_cmd = None):
1417 """Page a file, using an optional pager command and starting line.
1424 """Page a file, using an optional pager command and starting line.
1418 """
1425 """
1419
1426
1420 pager_cmd = get_pager_cmd(pager_cmd)
1427 pager_cmd = get_pager_cmd(pager_cmd)
1421 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1428 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1422
1429
1423 try:
1430 try:
1424 if os.environ['TERM'] in ['emacs','dumb']:
1431 if os.environ['TERM'] in ['emacs','dumb']:
1425 raise EnvironmentError
1432 raise EnvironmentError
1426 xsys(pager_cmd + ' ' + fname)
1433 xsys(pager_cmd + ' ' + fname)
1427 except:
1434 except:
1428 try:
1435 try:
1429 if start > 0:
1436 if start > 0:
1430 start -= 1
1437 start -= 1
1431 page(open(fname).read(),start)
1438 page(open(fname).read(),start)
1432 except:
1439 except:
1433 print 'Unable to show file',`fname`
1440 print 'Unable to show file',`fname`
1434
1441
1435 #----------------------------------------------------------------------------
1442 #----------------------------------------------------------------------------
1436 def snip_print(str,width = 75,print_full = 0,header = ''):
1443 def snip_print(str,width = 75,print_full = 0,header = ''):
1437 """Print a string snipping the midsection to fit in width.
1444 """Print a string snipping the midsection to fit in width.
1438
1445
1439 print_full: mode control:
1446 print_full: mode control:
1440 - 0: only snip long strings
1447 - 0: only snip long strings
1441 - 1: send to page() directly.
1448 - 1: send to page() directly.
1442 - 2: snip long strings and ask for full length viewing with page()
1449 - 2: snip long strings and ask for full length viewing with page()
1443 Return 1 if snipping was necessary, 0 otherwise."""
1450 Return 1 if snipping was necessary, 0 otherwise."""
1444
1451
1445 if print_full == 1:
1452 if print_full == 1:
1446 page(header+str)
1453 page(header+str)
1447 return 0
1454 return 0
1448
1455
1449 print header,
1456 print header,
1450 if len(str) < width:
1457 if len(str) < width:
1451 print str
1458 print str
1452 snip = 0
1459 snip = 0
1453 else:
1460 else:
1454 whalf = int((width -5)/2)
1461 whalf = int((width -5)/2)
1455 print str[:whalf] + ' <...> ' + str[-whalf:]
1462 print str[:whalf] + ' <...> ' + str[-whalf:]
1456 snip = 1
1463 snip = 1
1457 if snip and print_full == 2:
1464 if snip and print_full == 2:
1458 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1465 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1459 page(str)
1466 page(str)
1460 return snip
1467 return snip
1461
1468
1462 #****************************************************************************
1469 #****************************************************************************
1463 # lists, dicts and structures
1470 # lists, dicts and structures
1464
1471
1465 def belong(candidates,checklist):
1472 def belong(candidates,checklist):
1466 """Check whether a list of items appear in a given list of options.
1473 """Check whether a list of items appear in a given list of options.
1467
1474
1468 Returns a list of 1 and 0, one for each candidate given."""
1475 Returns a list of 1 and 0, one for each candidate given."""
1469
1476
1470 return [x in checklist for x in candidates]
1477 return [x in checklist for x in candidates]
1471
1478
1472 #----------------------------------------------------------------------------
1479 #----------------------------------------------------------------------------
1473 def uniq_stable(elems):
1480 def uniq_stable(elems):
1474 """uniq_stable(elems) -> list
1481 """uniq_stable(elems) -> list
1475
1482
1476 Return from an iterable, a list of all the unique elements in the input,
1483 Return from an iterable, a list of all the unique elements in the input,
1477 but maintaining the order in which they first appear.
1484 but maintaining the order in which they first appear.
1478
1485
1479 A naive solution to this problem which just makes a dictionary with the
1486 A naive solution to this problem which just makes a dictionary with the
1480 elements as keys fails to respect the stability condition, since
1487 elements as keys fails to respect the stability condition, since
1481 dictionaries are unsorted by nature.
1488 dictionaries are unsorted by nature.
1482
1489
1483 Note: All elements in the input must be valid dictionary keys for this
1490 Note: All elements in the input must be valid dictionary keys for this
1484 routine to work, as it internally uses a dictionary for efficiency
1491 routine to work, as it internally uses a dictionary for efficiency
1485 reasons."""
1492 reasons."""
1486
1493
1487 unique = []
1494 unique = []
1488 unique_dict = {}
1495 unique_dict = {}
1489 for nn in elems:
1496 for nn in elems:
1490 if nn not in unique_dict:
1497 if nn not in unique_dict:
1491 unique.append(nn)
1498 unique.append(nn)
1492 unique_dict[nn] = None
1499 unique_dict[nn] = None
1493 return unique
1500 return unique
1494
1501
1495 #----------------------------------------------------------------------------
1502 #----------------------------------------------------------------------------
1496 class NLprinter:
1503 class NLprinter:
1497 """Print an arbitrarily nested list, indicating index numbers.
1504 """Print an arbitrarily nested list, indicating index numbers.
1498
1505
1499 An instance of this class called nlprint is available and callable as a
1506 An instance of this class called nlprint is available and callable as a
1500 function.
1507 function.
1501
1508
1502 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1509 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1503 and using 'sep' to separate the index from the value. """
1510 and using 'sep' to separate the index from the value. """
1504
1511
1505 def __init__(self):
1512 def __init__(self):
1506 self.depth = 0
1513 self.depth = 0
1507
1514
1508 def __call__(self,lst,pos='',**kw):
1515 def __call__(self,lst,pos='',**kw):
1509 """Prints the nested list numbering levels."""
1516 """Prints the nested list numbering levels."""
1510 kw.setdefault('indent',' ')
1517 kw.setdefault('indent',' ')
1511 kw.setdefault('sep',': ')
1518 kw.setdefault('sep',': ')
1512 kw.setdefault('start',0)
1519 kw.setdefault('start',0)
1513 kw.setdefault('stop',len(lst))
1520 kw.setdefault('stop',len(lst))
1514 # we need to remove start and stop from kw so they don't propagate
1521 # we need to remove start and stop from kw so they don't propagate
1515 # into a recursive call for a nested list.
1522 # into a recursive call for a nested list.
1516 start = kw['start']; del kw['start']
1523 start = kw['start']; del kw['start']
1517 stop = kw['stop']; del kw['stop']
1524 stop = kw['stop']; del kw['stop']
1518 if self.depth == 0 and 'header' in kw.keys():
1525 if self.depth == 0 and 'header' in kw.keys():
1519 print kw['header']
1526 print kw['header']
1520
1527
1521 for idx in range(start,stop):
1528 for idx in range(start,stop):
1522 elem = lst[idx]
1529 elem = lst[idx]
1523 if type(elem)==type([]):
1530 if type(elem)==type([]):
1524 self.depth += 1
1531 self.depth += 1
1525 self.__call__(elem,itpl('$pos$idx,'),**kw)
1532 self.__call__(elem,itpl('$pos$idx,'),**kw)
1526 self.depth -= 1
1533 self.depth -= 1
1527 else:
1534 else:
1528 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1535 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1529
1536
1530 nlprint = NLprinter()
1537 nlprint = NLprinter()
1531 #----------------------------------------------------------------------------
1538 #----------------------------------------------------------------------------
1532 def all_belong(candidates,checklist):
1539 def all_belong(candidates,checklist):
1533 """Check whether a list of items ALL appear in a given list of options.
1540 """Check whether a list of items ALL appear in a given list of options.
1534
1541
1535 Returns a single 1 or 0 value."""
1542 Returns a single 1 or 0 value."""
1536
1543
1537 return 1-(0 in [x in checklist for x in candidates])
1544 return 1-(0 in [x in checklist for x in candidates])
1538
1545
1539 #----------------------------------------------------------------------------
1546 #----------------------------------------------------------------------------
1540 def sort_compare(lst1,lst2,inplace = 1):
1547 def sort_compare(lst1,lst2,inplace = 1):
1541 """Sort and compare two lists.
1548 """Sort and compare two lists.
1542
1549
1543 By default it does it in place, thus modifying the lists. Use inplace = 0
1550 By default it does it in place, thus modifying the lists. Use inplace = 0
1544 to avoid that (at the cost of temporary copy creation)."""
1551 to avoid that (at the cost of temporary copy creation)."""
1545 if not inplace:
1552 if not inplace:
1546 lst1 = lst1[:]
1553 lst1 = lst1[:]
1547 lst2 = lst2[:]
1554 lst2 = lst2[:]
1548 lst1.sort(); lst2.sort()
1555 lst1.sort(); lst2.sort()
1549 return lst1 == lst2
1556 return lst1 == lst2
1550
1557
1551 #----------------------------------------------------------------------------
1558 #----------------------------------------------------------------------------
1552 def mkdict(**kwargs):
1559 def mkdict(**kwargs):
1553 """Return a dict from a keyword list.
1560 """Return a dict from a keyword list.
1554
1561
1555 It's just syntactic sugar for making ditcionary creation more convenient:
1562 It's just syntactic sugar for making ditcionary creation more convenient:
1556 # the standard way
1563 # the standard way
1557 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1564 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1558 # a cleaner way
1565 # a cleaner way
1559 >>>data = dict(red=1, green=2, blue=3)
1566 >>>data = dict(red=1, green=2, blue=3)
1560
1567
1561 If you need more than this, look at the Struct() class."""
1568 If you need more than this, look at the Struct() class."""
1562
1569
1563 return kwargs
1570 return kwargs
1564
1571
1565 #----------------------------------------------------------------------------
1572 #----------------------------------------------------------------------------
1566 def list2dict(lst):
1573 def list2dict(lst):
1567 """Takes a list of (key,value) pairs and turns it into a dict."""
1574 """Takes a list of (key,value) pairs and turns it into a dict."""
1568
1575
1569 dic = {}
1576 dic = {}
1570 for k,v in lst: dic[k] = v
1577 for k,v in lst: dic[k] = v
1571 return dic
1578 return dic
1572
1579
1573 #----------------------------------------------------------------------------
1580 #----------------------------------------------------------------------------
1574 def list2dict2(lst,default=''):
1581 def list2dict2(lst,default=''):
1575 """Takes a list and turns it into a dict.
1582 """Takes a list and turns it into a dict.
1576 Much slower than list2dict, but more versatile. This version can take
1583 Much slower than list2dict, but more versatile. This version can take
1577 lists with sublists of arbitrary length (including sclars)."""
1584 lists with sublists of arbitrary length (including sclars)."""
1578
1585
1579 dic = {}
1586 dic = {}
1580 for elem in lst:
1587 for elem in lst:
1581 if type(elem) in (types.ListType,types.TupleType):
1588 if type(elem) in (types.ListType,types.TupleType):
1582 size = len(elem)
1589 size = len(elem)
1583 if size == 0:
1590 if size == 0:
1584 pass
1591 pass
1585 elif size == 1:
1592 elif size == 1:
1586 dic[elem] = default
1593 dic[elem] = default
1587 else:
1594 else:
1588 k,v = elem[0], elem[1:]
1595 k,v = elem[0], elem[1:]
1589 if len(v) == 1: v = v[0]
1596 if len(v) == 1: v = v[0]
1590 dic[k] = v
1597 dic[k] = v
1591 else:
1598 else:
1592 dic[elem] = default
1599 dic[elem] = default
1593 return dic
1600 return dic
1594
1601
1595 #----------------------------------------------------------------------------
1602 #----------------------------------------------------------------------------
1596 def flatten(seq):
1603 def flatten(seq):
1597 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1604 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1598
1605
1599 return [x for subseq in seq for x in subseq]
1606 return [x for subseq in seq for x in subseq]
1600
1607
1601 #----------------------------------------------------------------------------
1608 #----------------------------------------------------------------------------
1602 def get_slice(seq,start=0,stop=None,step=1):
1609 def get_slice(seq,start=0,stop=None,step=1):
1603 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1610 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1604 if stop == None:
1611 if stop == None:
1605 stop = len(seq)
1612 stop = len(seq)
1606 item = lambda i: seq[i]
1613 item = lambda i: seq[i]
1607 return map(item,xrange(start,stop,step))
1614 return map(item,xrange(start,stop,step))
1608
1615
1609 #----------------------------------------------------------------------------
1616 #----------------------------------------------------------------------------
1610 def chop(seq,size):
1617 def chop(seq,size):
1611 """Chop a sequence into chunks of the given size."""
1618 """Chop a sequence into chunks of the given size."""
1612 chunk = lambda i: seq[i:i+size]
1619 chunk = lambda i: seq[i:i+size]
1613 return map(chunk,xrange(0,len(seq),size))
1620 return map(chunk,xrange(0,len(seq),size))
1614
1621
1615 #----------------------------------------------------------------------------
1622 #----------------------------------------------------------------------------
1616 # with is a keyword as of python 2.5, so this function is renamed to withobj
1623 # with is a keyword as of python 2.5, so this function is renamed to withobj
1617 # from its old 'with' name.
1624 # from its old 'with' name.
1618 def with_obj(object, **args):
1625 def with_obj(object, **args):
1619 """Set multiple attributes for an object, similar to Pascal's with.
1626 """Set multiple attributes for an object, similar to Pascal's with.
1620
1627
1621 Example:
1628 Example:
1622 with_obj(jim,
1629 with_obj(jim,
1623 born = 1960,
1630 born = 1960,
1624 haircolour = 'Brown',
1631 haircolour = 'Brown',
1625 eyecolour = 'Green')
1632 eyecolour = 'Green')
1626
1633
1627 Credit: Greg Ewing, in
1634 Credit: Greg Ewing, in
1628 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
1635 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
1629
1636
1630 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
1637 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
1631 has become a keyword for Python 2.5, so we had to rename it."""
1638 has become a keyword for Python 2.5, so we had to rename it."""
1632
1639
1633 object.__dict__.update(args)
1640 object.__dict__.update(args)
1634
1641
1635 #----------------------------------------------------------------------------
1642 #----------------------------------------------------------------------------
1636 def setattr_list(obj,alist,nspace = None):
1643 def setattr_list(obj,alist,nspace = None):
1637 """Set a list of attributes for an object taken from a namespace.
1644 """Set a list of attributes for an object taken from a namespace.
1638
1645
1639 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1646 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1640 alist with their values taken from nspace, which must be a dict (something
1647 alist with their values taken from nspace, which must be a dict (something
1641 like locals() will often do) If nspace isn't given, locals() of the
1648 like locals() will often do) If nspace isn't given, locals() of the
1642 *caller* is used, so in most cases you can omit it.
1649 *caller* is used, so in most cases you can omit it.
1643
1650
1644 Note that alist can be given as a string, which will be automatically
1651 Note that alist can be given as a string, which will be automatically
1645 split into a list on whitespace. If given as a list, it must be a list of
1652 split into a list on whitespace. If given as a list, it must be a list of
1646 *strings* (the variable names themselves), not of variables."""
1653 *strings* (the variable names themselves), not of variables."""
1647
1654
1648 # this grabs the local variables from the *previous* call frame -- that is
1655 # this grabs the local variables from the *previous* call frame -- that is
1649 # the locals from the function that called setattr_list().
1656 # the locals from the function that called setattr_list().
1650 # - snipped from weave.inline()
1657 # - snipped from weave.inline()
1651 if nspace is None:
1658 if nspace is None:
1652 call_frame = sys._getframe().f_back
1659 call_frame = sys._getframe().f_back
1653 nspace = call_frame.f_locals
1660 nspace = call_frame.f_locals
1654
1661
1655 if type(alist) in StringTypes:
1662 if type(alist) in StringTypes:
1656 alist = alist.split()
1663 alist = alist.split()
1657 for attr in alist:
1664 for attr in alist:
1658 val = eval(attr,nspace)
1665 val = eval(attr,nspace)
1659 setattr(obj,attr,val)
1666 setattr(obj,attr,val)
1660
1667
1661 #----------------------------------------------------------------------------
1668 #----------------------------------------------------------------------------
1662 def getattr_list(obj,alist,*args):
1669 def getattr_list(obj,alist,*args):
1663 """getattr_list(obj,alist[, default]) -> attribute list.
1670 """getattr_list(obj,alist[, default]) -> attribute list.
1664
1671
1665 Get a list of named attributes for an object. When a default argument is
1672 Get a list of named attributes for an object. When a default argument is
1666 given, it is returned when the attribute doesn't exist; without it, an
1673 given, it is returned when the attribute doesn't exist; without it, an
1667 exception is raised in that case.
1674 exception is raised in that case.
1668
1675
1669 Note that alist can be given as a string, which will be automatically
1676 Note that alist can be given as a string, which will be automatically
1670 split into a list on whitespace. If given as a list, it must be a list of
1677 split into a list on whitespace. If given as a list, it must be a list of
1671 *strings* (the variable names themselves), not of variables."""
1678 *strings* (the variable names themselves), not of variables."""
1672
1679
1673 if type(alist) in StringTypes:
1680 if type(alist) in StringTypes:
1674 alist = alist.split()
1681 alist = alist.split()
1675 if args:
1682 if args:
1676 if len(args)==1:
1683 if len(args)==1:
1677 default = args[0]
1684 default = args[0]
1678 return map(lambda attr: getattr(obj,attr,default),alist)
1685 return map(lambda attr: getattr(obj,attr,default),alist)
1679 else:
1686 else:
1680 raise ValueError,'getattr_list() takes only one optional argument'
1687 raise ValueError,'getattr_list() takes only one optional argument'
1681 else:
1688 else:
1682 return map(lambda attr: getattr(obj,attr),alist)
1689 return map(lambda attr: getattr(obj,attr),alist)
1683
1690
1684 #----------------------------------------------------------------------------
1691 #----------------------------------------------------------------------------
1685 def map_method(method,object_list,*argseq,**kw):
1692 def map_method(method,object_list,*argseq,**kw):
1686 """map_method(method,object_list,*args,**kw) -> list
1693 """map_method(method,object_list,*args,**kw) -> list
1687
1694
1688 Return a list of the results of applying the methods to the items of the
1695 Return a list of the results of applying the methods to the items of the
1689 argument sequence(s). If more than one sequence is given, the method is
1696 argument sequence(s). If more than one sequence is given, the method is
1690 called with an argument list consisting of the corresponding item of each
1697 called with an argument list consisting of the corresponding item of each
1691 sequence. All sequences must be of the same length.
1698 sequence. All sequences must be of the same length.
1692
1699
1693 Keyword arguments are passed verbatim to all objects called.
1700 Keyword arguments are passed verbatim to all objects called.
1694
1701
1695 This is Python code, so it's not nearly as fast as the builtin map()."""
1702 This is Python code, so it's not nearly as fast as the builtin map()."""
1696
1703
1697 out_list = []
1704 out_list = []
1698 idx = 0
1705 idx = 0
1699 for object in object_list:
1706 for object in object_list:
1700 try:
1707 try:
1701 handler = getattr(object, method)
1708 handler = getattr(object, method)
1702 except AttributeError:
1709 except AttributeError:
1703 out_list.append(None)
1710 out_list.append(None)
1704 else:
1711 else:
1705 if argseq:
1712 if argseq:
1706 args = map(lambda lst:lst[idx],argseq)
1713 args = map(lambda lst:lst[idx],argseq)
1707 #print 'ob',object,'hand',handler,'ar',args # dbg
1714 #print 'ob',object,'hand',handler,'ar',args # dbg
1708 out_list.append(handler(args,**kw))
1715 out_list.append(handler(args,**kw))
1709 else:
1716 else:
1710 out_list.append(handler(**kw))
1717 out_list.append(handler(**kw))
1711 idx += 1
1718 idx += 1
1712 return out_list
1719 return out_list
1713
1720
1714 #----------------------------------------------------------------------------
1721 #----------------------------------------------------------------------------
1715 def import_fail_info(mod_name,fns=None):
1722 def import_fail_info(mod_name,fns=None):
1716 """Inform load failure for a module."""
1723 """Inform load failure for a module."""
1717
1724
1718 if fns == None:
1725 if fns == None:
1719 warn("Loading of %s failed.\n" % (mod_name,))
1726 warn("Loading of %s failed.\n" % (mod_name,))
1720 else:
1727 else:
1721 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1728 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1722
1729
1723 #----------------------------------------------------------------------------
1730 #----------------------------------------------------------------------------
1724 # Proposed popitem() extension, written as a method
1731 # Proposed popitem() extension, written as a method
1725
1732
1726
1733
1727 class NotGiven: pass
1734 class NotGiven: pass
1728
1735
1729 def popkey(dct,key,default=NotGiven):
1736 def popkey(dct,key,default=NotGiven):
1730 """Return dct[key] and delete dct[key].
1737 """Return dct[key] and delete dct[key].
1731
1738
1732 If default is given, return it if dct[key] doesn't exist, otherwise raise
1739 If default is given, return it if dct[key] doesn't exist, otherwise raise
1733 KeyError. """
1740 KeyError. """
1734
1741
1735 try:
1742 try:
1736 val = dct[key]
1743 val = dct[key]
1737 except KeyError:
1744 except KeyError:
1738 if default is NotGiven:
1745 if default is NotGiven:
1739 raise
1746 raise
1740 else:
1747 else:
1741 return default
1748 return default
1742 else:
1749 else:
1743 del dct[key]
1750 del dct[key]
1744 return val
1751 return val
1745
1752
1746 def wrap_deprecated(func, suggest = '<nothing>'):
1753 def wrap_deprecated(func, suggest = '<nothing>'):
1747 def newFunc(*args, **kwargs):
1754 def newFunc(*args, **kwargs):
1748 warnings.warn("Call to deprecated function %s, use %s instead" %
1755 warnings.warn("Call to deprecated function %s, use %s instead" %
1749 ( func.__name__, suggest),
1756 ( func.__name__, suggest),
1750 category=DeprecationWarning,
1757 category=DeprecationWarning,
1751 stacklevel = 2)
1758 stacklevel = 2)
1752 return func(*args, **kwargs)
1759 return func(*args, **kwargs)
1753 return newFunc
1760 return newFunc
1754
1761
1755 #*************************** end of file <genutils.py> **********************
1762 #*************************** end of file <genutils.py> **********************
1756
1763
@@ -1,2579 +1,2580 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.3 or newer.
5 Requires Python 2.3 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 $Id: iplib.py 2187 2007-03-30 04:56:40Z fperez $
9 $Id: iplib.py 2190 2007-03-30 18:35:46Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from IPython import Release
31 from IPython import Release
32 __author__ = '%s <%s>\n%s <%s>' % \
32 __author__ = '%s <%s>\n%s <%s>' % \
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 __license__ = Release.license
34 __license__ = Release.license
35 __version__ = Release.version
35 __version__ = Release.version
36
36
37 # Python standard modules
37 # Python standard modules
38 import __main__
38 import __main__
39 import __builtin__
39 import __builtin__
40 import StringIO
40 import StringIO
41 import bdb
41 import bdb
42 import cPickle as pickle
42 import cPickle as pickle
43 import codeop
43 import codeop
44 import exceptions
44 import exceptions
45 import glob
45 import glob
46 import inspect
46 import inspect
47 import keyword
47 import keyword
48 import new
48 import new
49 import os
49 import os
50 import pydoc
50 import pydoc
51 import re
51 import re
52 import shutil
52 import shutil
53 import string
53 import string
54 import sys
54 import sys
55 import tempfile
55 import tempfile
56 import traceback
56 import traceback
57 import types
57 import types
58 import pickleshare
58 import pickleshare
59 from sets import Set
59 from sets import Set
60 from pprint import pprint, pformat
60 from pprint import pprint, pformat
61
61
62 # IPython's own modules
62 # IPython's own modules
63 import IPython
63 import IPython
64 from IPython import OInspect,PyColorize,ultraTB
64 from IPython import OInspect,PyColorize,ultraTB
65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.FakeModule import FakeModule
66 from IPython.FakeModule import FakeModule
67 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
67 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Logger import Logger
68 from IPython.Logger import Logger
69 from IPython.Magic import Magic
69 from IPython.Magic import Magic
70 from IPython.Prompts import CachedOutput
70 from IPython.Prompts import CachedOutput
71 from IPython.ipstruct import Struct
71 from IPython.ipstruct import Struct
72 from IPython.background_jobs import BackgroundJobManager
72 from IPython.background_jobs import BackgroundJobManager
73 from IPython.usage import cmd_line_usage,interactive_usage
73 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.genutils import *
74 from IPython.genutils import *
75 from IPython.strdispatch import StrDispatch
75 from IPython.strdispatch import StrDispatch
76 import IPython.ipapi
76 import IPython.ipapi
77
77
78 # Globals
78 # Globals
79
79
80 # store the builtin raw_input globally, and use this always, in case user code
80 # store the builtin raw_input globally, and use this always, in case user code
81 # overwrites it (like wx.py.PyShell does)
81 # overwrites it (like wx.py.PyShell does)
82 raw_input_original = raw_input
82 raw_input_original = raw_input
83
83
84 # compiled regexps for autoindent management
84 # compiled regexps for autoindent management
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86
86
87
87
88 #****************************************************************************
88 #****************************************************************************
89 # Some utility function definitions
89 # Some utility function definitions
90
90
91 ini_spaces_re = re.compile(r'^(\s+)')
91 ini_spaces_re = re.compile(r'^(\s+)')
92
92
93 def num_ini_spaces(strng):
93 def num_ini_spaces(strng):
94 """Return the number of initial spaces in a string"""
94 """Return the number of initial spaces in a string"""
95
95
96 ini_spaces = ini_spaces_re.match(strng)
96 ini_spaces = ini_spaces_re.match(strng)
97 if ini_spaces:
97 if ini_spaces:
98 return ini_spaces.end()
98 return ini_spaces.end()
99 else:
99 else:
100 return 0
100 return 0
101
101
102 def softspace(file, newvalue):
102 def softspace(file, newvalue):
103 """Copied from code.py, to remove the dependency"""
103 """Copied from code.py, to remove the dependency"""
104
104
105 oldvalue = 0
105 oldvalue = 0
106 try:
106 try:
107 oldvalue = file.softspace
107 oldvalue = file.softspace
108 except AttributeError:
108 except AttributeError:
109 pass
109 pass
110 try:
110 try:
111 file.softspace = newvalue
111 file.softspace = newvalue
112 except (AttributeError, TypeError):
112 except (AttributeError, TypeError):
113 # "attribute-less object" or "read-only attributes"
113 # "attribute-less object" or "read-only attributes"
114 pass
114 pass
115 return oldvalue
115 return oldvalue
116
116
117
117
118 #****************************************************************************
118 #****************************************************************************
119 # Local use exceptions
119 # Local use exceptions
120 class SpaceInInput(exceptions.Exception): pass
120 class SpaceInInput(exceptions.Exception): pass
121
121
122
122
123 #****************************************************************************
123 #****************************************************************************
124 # Local use classes
124 # Local use classes
125 class Bunch: pass
125 class Bunch: pass
126
126
127 class Undefined: pass
127 class Undefined: pass
128
128
129 class Quitter(object):
129 class Quitter(object):
130 """Simple class to handle exit, similar to Python 2.5's.
130 """Simple class to handle exit, similar to Python 2.5's.
131
131
132 It handles exiting in an ipython-safe manner, which the one in Python 2.5
132 It handles exiting in an ipython-safe manner, which the one in Python 2.5
133 doesn't do (obviously, since it doesn't know about ipython)."""
133 doesn't do (obviously, since it doesn't know about ipython)."""
134
134
135 def __init__(self,shell,name):
135 def __init__(self,shell,name):
136 self.shell = shell
136 self.shell = shell
137 self.name = name
137 self.name = name
138
138
139 def __repr__(self):
139 def __repr__(self):
140 return 'Type %s() to exit.' % self.name
140 return 'Type %s() to exit.' % self.name
141 __str__ = __repr__
141 __str__ = __repr__
142
142
143 def __call__(self):
143 def __call__(self):
144 self.shell.exit()
144 self.shell.exit()
145
145
146 class InputList(list):
146 class InputList(list):
147 """Class to store user input.
147 """Class to store user input.
148
148
149 It's basically a list, but slices return a string instead of a list, thus
149 It's basically a list, but slices return a string instead of a list, thus
150 allowing things like (assuming 'In' is an instance):
150 allowing things like (assuming 'In' is an instance):
151
151
152 exec In[4:7]
152 exec In[4:7]
153
153
154 or
154 or
155
155
156 exec In[5:9] + In[14] + In[21:25]"""
156 exec In[5:9] + In[14] + In[21:25]"""
157
157
158 def __getslice__(self,i,j):
158 def __getslice__(self,i,j):
159 return ''.join(list.__getslice__(self,i,j))
159 return ''.join(list.__getslice__(self,i,j))
160
160
161 class SyntaxTB(ultraTB.ListTB):
161 class SyntaxTB(ultraTB.ListTB):
162 """Extension which holds some state: the last exception value"""
162 """Extension which holds some state: the last exception value"""
163
163
164 def __init__(self,color_scheme = 'NoColor'):
164 def __init__(self,color_scheme = 'NoColor'):
165 ultraTB.ListTB.__init__(self,color_scheme)
165 ultraTB.ListTB.__init__(self,color_scheme)
166 self.last_syntax_error = None
166 self.last_syntax_error = None
167
167
168 def __call__(self, etype, value, elist):
168 def __call__(self, etype, value, elist):
169 self.last_syntax_error = value
169 self.last_syntax_error = value
170 ultraTB.ListTB.__call__(self,etype,value,elist)
170 ultraTB.ListTB.__call__(self,etype,value,elist)
171
171
172 def clear_err_state(self):
172 def clear_err_state(self):
173 """Return the current error state and clear it"""
173 """Return the current error state and clear it"""
174 e = self.last_syntax_error
174 e = self.last_syntax_error
175 self.last_syntax_error = None
175 self.last_syntax_error = None
176 return e
176 return e
177
177
178 #****************************************************************************
178 #****************************************************************************
179 # Main IPython class
179 # Main IPython class
180
180
181 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
181 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
182 # until a full rewrite is made. I've cleaned all cross-class uses of
182 # until a full rewrite is made. I've cleaned all cross-class uses of
183 # attributes and methods, but too much user code out there relies on the
183 # attributes and methods, but too much user code out there relies on the
184 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
184 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
185 #
185 #
186 # But at least now, all the pieces have been separated and we could, in
186 # But at least now, all the pieces have been separated and we could, in
187 # principle, stop using the mixin. This will ease the transition to the
187 # principle, stop using the mixin. This will ease the transition to the
188 # chainsaw branch.
188 # chainsaw branch.
189
189
190 # For reference, the following is the list of 'self.foo' uses in the Magic
190 # For reference, the following is the list of 'self.foo' uses in the Magic
191 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
191 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
192 # class, to prevent clashes.
192 # class, to prevent clashes.
193
193
194 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
194 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
195 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
195 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
196 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
196 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
197 # 'self.value']
197 # 'self.value']
198
198
199 class InteractiveShell(object,Magic):
199 class InteractiveShell(object,Magic):
200 """An enhanced console for Python."""
200 """An enhanced console for Python."""
201
201
202 # class attribute to indicate whether the class supports threads or not.
202 # class attribute to indicate whether the class supports threads or not.
203 # Subclasses with thread support should override this as needed.
203 # Subclasses with thread support should override this as needed.
204 isthreaded = False
204 isthreaded = False
205
205
206 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
206 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
207 user_ns = None,user_global_ns=None,banner2='',
207 user_ns = None,user_global_ns=None,banner2='',
208 custom_exceptions=((),None),embedded=False):
208 custom_exceptions=((),None),embedded=False):
209
209
210 # log system
210 # log system
211 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
211 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
212
212
213 # some minimal strict typechecks. For some core data structures, I
213 # some minimal strict typechecks. For some core data structures, I
214 # want actual basic python types, not just anything that looks like
214 # want actual basic python types, not just anything that looks like
215 # one. This is especially true for namespaces.
215 # one. This is especially true for namespaces.
216 for ns in (user_ns,user_global_ns):
216 for ns in (user_ns,user_global_ns):
217 if ns is not None and type(ns) != types.DictType:
217 if ns is not None and type(ns) != types.DictType:
218 raise TypeError,'namespace must be a dictionary'
218 raise TypeError,'namespace must be a dictionary'
219
219
220 # Job manager (for jobs run as background threads)
220 # Job manager (for jobs run as background threads)
221 self.jobs = BackgroundJobManager()
221 self.jobs = BackgroundJobManager()
222
222
223 # Store the actual shell's name
223 # Store the actual shell's name
224 self.name = name
224 self.name = name
225
225
226 # We need to know whether the instance is meant for embedding, since
226 # We need to know whether the instance is meant for embedding, since
227 # global/local namespaces need to be handled differently in that case
227 # global/local namespaces need to be handled differently in that case
228 self.embedded = embedded
228 self.embedded = embedded
229
229
230 # command compiler
230 # command compiler
231 self.compile = codeop.CommandCompiler()
231 self.compile = codeop.CommandCompiler()
232
232
233 # User input buffer
233 # User input buffer
234 self.buffer = []
234 self.buffer = []
235
235
236 # Default name given in compilation of code
236 # Default name given in compilation of code
237 self.filename = '<ipython console>'
237 self.filename = '<ipython console>'
238
238
239 # Install our own quitter instead of the builtins. For python2.3-2.4,
239 # Install our own quitter instead of the builtins. For python2.3-2.4,
240 # this brings in behavior like 2.5, and for 2.5 it's identical.
240 # this brings in behavior like 2.5, and for 2.5 it's identical.
241 __builtin__.exit = Quitter(self,'exit')
241 __builtin__.exit = Quitter(self,'exit')
242 __builtin__.quit = Quitter(self,'quit')
242 __builtin__.quit = Quitter(self,'quit')
243
243
244 # Make an empty namespace, which extension writers can rely on both
244 # Make an empty namespace, which extension writers can rely on both
245 # existing and NEVER being used by ipython itself. This gives them a
245 # existing and NEVER being used by ipython itself. This gives them a
246 # convenient location for storing additional information and state
246 # convenient location for storing additional information and state
247 # their extensions may require, without fear of collisions with other
247 # their extensions may require, without fear of collisions with other
248 # ipython names that may develop later.
248 # ipython names that may develop later.
249 self.meta = Struct()
249 self.meta = Struct()
250
250
251 # Create the namespace where the user will operate. user_ns is
251 # Create the namespace where the user will operate. user_ns is
252 # normally the only one used, and it is passed to the exec calls as
252 # normally the only one used, and it is passed to the exec calls as
253 # the locals argument. But we do carry a user_global_ns namespace
253 # the locals argument. But we do carry a user_global_ns namespace
254 # given as the exec 'globals' argument, This is useful in embedding
254 # given as the exec 'globals' argument, This is useful in embedding
255 # situations where the ipython shell opens in a context where the
255 # situations where the ipython shell opens in a context where the
256 # distinction between locals and globals is meaningful.
256 # distinction between locals and globals is meaningful.
257
257
258 # FIXME. For some strange reason, __builtins__ is showing up at user
258 # FIXME. For some strange reason, __builtins__ is showing up at user
259 # level as a dict instead of a module. This is a manual fix, but I
259 # level as a dict instead of a module. This is a manual fix, but I
260 # should really track down where the problem is coming from. Alex
260 # should really track down where the problem is coming from. Alex
261 # Schmolck reported this problem first.
261 # Schmolck reported this problem first.
262
262
263 # A useful post by Alex Martelli on this topic:
263 # A useful post by Alex Martelli on this topic:
264 # Re: inconsistent value from __builtins__
264 # Re: inconsistent value from __builtins__
265 # Von: Alex Martelli <aleaxit@yahoo.com>
265 # Von: Alex Martelli <aleaxit@yahoo.com>
266 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
266 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
267 # Gruppen: comp.lang.python
267 # Gruppen: comp.lang.python
268
268
269 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
269 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
270 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
270 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
271 # > <type 'dict'>
271 # > <type 'dict'>
272 # > >>> print type(__builtins__)
272 # > >>> print type(__builtins__)
273 # > <type 'module'>
273 # > <type 'module'>
274 # > Is this difference in return value intentional?
274 # > Is this difference in return value intentional?
275
275
276 # Well, it's documented that '__builtins__' can be either a dictionary
276 # Well, it's documented that '__builtins__' can be either a dictionary
277 # or a module, and it's been that way for a long time. Whether it's
277 # or a module, and it's been that way for a long time. Whether it's
278 # intentional (or sensible), I don't know. In any case, the idea is
278 # intentional (or sensible), I don't know. In any case, the idea is
279 # that if you need to access the built-in namespace directly, you
279 # that if you need to access the built-in namespace directly, you
280 # should start with "import __builtin__" (note, no 's') which will
280 # should start with "import __builtin__" (note, no 's') which will
281 # definitely give you a module. Yeah, it's somewhat confusing:-(.
281 # definitely give you a module. Yeah, it's somewhat confusing:-(.
282
282
283 # These routines return properly built dicts as needed by the rest of
283 # These routines return properly built dicts as needed by the rest of
284 # the code, and can also be used by extension writers to generate
284 # the code, and can also be used by extension writers to generate
285 # properly initialized namespaces.
285 # properly initialized namespaces.
286 user_ns = IPython.ipapi.make_user_ns(user_ns)
286 user_ns = IPython.ipapi.make_user_ns(user_ns)
287 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
287 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
288
288
289 # Assign namespaces
289 # Assign namespaces
290 # This is the namespace where all normal user variables live
290 # This is the namespace where all normal user variables live
291 self.user_ns = user_ns
291 self.user_ns = user_ns
292 # Embedded instances require a separate namespace for globals.
292 # Embedded instances require a separate namespace for globals.
293 # Normally this one is unused by non-embedded instances.
293 # Normally this one is unused by non-embedded instances.
294 self.user_global_ns = user_global_ns
294 self.user_global_ns = user_global_ns
295 # A namespace to keep track of internal data structures to prevent
295 # A namespace to keep track of internal data structures to prevent
296 # them from cluttering user-visible stuff. Will be updated later
296 # them from cluttering user-visible stuff. Will be updated later
297 self.internal_ns = {}
297 self.internal_ns = {}
298
298
299 # Namespace of system aliases. Each entry in the alias
299 # Namespace of system aliases. Each entry in the alias
300 # table must be a 2-tuple of the form (N,name), where N is the number
300 # table must be a 2-tuple of the form (N,name), where N is the number
301 # of positional arguments of the alias.
301 # of positional arguments of the alias.
302 self.alias_table = {}
302 self.alias_table = {}
303
303
304 # A table holding all the namespaces IPython deals with, so that
304 # A table holding all the namespaces IPython deals with, so that
305 # introspection facilities can search easily.
305 # introspection facilities can search easily.
306 self.ns_table = {'user':user_ns,
306 self.ns_table = {'user':user_ns,
307 'user_global':user_global_ns,
307 'user_global':user_global_ns,
308 'alias':self.alias_table,
308 'alias':self.alias_table,
309 'internal':self.internal_ns,
309 'internal':self.internal_ns,
310 'builtin':__builtin__.__dict__
310 'builtin':__builtin__.__dict__
311 }
311 }
312
312
313 # The user namespace MUST have a pointer to the shell itself.
313 # The user namespace MUST have a pointer to the shell itself.
314 self.user_ns[name] = self
314 self.user_ns[name] = self
315
315
316 # We need to insert into sys.modules something that looks like a
316 # We need to insert into sys.modules something that looks like a
317 # module but which accesses the IPython namespace, for shelve and
317 # module but which accesses the IPython namespace, for shelve and
318 # pickle to work interactively. Normally they rely on getting
318 # pickle to work interactively. Normally they rely on getting
319 # everything out of __main__, but for embedding purposes each IPython
319 # everything out of __main__, but for embedding purposes each IPython
320 # instance has its own private namespace, so we can't go shoving
320 # instance has its own private namespace, so we can't go shoving
321 # everything into __main__.
321 # everything into __main__.
322
322
323 # note, however, that we should only do this for non-embedded
323 # note, however, that we should only do this for non-embedded
324 # ipythons, which really mimic the __main__.__dict__ with their own
324 # ipythons, which really mimic the __main__.__dict__ with their own
325 # namespace. Embedded instances, on the other hand, should not do
325 # namespace. Embedded instances, on the other hand, should not do
326 # this because they need to manage the user local/global namespaces
326 # this because they need to manage the user local/global namespaces
327 # only, but they live within a 'normal' __main__ (meaning, they
327 # only, but they live within a 'normal' __main__ (meaning, they
328 # shouldn't overtake the execution environment of the script they're
328 # shouldn't overtake the execution environment of the script they're
329 # embedded in).
329 # embedded in).
330
330
331 if not embedded:
331 if not embedded:
332 try:
332 try:
333 main_name = self.user_ns['__name__']
333 main_name = self.user_ns['__name__']
334 except KeyError:
334 except KeyError:
335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
336 else:
336 else:
337 #print "pickle hack in place" # dbg
337 #print "pickle hack in place" # dbg
338 #print 'main_name:',main_name # dbg
338 #print 'main_name:',main_name # dbg
339 sys.modules[main_name] = FakeModule(self.user_ns)
339 sys.modules[main_name] = FakeModule(self.user_ns)
340
340
341 # List of input with multi-line handling.
341 # List of input with multi-line handling.
342 # Fill its zero entry, user counter starts at 1
342 # Fill its zero entry, user counter starts at 1
343 self.input_hist = InputList(['\n'])
343 self.input_hist = InputList(['\n'])
344 # This one will hold the 'raw' input history, without any
344 # This one will hold the 'raw' input history, without any
345 # pre-processing. This will allow users to retrieve the input just as
345 # pre-processing. This will allow users to retrieve the input just as
346 # it was exactly typed in by the user, with %hist -r.
346 # it was exactly typed in by the user, with %hist -r.
347 self.input_hist_raw = InputList(['\n'])
347 self.input_hist_raw = InputList(['\n'])
348
348
349 # list of visited directories
349 # list of visited directories
350 try:
350 try:
351 self.dir_hist = [os.getcwd()]
351 self.dir_hist = [os.getcwd()]
352 except IOError, e:
352 except IOError, e:
353 self.dir_hist = []
353 self.dir_hist = []
354
354
355 # dict of output history
355 # dict of output history
356 self.output_hist = {}
356 self.output_hist = {}
357
357
358 # dict of things NOT to alias (keywords, builtins and some magics)
358 # dict of things NOT to alias (keywords, builtins and some magics)
359 no_alias = {}
359 no_alias = {}
360 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
360 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
361 for key in keyword.kwlist + no_alias_magics:
361 for key in keyword.kwlist + no_alias_magics:
362 no_alias[key] = 1
362 no_alias[key] = 1
363 no_alias.update(__builtin__.__dict__)
363 no_alias.update(__builtin__.__dict__)
364 self.no_alias = no_alias
364 self.no_alias = no_alias
365
365
366 # make global variables for user access to these
366 # make global variables for user access to these
367 self.user_ns['_ih'] = self.input_hist
367 self.user_ns['_ih'] = self.input_hist
368 self.user_ns['_oh'] = self.output_hist
368 self.user_ns['_oh'] = self.output_hist
369 self.user_ns['_dh'] = self.dir_hist
369 self.user_ns['_dh'] = self.dir_hist
370
370
371 # user aliases to input and output histories
371 # user aliases to input and output histories
372 self.user_ns['In'] = self.input_hist
372 self.user_ns['In'] = self.input_hist
373 self.user_ns['Out'] = self.output_hist
373 self.user_ns['Out'] = self.output_hist
374
374
375 # Object variable to store code object waiting execution. This is
375 # Object variable to store code object waiting execution. This is
376 # used mainly by the multithreaded shells, but it can come in handy in
376 # used mainly by the multithreaded shells, but it can come in handy in
377 # other situations. No need to use a Queue here, since it's a single
377 # other situations. No need to use a Queue here, since it's a single
378 # item which gets cleared once run.
378 # item which gets cleared once run.
379 self.code_to_run = None
379 self.code_to_run = None
380
380
381 # escapes for automatic behavior on the command line
381 # escapes for automatic behavior on the command line
382 self.ESC_SHELL = '!'
382 self.ESC_SHELL = '!'
383 self.ESC_HELP = '?'
383 self.ESC_HELP = '?'
384 self.ESC_MAGIC = '%'
384 self.ESC_MAGIC = '%'
385 self.ESC_QUOTE = ','
385 self.ESC_QUOTE = ','
386 self.ESC_QUOTE2 = ';'
386 self.ESC_QUOTE2 = ';'
387 self.ESC_PAREN = '/'
387 self.ESC_PAREN = '/'
388
388
389 # And their associated handlers
389 # And their associated handlers
390 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
390 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
391 self.ESC_QUOTE : self.handle_auto,
391 self.ESC_QUOTE : self.handle_auto,
392 self.ESC_QUOTE2 : self.handle_auto,
392 self.ESC_QUOTE2 : self.handle_auto,
393 self.ESC_MAGIC : self.handle_magic,
393 self.ESC_MAGIC : self.handle_magic,
394 self.ESC_HELP : self.handle_help,
394 self.ESC_HELP : self.handle_help,
395 self.ESC_SHELL : self.handle_shell_escape,
395 self.ESC_SHELL : self.handle_shell_escape,
396 }
396 }
397
397
398 # class initializations
398 # class initializations
399 Magic.__init__(self,self)
399 Magic.__init__(self,self)
400
400
401 # Python source parser/formatter for syntax highlighting
401 # Python source parser/formatter for syntax highlighting
402 pyformat = PyColorize.Parser().format
402 pyformat = PyColorize.Parser().format
403 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
403 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
404
404
405 # hooks holds pointers used for user-side customizations
405 # hooks holds pointers used for user-side customizations
406 self.hooks = Struct()
406 self.hooks = Struct()
407
407
408 self.strdispatchers = {}
408 self.strdispatchers = {}
409
409
410 # Set all default hooks, defined in the IPython.hooks module.
410 # Set all default hooks, defined in the IPython.hooks module.
411 hooks = IPython.hooks
411 hooks = IPython.hooks
412 for hook_name in hooks.__all__:
412 for hook_name in hooks.__all__:
413 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
413 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
414 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
414 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
415 #print "bound hook",hook_name
415 #print "bound hook",hook_name
416
416
417 # Flag to mark unconditional exit
417 # Flag to mark unconditional exit
418 self.exit_now = False
418 self.exit_now = False
419
419
420 self.usage_min = """\
420 self.usage_min = """\
421 An enhanced console for Python.
421 An enhanced console for Python.
422 Some of its features are:
422 Some of its features are:
423 - Readline support if the readline library is present.
423 - Readline support if the readline library is present.
424 - Tab completion in the local namespace.
424 - Tab completion in the local namespace.
425 - Logging of input, see command-line options.
425 - Logging of input, see command-line options.
426 - System shell escape via ! , eg !ls.
426 - System shell escape via ! , eg !ls.
427 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
427 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
428 - Keeps track of locally defined variables via %who, %whos.
428 - Keeps track of locally defined variables via %who, %whos.
429 - Show object information with a ? eg ?x or x? (use ?? for more info).
429 - Show object information with a ? eg ?x or x? (use ?? for more info).
430 """
430 """
431 if usage: self.usage = usage
431 if usage: self.usage = usage
432 else: self.usage = self.usage_min
432 else: self.usage = self.usage_min
433
433
434 # Storage
434 # Storage
435 self.rc = rc # This will hold all configuration information
435 self.rc = rc # This will hold all configuration information
436 self.pager = 'less'
436 self.pager = 'less'
437 # temporary files used for various purposes. Deleted at exit.
437 # temporary files used for various purposes. Deleted at exit.
438 self.tempfiles = []
438 self.tempfiles = []
439
439
440 # Keep track of readline usage (later set by init_readline)
440 # Keep track of readline usage (later set by init_readline)
441 self.has_readline = False
441 self.has_readline = False
442
442
443 # template for logfile headers. It gets resolved at runtime by the
443 # template for logfile headers. It gets resolved at runtime by the
444 # logstart method.
444 # logstart method.
445 self.loghead_tpl = \
445 self.loghead_tpl = \
446 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
446 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
447 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
447 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
448 #log# opts = %s
448 #log# opts = %s
449 #log# args = %s
449 #log# args = %s
450 #log# It is safe to make manual edits below here.
450 #log# It is safe to make manual edits below here.
451 #log#-----------------------------------------------------------------------
451 #log#-----------------------------------------------------------------------
452 """
452 """
453 # for pushd/popd management
453 # for pushd/popd management
454 try:
454 try:
455 self.home_dir = get_home_dir()
455 self.home_dir = get_home_dir()
456 except HomeDirError,msg:
456 except HomeDirError,msg:
457 fatal(msg)
457 fatal(msg)
458
458
459 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
459 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
460
460
461 # Functions to call the underlying shell.
461 # Functions to call the underlying shell.
462
462
463 # The first is similar to os.system, but it doesn't return a value,
463 # The first is similar to os.system, but it doesn't return a value,
464 # and it allows interpolation of variables in the user's namespace.
464 # and it allows interpolation of variables in the user's namespace.
465 self.system = lambda cmd: \
465 self.system = lambda cmd: \
466 shell(self.var_expand(cmd,depth=2),
466 shell(self.var_expand(cmd,depth=2),
467 header=self.rc.system_header,
467 header=self.rc.system_header,
468 verbose=self.rc.system_verbose)
468 verbose=self.rc.system_verbose)
469
469
470 # These are for getoutput and getoutputerror:
470 # These are for getoutput and getoutputerror:
471 self.getoutput = lambda cmd: \
471 self.getoutput = lambda cmd: \
472 getoutput(self.var_expand(cmd,depth=2),
472 getoutput(self.var_expand(cmd,depth=2),
473 header=self.rc.system_header,
473 header=self.rc.system_header,
474 verbose=self.rc.system_verbose)
474 verbose=self.rc.system_verbose)
475
475
476 self.getoutputerror = lambda cmd: \
476 self.getoutputerror = lambda cmd: \
477 getoutputerror(self.var_expand(cmd,depth=2),
477 getoutputerror(self.var_expand(cmd,depth=2),
478 header=self.rc.system_header,
478 header=self.rc.system_header,
479 verbose=self.rc.system_verbose)
479 verbose=self.rc.system_verbose)
480
480
481 # RegExp for splitting line contents into pre-char//first
481 # RegExp for splitting line contents into pre-char//first
482 # word-method//rest. For clarity, each group in on one line.
482 # word-method//rest. For clarity, each group in on one line.
483
483
484 # WARNING: update the regexp if the above escapes are changed, as they
484 # WARNING: update the regexp if the above escapes are changed, as they
485 # are hardwired in.
485 # are hardwired in.
486
486
487 # Don't get carried away with trying to make the autocalling catch too
487 # Don't get carried away with trying to make the autocalling catch too
488 # much: it's better to be conservative rather than to trigger hidden
488 # much: it's better to be conservative rather than to trigger hidden
489 # evals() somewhere and end up causing side effects.
489 # evals() somewhere and end up causing side effects.
490 self.line_split = re.compile(r'^(\s*[,;/]?\s*)'
490 self.line_split = re.compile(r'^(\s*[,;/]?\s*)'
491 r'([\?\w\.]+\w*\s*)'
491 r'([\?\w\.]+\w*\s*)'
492 r'(\(?.*$)')
492 r'(\(?.*$)')
493
493
494 self.shell_line_split = re.compile(r'^(\s*)'
494 self.shell_line_split = re.compile(r'^(\s*)'
495 r'(\S*\s*)'
495 r'(\S*\s*)'
496 r'(\(?.*$)')
496 r'(\(?.*$)')
497
497
498
498
499 # A simpler regexp used as a fallback if the above doesn't work. This
499 # A simpler regexp used as a fallback if the above doesn't work. This
500 # one is more conservative in how it partitions the input. This code
500 # one is more conservative in how it partitions the input. This code
501 # can probably be cleaned up to do everything with just one regexp, but
501 # can probably be cleaned up to do everything with just one regexp, but
502 # I'm afraid of breaking something; do it once the unit tests are in
502 # I'm afraid of breaking something; do it once the unit tests are in
503 # place.
503 # place.
504 self.line_split_fallback = re.compile(r'^(\s*)'
504 self.line_split_fallback = re.compile(r'^(\s*)'
505 r'([%\!\?\w\.]*)'
505 r'([%\!\?\w\.]*)'
506 r'(.*)')
506 r'(.*)')
507
507
508 # Original re, keep around for a while in case changes break something
508 # Original re, keep around for a while in case changes break something
509 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
509 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
510 # r'(\s*[\?\w\.]+\w*\s*)'
510 # r'(\s*[\?\w\.]+\w*\s*)'
511 # r'(\(?.*$)')
511 # r'(\(?.*$)')
512
512
513 # RegExp to identify potential function names
513 # RegExp to identify potential function names
514 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
514 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
515
515
516 # RegExp to exclude strings with this start from autocalling. In
516 # RegExp to exclude strings with this start from autocalling. In
517 # particular, all binary operators should be excluded, so that if foo
517 # particular, all binary operators should be excluded, so that if foo
518 # is callable, foo OP bar doesn't become foo(OP bar), which is
518 # is callable, foo OP bar doesn't become foo(OP bar), which is
519 # invalid. The characters '!=()' don't need to be checked for, as the
519 # invalid. The characters '!=()' don't need to be checked for, as the
520 # _prefilter routine explicitely does so, to catch direct calls and
520 # _prefilter routine explicitely does so, to catch direct calls and
521 # rebindings of existing names.
521 # rebindings of existing names.
522
522
523 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
523 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
524 # it affects the rest of the group in square brackets.
524 # it affects the rest of the group in square brackets.
525 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
525 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
526 '|^is |^not |^in |^and |^or ')
526 '|^is |^not |^in |^and |^or ')
527
527
528 # try to catch also methods for stuff in lists/tuples/dicts: off
528 # try to catch also methods for stuff in lists/tuples/dicts: off
529 # (experimental). For this to work, the line_split regexp would need
529 # (experimental). For this to work, the line_split regexp would need
530 # to be modified so it wouldn't break things at '['. That line is
530 # to be modified so it wouldn't break things at '['. That line is
531 # nasty enough that I shouldn't change it until I can test it _well_.
531 # nasty enough that I shouldn't change it until I can test it _well_.
532 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
532 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
533
533
534 # keep track of where we started running (mainly for crash post-mortem)
534 # keep track of where we started running (mainly for crash post-mortem)
535 self.starting_dir = os.getcwd()
535 self.starting_dir = os.getcwd()
536
536
537 # Various switches which can be set
537 # Various switches which can be set
538 self.CACHELENGTH = 5000 # this is cheap, it's just text
538 self.CACHELENGTH = 5000 # this is cheap, it's just text
539 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
539 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
540 self.banner2 = banner2
540 self.banner2 = banner2
541
541
542 # TraceBack handlers:
542 # TraceBack handlers:
543
543
544 # Syntax error handler.
544 # Syntax error handler.
545 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
545 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
546
546
547 # The interactive one is initialized with an offset, meaning we always
547 # The interactive one is initialized with an offset, meaning we always
548 # want to remove the topmost item in the traceback, which is our own
548 # want to remove the topmost item in the traceback, which is our own
549 # internal code. Valid modes: ['Plain','Context','Verbose']
549 # internal code. Valid modes: ['Plain','Context','Verbose']
550 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
550 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
551 color_scheme='NoColor',
551 color_scheme='NoColor',
552 tb_offset = 1)
552 tb_offset = 1)
553
553
554 # IPython itself shouldn't crash. This will produce a detailed
554 # IPython itself shouldn't crash. This will produce a detailed
555 # post-mortem if it does. But we only install the crash handler for
555 # post-mortem if it does. But we only install the crash handler for
556 # non-threaded shells, the threaded ones use a normal verbose reporter
556 # non-threaded shells, the threaded ones use a normal verbose reporter
557 # and lose the crash handler. This is because exceptions in the main
557 # and lose the crash handler. This is because exceptions in the main
558 # thread (such as in GUI code) propagate directly to sys.excepthook,
558 # thread (such as in GUI code) propagate directly to sys.excepthook,
559 # and there's no point in printing crash dumps for every user exception.
559 # and there's no point in printing crash dumps for every user exception.
560 if self.isthreaded:
560 if self.isthreaded:
561 ipCrashHandler = ultraTB.FormattedTB()
561 ipCrashHandler = ultraTB.FormattedTB()
562 else:
562 else:
563 from IPython import CrashHandler
563 from IPython import CrashHandler
564 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
564 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
565 self.set_crash_handler(ipCrashHandler)
565 self.set_crash_handler(ipCrashHandler)
566
566
567 # and add any custom exception handlers the user may have specified
567 # and add any custom exception handlers the user may have specified
568 self.set_custom_exc(*custom_exceptions)
568 self.set_custom_exc(*custom_exceptions)
569
569
570 # indentation management
570 # indentation management
571 self.autoindent = False
571 self.autoindent = False
572 self.indent_current_nsp = 0
572 self.indent_current_nsp = 0
573
573
574 # Make some aliases automatically
574 # Make some aliases automatically
575 # Prepare list of shell aliases to auto-define
575 # Prepare list of shell aliases to auto-define
576 if os.name == 'posix':
576 if os.name == 'posix':
577 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
577 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
578 'mv mv -i','rm rm -i','cp cp -i',
578 'mv mv -i','rm rm -i','cp cp -i',
579 'cat cat','less less','clear clear',
579 'cat cat','less less','clear clear',
580 # a better ls
580 # a better ls
581 'ls ls -F',
581 'ls ls -F',
582 # long ls
582 # long ls
583 'll ls -lF')
583 'll ls -lF')
584 # Extra ls aliases with color, which need special treatment on BSD
584 # Extra ls aliases with color, which need special treatment on BSD
585 # variants
585 # variants
586 ls_extra = ( # color ls
586 ls_extra = ( # color ls
587 'lc ls -F -o --color',
587 'lc ls -F -o --color',
588 # ls normal files only
588 # ls normal files only
589 'lf ls -F -o --color %l | grep ^-',
589 'lf ls -F -o --color %l | grep ^-',
590 # ls symbolic links
590 # ls symbolic links
591 'lk ls -F -o --color %l | grep ^l',
591 'lk ls -F -o --color %l | grep ^l',
592 # directories or links to directories,
592 # directories or links to directories,
593 'ldir ls -F -o --color %l | grep /$',
593 'ldir ls -F -o --color %l | grep /$',
594 # things which are executable
594 # things which are executable
595 'lx ls -F -o --color %l | grep ^-..x',
595 'lx ls -F -o --color %l | grep ^-..x',
596 )
596 )
597 # The BSDs don't ship GNU ls, so they don't understand the
597 # The BSDs don't ship GNU ls, so they don't understand the
598 # --color switch out of the box
598 # --color switch out of the box
599 if 'bsd' in sys.platform:
599 if 'bsd' in sys.platform:
600 ls_extra = ( # ls normal files only
600 ls_extra = ( # ls normal files only
601 'lf ls -lF | grep ^-',
601 'lf ls -lF | grep ^-',
602 # ls symbolic links
602 # ls symbolic links
603 'lk ls -lF | grep ^l',
603 'lk ls -lF | grep ^l',
604 # directories or links to directories,
604 # directories or links to directories,
605 'ldir ls -lF | grep /$',
605 'ldir ls -lF | grep /$',
606 # things which are executable
606 # things which are executable
607 'lx ls -lF | grep ^-..x',
607 'lx ls -lF | grep ^-..x',
608 )
608 )
609 auto_alias = auto_alias + ls_extra
609 auto_alias = auto_alias + ls_extra
610 elif os.name in ['nt','dos']:
610 elif os.name in ['nt','dos']:
611 auto_alias = ('dir dir /on', 'ls dir /on',
611 auto_alias = ('dir dir /on', 'ls dir /on',
612 'ddir dir /ad /on', 'ldir dir /ad /on',
612 'ddir dir /ad /on', 'ldir dir /ad /on',
613 'mkdir mkdir','rmdir rmdir','echo echo',
613 'mkdir mkdir','rmdir rmdir','echo echo',
614 'ren ren','cls cls','copy copy')
614 'ren ren','cls cls','copy copy')
615 else:
615 else:
616 auto_alias = ()
616 auto_alias = ()
617 self.auto_alias = [s.split(None,1) for s in auto_alias]
617 self.auto_alias = [s.split(None,1) for s in auto_alias]
618 # Call the actual (public) initializer
618 # Call the actual (public) initializer
619 self.init_auto_alias()
619 self.init_auto_alias()
620
620
621 # Produce a public API instance
621 # Produce a public API instance
622 self.api = IPython.ipapi.IPApi(self)
622 self.api = IPython.ipapi.IPApi(self)
623
623
624 # track which builtins we add, so we can clean up later
624 # track which builtins we add, so we can clean up later
625 self.builtins_added = {}
625 self.builtins_added = {}
626 # This method will add the necessary builtins for operation, but
626 # This method will add the necessary builtins for operation, but
627 # tracking what it did via the builtins_added dict.
627 # tracking what it did via the builtins_added dict.
628 self.add_builtins()
628 self.add_builtins()
629
629
630 # end __init__
630 # end __init__
631
631
632 def var_expand(self,cmd,depth=0):
632 def var_expand(self,cmd,depth=0):
633 """Expand python variables in a string.
633 """Expand python variables in a string.
634
634
635 The depth argument indicates how many frames above the caller should
635 The depth argument indicates how many frames above the caller should
636 be walked to look for the local namespace where to expand variables.
636 be walked to look for the local namespace where to expand variables.
637
637
638 The global namespace for expansion is always the user's interactive
638 The global namespace for expansion is always the user's interactive
639 namespace.
639 namespace.
640 """
640 """
641
641
642 return str(ItplNS(cmd.replace('#','\#'),
642 return str(ItplNS(cmd.replace('#','\#'),
643 self.user_ns, # globals
643 self.user_ns, # globals
644 # Skip our own frame in searching for locals:
644 # Skip our own frame in searching for locals:
645 sys._getframe(depth+1).f_locals # locals
645 sys._getframe(depth+1).f_locals # locals
646 ))
646 ))
647
647
648 def pre_config_initialization(self):
648 def pre_config_initialization(self):
649 """Pre-configuration init method
649 """Pre-configuration init method
650
650
651 This is called before the configuration files are processed to
651 This is called before the configuration files are processed to
652 prepare the services the config files might need.
652 prepare the services the config files might need.
653
653
654 self.rc already has reasonable default values at this point.
654 self.rc already has reasonable default values at this point.
655 """
655 """
656 rc = self.rc
656 rc = self.rc
657
657
658 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
658 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
659
659
660 def post_config_initialization(self):
660 def post_config_initialization(self):
661 """Post configuration init method
661 """Post configuration init method
662
662
663 This is called after the configuration files have been processed to
663 This is called after the configuration files have been processed to
664 'finalize' the initialization."""
664 'finalize' the initialization."""
665
665
666 rc = self.rc
666 rc = self.rc
667
667
668 # Object inspector
668 # Object inspector
669 self.inspector = OInspect.Inspector(OInspect.InspectColors,
669 self.inspector = OInspect.Inspector(OInspect.InspectColors,
670 PyColorize.ANSICodeColors,
670 PyColorize.ANSICodeColors,
671 'NoColor',
671 'NoColor',
672 rc.object_info_string_level)
672 rc.object_info_string_level)
673
673
674 # Load readline proper
674 # Load readline proper
675 if rc.readline:
675 if rc.readline:
676 self.init_readline()
676 self.init_readline()
677
677
678 # local shortcut, this is used a LOT
678 # local shortcut, this is used a LOT
679 self.log = self.logger.log
679 self.log = self.logger.log
680
680
681 # Initialize cache, set in/out prompts and printing system
681 # Initialize cache, set in/out prompts and printing system
682 self.outputcache = CachedOutput(self,
682 self.outputcache = CachedOutput(self,
683 rc.cache_size,
683 rc.cache_size,
684 rc.pprint,
684 rc.pprint,
685 input_sep = rc.separate_in,
685 input_sep = rc.separate_in,
686 output_sep = rc.separate_out,
686 output_sep = rc.separate_out,
687 output_sep2 = rc.separate_out2,
687 output_sep2 = rc.separate_out2,
688 ps1 = rc.prompt_in1,
688 ps1 = rc.prompt_in1,
689 ps2 = rc.prompt_in2,
689 ps2 = rc.prompt_in2,
690 ps_out = rc.prompt_out,
690 ps_out = rc.prompt_out,
691 pad_left = rc.prompts_pad_left)
691 pad_left = rc.prompts_pad_left)
692
692
693 # user may have over-ridden the default print hook:
693 # user may have over-ridden the default print hook:
694 try:
694 try:
695 self.outputcache.__class__.display = self.hooks.display
695 self.outputcache.__class__.display = self.hooks.display
696 except AttributeError:
696 except AttributeError:
697 pass
697 pass
698
698
699 # I don't like assigning globally to sys, because it means when
699 # I don't like assigning globally to sys, because it means when
700 # embedding instances, each embedded instance overrides the previous
700 # embedding instances, each embedded instance overrides the previous
701 # choice. But sys.displayhook seems to be called internally by exec,
701 # choice. But sys.displayhook seems to be called internally by exec,
702 # so I don't see a way around it. We first save the original and then
702 # so I don't see a way around it. We first save the original and then
703 # overwrite it.
703 # overwrite it.
704 self.sys_displayhook = sys.displayhook
704 self.sys_displayhook = sys.displayhook
705 sys.displayhook = self.outputcache
705 sys.displayhook = self.outputcache
706
706
707 # Set user colors (don't do it in the constructor above so that it
707 # Set user colors (don't do it in the constructor above so that it
708 # doesn't crash if colors option is invalid)
708 # doesn't crash if colors option is invalid)
709 self.magic_colors(rc.colors)
709 self.magic_colors(rc.colors)
710
710
711 # Set calling of pdb on exceptions
711 # Set calling of pdb on exceptions
712 self.call_pdb = rc.pdb
712 self.call_pdb = rc.pdb
713
713
714 # Load user aliases
714 # Load user aliases
715 for alias in rc.alias:
715 for alias in rc.alias:
716 self.magic_alias(alias)
716 self.magic_alias(alias)
717 self.hooks.late_startup_hook()
717 self.hooks.late_startup_hook()
718
718
719 batchrun = False
719 batchrun = False
720 for batchfile in [path(arg) for arg in self.rc.args
720 for batchfile in [path(arg) for arg in self.rc.args
721 if arg.lower().endswith('.ipy')]:
721 if arg.lower().endswith('.ipy')]:
722 if not batchfile.isfile():
722 if not batchfile.isfile():
723 print "No such batch file:", batchfile
723 print "No such batch file:", batchfile
724 continue
724 continue
725 self.api.runlines(batchfile.text())
725 self.api.runlines(batchfile.text())
726 batchrun = True
726 batchrun = True
727 if batchrun:
727 if batchrun:
728 self.exit_now = True
728 self.exit_now = True
729
729
730 def add_builtins(self):
730 def add_builtins(self):
731 """Store ipython references into the builtin namespace.
731 """Store ipython references into the builtin namespace.
732
732
733 Some parts of ipython operate via builtins injected here, which hold a
733 Some parts of ipython operate via builtins injected here, which hold a
734 reference to IPython itself."""
734 reference to IPython itself."""
735
735
736 # TODO: deprecate all except _ip; 'jobs' should be installed
736 # TODO: deprecate all except _ip; 'jobs' should be installed
737 # by an extension and the rest are under _ip, ipalias is redundant
737 # by an extension and the rest are under _ip, ipalias is redundant
738 builtins_new = dict(__IPYTHON__ = self,
738 builtins_new = dict(__IPYTHON__ = self,
739 ip_set_hook = self.set_hook,
739 ip_set_hook = self.set_hook,
740 jobs = self.jobs,
740 jobs = self.jobs,
741 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
741 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
742 ipalias = wrap_deprecated(self.ipalias),
742 ipalias = wrap_deprecated(self.ipalias),
743 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
743 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
744 _ip = self.api
744 _ip = self.api
745 )
745 )
746 for biname,bival in builtins_new.items():
746 for biname,bival in builtins_new.items():
747 try:
747 try:
748 # store the orignal value so we can restore it
748 # store the orignal value so we can restore it
749 self.builtins_added[biname] = __builtin__.__dict__[biname]
749 self.builtins_added[biname] = __builtin__.__dict__[biname]
750 except KeyError:
750 except KeyError:
751 # or mark that it wasn't defined, and we'll just delete it at
751 # or mark that it wasn't defined, and we'll just delete it at
752 # cleanup
752 # cleanup
753 self.builtins_added[biname] = Undefined
753 self.builtins_added[biname] = Undefined
754 __builtin__.__dict__[biname] = bival
754 __builtin__.__dict__[biname] = bival
755
755
756 # Keep in the builtins a flag for when IPython is active. We set it
756 # Keep in the builtins a flag for when IPython is active. We set it
757 # with setdefault so that multiple nested IPythons don't clobber one
757 # with setdefault so that multiple nested IPythons don't clobber one
758 # another. Each will increase its value by one upon being activated,
758 # another. Each will increase its value by one upon being activated,
759 # which also gives us a way to determine the nesting level.
759 # which also gives us a way to determine the nesting level.
760 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
760 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
761
761
762 def clean_builtins(self):
762 def clean_builtins(self):
763 """Remove any builtins which might have been added by add_builtins, or
763 """Remove any builtins which might have been added by add_builtins, or
764 restore overwritten ones to their previous values."""
764 restore overwritten ones to their previous values."""
765 for biname,bival in self.builtins_added.items():
765 for biname,bival in self.builtins_added.items():
766 if bival is Undefined:
766 if bival is Undefined:
767 del __builtin__.__dict__[biname]
767 del __builtin__.__dict__[biname]
768 else:
768 else:
769 __builtin__.__dict__[biname] = bival
769 __builtin__.__dict__[biname] = bival
770 self.builtins_added.clear()
770 self.builtins_added.clear()
771
771
772 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
772 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
773 """set_hook(name,hook) -> sets an internal IPython hook.
773 """set_hook(name,hook) -> sets an internal IPython hook.
774
774
775 IPython exposes some of its internal API as user-modifiable hooks. By
775 IPython exposes some of its internal API as user-modifiable hooks. By
776 adding your function to one of these hooks, you can modify IPython's
776 adding your function to one of these hooks, you can modify IPython's
777 behavior to call at runtime your own routines."""
777 behavior to call at runtime your own routines."""
778
778
779 # At some point in the future, this should validate the hook before it
779 # At some point in the future, this should validate the hook before it
780 # accepts it. Probably at least check that the hook takes the number
780 # accepts it. Probably at least check that the hook takes the number
781 # of args it's supposed to.
781 # of args it's supposed to.
782
782
783 f = new.instancemethod(hook,self,self.__class__)
783 f = new.instancemethod(hook,self,self.__class__)
784
784
785 # check if the hook is for strdispatcher first
785 # check if the hook is for strdispatcher first
786 if str_key is not None:
786 if str_key is not None:
787 sdp = self.strdispatchers.get(name, StrDispatch())
787 sdp = self.strdispatchers.get(name, StrDispatch())
788 sdp.add_s(str_key, f, priority )
788 sdp.add_s(str_key, f, priority )
789 self.strdispatchers[name] = sdp
789 self.strdispatchers[name] = sdp
790 return
790 return
791 if re_key is not None:
791 if re_key is not None:
792 sdp = self.strdispatchers.get(name, StrDispatch())
792 sdp = self.strdispatchers.get(name, StrDispatch())
793 sdp.add_re(re.compile(re_key), f, priority )
793 sdp.add_re(re.compile(re_key), f, priority )
794 self.strdispatchers[name] = sdp
794 self.strdispatchers[name] = sdp
795 return
795 return
796
796
797 dp = getattr(self.hooks, name, None)
797 dp = getattr(self.hooks, name, None)
798 if name not in IPython.hooks.__all__:
798 if name not in IPython.hooks.__all__:
799 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
799 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
800 if not dp:
800 if not dp:
801 dp = IPython.hooks.CommandChainDispatcher()
801 dp = IPython.hooks.CommandChainDispatcher()
802
802
803 try:
803 try:
804 dp.add(f,priority)
804 dp.add(f,priority)
805 except AttributeError:
805 except AttributeError:
806 # it was not commandchain, plain old func - replace
806 # it was not commandchain, plain old func - replace
807 dp = f
807 dp = f
808
808
809 setattr(self.hooks,name, dp)
809 setattr(self.hooks,name, dp)
810
810
811
811
812 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
812 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
813
813
814 def set_crash_handler(self,crashHandler):
814 def set_crash_handler(self,crashHandler):
815 """Set the IPython crash handler.
815 """Set the IPython crash handler.
816
816
817 This must be a callable with a signature suitable for use as
817 This must be a callable with a signature suitable for use as
818 sys.excepthook."""
818 sys.excepthook."""
819
819
820 # Install the given crash handler as the Python exception hook
820 # Install the given crash handler as the Python exception hook
821 sys.excepthook = crashHandler
821 sys.excepthook = crashHandler
822
822
823 # The instance will store a pointer to this, so that runtime code
823 # The instance will store a pointer to this, so that runtime code
824 # (such as magics) can access it. This is because during the
824 # (such as magics) can access it. This is because during the
825 # read-eval loop, it gets temporarily overwritten (to deal with GUI
825 # read-eval loop, it gets temporarily overwritten (to deal with GUI
826 # frameworks).
826 # frameworks).
827 self.sys_excepthook = sys.excepthook
827 self.sys_excepthook = sys.excepthook
828
828
829
829
830 def set_custom_exc(self,exc_tuple,handler):
830 def set_custom_exc(self,exc_tuple,handler):
831 """set_custom_exc(exc_tuple,handler)
831 """set_custom_exc(exc_tuple,handler)
832
832
833 Set a custom exception handler, which will be called if any of the
833 Set a custom exception handler, which will be called if any of the
834 exceptions in exc_tuple occur in the mainloop (specifically, in the
834 exceptions in exc_tuple occur in the mainloop (specifically, in the
835 runcode() method.
835 runcode() method.
836
836
837 Inputs:
837 Inputs:
838
838
839 - exc_tuple: a *tuple* of valid exceptions to call the defined
839 - exc_tuple: a *tuple* of valid exceptions to call the defined
840 handler for. It is very important that you use a tuple, and NOT A
840 handler for. It is very important that you use a tuple, and NOT A
841 LIST here, because of the way Python's except statement works. If
841 LIST here, because of the way Python's except statement works. If
842 you only want to trap a single exception, use a singleton tuple:
842 you only want to trap a single exception, use a singleton tuple:
843
843
844 exc_tuple == (MyCustomException,)
844 exc_tuple == (MyCustomException,)
845
845
846 - handler: this must be defined as a function with the following
846 - handler: this must be defined as a function with the following
847 basic interface: def my_handler(self,etype,value,tb).
847 basic interface: def my_handler(self,etype,value,tb).
848
848
849 This will be made into an instance method (via new.instancemethod)
849 This will be made into an instance method (via new.instancemethod)
850 of IPython itself, and it will be called if any of the exceptions
850 of IPython itself, and it will be called if any of the exceptions
851 listed in the exc_tuple are caught. If the handler is None, an
851 listed in the exc_tuple are caught. If the handler is None, an
852 internal basic one is used, which just prints basic info.
852 internal basic one is used, which just prints basic info.
853
853
854 WARNING: by putting in your own exception handler into IPython's main
854 WARNING: by putting in your own exception handler into IPython's main
855 execution loop, you run a very good chance of nasty crashes. This
855 execution loop, you run a very good chance of nasty crashes. This
856 facility should only be used if you really know what you are doing."""
856 facility should only be used if you really know what you are doing."""
857
857
858 assert type(exc_tuple)==type(()) , \
858 assert type(exc_tuple)==type(()) , \
859 "The custom exceptions must be given AS A TUPLE."
859 "The custom exceptions must be given AS A TUPLE."
860
860
861 def dummy_handler(self,etype,value,tb):
861 def dummy_handler(self,etype,value,tb):
862 print '*** Simple custom exception handler ***'
862 print '*** Simple custom exception handler ***'
863 print 'Exception type :',etype
863 print 'Exception type :',etype
864 print 'Exception value:',value
864 print 'Exception value:',value
865 print 'Traceback :',tb
865 print 'Traceback :',tb
866 print 'Source code :','\n'.join(self.buffer)
866 print 'Source code :','\n'.join(self.buffer)
867
867
868 if handler is None: handler = dummy_handler
868 if handler is None: handler = dummy_handler
869
869
870 self.CustomTB = new.instancemethod(handler,self,self.__class__)
870 self.CustomTB = new.instancemethod(handler,self,self.__class__)
871 self.custom_exceptions = exc_tuple
871 self.custom_exceptions = exc_tuple
872
872
873 def set_custom_completer(self,completer,pos=0):
873 def set_custom_completer(self,completer,pos=0):
874 """set_custom_completer(completer,pos=0)
874 """set_custom_completer(completer,pos=0)
875
875
876 Adds a new custom completer function.
876 Adds a new custom completer function.
877
877
878 The position argument (defaults to 0) is the index in the completers
878 The position argument (defaults to 0) is the index in the completers
879 list where you want the completer to be inserted."""
879 list where you want the completer to be inserted."""
880
880
881 newcomp = new.instancemethod(completer,self.Completer,
881 newcomp = new.instancemethod(completer,self.Completer,
882 self.Completer.__class__)
882 self.Completer.__class__)
883 self.Completer.matchers.insert(pos,newcomp)
883 self.Completer.matchers.insert(pos,newcomp)
884
884
885 def _get_call_pdb(self):
885 def _get_call_pdb(self):
886 return self._call_pdb
886 return self._call_pdb
887
887
888 def _set_call_pdb(self,val):
888 def _set_call_pdb(self,val):
889
889
890 if val not in (0,1,False,True):
890 if val not in (0,1,False,True):
891 raise ValueError,'new call_pdb value must be boolean'
891 raise ValueError,'new call_pdb value must be boolean'
892
892
893 # store value in instance
893 # store value in instance
894 self._call_pdb = val
894 self._call_pdb = val
895
895
896 # notify the actual exception handlers
896 # notify the actual exception handlers
897 self.InteractiveTB.call_pdb = val
897 self.InteractiveTB.call_pdb = val
898 if self.isthreaded:
898 if self.isthreaded:
899 try:
899 try:
900 self.sys_excepthook.call_pdb = val
900 self.sys_excepthook.call_pdb = val
901 except:
901 except:
902 warn('Failed to activate pdb for threaded exception handler')
902 warn('Failed to activate pdb for threaded exception handler')
903
903
904 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
904 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
905 'Control auto-activation of pdb at exceptions')
905 'Control auto-activation of pdb at exceptions')
906
906
907
907
908 # These special functions get installed in the builtin namespace, to
908 # These special functions get installed in the builtin namespace, to
909 # provide programmatic (pure python) access to magics, aliases and system
909 # provide programmatic (pure python) access to magics, aliases and system
910 # calls. This is important for logging, user scripting, and more.
910 # calls. This is important for logging, user scripting, and more.
911
911
912 # We are basically exposing, via normal python functions, the three
912 # We are basically exposing, via normal python functions, the three
913 # mechanisms in which ipython offers special call modes (magics for
913 # mechanisms in which ipython offers special call modes (magics for
914 # internal control, aliases for direct system access via pre-selected
914 # internal control, aliases for direct system access via pre-selected
915 # names, and !cmd for calling arbitrary system commands).
915 # names, and !cmd for calling arbitrary system commands).
916
916
917 def ipmagic(self,arg_s):
917 def ipmagic(self,arg_s):
918 """Call a magic function by name.
918 """Call a magic function by name.
919
919
920 Input: a string containing the name of the magic function to call and any
920 Input: a string containing the name of the magic function to call and any
921 additional arguments to be passed to the magic.
921 additional arguments to be passed to the magic.
922
922
923 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
923 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
924 prompt:
924 prompt:
925
925
926 In[1]: %name -opt foo bar
926 In[1]: %name -opt foo bar
927
927
928 To call a magic without arguments, simply use ipmagic('name').
928 To call a magic without arguments, simply use ipmagic('name').
929
929
930 This provides a proper Python function to call IPython's magics in any
930 This provides a proper Python function to call IPython's magics in any
931 valid Python code you can type at the interpreter, including loops and
931 valid Python code you can type at the interpreter, including loops and
932 compound statements. It is added by IPython to the Python builtin
932 compound statements. It is added by IPython to the Python builtin
933 namespace upon initialization."""
933 namespace upon initialization."""
934
934
935 args = arg_s.split(' ',1)
935 args = arg_s.split(' ',1)
936 magic_name = args[0]
936 magic_name = args[0]
937 magic_name = magic_name.lstrip(self.ESC_MAGIC)
937 magic_name = magic_name.lstrip(self.ESC_MAGIC)
938
938
939 try:
939 try:
940 magic_args = args[1]
940 magic_args = args[1]
941 except IndexError:
941 except IndexError:
942 magic_args = ''
942 magic_args = ''
943 fn = getattr(self,'magic_'+magic_name,None)
943 fn = getattr(self,'magic_'+magic_name,None)
944 if fn is None:
944 if fn is None:
945 error("Magic function `%s` not found." % magic_name)
945 error("Magic function `%s` not found." % magic_name)
946 else:
946 else:
947 magic_args = self.var_expand(magic_args,1)
947 magic_args = self.var_expand(magic_args,1)
948 return fn(magic_args)
948 return fn(magic_args)
949
949
950 def ipalias(self,arg_s):
950 def ipalias(self,arg_s):
951 """Call an alias by name.
951 """Call an alias by name.
952
952
953 Input: a string containing the name of the alias to call and any
953 Input: a string containing the name of the alias to call and any
954 additional arguments to be passed to the magic.
954 additional arguments to be passed to the magic.
955
955
956 ipalias('name -opt foo bar') is equivalent to typing at the ipython
956 ipalias('name -opt foo bar') is equivalent to typing at the ipython
957 prompt:
957 prompt:
958
958
959 In[1]: name -opt foo bar
959 In[1]: name -opt foo bar
960
960
961 To call an alias without arguments, simply use ipalias('name').
961 To call an alias without arguments, simply use ipalias('name').
962
962
963 This provides a proper Python function to call IPython's aliases in any
963 This provides a proper Python function to call IPython's aliases in any
964 valid Python code you can type at the interpreter, including loops and
964 valid Python code you can type at the interpreter, including loops and
965 compound statements. It is added by IPython to the Python builtin
965 compound statements. It is added by IPython to the Python builtin
966 namespace upon initialization."""
966 namespace upon initialization."""
967
967
968 args = arg_s.split(' ',1)
968 args = arg_s.split(' ',1)
969 alias_name = args[0]
969 alias_name = args[0]
970 try:
970 try:
971 alias_args = args[1]
971 alias_args = args[1]
972 except IndexError:
972 except IndexError:
973 alias_args = ''
973 alias_args = ''
974 if alias_name in self.alias_table:
974 if alias_name in self.alias_table:
975 self.call_alias(alias_name,alias_args)
975 self.call_alias(alias_name,alias_args)
976 else:
976 else:
977 error("Alias `%s` not found." % alias_name)
977 error("Alias `%s` not found." % alias_name)
978
978
979 def ipsystem(self,arg_s):
979 def ipsystem(self,arg_s):
980 """Make a system call, using IPython."""
980 """Make a system call, using IPython."""
981
981
982 self.system(arg_s)
982 self.system(arg_s)
983
983
984 def complete(self,text):
984 def complete(self,text):
985 """Return a sorted list of all possible completions on text.
985 """Return a sorted list of all possible completions on text.
986
986
987 Inputs:
987 Inputs:
988
988
989 - text: a string of text to be completed on.
989 - text: a string of text to be completed on.
990
990
991 This is a wrapper around the completion mechanism, similar to what
991 This is a wrapper around the completion mechanism, similar to what
992 readline does at the command line when the TAB key is hit. By
992 readline does at the command line when the TAB key is hit. By
993 exposing it as a method, it can be used by other non-readline
993 exposing it as a method, it can be used by other non-readline
994 environments (such as GUIs) for text completion.
994 environments (such as GUIs) for text completion.
995
995
996 Simple usage example:
996 Simple usage example:
997
997
998 In [1]: x = 'hello'
998 In [1]: x = 'hello'
999
999
1000 In [2]: __IP.complete('x.l')
1000 In [2]: __IP.complete('x.l')
1001 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
1001 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
1002
1002
1003 complete = self.Completer.complete
1003 complete = self.Completer.complete
1004 state = 0
1004 state = 0
1005 # use a dict so we get unique keys, since ipyhton's multiple
1005 # use a dict so we get unique keys, since ipyhton's multiple
1006 # completers can return duplicates.
1006 # completers can return duplicates.
1007 comps = {}
1007 comps = {}
1008 while True:
1008 while True:
1009 newcomp = complete(text,state)
1009 newcomp = complete(text,state)
1010 if newcomp is None:
1010 if newcomp is None:
1011 break
1011 break
1012 comps[newcomp] = 1
1012 comps[newcomp] = 1
1013 state += 1
1013 state += 1
1014 outcomps = comps.keys()
1014 outcomps = comps.keys()
1015 outcomps.sort()
1015 outcomps.sort()
1016 return outcomps
1016 return outcomps
1017
1017
1018 def set_completer_frame(self, frame=None):
1018 def set_completer_frame(self, frame=None):
1019 if frame:
1019 if frame:
1020 self.Completer.namespace = frame.f_locals
1020 self.Completer.namespace = frame.f_locals
1021 self.Completer.global_namespace = frame.f_globals
1021 self.Completer.global_namespace = frame.f_globals
1022 else:
1022 else:
1023 self.Completer.namespace = self.user_ns
1023 self.Completer.namespace = self.user_ns
1024 self.Completer.global_namespace = self.user_global_ns
1024 self.Completer.global_namespace = self.user_global_ns
1025
1025
1026 def init_auto_alias(self):
1026 def init_auto_alias(self):
1027 """Define some aliases automatically.
1027 """Define some aliases automatically.
1028
1028
1029 These are ALL parameter-less aliases"""
1029 These are ALL parameter-less aliases"""
1030
1030
1031 for alias,cmd in self.auto_alias:
1031 for alias,cmd in self.auto_alias:
1032 self.alias_table[alias] = (0,cmd)
1032 self.alias_table[alias] = (0,cmd)
1033
1033
1034 def alias_table_validate(self,verbose=0):
1034 def alias_table_validate(self,verbose=0):
1035 """Update information about the alias table.
1035 """Update information about the alias table.
1036
1036
1037 In particular, make sure no Python keywords/builtins are in it."""
1037 In particular, make sure no Python keywords/builtins are in it."""
1038
1038
1039 no_alias = self.no_alias
1039 no_alias = self.no_alias
1040 for k in self.alias_table.keys():
1040 for k in self.alias_table.keys():
1041 if k in no_alias:
1041 if k in no_alias:
1042 del self.alias_table[k]
1042 del self.alias_table[k]
1043 if verbose:
1043 if verbose:
1044 print ("Deleting alias <%s>, it's a Python "
1044 print ("Deleting alias <%s>, it's a Python "
1045 "keyword or builtin." % k)
1045 "keyword or builtin." % k)
1046
1046
1047 def set_autoindent(self,value=None):
1047 def set_autoindent(self,value=None):
1048 """Set the autoindent flag, checking for readline support.
1048 """Set the autoindent flag, checking for readline support.
1049
1049
1050 If called with no arguments, it acts as a toggle."""
1050 If called with no arguments, it acts as a toggle."""
1051
1051
1052 if not self.has_readline:
1052 if not self.has_readline:
1053 if os.name == 'posix':
1053 if os.name == 'posix':
1054 warn("The auto-indent feature requires the readline library")
1054 warn("The auto-indent feature requires the readline library")
1055 self.autoindent = 0
1055 self.autoindent = 0
1056 return
1056 return
1057 if value is None:
1057 if value is None:
1058 self.autoindent = not self.autoindent
1058 self.autoindent = not self.autoindent
1059 else:
1059 else:
1060 self.autoindent = value
1060 self.autoindent = value
1061
1061
1062 def rc_set_toggle(self,rc_field,value=None):
1062 def rc_set_toggle(self,rc_field,value=None):
1063 """Set or toggle a field in IPython's rc config. structure.
1063 """Set or toggle a field in IPython's rc config. structure.
1064
1064
1065 If called with no arguments, it acts as a toggle.
1065 If called with no arguments, it acts as a toggle.
1066
1066
1067 If called with a non-existent field, the resulting AttributeError
1067 If called with a non-existent field, the resulting AttributeError
1068 exception will propagate out."""
1068 exception will propagate out."""
1069
1069
1070 rc_val = getattr(self.rc,rc_field)
1070 rc_val = getattr(self.rc,rc_field)
1071 if value is None:
1071 if value is None:
1072 value = not rc_val
1072 value = not rc_val
1073 setattr(self.rc,rc_field,value)
1073 setattr(self.rc,rc_field,value)
1074
1074
1075 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1075 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1076 """Install the user configuration directory.
1076 """Install the user configuration directory.
1077
1077
1078 Can be called when running for the first time or to upgrade the user's
1078 Can be called when running for the first time or to upgrade the user's
1079 .ipython/ directory with the mode parameter. Valid modes are 'install'
1079 .ipython/ directory with the mode parameter. Valid modes are 'install'
1080 and 'upgrade'."""
1080 and 'upgrade'."""
1081
1081
1082 def wait():
1082 def wait():
1083 try:
1083 try:
1084 raw_input("Please press <RETURN> to start IPython.")
1084 raw_input("Please press <RETURN> to start IPython.")
1085 except EOFError:
1085 except EOFError:
1086 print >> Term.cout
1086 print >> Term.cout
1087 print '*'*70
1087 print '*'*70
1088
1088
1089 cwd = os.getcwd() # remember where we started
1089 cwd = os.getcwd() # remember where we started
1090 glb = glob.glob
1090 glb = glob.glob
1091 print '*'*70
1091 print '*'*70
1092 if mode == 'install':
1092 if mode == 'install':
1093 print \
1093 print \
1094 """Welcome to IPython. I will try to create a personal configuration directory
1094 """Welcome to IPython. I will try to create a personal configuration directory
1095 where you can customize many aspects of IPython's functionality in:\n"""
1095 where you can customize many aspects of IPython's functionality in:\n"""
1096 else:
1096 else:
1097 print 'I am going to upgrade your configuration in:'
1097 print 'I am going to upgrade your configuration in:'
1098
1098
1099 print ipythondir
1099 print ipythondir
1100
1100
1101 rcdirend = os.path.join('IPython','UserConfig')
1101 rcdirend = os.path.join('IPython','UserConfig')
1102 cfg = lambda d: os.path.join(d,rcdirend)
1102 cfg = lambda d: os.path.join(d,rcdirend)
1103 try:
1103 try:
1104 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1104 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1105 except IOError:
1105 except IOError:
1106 warning = """
1106 warning = """
1107 Installation error. IPython's directory was not found.
1107 Installation error. IPython's directory was not found.
1108
1108
1109 Check the following:
1109 Check the following:
1110
1110
1111 The ipython/IPython directory should be in a directory belonging to your
1111 The ipython/IPython directory should be in a directory belonging to your
1112 PYTHONPATH environment variable (that is, it should be in a directory
1112 PYTHONPATH environment variable (that is, it should be in a directory
1113 belonging to sys.path). You can copy it explicitly there or just link to it.
1113 belonging to sys.path). You can copy it explicitly there or just link to it.
1114
1114
1115 IPython will proceed with builtin defaults.
1115 IPython will proceed with builtin defaults.
1116 """
1116 """
1117 warn(warning)
1117 warn(warning)
1118 wait()
1118 wait()
1119 return
1119 return
1120
1120
1121 if mode == 'install':
1121 if mode == 'install':
1122 try:
1122 try:
1123 shutil.copytree(rcdir,ipythondir)
1123 shutil.copytree(rcdir,ipythondir)
1124 os.chdir(ipythondir)
1124 os.chdir(ipythondir)
1125 rc_files = glb("ipythonrc*")
1125 rc_files = glb("ipythonrc*")
1126 for rc_file in rc_files:
1126 for rc_file in rc_files:
1127 os.rename(rc_file,rc_file+rc_suffix)
1127 os.rename(rc_file,rc_file+rc_suffix)
1128 except:
1128 except:
1129 warning = """
1129 warning = """
1130
1130
1131 There was a problem with the installation:
1131 There was a problem with the installation:
1132 %s
1132 %s
1133 Try to correct it or contact the developers if you think it's a bug.
1133 Try to correct it or contact the developers if you think it's a bug.
1134 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1134 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1135 warn(warning)
1135 warn(warning)
1136 wait()
1136 wait()
1137 return
1137 return
1138
1138
1139 elif mode == 'upgrade':
1139 elif mode == 'upgrade':
1140 try:
1140 try:
1141 os.chdir(ipythondir)
1141 os.chdir(ipythondir)
1142 except:
1142 except:
1143 print """
1143 print """
1144 Can not upgrade: changing to directory %s failed. Details:
1144 Can not upgrade: changing to directory %s failed. Details:
1145 %s
1145 %s
1146 """ % (ipythondir,sys.exc_info()[1])
1146 """ % (ipythondir,sys.exc_info()[1])
1147 wait()
1147 wait()
1148 return
1148 return
1149 else:
1149 else:
1150 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1150 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1151 for new_full_path in sources:
1151 for new_full_path in sources:
1152 new_filename = os.path.basename(new_full_path)
1152 new_filename = os.path.basename(new_full_path)
1153 if new_filename.startswith('ipythonrc'):
1153 if new_filename.startswith('ipythonrc'):
1154 new_filename = new_filename + rc_suffix
1154 new_filename = new_filename + rc_suffix
1155 # The config directory should only contain files, skip any
1155 # The config directory should only contain files, skip any
1156 # directories which may be there (like CVS)
1156 # directories which may be there (like CVS)
1157 if os.path.isdir(new_full_path):
1157 if os.path.isdir(new_full_path):
1158 continue
1158 continue
1159 if os.path.exists(new_filename):
1159 if os.path.exists(new_filename):
1160 old_file = new_filename+'.old'
1160 old_file = new_filename+'.old'
1161 if os.path.exists(old_file):
1161 if os.path.exists(old_file):
1162 os.remove(old_file)
1162 os.remove(old_file)
1163 os.rename(new_filename,old_file)
1163 os.rename(new_filename,old_file)
1164 shutil.copy(new_full_path,new_filename)
1164 shutil.copy(new_full_path,new_filename)
1165 else:
1165 else:
1166 raise ValueError,'unrecognized mode for install:',`mode`
1166 raise ValueError,'unrecognized mode for install:',`mode`
1167
1167
1168 # Fix line-endings to those native to each platform in the config
1168 # Fix line-endings to those native to each platform in the config
1169 # directory.
1169 # directory.
1170 try:
1170 try:
1171 os.chdir(ipythondir)
1171 os.chdir(ipythondir)
1172 except:
1172 except:
1173 print """
1173 print """
1174 Problem: changing to directory %s failed.
1174 Problem: changing to directory %s failed.
1175 Details:
1175 Details:
1176 %s
1176 %s
1177
1177
1178 Some configuration files may have incorrect line endings. This should not
1178 Some configuration files may have incorrect line endings. This should not
1179 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1179 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1180 wait()
1180 wait()
1181 else:
1181 else:
1182 for fname in glb('ipythonrc*'):
1182 for fname in glb('ipythonrc*'):
1183 try:
1183 try:
1184 native_line_ends(fname,backup=0)
1184 native_line_ends(fname,backup=0)
1185 except IOError:
1185 except IOError:
1186 pass
1186 pass
1187
1187
1188 if mode == 'install':
1188 if mode == 'install':
1189 print """
1189 print """
1190 Successful installation!
1190 Successful installation!
1191
1191
1192 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1192 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1193 IPython manual (there are both HTML and PDF versions supplied with the
1193 IPython manual (there are both HTML and PDF versions supplied with the
1194 distribution) to make sure that your system environment is properly configured
1194 distribution) to make sure that your system environment is properly configured
1195 to take advantage of IPython's features.
1195 to take advantage of IPython's features.
1196
1196
1197 Important note: the configuration system has changed! The old system is
1197 Important note: the configuration system has changed! The old system is
1198 still in place, but its setting may be partly overridden by the settings in
1198 still in place, but its setting may be partly overridden by the settings in
1199 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1199 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1200 if some of the new settings bother you.
1200 if some of the new settings bother you.
1201
1201
1202 """
1202 """
1203 else:
1203 else:
1204 print """
1204 print """
1205 Successful upgrade!
1205 Successful upgrade!
1206
1206
1207 All files in your directory:
1207 All files in your directory:
1208 %(ipythondir)s
1208 %(ipythondir)s
1209 which would have been overwritten by the upgrade were backed up with a .old
1209 which would have been overwritten by the upgrade were backed up with a .old
1210 extension. If you had made particular customizations in those files you may
1210 extension. If you had made particular customizations in those files you may
1211 want to merge them back into the new files.""" % locals()
1211 want to merge them back into the new files.""" % locals()
1212 wait()
1212 wait()
1213 os.chdir(cwd)
1213 os.chdir(cwd)
1214 # end user_setup()
1214 # end user_setup()
1215
1215
1216 def atexit_operations(self):
1216 def atexit_operations(self):
1217 """This will be executed at the time of exit.
1217 """This will be executed at the time of exit.
1218
1218
1219 Saving of persistent data should be performed here. """
1219 Saving of persistent data should be performed here. """
1220
1220
1221 #print '*** IPython exit cleanup ***' # dbg
1221 #print '*** IPython exit cleanup ***' # dbg
1222 # input history
1222 # input history
1223 self.savehist()
1223 self.savehist()
1224
1224
1225 # Cleanup all tempfiles left around
1225 # Cleanup all tempfiles left around
1226 for tfile in self.tempfiles:
1226 for tfile in self.tempfiles:
1227 try:
1227 try:
1228 os.unlink(tfile)
1228 os.unlink(tfile)
1229 except OSError:
1229 except OSError:
1230 pass
1230 pass
1231
1231
1232 # save the "persistent data" catch-all dictionary
1232 # save the "persistent data" catch-all dictionary
1233 self.hooks.shutdown_hook()
1233 self.hooks.shutdown_hook()
1234
1234
1235 def savehist(self):
1235 def savehist(self):
1236 """Save input history to a file (via readline library)."""
1236 """Save input history to a file (via readline library)."""
1237 try:
1237 try:
1238 self.readline.write_history_file(self.histfile)
1238 self.readline.write_history_file(self.histfile)
1239 except:
1239 except:
1240 print 'Unable to save IPython command history to file: ' + \
1240 print 'Unable to save IPython command history to file: ' + \
1241 `self.histfile`
1241 `self.histfile`
1242
1242
1243 def history_saving_wrapper(self, func):
1243 def history_saving_wrapper(self, func):
1244 """ Wrap func for readline history saving
1244 """ Wrap func for readline history saving
1245
1245
1246 Convert func into callable that saves & restores
1246 Convert func into callable that saves & restores
1247 history around the call """
1247 history around the call """
1248
1248
1249 if not self.has_readline:
1249 if not self.has_readline:
1250 return func
1250 return func
1251
1251
1252 def wrapper():
1252 def wrapper():
1253 self.savehist()
1253 self.savehist()
1254 try:
1254 try:
1255 func()
1255 func()
1256 finally:
1256 finally:
1257 readline.read_history_file(self.histfile)
1257 readline.read_history_file(self.histfile)
1258 return wrapper
1258 return wrapper
1259
1259
1260
1260
1261 def pre_readline(self):
1261 def pre_readline(self):
1262 """readline hook to be used at the start of each line.
1262 """readline hook to be used at the start of each line.
1263
1263
1264 Currently it handles auto-indent only."""
1264 Currently it handles auto-indent only."""
1265
1265
1266 #debugx('self.indent_current_nsp','pre_readline:')
1266 #debugx('self.indent_current_nsp','pre_readline:')
1267 self.readline.insert_text(self.indent_current_str())
1267 self.readline.insert_text(self.indent_current_str())
1268
1268
1269 def init_readline(self):
1269 def init_readline(self):
1270 """Command history completion/saving/reloading."""
1270 """Command history completion/saving/reloading."""
1271
1271
1272 import IPython.rlineimpl as readline
1272 import IPython.rlineimpl as readline
1273 if not readline.have_readline:
1273 if not readline.have_readline:
1274 self.has_readline = 0
1274 self.has_readline = 0
1275 self.readline = None
1275 self.readline = None
1276 # no point in bugging windows users with this every time:
1276 # no point in bugging windows users with this every time:
1277 warn('Readline services not available on this platform.')
1277 warn('Readline services not available on this platform.')
1278 else:
1278 else:
1279 sys.modules['readline'] = readline
1279 sys.modules['readline'] = readline
1280 import atexit
1280 import atexit
1281 from IPython.completer import IPCompleter
1281 from IPython.completer import IPCompleter
1282 self.Completer = IPCompleter(self,
1282 self.Completer = IPCompleter(self,
1283 self.user_ns,
1283 self.user_ns,
1284 self.user_global_ns,
1284 self.user_global_ns,
1285 self.rc.readline_omit__names,
1285 self.rc.readline_omit__names,
1286 self.alias_table)
1286 self.alias_table)
1287 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1287 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1288 self.strdispatchers['complete_command'] = sdisp
1288 self.strdispatchers['complete_command'] = sdisp
1289 self.Completer.custom_completers = sdisp
1289 self.Completer.custom_completers = sdisp
1290 # Platform-specific configuration
1290 # Platform-specific configuration
1291 if os.name == 'nt':
1291 if os.name == 'nt':
1292 self.readline_startup_hook = readline.set_pre_input_hook
1292 self.readline_startup_hook = readline.set_pre_input_hook
1293 else:
1293 else:
1294 self.readline_startup_hook = readline.set_startup_hook
1294 self.readline_startup_hook = readline.set_startup_hook
1295
1295
1296 # Load user's initrc file (readline config)
1296 # Load user's initrc file (readline config)
1297 inputrc_name = os.environ.get('INPUTRC')
1297 inputrc_name = os.environ.get('INPUTRC')
1298 if inputrc_name is None:
1298 if inputrc_name is None:
1299 home_dir = get_home_dir()
1299 home_dir = get_home_dir()
1300 if home_dir is not None:
1300 if home_dir is not None:
1301 inputrc_name = os.path.join(home_dir,'.inputrc')
1301 inputrc_name = os.path.join(home_dir,'.inputrc')
1302 if os.path.isfile(inputrc_name):
1302 if os.path.isfile(inputrc_name):
1303 try:
1303 try:
1304 readline.read_init_file(inputrc_name)
1304 readline.read_init_file(inputrc_name)
1305 except:
1305 except:
1306 warn('Problems reading readline initialization file <%s>'
1306 warn('Problems reading readline initialization file <%s>'
1307 % inputrc_name)
1307 % inputrc_name)
1308
1308
1309 self.has_readline = 1
1309 self.has_readline = 1
1310 self.readline = readline
1310 self.readline = readline
1311 # save this in sys so embedded copies can restore it properly
1311 # save this in sys so embedded copies can restore it properly
1312 sys.ipcompleter = self.Completer.complete
1312 sys.ipcompleter = self.Completer.complete
1313 readline.set_completer(self.Completer.complete)
1313 readline.set_completer(self.Completer.complete)
1314
1314
1315 # Configure readline according to user's prefs
1315 # Configure readline according to user's prefs
1316 for rlcommand in self.rc.readline_parse_and_bind:
1316 for rlcommand in self.rc.readline_parse_and_bind:
1317 readline.parse_and_bind(rlcommand)
1317 readline.parse_and_bind(rlcommand)
1318
1318
1319 # remove some chars from the delimiters list
1319 # remove some chars from the delimiters list
1320 delims = readline.get_completer_delims()
1320 delims = readline.get_completer_delims()
1321 delims = delims.translate(string._idmap,
1321 delims = delims.translate(string._idmap,
1322 self.rc.readline_remove_delims)
1322 self.rc.readline_remove_delims)
1323 readline.set_completer_delims(delims)
1323 readline.set_completer_delims(delims)
1324 # otherwise we end up with a monster history after a while:
1324 # otherwise we end up with a monster history after a while:
1325 readline.set_history_length(1000)
1325 readline.set_history_length(1000)
1326 try:
1326 try:
1327 #print '*** Reading readline history' # dbg
1327 #print '*** Reading readline history' # dbg
1328 readline.read_history_file(self.histfile)
1328 readline.read_history_file(self.histfile)
1329 except IOError:
1329 except IOError:
1330 pass # It doesn't exist yet.
1330 pass # It doesn't exist yet.
1331
1331
1332 atexit.register(self.atexit_operations)
1332 atexit.register(self.atexit_operations)
1333 del atexit
1333 del atexit
1334
1334
1335 # Configure auto-indent for all platforms
1335 # Configure auto-indent for all platforms
1336 self.set_autoindent(self.rc.autoindent)
1336 self.set_autoindent(self.rc.autoindent)
1337
1337
1338 def ask_yes_no(self,prompt,default=True):
1338 def ask_yes_no(self,prompt,default=True):
1339 if self.rc.quiet:
1339 if self.rc.quiet:
1340 return True
1340 return True
1341 return ask_yes_no(prompt,default)
1341 return ask_yes_no(prompt,default)
1342
1342
1343 def _should_recompile(self,e):
1343 def _should_recompile(self,e):
1344 """Utility routine for edit_syntax_error"""
1344 """Utility routine for edit_syntax_error"""
1345
1345
1346 if e.filename in ('<ipython console>','<input>','<string>',
1346 if e.filename in ('<ipython console>','<input>','<string>',
1347 '<console>','<BackgroundJob compilation>',
1347 '<console>','<BackgroundJob compilation>',
1348 None):
1348 None):
1349
1349
1350 return False
1350 return False
1351 try:
1351 try:
1352 if (self.rc.autoedit_syntax and
1352 if (self.rc.autoedit_syntax and
1353 not self.ask_yes_no('Return to editor to correct syntax error? '
1353 not self.ask_yes_no('Return to editor to correct syntax error? '
1354 '[Y/n] ','y')):
1354 '[Y/n] ','y')):
1355 return False
1355 return False
1356 except EOFError:
1356 except EOFError:
1357 return False
1357 return False
1358
1358
1359 def int0(x):
1359 def int0(x):
1360 try:
1360 try:
1361 return int(x)
1361 return int(x)
1362 except TypeError:
1362 except TypeError:
1363 return 0
1363 return 0
1364 # always pass integer line and offset values to editor hook
1364 # always pass integer line and offset values to editor hook
1365 self.hooks.fix_error_editor(e.filename,
1365 self.hooks.fix_error_editor(e.filename,
1366 int0(e.lineno),int0(e.offset),e.msg)
1366 int0(e.lineno),int0(e.offset),e.msg)
1367 return True
1367 return True
1368
1368
1369 def edit_syntax_error(self):
1369 def edit_syntax_error(self):
1370 """The bottom half of the syntax error handler called in the main loop.
1370 """The bottom half of the syntax error handler called in the main loop.
1371
1371
1372 Loop until syntax error is fixed or user cancels.
1372 Loop until syntax error is fixed or user cancels.
1373 """
1373 """
1374
1374
1375 while self.SyntaxTB.last_syntax_error:
1375 while self.SyntaxTB.last_syntax_error:
1376 # copy and clear last_syntax_error
1376 # copy and clear last_syntax_error
1377 err = self.SyntaxTB.clear_err_state()
1377 err = self.SyntaxTB.clear_err_state()
1378 if not self._should_recompile(err):
1378 if not self._should_recompile(err):
1379 return
1379 return
1380 try:
1380 try:
1381 # may set last_syntax_error again if a SyntaxError is raised
1381 # may set last_syntax_error again if a SyntaxError is raised
1382 self.safe_execfile(err.filename,self.user_ns)
1382 self.safe_execfile(err.filename,self.user_ns)
1383 except:
1383 except:
1384 self.showtraceback()
1384 self.showtraceback()
1385 else:
1385 else:
1386 try:
1386 try:
1387 f = file(err.filename)
1387 f = file(err.filename)
1388 try:
1388 try:
1389 sys.displayhook(f.read())
1389 sys.displayhook(f.read())
1390 finally:
1390 finally:
1391 f.close()
1391 f.close()
1392 except:
1392 except:
1393 self.showtraceback()
1393 self.showtraceback()
1394
1394
1395 def showsyntaxerror(self, filename=None):
1395 def showsyntaxerror(self, filename=None):
1396 """Display the syntax error that just occurred.
1396 """Display the syntax error that just occurred.
1397
1397
1398 This doesn't display a stack trace because there isn't one.
1398 This doesn't display a stack trace because there isn't one.
1399
1399
1400 If a filename is given, it is stuffed in the exception instead
1400 If a filename is given, it is stuffed in the exception instead
1401 of what was there before (because Python's parser always uses
1401 of what was there before (because Python's parser always uses
1402 "<string>" when reading from a string).
1402 "<string>" when reading from a string).
1403 """
1403 """
1404 etype, value, last_traceback = sys.exc_info()
1404 etype, value, last_traceback = sys.exc_info()
1405
1405
1406 # See note about these variables in showtraceback() below
1406 # See note about these variables in showtraceback() below
1407 sys.last_type = etype
1407 sys.last_type = etype
1408 sys.last_value = value
1408 sys.last_value = value
1409 sys.last_traceback = last_traceback
1409 sys.last_traceback = last_traceback
1410
1410
1411 if filename and etype is SyntaxError:
1411 if filename and etype is SyntaxError:
1412 # Work hard to stuff the correct filename in the exception
1412 # Work hard to stuff the correct filename in the exception
1413 try:
1413 try:
1414 msg, (dummy_filename, lineno, offset, line) = value
1414 msg, (dummy_filename, lineno, offset, line) = value
1415 except:
1415 except:
1416 # Not the format we expect; leave it alone
1416 # Not the format we expect; leave it alone
1417 pass
1417 pass
1418 else:
1418 else:
1419 # Stuff in the right filename
1419 # Stuff in the right filename
1420 try:
1420 try:
1421 # Assume SyntaxError is a class exception
1421 # Assume SyntaxError is a class exception
1422 value = SyntaxError(msg, (filename, lineno, offset, line))
1422 value = SyntaxError(msg, (filename, lineno, offset, line))
1423 except:
1423 except:
1424 # If that failed, assume SyntaxError is a string
1424 # If that failed, assume SyntaxError is a string
1425 value = msg, (filename, lineno, offset, line)
1425 value = msg, (filename, lineno, offset, line)
1426 self.SyntaxTB(etype,value,[])
1426 self.SyntaxTB(etype,value,[])
1427
1427
1428 def debugger(self,force=False):
1428 def debugger(self,force=False):
1429 """Call the pydb/pdb debugger.
1429 """Call the pydb/pdb debugger.
1430
1430
1431 Keywords:
1431 Keywords:
1432
1432
1433 - force(False): by default, this routine checks the instance call_pdb
1433 - force(False): by default, this routine checks the instance call_pdb
1434 flag and does not actually invoke the debugger if the flag is false.
1434 flag and does not actually invoke the debugger if the flag is false.
1435 The 'force' option forces the debugger to activate even if the flag
1435 The 'force' option forces the debugger to activate even if the flag
1436 is false.
1436 is false.
1437 """
1437 """
1438
1438
1439 if not (force or self.call_pdb):
1439 if not (force or self.call_pdb):
1440 return
1440 return
1441
1441
1442 if not hasattr(sys,'last_traceback'):
1442 if not hasattr(sys,'last_traceback'):
1443 error('No traceback has been produced, nothing to debug.')
1443 error('No traceback has been produced, nothing to debug.')
1444 return
1444 return
1445
1445
1446 have_pydb = False
1446 have_pydb = False
1447 # use pydb if available
1447 # use pydb if available
1448 try:
1448 try:
1449 from pydb import pm
1449 from pydb import pm
1450 have_pydb = True
1450 have_pydb = True
1451 except ImportError:
1451 except ImportError:
1452 pass
1452 pass
1453 if not have_pydb:
1453 if not have_pydb:
1454 # fallback to our internal debugger
1454 # fallback to our internal debugger
1455 pm = lambda : self.InteractiveTB.debugger(force=True)
1455 pm = lambda : self.InteractiveTB.debugger(force=True)
1456 self.history_saving_wrapper(pm)()
1456 self.history_saving_wrapper(pm)()
1457
1457
1458 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1458 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1459 """Display the exception that just occurred.
1459 """Display the exception that just occurred.
1460
1460
1461 If nothing is known about the exception, this is the method which
1461 If nothing is known about the exception, this is the method which
1462 should be used throughout the code for presenting user tracebacks,
1462 should be used throughout the code for presenting user tracebacks,
1463 rather than directly invoking the InteractiveTB object.
1463 rather than directly invoking the InteractiveTB object.
1464
1464
1465 A specific showsyntaxerror() also exists, but this method can take
1465 A specific showsyntaxerror() also exists, but this method can take
1466 care of calling it if needed, so unless you are explicitly catching a
1466 care of calling it if needed, so unless you are explicitly catching a
1467 SyntaxError exception, don't try to analyze the stack manually and
1467 SyntaxError exception, don't try to analyze the stack manually and
1468 simply call this method."""
1468 simply call this method."""
1469
1469
1470 # Though this won't be called by syntax errors in the input line,
1470 # Though this won't be called by syntax errors in the input line,
1471 # there may be SyntaxError cases whith imported code.
1471 # there may be SyntaxError cases whith imported code.
1472 if exc_tuple is None:
1472 if exc_tuple is None:
1473 etype, value, tb = sys.exc_info()
1473 etype, value, tb = sys.exc_info()
1474 else:
1474 else:
1475 etype, value, tb = exc_tuple
1475 etype, value, tb = exc_tuple
1476
1476
1477 if etype is SyntaxError:
1477 if etype is SyntaxError:
1478 self.showsyntaxerror(filename)
1478 self.showsyntaxerror(filename)
1479 else:
1479 else:
1480 # WARNING: these variables are somewhat deprecated and not
1480 # WARNING: these variables are somewhat deprecated and not
1481 # necessarily safe to use in a threaded environment, but tools
1481 # necessarily safe to use in a threaded environment, but tools
1482 # like pdb depend on their existence, so let's set them. If we
1482 # like pdb depend on their existence, so let's set them. If we
1483 # find problems in the field, we'll need to revisit their use.
1483 # find problems in the field, we'll need to revisit their use.
1484 sys.last_type = etype
1484 sys.last_type = etype
1485 sys.last_value = value
1485 sys.last_value = value
1486 sys.last_traceback = tb
1486 sys.last_traceback = tb
1487
1487
1488 if etype in self.custom_exceptions:
1488 if etype in self.custom_exceptions:
1489 self.CustomTB(etype,value,tb)
1489 self.CustomTB(etype,value,tb)
1490 else:
1490 else:
1491 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1491 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1492 if self.InteractiveTB.call_pdb and self.has_readline:
1492 if self.InteractiveTB.call_pdb and self.has_readline:
1493 # pdb mucks up readline, fix it back
1493 # pdb mucks up readline, fix it back
1494 self.readline.set_completer(self.Completer.complete)
1494 self.readline.set_completer(self.Completer.complete)
1495
1495
1496 def mainloop(self,banner=None):
1496 def mainloop(self,banner=None):
1497 """Creates the local namespace and starts the mainloop.
1497 """Creates the local namespace and starts the mainloop.
1498
1498
1499 If an optional banner argument is given, it will override the
1499 If an optional banner argument is given, it will override the
1500 internally created default banner."""
1500 internally created default banner."""
1501
1501
1502 if self.rc.c: # Emulate Python's -c option
1502 if self.rc.c: # Emulate Python's -c option
1503 self.exec_init_cmd()
1503 self.exec_init_cmd()
1504 if banner is None:
1504 if banner is None:
1505 if not self.rc.banner:
1505 if not self.rc.banner:
1506 banner = ''
1506 banner = ''
1507 # banner is string? Use it directly!
1507 # banner is string? Use it directly!
1508 elif isinstance(self.rc.banner,basestring):
1508 elif isinstance(self.rc.banner,basestring):
1509 banner = self.rc.banner
1509 banner = self.rc.banner
1510 else:
1510 else:
1511 banner = self.BANNER+self.banner2
1511 banner = self.BANNER+self.banner2
1512
1512
1513 self.interact(banner)
1513 self.interact(banner)
1514
1514
1515 def exec_init_cmd(self):
1515 def exec_init_cmd(self):
1516 """Execute a command given at the command line.
1516 """Execute a command given at the command line.
1517
1517
1518 This emulates Python's -c option."""
1518 This emulates Python's -c option."""
1519
1519
1520 #sys.argv = ['-c']
1520 #sys.argv = ['-c']
1521 self.push(self.rc.c)
1521 self.push(self.rc.c)
1522
1522
1523 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1523 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1524 """Embeds IPython into a running python program.
1524 """Embeds IPython into a running python program.
1525
1525
1526 Input:
1526 Input:
1527
1527
1528 - header: An optional header message can be specified.
1528 - header: An optional header message can be specified.
1529
1529
1530 - local_ns, global_ns: working namespaces. If given as None, the
1530 - local_ns, global_ns: working namespaces. If given as None, the
1531 IPython-initialized one is updated with __main__.__dict__, so that
1531 IPython-initialized one is updated with __main__.__dict__, so that
1532 program variables become visible but user-specific configuration
1532 program variables become visible but user-specific configuration
1533 remains possible.
1533 remains possible.
1534
1534
1535 - stack_depth: specifies how many levels in the stack to go to
1535 - stack_depth: specifies how many levels in the stack to go to
1536 looking for namespaces (when local_ns and global_ns are None). This
1536 looking for namespaces (when local_ns and global_ns are None). This
1537 allows an intermediate caller to make sure that this function gets
1537 allows an intermediate caller to make sure that this function gets
1538 the namespace from the intended level in the stack. By default (0)
1538 the namespace from the intended level in the stack. By default (0)
1539 it will get its locals and globals from the immediate caller.
1539 it will get its locals and globals from the immediate caller.
1540
1540
1541 Warning: it's possible to use this in a program which is being run by
1541 Warning: it's possible to use this in a program which is being run by
1542 IPython itself (via %run), but some funny things will happen (a few
1542 IPython itself (via %run), but some funny things will happen (a few
1543 globals get overwritten). In the future this will be cleaned up, as
1543 globals get overwritten). In the future this will be cleaned up, as
1544 there is no fundamental reason why it can't work perfectly."""
1544 there is no fundamental reason why it can't work perfectly."""
1545
1545
1546 # Get locals and globals from caller
1546 # Get locals and globals from caller
1547 if local_ns is None or global_ns is None:
1547 if local_ns is None or global_ns is None:
1548 call_frame = sys._getframe(stack_depth).f_back
1548 call_frame = sys._getframe(stack_depth).f_back
1549
1549
1550 if local_ns is None:
1550 if local_ns is None:
1551 local_ns = call_frame.f_locals
1551 local_ns = call_frame.f_locals
1552 if global_ns is None:
1552 if global_ns is None:
1553 global_ns = call_frame.f_globals
1553 global_ns = call_frame.f_globals
1554
1554
1555 # Update namespaces and fire up interpreter
1555 # Update namespaces and fire up interpreter
1556
1556
1557 # The global one is easy, we can just throw it in
1557 # The global one is easy, we can just throw it in
1558 self.user_global_ns = global_ns
1558 self.user_global_ns = global_ns
1559
1559
1560 # but the user/local one is tricky: ipython needs it to store internal
1560 # but the user/local one is tricky: ipython needs it to store internal
1561 # data, but we also need the locals. We'll copy locals in the user
1561 # data, but we also need the locals. We'll copy locals in the user
1562 # one, but will track what got copied so we can delete them at exit.
1562 # one, but will track what got copied so we can delete them at exit.
1563 # This is so that a later embedded call doesn't see locals from a
1563 # This is so that a later embedded call doesn't see locals from a
1564 # previous call (which most likely existed in a separate scope).
1564 # previous call (which most likely existed in a separate scope).
1565 local_varnames = local_ns.keys()
1565 local_varnames = local_ns.keys()
1566 self.user_ns.update(local_ns)
1566 self.user_ns.update(local_ns)
1567
1567
1568 # Patch for global embedding to make sure that things don't overwrite
1568 # Patch for global embedding to make sure that things don't overwrite
1569 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1569 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1570 # FIXME. Test this a bit more carefully (the if.. is new)
1570 # FIXME. Test this a bit more carefully (the if.. is new)
1571 if local_ns is None and global_ns is None:
1571 if local_ns is None and global_ns is None:
1572 self.user_global_ns.update(__main__.__dict__)
1572 self.user_global_ns.update(__main__.__dict__)
1573
1573
1574 # make sure the tab-completer has the correct frame information, so it
1574 # make sure the tab-completer has the correct frame information, so it
1575 # actually completes using the frame's locals/globals
1575 # actually completes using the frame's locals/globals
1576 self.set_completer_frame()
1576 self.set_completer_frame()
1577
1577
1578 # before activating the interactive mode, we need to make sure that
1578 # before activating the interactive mode, we need to make sure that
1579 # all names in the builtin namespace needed by ipython point to
1579 # all names in the builtin namespace needed by ipython point to
1580 # ourselves, and not to other instances.
1580 # ourselves, and not to other instances.
1581 self.add_builtins()
1581 self.add_builtins()
1582
1582
1583 self.interact(header)
1583 self.interact(header)
1584
1584
1585 # now, purge out the user namespace from anything we might have added
1585 # now, purge out the user namespace from anything we might have added
1586 # from the caller's local namespace
1586 # from the caller's local namespace
1587 delvar = self.user_ns.pop
1587 delvar = self.user_ns.pop
1588 for var in local_varnames:
1588 for var in local_varnames:
1589 delvar(var,None)
1589 delvar(var,None)
1590 # and clean builtins we may have overridden
1590 # and clean builtins we may have overridden
1591 self.clean_builtins()
1591 self.clean_builtins()
1592
1592
1593 def interact(self, banner=None):
1593 def interact(self, banner=None):
1594 """Closely emulate the interactive Python console.
1594 """Closely emulate the interactive Python console.
1595
1595
1596 The optional banner argument specify the banner to print
1596 The optional banner argument specify the banner to print
1597 before the first interaction; by default it prints a banner
1597 before the first interaction; by default it prints a banner
1598 similar to the one printed by the real Python interpreter,
1598 similar to the one printed by the real Python interpreter,
1599 followed by the current class name in parentheses (so as not
1599 followed by the current class name in parentheses (so as not
1600 to confuse this with the real interpreter -- since it's so
1600 to confuse this with the real interpreter -- since it's so
1601 close!).
1601 close!).
1602
1602
1603 """
1603 """
1604
1604
1605 if self.exit_now:
1605 if self.exit_now:
1606 # batch run -> do not interact
1606 # batch run -> do not interact
1607 return
1607 return
1608 cprt = 'Type "copyright", "credits" or "license" for more information.'
1608 cprt = 'Type "copyright", "credits" or "license" for more information.'
1609 if banner is None:
1609 if banner is None:
1610 self.write("Python %s on %s\n%s\n(%s)\n" %
1610 self.write("Python %s on %s\n%s\n(%s)\n" %
1611 (sys.version, sys.platform, cprt,
1611 (sys.version, sys.platform, cprt,
1612 self.__class__.__name__))
1612 self.__class__.__name__))
1613 else:
1613 else:
1614 self.write(banner)
1614 self.write(banner)
1615
1615
1616 more = 0
1616 more = 0
1617
1617
1618 # Mark activity in the builtins
1618 # Mark activity in the builtins
1619 __builtin__.__dict__['__IPYTHON__active'] += 1
1619 __builtin__.__dict__['__IPYTHON__active'] += 1
1620
1620
1621 # exit_now is set by a call to %Exit or %Quit
1621 # exit_now is set by a call to %Exit or %Quit
1622 while not self.exit_now:
1622 while not self.exit_now:
1623 if more:
1623 if more:
1624 prompt = self.hooks.generate_prompt(True)
1624 prompt = self.hooks.generate_prompt(True)
1625 if self.autoindent:
1625 if self.autoindent:
1626 self.readline_startup_hook(self.pre_readline)
1626 self.readline_startup_hook(self.pre_readline)
1627 else:
1627 else:
1628 prompt = self.hooks.generate_prompt(False)
1628 prompt = self.hooks.generate_prompt(False)
1629 try:
1629 try:
1630 line = self.raw_input(prompt,more)
1630 line = self.raw_input(prompt,more)
1631 if self.exit_now:
1631 if self.exit_now:
1632 # quick exit on sys.std[in|out] close
1632 # quick exit on sys.std[in|out] close
1633 break
1633 break
1634 if self.autoindent:
1634 if self.autoindent:
1635 self.readline_startup_hook(None)
1635 self.readline_startup_hook(None)
1636 except KeyboardInterrupt:
1636 except KeyboardInterrupt:
1637 self.write('\nKeyboardInterrupt\n')
1637 self.write('\nKeyboardInterrupt\n')
1638 self.resetbuffer()
1638 self.resetbuffer()
1639 # keep cache in sync with the prompt counter:
1639 # keep cache in sync with the prompt counter:
1640 self.outputcache.prompt_count -= 1
1640 self.outputcache.prompt_count -= 1
1641
1641
1642 if self.autoindent:
1642 if self.autoindent:
1643 self.indent_current_nsp = 0
1643 self.indent_current_nsp = 0
1644 more = 0
1644 more = 0
1645 except EOFError:
1645 except EOFError:
1646 if self.autoindent:
1646 if self.autoindent:
1647 self.readline_startup_hook(None)
1647 self.readline_startup_hook(None)
1648 self.write('\n')
1648 self.write('\n')
1649 self.exit()
1649 self.exit()
1650 except bdb.BdbQuit:
1650 except bdb.BdbQuit:
1651 warn('The Python debugger has exited with a BdbQuit exception.\n'
1651 warn('The Python debugger has exited with a BdbQuit exception.\n'
1652 'Because of how pdb handles the stack, it is impossible\n'
1652 'Because of how pdb handles the stack, it is impossible\n'
1653 'for IPython to properly format this particular exception.\n'
1653 'for IPython to properly format this particular exception.\n'
1654 'IPython will resume normal operation.')
1654 'IPython will resume normal operation.')
1655 except:
1655 except:
1656 # exceptions here are VERY RARE, but they can be triggered
1656 # exceptions here are VERY RARE, but they can be triggered
1657 # asynchronously by signal handlers, for example.
1657 # asynchronously by signal handlers, for example.
1658 self.showtraceback()
1658 self.showtraceback()
1659 else:
1659 else:
1660 more = self.push(line)
1660 more = self.push(line)
1661 if (self.SyntaxTB.last_syntax_error and
1661 if (self.SyntaxTB.last_syntax_error and
1662 self.rc.autoedit_syntax):
1662 self.rc.autoedit_syntax):
1663 self.edit_syntax_error()
1663 self.edit_syntax_error()
1664
1664
1665 # We are off again...
1665 # We are off again...
1666 __builtin__.__dict__['__IPYTHON__active'] -= 1
1666 __builtin__.__dict__['__IPYTHON__active'] -= 1
1667
1667
1668 def excepthook(self, etype, value, tb):
1668 def excepthook(self, etype, value, tb):
1669 """One more defense for GUI apps that call sys.excepthook.
1669 """One more defense for GUI apps that call sys.excepthook.
1670
1670
1671 GUI frameworks like wxPython trap exceptions and call
1671 GUI frameworks like wxPython trap exceptions and call
1672 sys.excepthook themselves. I guess this is a feature that
1672 sys.excepthook themselves. I guess this is a feature that
1673 enables them to keep running after exceptions that would
1673 enables them to keep running after exceptions that would
1674 otherwise kill their mainloop. This is a bother for IPython
1674 otherwise kill their mainloop. This is a bother for IPython
1675 which excepts to catch all of the program exceptions with a try:
1675 which excepts to catch all of the program exceptions with a try:
1676 except: statement.
1676 except: statement.
1677
1677
1678 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1678 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1679 any app directly invokes sys.excepthook, it will look to the user like
1679 any app directly invokes sys.excepthook, it will look to the user like
1680 IPython crashed. In order to work around this, we can disable the
1680 IPython crashed. In order to work around this, we can disable the
1681 CrashHandler and replace it with this excepthook instead, which prints a
1681 CrashHandler and replace it with this excepthook instead, which prints a
1682 regular traceback using our InteractiveTB. In this fashion, apps which
1682 regular traceback using our InteractiveTB. In this fashion, apps which
1683 call sys.excepthook will generate a regular-looking exception from
1683 call sys.excepthook will generate a regular-looking exception from
1684 IPython, and the CrashHandler will only be triggered by real IPython
1684 IPython, and the CrashHandler will only be triggered by real IPython
1685 crashes.
1685 crashes.
1686
1686
1687 This hook should be used sparingly, only in places which are not likely
1687 This hook should be used sparingly, only in places which are not likely
1688 to be true IPython errors.
1688 to be true IPython errors.
1689 """
1689 """
1690 self.showtraceback((etype,value,tb),tb_offset=0)
1690 self.showtraceback((etype,value,tb),tb_offset=0)
1691
1691
1692 def expand_aliases(self,fn,rest):
1692 def expand_aliases(self,fn,rest):
1693 """ Expand multiple levels of aliases:
1693 """ Expand multiple levels of aliases:
1694
1694
1695 if:
1695 if:
1696
1696
1697 alias foo bar /tmp
1697 alias foo bar /tmp
1698 alias baz foo
1698 alias baz foo
1699
1699
1700 then:
1700 then:
1701
1701
1702 baz huhhahhei -> bar /tmp huhhahhei
1702 baz huhhahhei -> bar /tmp huhhahhei
1703
1703
1704 """
1704 """
1705 line = fn + " " + rest
1705 line = fn + " " + rest
1706
1706
1707 done = Set()
1707 done = Set()
1708 while 1:
1708 while 1:
1709 pre,fn,rest = self.split_user_input(line, pattern = self.shell_line_split)
1709 pre,fn,rest = self.split_user_input(line, pattern = self.shell_line_split)
1710 # print "!",fn,"!",rest # dbg
1710 # print "!",fn,"!",rest # dbg
1711 if fn in self.alias_table:
1711 if fn in self.alias_table:
1712 if fn in done:
1712 if fn in done:
1713 warn("Cyclic alias definition, repeated '%s'" % fn)
1713 warn("Cyclic alias definition, repeated '%s'" % fn)
1714 return ""
1714 return ""
1715 done.add(fn)
1715 done.add(fn)
1716
1716
1717 l2 = self.transform_alias(fn,rest)
1717 l2 = self.transform_alias(fn,rest)
1718 # dir -> dir
1718 # dir -> dir
1719 # print "alias",line, "->",l2 #dbg
1719 # print "alias",line, "->",l2 #dbg
1720 if l2 == line:
1720 if l2 == line:
1721 break
1721 break
1722 # ls -> ls -F should not recurse forever
1722 # ls -> ls -F should not recurse forever
1723 if l2.split(None,1)[0] == line.split(None,1)[0]:
1723 if l2.split(None,1)[0] == line.split(None,1)[0]:
1724 line = l2
1724 line = l2
1725 break
1725 break
1726
1726
1727 line=l2
1727 line=l2
1728
1728
1729
1729
1730 # print "al expand to",line #dbg
1730 # print "al expand to",line #dbg
1731 else:
1731 else:
1732 break
1732 break
1733
1733
1734 return line
1734 return line
1735
1735
1736 def transform_alias(self, alias,rest=''):
1736 def transform_alias(self, alias,rest=''):
1737 """ Transform alias to system command string.
1737 """ Transform alias to system command string.
1738 """
1738 """
1739 nargs,cmd = self.alias_table[alias]
1739 nargs,cmd = self.alias_table[alias]
1740 if ' ' in cmd and os.path.isfile(cmd):
1740 if ' ' in cmd and os.path.isfile(cmd):
1741 cmd = '"%s"' % cmd
1741 cmd = '"%s"' % cmd
1742
1742
1743 # Expand the %l special to be the user's input line
1743 # Expand the %l special to be the user's input line
1744 if cmd.find('%l') >= 0:
1744 if cmd.find('%l') >= 0:
1745 cmd = cmd.replace('%l',rest)
1745 cmd = cmd.replace('%l',rest)
1746 rest = ''
1746 rest = ''
1747 if nargs==0:
1747 if nargs==0:
1748 # Simple, argument-less aliases
1748 # Simple, argument-less aliases
1749 cmd = '%s %s' % (cmd,rest)
1749 cmd = '%s %s' % (cmd,rest)
1750 else:
1750 else:
1751 # Handle aliases with positional arguments
1751 # Handle aliases with positional arguments
1752 args = rest.split(None,nargs)
1752 args = rest.split(None,nargs)
1753 if len(args)< nargs:
1753 if len(args)< nargs:
1754 error('Alias <%s> requires %s arguments, %s given.' %
1754 error('Alias <%s> requires %s arguments, %s given.' %
1755 (alias,nargs,len(args)))
1755 (alias,nargs,len(args)))
1756 return None
1756 return None
1757 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1757 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1758 # Now call the macro, evaluating in the user's namespace
1758 # Now call the macro, evaluating in the user's namespace
1759 #print 'new command: <%r>' % cmd # dbg
1759 #print 'new command: <%r>' % cmd # dbg
1760 return cmd
1760 return cmd
1761
1761
1762 def call_alias(self,alias,rest=''):
1762 def call_alias(self,alias,rest=''):
1763 """Call an alias given its name and the rest of the line.
1763 """Call an alias given its name and the rest of the line.
1764
1764
1765 This is only used to provide backwards compatibility for users of
1765 This is only used to provide backwards compatibility for users of
1766 ipalias(), use of which is not recommended for anymore."""
1766 ipalias(), use of which is not recommended for anymore."""
1767
1767
1768 # Now call the macro, evaluating in the user's namespace
1768 # Now call the macro, evaluating in the user's namespace
1769 cmd = self.transform_alias(alias, rest)
1769 cmd = self.transform_alias(alias, rest)
1770 try:
1770 try:
1771 self.system(cmd)
1771 self.system(cmd)
1772 except:
1772 except:
1773 self.showtraceback()
1773 self.showtraceback()
1774
1774
1775 def indent_current_str(self):
1775 def indent_current_str(self):
1776 """return the current level of indentation as a string"""
1776 """return the current level of indentation as a string"""
1777 return self.indent_current_nsp * ' '
1777 return self.indent_current_nsp * ' '
1778
1778
1779 def autoindent_update(self,line):
1779 def autoindent_update(self,line):
1780 """Keep track of the indent level."""
1780 """Keep track of the indent level."""
1781
1781
1782 #debugx('line')
1782 #debugx('line')
1783 #debugx('self.indent_current_nsp')
1783 #debugx('self.indent_current_nsp')
1784 if self.autoindent:
1784 if self.autoindent:
1785 if line:
1785 if line:
1786 inisp = num_ini_spaces(line)
1786 inisp = num_ini_spaces(line)
1787 if inisp < self.indent_current_nsp:
1787 if inisp < self.indent_current_nsp:
1788 self.indent_current_nsp = inisp
1788 self.indent_current_nsp = inisp
1789
1789
1790 if line[-1] == ':':
1790 if line[-1] == ':':
1791 self.indent_current_nsp += 4
1791 self.indent_current_nsp += 4
1792 elif dedent_re.match(line):
1792 elif dedent_re.match(line):
1793 self.indent_current_nsp -= 4
1793 self.indent_current_nsp -= 4
1794 else:
1794 else:
1795 self.indent_current_nsp = 0
1795 self.indent_current_nsp = 0
1796
1796
1797 def runlines(self,lines):
1797 def runlines(self,lines):
1798 """Run a string of one or more lines of source.
1798 """Run a string of one or more lines of source.
1799
1799
1800 This method is capable of running a string containing multiple source
1800 This method is capable of running a string containing multiple source
1801 lines, as if they had been entered at the IPython prompt. Since it
1801 lines, as if they had been entered at the IPython prompt. Since it
1802 exposes IPython's processing machinery, the given strings can contain
1802 exposes IPython's processing machinery, the given strings can contain
1803 magic calls (%magic), special shell access (!cmd), etc."""
1803 magic calls (%magic), special shell access (!cmd), etc."""
1804
1804
1805 # We must start with a clean buffer, in case this is run from an
1805 # We must start with a clean buffer, in case this is run from an
1806 # interactive IPython session (via a magic, for example).
1806 # interactive IPython session (via a magic, for example).
1807 self.resetbuffer()
1807 self.resetbuffer()
1808 lines = lines.split('\n')
1808 lines = lines.split('\n')
1809 more = 0
1809 more = 0
1810 for line in lines:
1810 for line in lines:
1811 # skip blank lines so we don't mess up the prompt counter, but do
1811 # skip blank lines so we don't mess up the prompt counter, but do
1812 # NOT skip even a blank line if we are in a code block (more is
1812 # NOT skip even a blank line if we are in a code block (more is
1813 # true)
1813 # true)
1814 if line or more:
1814 if line or more:
1815 more = self.push(self.prefilter(line,more))
1815 more = self.push(self.prefilter(line,more))
1816 # IPython's runsource returns None if there was an error
1816 # IPython's runsource returns None if there was an error
1817 # compiling the code. This allows us to stop processing right
1817 # compiling the code. This allows us to stop processing right
1818 # away, so the user gets the error message at the right place.
1818 # away, so the user gets the error message at the right place.
1819 if more is None:
1819 if more is None:
1820 break
1820 break
1821 # final newline in case the input didn't have it, so that the code
1821 # final newline in case the input didn't have it, so that the code
1822 # actually does get executed
1822 # actually does get executed
1823 if more:
1823 if more:
1824 self.push('\n')
1824 self.push('\n')
1825
1825
1826 def runsource(self, source, filename='<input>', symbol='single'):
1826 def runsource(self, source, filename='<input>', symbol='single'):
1827 """Compile and run some source in the interpreter.
1827 """Compile and run some source in the interpreter.
1828
1828
1829 Arguments are as for compile_command().
1829 Arguments are as for compile_command().
1830
1830
1831 One several things can happen:
1831 One several things can happen:
1832
1832
1833 1) The input is incorrect; compile_command() raised an
1833 1) The input is incorrect; compile_command() raised an
1834 exception (SyntaxError or OverflowError). A syntax traceback
1834 exception (SyntaxError or OverflowError). A syntax traceback
1835 will be printed by calling the showsyntaxerror() method.
1835 will be printed by calling the showsyntaxerror() method.
1836
1836
1837 2) The input is incomplete, and more input is required;
1837 2) The input is incomplete, and more input is required;
1838 compile_command() returned None. Nothing happens.
1838 compile_command() returned None. Nothing happens.
1839
1839
1840 3) The input is complete; compile_command() returned a code
1840 3) The input is complete; compile_command() returned a code
1841 object. The code is executed by calling self.runcode() (which
1841 object. The code is executed by calling self.runcode() (which
1842 also handles run-time exceptions, except for SystemExit).
1842 also handles run-time exceptions, except for SystemExit).
1843
1843
1844 The return value is:
1844 The return value is:
1845
1845
1846 - True in case 2
1846 - True in case 2
1847
1847
1848 - False in the other cases, unless an exception is raised, where
1848 - False in the other cases, unless an exception is raised, where
1849 None is returned instead. This can be used by external callers to
1849 None is returned instead. This can be used by external callers to
1850 know whether to continue feeding input or not.
1850 know whether to continue feeding input or not.
1851
1851
1852 The return value can be used to decide whether to use sys.ps1 or
1852 The return value can be used to decide whether to use sys.ps1 or
1853 sys.ps2 to prompt the next line."""
1853 sys.ps2 to prompt the next line."""
1854
1854
1855 # if the source code has leading blanks, add 'if 1:\n' to it
1855 # if the source code has leading blanks, add 'if 1:\n' to it
1856 # this allows execution of indented pasted code. It is tempting
1856 # this allows execution of indented pasted code. It is tempting
1857 # to add '\n' at the end of source to run commands like ' a=1'
1857 # to add '\n' at the end of source to run commands like ' a=1'
1858 # directly, but this fails for more complicated scenarios
1858 # directly, but this fails for more complicated scenarios
1859 if source[:1] in [' ', '\t']:
1859 if source[:1] in [' ', '\t']:
1860 source = 'if 1:\n%s' % source
1860 source = 'if 1:\n%s' % source
1861
1861
1862 try:
1862 try:
1863 code = self.compile(source,filename,symbol)
1863 code = self.compile(source,filename,symbol)
1864 except (OverflowError, SyntaxError, ValueError):
1864 except (OverflowError, SyntaxError, ValueError):
1865 # Case 1
1865 # Case 1
1866 self.showsyntaxerror(filename)
1866 self.showsyntaxerror(filename)
1867 return None
1867 return None
1868
1868
1869 if code is None:
1869 if code is None:
1870 # Case 2
1870 # Case 2
1871 return True
1871 return True
1872
1872
1873 # Case 3
1873 # Case 3
1874 # We store the code object so that threaded shells and
1874 # We store the code object so that threaded shells and
1875 # custom exception handlers can access all this info if needed.
1875 # custom exception handlers can access all this info if needed.
1876 # The source corresponding to this can be obtained from the
1876 # The source corresponding to this can be obtained from the
1877 # buffer attribute as '\n'.join(self.buffer).
1877 # buffer attribute as '\n'.join(self.buffer).
1878 self.code_to_run = code
1878 self.code_to_run = code
1879 # now actually execute the code object
1879 # now actually execute the code object
1880 if self.runcode(code) == 0:
1880 if self.runcode(code) == 0:
1881 return False
1881 return False
1882 else:
1882 else:
1883 return None
1883 return None
1884
1884
1885 def runcode(self,code_obj):
1885 def runcode(self,code_obj):
1886 """Execute a code object.
1886 """Execute a code object.
1887
1887
1888 When an exception occurs, self.showtraceback() is called to display a
1888 When an exception occurs, self.showtraceback() is called to display a
1889 traceback.
1889 traceback.
1890
1890
1891 Return value: a flag indicating whether the code to be run completed
1891 Return value: a flag indicating whether the code to be run completed
1892 successfully:
1892 successfully:
1893
1893
1894 - 0: successful execution.
1894 - 0: successful execution.
1895 - 1: an error occurred.
1895 - 1: an error occurred.
1896 """
1896 """
1897
1897
1898 # Set our own excepthook in case the user code tries to call it
1898 # Set our own excepthook in case the user code tries to call it
1899 # directly, so that the IPython crash handler doesn't get triggered
1899 # directly, so that the IPython crash handler doesn't get triggered
1900 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1900 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1901
1901
1902 # we save the original sys.excepthook in the instance, in case config
1902 # we save the original sys.excepthook in the instance, in case config
1903 # code (such as magics) needs access to it.
1903 # code (such as magics) needs access to it.
1904 self.sys_excepthook = old_excepthook
1904 self.sys_excepthook = old_excepthook
1905 outflag = 1 # happens in more places, so it's easier as default
1905 outflag = 1 # happens in more places, so it's easier as default
1906 try:
1906 try:
1907 try:
1907 try:
1908 # Embedded instances require separate global/local namespaces
1908 # Embedded instances require separate global/local namespaces
1909 # so they can see both the surrounding (local) namespace and
1909 # so they can see both the surrounding (local) namespace and
1910 # the module-level globals when called inside another function.
1910 # the module-level globals when called inside another function.
1911 if self.embedded:
1911 if self.embedded:
1912 exec code_obj in self.user_global_ns, self.user_ns
1912 exec code_obj in self.user_global_ns, self.user_ns
1913 # Normal (non-embedded) instances should only have a single
1913 # Normal (non-embedded) instances should only have a single
1914 # namespace for user code execution, otherwise functions won't
1914 # namespace for user code execution, otherwise functions won't
1915 # see interactive top-level globals.
1915 # see interactive top-level globals.
1916 else:
1916 else:
1917 exec code_obj in self.user_ns
1917 exec code_obj in self.user_ns
1918 finally:
1918 finally:
1919 # Reset our crash handler in place
1919 # Reset our crash handler in place
1920 sys.excepthook = old_excepthook
1920 sys.excepthook = old_excepthook
1921 except SystemExit:
1921 except SystemExit:
1922 self.resetbuffer()
1922 self.resetbuffer()
1923 self.showtraceback()
1923 self.showtraceback()
1924 warn("Type %exit or %quit to exit IPython "
1924 warn("Type %exit or %quit to exit IPython "
1925 "(%Exit or %Quit do so unconditionally).",level=1)
1925 "(%Exit or %Quit do so unconditionally).",level=1)
1926 except self.custom_exceptions:
1926 except self.custom_exceptions:
1927 etype,value,tb = sys.exc_info()
1927 etype,value,tb = sys.exc_info()
1928 self.CustomTB(etype,value,tb)
1928 self.CustomTB(etype,value,tb)
1929 except:
1929 except:
1930 self.showtraceback()
1930 self.showtraceback()
1931 else:
1931 else:
1932 outflag = 0
1932 outflag = 0
1933 if softspace(sys.stdout, 0):
1933 if softspace(sys.stdout, 0):
1934 print
1934 print
1935 # Flush out code object which has been run (and source)
1935 # Flush out code object which has been run (and source)
1936 self.code_to_run = None
1936 self.code_to_run = None
1937 return outflag
1937 return outflag
1938
1938
1939 def push(self, line):
1939 def push(self, line):
1940 """Push a line to the interpreter.
1940 """Push a line to the interpreter.
1941
1941
1942 The line should not have a trailing newline; it may have
1942 The line should not have a trailing newline; it may have
1943 internal newlines. The line is appended to a buffer and the
1943 internal newlines. The line is appended to a buffer and the
1944 interpreter's runsource() method is called with the
1944 interpreter's runsource() method is called with the
1945 concatenated contents of the buffer as source. If this
1945 concatenated contents of the buffer as source. If this
1946 indicates that the command was executed or invalid, the buffer
1946 indicates that the command was executed or invalid, the buffer
1947 is reset; otherwise, the command is incomplete, and the buffer
1947 is reset; otherwise, the command is incomplete, and the buffer
1948 is left as it was after the line was appended. The return
1948 is left as it was after the line was appended. The return
1949 value is 1 if more input is required, 0 if the line was dealt
1949 value is 1 if more input is required, 0 if the line was dealt
1950 with in some way (this is the same as runsource()).
1950 with in some way (this is the same as runsource()).
1951 """
1951 """
1952
1952
1953 # autoindent management should be done here, and not in the
1953 # autoindent management should be done here, and not in the
1954 # interactive loop, since that one is only seen by keyboard input. We
1954 # interactive loop, since that one is only seen by keyboard input. We
1955 # need this done correctly even for code run via runlines (which uses
1955 # need this done correctly even for code run via runlines (which uses
1956 # push).
1956 # push).
1957
1957
1958 #print 'push line: <%s>' % line # dbg
1958 #print 'push line: <%s>' % line # dbg
1959 for subline in line.splitlines():
1959 for subline in line.splitlines():
1960 self.autoindent_update(subline)
1960 self.autoindent_update(subline)
1961 self.buffer.append(line)
1961 self.buffer.append(line)
1962 more = self.runsource('\n'.join(self.buffer), self.filename)
1962 more = self.runsource('\n'.join(self.buffer), self.filename)
1963 if not more:
1963 if not more:
1964 self.resetbuffer()
1964 self.resetbuffer()
1965 return more
1965 return more
1966
1966
1967 def resetbuffer(self):
1967 def resetbuffer(self):
1968 """Reset the input buffer."""
1968 """Reset the input buffer."""
1969 self.buffer[:] = []
1969 self.buffer[:] = []
1970
1970
1971 def raw_input(self,prompt='',continue_prompt=False):
1971 def raw_input(self,prompt='',continue_prompt=False):
1972 """Write a prompt and read a line.
1972 """Write a prompt and read a line.
1973
1973
1974 The returned line does not include the trailing newline.
1974 The returned line does not include the trailing newline.
1975 When the user enters the EOF key sequence, EOFError is raised.
1975 When the user enters the EOF key sequence, EOFError is raised.
1976
1976
1977 Optional inputs:
1977 Optional inputs:
1978
1978
1979 - prompt(''): a string to be printed to prompt the user.
1979 - prompt(''): a string to be printed to prompt the user.
1980
1980
1981 - continue_prompt(False): whether this line is the first one or a
1981 - continue_prompt(False): whether this line is the first one or a
1982 continuation in a sequence of inputs.
1982 continuation in a sequence of inputs.
1983 """
1983 """
1984
1984
1985 try:
1985 try:
1986 line = raw_input_original(prompt).decode(sys.stdin.encoding)
1986 line = raw_input_original(prompt).decode(sys.stdin.encoding)
1987 #line = raw_input_original(prompt)
1987 except ValueError:
1988 except ValueError:
1988 warn("\n********\nYou or a %run:ed script called sys.stdin.close() or sys.stdout.close()!\nExiting IPython!")
1989 warn("\n********\nYou or a %run:ed script called sys.stdin.close() or sys.stdout.close()!\nExiting IPython!")
1989 self.exit_now = True
1990 self.exit_now = True
1990 return ""
1991 return ""
1991
1992
1992
1993
1993 # Try to be reasonably smart about not re-indenting pasted input more
1994 # Try to be reasonably smart about not re-indenting pasted input more
1994 # than necessary. We do this by trimming out the auto-indent initial
1995 # than necessary. We do this by trimming out the auto-indent initial
1995 # spaces, if the user's actual input started itself with whitespace.
1996 # spaces, if the user's actual input started itself with whitespace.
1996 #debugx('self.buffer[-1]')
1997 #debugx('self.buffer[-1]')
1997
1998
1998 if self.autoindent:
1999 if self.autoindent:
1999 if num_ini_spaces(line) > self.indent_current_nsp:
2000 if num_ini_spaces(line) > self.indent_current_nsp:
2000 line = line[self.indent_current_nsp:]
2001 line = line[self.indent_current_nsp:]
2001 self.indent_current_nsp = 0
2002 self.indent_current_nsp = 0
2002
2003
2003 # store the unfiltered input before the user has any chance to modify
2004 # store the unfiltered input before the user has any chance to modify
2004 # it.
2005 # it.
2005 if line.strip():
2006 if line.strip():
2006 if continue_prompt:
2007 if continue_prompt:
2007 self.input_hist_raw[-1] += '%s\n' % line
2008 self.input_hist_raw[-1] += '%s\n' % line
2008 if self.has_readline: # and some config option is set?
2009 if self.has_readline: # and some config option is set?
2009 try:
2010 try:
2010 histlen = self.readline.get_current_history_length()
2011 histlen = self.readline.get_current_history_length()
2011 newhist = self.input_hist_raw[-1].rstrip()
2012 newhist = self.input_hist_raw[-1].rstrip()
2012 self.readline.remove_history_item(histlen-1)
2013 self.readline.remove_history_item(histlen-1)
2013 self.readline.replace_history_item(histlen-2,newhist)
2014 self.readline.replace_history_item(histlen-2,newhist)
2014 except AttributeError:
2015 except AttributeError:
2015 pass # re{move,place}_history_item are new in 2.4.
2016 pass # re{move,place}_history_item are new in 2.4.
2016 else:
2017 else:
2017 self.input_hist_raw.append('%s\n' % line)
2018 self.input_hist_raw.append('%s\n' % line)
2018
2019
2019 try:
2020 try:
2020 lineout = self.prefilter(line,continue_prompt)
2021 lineout = self.prefilter(line,continue_prompt)
2021 except:
2022 except:
2022 # blanket except, in case a user-defined prefilter crashes, so it
2023 # blanket except, in case a user-defined prefilter crashes, so it
2023 # can't take all of ipython with it.
2024 # can't take all of ipython with it.
2024 self.showtraceback()
2025 self.showtraceback()
2025 return ''
2026 return ''
2026 else:
2027 else:
2027 return lineout
2028 return lineout
2028
2029
2029 def split_user_input(self,line, pattern = None):
2030 def split_user_input(self,line, pattern = None):
2030 """Split user input into pre-char, function part and rest."""
2031 """Split user input into pre-char, function part and rest."""
2031
2032
2032 if pattern is None:
2033 if pattern is None:
2033 pattern = self.line_split
2034 pattern = self.line_split
2034
2035
2035 lsplit = pattern.match(line)
2036 lsplit = pattern.match(line)
2036 if lsplit is None: # no regexp match returns None
2037 if lsplit is None: # no regexp match returns None
2037 #print "match failed for line '%s'" % line # dbg
2038 #print "match failed for line '%s'" % line # dbg
2038 try:
2039 try:
2039 iFun,theRest = line.split(None,1)
2040 iFun,theRest = line.split(None,1)
2040 except ValueError:
2041 except ValueError:
2041 #print "split failed for line '%s'" % line # dbg
2042 #print "split failed for line '%s'" % line # dbg
2042 iFun,theRest = line,''
2043 iFun,theRest = line,''
2043 pre = re.match('^(\s*)(.*)',line).groups()[0]
2044 pre = re.match('^(\s*)(.*)',line).groups()[0]
2044 else:
2045 else:
2045 pre,iFun,theRest = lsplit.groups()
2046 pre,iFun,theRest = lsplit.groups()
2046
2047
2047 #print 'line:<%s>' % line # dbg
2048 #print 'line:<%s>' % line # dbg
2048 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
2049 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
2049 return pre,iFun.strip(),theRest
2050 return pre,iFun.strip(),theRest
2050
2051
2051 # THIS VERSION IS BROKEN!!! It was intended to prevent spurious attribute
2052 # THIS VERSION IS BROKEN!!! It was intended to prevent spurious attribute
2052 # accesses with a more stringent check of inputs, but it introduced other
2053 # accesses with a more stringent check of inputs, but it introduced other
2053 # bugs. Disable it for now until I can properly fix it.
2054 # bugs. Disable it for now until I can properly fix it.
2054 def split_user_inputBROKEN(self,line):
2055 def split_user_inputBROKEN(self,line):
2055 """Split user input into pre-char, function part and rest."""
2056 """Split user input into pre-char, function part and rest."""
2056
2057
2057 lsplit = self.line_split.match(line)
2058 lsplit = self.line_split.match(line)
2058 if lsplit is None: # no regexp match returns None
2059 if lsplit is None: # no regexp match returns None
2059 lsplit = self.line_split_fallback.match(line)
2060 lsplit = self.line_split_fallback.match(line)
2060
2061
2061 #pre,iFun,theRest = lsplit.groups() # dbg
2062 #pre,iFun,theRest = lsplit.groups() # dbg
2062 #print 'line:<%s>' % line # dbg
2063 #print 'line:<%s>' % line # dbg
2063 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
2064 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
2064 #return pre,iFun.strip(),theRest # dbg
2065 #return pre,iFun.strip(),theRest # dbg
2065
2066
2066 return lsplit.groups()
2067 return lsplit.groups()
2067
2068
2068 def _prefilter(self, line, continue_prompt):
2069 def _prefilter(self, line, continue_prompt):
2069 """Calls different preprocessors, depending on the form of line."""
2070 """Calls different preprocessors, depending on the form of line."""
2070
2071
2071 # All handlers *must* return a value, even if it's blank ('').
2072 # All handlers *must* return a value, even if it's blank ('').
2072
2073
2073 # Lines are NOT logged here. Handlers should process the line as
2074 # Lines are NOT logged here. Handlers should process the line as
2074 # needed, update the cache AND log it (so that the input cache array
2075 # needed, update the cache AND log it (so that the input cache array
2075 # stays synced).
2076 # stays synced).
2076
2077
2077 # This function is _very_ delicate, and since it's also the one which
2078 # This function is _very_ delicate, and since it's also the one which
2078 # determines IPython's response to user input, it must be as efficient
2079 # determines IPython's response to user input, it must be as efficient
2079 # as possible. For this reason it has _many_ returns in it, trying
2080 # as possible. For this reason it has _many_ returns in it, trying
2080 # always to exit as quickly as it can figure out what it needs to do.
2081 # always to exit as quickly as it can figure out what it needs to do.
2081
2082
2082 # This function is the main responsible for maintaining IPython's
2083 # This function is the main responsible for maintaining IPython's
2083 # behavior respectful of Python's semantics. So be _very_ careful if
2084 # behavior respectful of Python's semantics. So be _very_ careful if
2084 # making changes to anything here.
2085 # making changes to anything here.
2085
2086
2086 #.....................................................................
2087 #.....................................................................
2087 # Code begins
2088 # Code begins
2088
2089
2089 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2090 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2090
2091
2091 # save the line away in case we crash, so the post-mortem handler can
2092 # save the line away in case we crash, so the post-mortem handler can
2092 # record it
2093 # record it
2093 self._last_input_line = line
2094 self._last_input_line = line
2094
2095
2095 #print '***line: <%s>' % line # dbg
2096 #print '***line: <%s>' % line # dbg
2096
2097
2097 # the input history needs to track even empty lines
2098 # the input history needs to track even empty lines
2098 stripped = line.strip()
2099 stripped = line.strip()
2099
2100
2100 if not stripped:
2101 if not stripped:
2101 if not continue_prompt:
2102 if not continue_prompt:
2102 self.outputcache.prompt_count -= 1
2103 self.outputcache.prompt_count -= 1
2103 return self.handle_normal(line,continue_prompt)
2104 return self.handle_normal(line,continue_prompt)
2104 #return self.handle_normal('',continue_prompt)
2105 #return self.handle_normal('',continue_prompt)
2105
2106
2106 # print '***cont',continue_prompt # dbg
2107 # print '***cont',continue_prompt # dbg
2107 # special handlers are only allowed for single line statements
2108 # special handlers are only allowed for single line statements
2108 if continue_prompt and not self.rc.multi_line_specials:
2109 if continue_prompt and not self.rc.multi_line_specials:
2109 return self.handle_normal(line,continue_prompt)
2110 return self.handle_normal(line,continue_prompt)
2110
2111
2111
2112
2112 # For the rest, we need the structure of the input
2113 # For the rest, we need the structure of the input
2113 pre,iFun,theRest = self.split_user_input(line)
2114 pre,iFun,theRest = self.split_user_input(line)
2114
2115
2115 # See whether any pre-existing handler can take care of it
2116 # See whether any pre-existing handler can take care of it
2116
2117
2117 rewritten = self.hooks.input_prefilter(stripped)
2118 rewritten = self.hooks.input_prefilter(stripped)
2118 if rewritten != stripped: # ok, some prefilter did something
2119 if rewritten != stripped: # ok, some prefilter did something
2119 rewritten = pre + rewritten # add indentation
2120 rewritten = pre + rewritten # add indentation
2120 return self.handle_normal(rewritten)
2121 return self.handle_normal(rewritten)
2121
2122
2122 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2123 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2123
2124
2124 # Next, check if we can automatically execute this thing
2125 # Next, check if we can automatically execute this thing
2125
2126
2126 # Allow ! in multi-line statements if multi_line_specials is on:
2127 # Allow ! in multi-line statements if multi_line_specials is on:
2127 if continue_prompt and self.rc.multi_line_specials and \
2128 if continue_prompt and self.rc.multi_line_specials and \
2128 iFun.startswith(self.ESC_SHELL):
2129 iFun.startswith(self.ESC_SHELL):
2129 return self.handle_shell_escape(line,continue_prompt,
2130 return self.handle_shell_escape(line,continue_prompt,
2130 pre=pre,iFun=iFun,
2131 pre=pre,iFun=iFun,
2131 theRest=theRest)
2132 theRest=theRest)
2132
2133
2133 # First check for explicit escapes in the last/first character
2134 # First check for explicit escapes in the last/first character
2134 handler = None
2135 handler = None
2135 if line[-1] == self.ESC_HELP:
2136 if line[-1] == self.ESC_HELP:
2136 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
2137 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
2137 if handler is None:
2138 if handler is None:
2138 # look at the first character of iFun, NOT of line, so we skip
2139 # look at the first character of iFun, NOT of line, so we skip
2139 # leading whitespace in multiline input
2140 # leading whitespace in multiline input
2140 handler = self.esc_handlers.get(iFun[0:1])
2141 handler = self.esc_handlers.get(iFun[0:1])
2141 if handler is not None:
2142 if handler is not None:
2142 return handler(line,continue_prompt,pre,iFun,theRest)
2143 return handler(line,continue_prompt,pre,iFun,theRest)
2143 # Emacs ipython-mode tags certain input lines
2144 # Emacs ipython-mode tags certain input lines
2144 if line.endswith('# PYTHON-MODE'):
2145 if line.endswith('# PYTHON-MODE'):
2145 return self.handle_emacs(line,continue_prompt)
2146 return self.handle_emacs(line,continue_prompt)
2146
2147
2147 # Let's try to find if the input line is a magic fn
2148 # Let's try to find if the input line is a magic fn
2148 oinfo = None
2149 oinfo = None
2149 if hasattr(self,'magic_'+iFun):
2150 if hasattr(self,'magic_'+iFun):
2150 # WARNING: _ofind uses getattr(), so it can consume generators and
2151 # WARNING: _ofind uses getattr(), so it can consume generators and
2151 # cause other side effects.
2152 # cause other side effects.
2152 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2153 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2153 if oinfo['ismagic']:
2154 if oinfo['ismagic']:
2154 # Be careful not to call magics when a variable assignment is
2155 # Be careful not to call magics when a variable assignment is
2155 # being made (ls='hi', for example)
2156 # being made (ls='hi', for example)
2156 if self.rc.automagic and \
2157 if self.rc.automagic and \
2157 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
2158 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
2158 (self.rc.multi_line_specials or not continue_prompt):
2159 (self.rc.multi_line_specials or not continue_prompt):
2159 return self.handle_magic(line,continue_prompt,
2160 return self.handle_magic(line,continue_prompt,
2160 pre,iFun,theRest)
2161 pre,iFun,theRest)
2161 else:
2162 else:
2162 return self.handle_normal(line,continue_prompt)
2163 return self.handle_normal(line,continue_prompt)
2163
2164
2164 # If the rest of the line begins with an (in)equality, assginment or
2165 # If the rest of the line begins with an (in)equality, assginment or
2165 # function call, we should not call _ofind but simply execute it.
2166 # function call, we should not call _ofind but simply execute it.
2166 # This avoids spurious geattr() accesses on objects upon assignment.
2167 # This avoids spurious geattr() accesses on objects upon assignment.
2167 #
2168 #
2168 # It also allows users to assign to either alias or magic names true
2169 # It also allows users to assign to either alias or magic names true
2169 # python variables (the magic/alias systems always take second seat to
2170 # python variables (the magic/alias systems always take second seat to
2170 # true python code).
2171 # true python code).
2171 if theRest and theRest[0] in '!=()':
2172 if theRest and theRest[0] in '!=()':
2172 return self.handle_normal(line,continue_prompt)
2173 return self.handle_normal(line,continue_prompt)
2173
2174
2174 if oinfo is None:
2175 if oinfo is None:
2175 # let's try to ensure that _oinfo is ONLY called when autocall is
2176 # let's try to ensure that _oinfo is ONLY called when autocall is
2176 # on. Since it has inevitable potential side effects, at least
2177 # on. Since it has inevitable potential side effects, at least
2177 # having autocall off should be a guarantee to the user that no
2178 # having autocall off should be a guarantee to the user that no
2178 # weird things will happen.
2179 # weird things will happen.
2179
2180
2180 if self.rc.autocall:
2181 if self.rc.autocall:
2181 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2182 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2182 else:
2183 else:
2183 # in this case, all that's left is either an alias or
2184 # in this case, all that's left is either an alias or
2184 # processing the line normally.
2185 # processing the line normally.
2185 if iFun in self.alias_table:
2186 if iFun in self.alias_table:
2186 # if autocall is off, by not running _ofind we won't know
2187 # if autocall is off, by not running _ofind we won't know
2187 # whether the given name may also exist in one of the
2188 # whether the given name may also exist in one of the
2188 # user's namespace. At this point, it's best to do a
2189 # user's namespace. At this point, it's best to do a
2189 # quick check just to be sure that we don't let aliases
2190 # quick check just to be sure that we don't let aliases
2190 # shadow variables.
2191 # shadow variables.
2191 head = iFun.split('.',1)[0]
2192 head = iFun.split('.',1)[0]
2192 if head in self.user_ns or head in self.internal_ns \
2193 if head in self.user_ns or head in self.internal_ns \
2193 or head in __builtin__.__dict__:
2194 or head in __builtin__.__dict__:
2194 return self.handle_normal(line,continue_prompt)
2195 return self.handle_normal(line,continue_prompt)
2195 else:
2196 else:
2196 return self.handle_alias(line,continue_prompt,
2197 return self.handle_alias(line,continue_prompt,
2197 pre,iFun,theRest)
2198 pre,iFun,theRest)
2198
2199
2199 else:
2200 else:
2200 return self.handle_normal(line,continue_prompt)
2201 return self.handle_normal(line,continue_prompt)
2201
2202
2202 if not oinfo['found']:
2203 if not oinfo['found']:
2203 return self.handle_normal(line,continue_prompt)
2204 return self.handle_normal(line,continue_prompt)
2204 else:
2205 else:
2205 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2206 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2206 if oinfo['isalias']:
2207 if oinfo['isalias']:
2207 return self.handle_alias(line,continue_prompt,
2208 return self.handle_alias(line,continue_prompt,
2208 pre,iFun,theRest)
2209 pre,iFun,theRest)
2209
2210
2210 if (self.rc.autocall
2211 if (self.rc.autocall
2211 and
2212 and
2212 (
2213 (
2213 #only consider exclusion re if not "," or ";" autoquoting
2214 #only consider exclusion re if not "," or ";" autoquoting
2214 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
2215 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
2215 or pre == self.ESC_PAREN) or
2216 or pre == self.ESC_PAREN) or
2216 (not self.re_exclude_auto.match(theRest)))
2217 (not self.re_exclude_auto.match(theRest)))
2217 and
2218 and
2218 self.re_fun_name.match(iFun) and
2219 self.re_fun_name.match(iFun) and
2219 callable(oinfo['obj'])) :
2220 callable(oinfo['obj'])) :
2220 #print 'going auto' # dbg
2221 #print 'going auto' # dbg
2221 return self.handle_auto(line,continue_prompt,
2222 return self.handle_auto(line,continue_prompt,
2222 pre,iFun,theRest,oinfo['obj'])
2223 pre,iFun,theRest,oinfo['obj'])
2223 else:
2224 else:
2224 #print 'was callable?', callable(oinfo['obj']) # dbg
2225 #print 'was callable?', callable(oinfo['obj']) # dbg
2225 return self.handle_normal(line,continue_prompt)
2226 return self.handle_normal(line,continue_prompt)
2226
2227
2227 # If we get here, we have a normal Python line. Log and return.
2228 # If we get here, we have a normal Python line. Log and return.
2228 return self.handle_normal(line,continue_prompt)
2229 return self.handle_normal(line,continue_prompt)
2229
2230
2230 def _prefilter_dumb(self, line, continue_prompt):
2231 def _prefilter_dumb(self, line, continue_prompt):
2231 """simple prefilter function, for debugging"""
2232 """simple prefilter function, for debugging"""
2232 return self.handle_normal(line,continue_prompt)
2233 return self.handle_normal(line,continue_prompt)
2233
2234
2234
2235
2235 def multiline_prefilter(self, line, continue_prompt):
2236 def multiline_prefilter(self, line, continue_prompt):
2236 """ Run _prefilter for each line of input
2237 """ Run _prefilter for each line of input
2237
2238
2238 Covers cases where there are multiple lines in the user entry,
2239 Covers cases where there are multiple lines in the user entry,
2239 which is the case when the user goes back to a multiline history
2240 which is the case when the user goes back to a multiline history
2240 entry and presses enter.
2241 entry and presses enter.
2241
2242
2242 """
2243 """
2243 out = []
2244 out = []
2244 for l in line.rstrip('\n').split('\n'):
2245 for l in line.rstrip('\n').split('\n'):
2245 out.append(self._prefilter(l, continue_prompt))
2246 out.append(self._prefilter(l, continue_prompt))
2246 return '\n'.join(out)
2247 return '\n'.join(out)
2247
2248
2248 # Set the default prefilter() function (this can be user-overridden)
2249 # Set the default prefilter() function (this can be user-overridden)
2249 prefilter = multiline_prefilter
2250 prefilter = multiline_prefilter
2250
2251
2251 def handle_normal(self,line,continue_prompt=None,
2252 def handle_normal(self,line,continue_prompt=None,
2252 pre=None,iFun=None,theRest=None):
2253 pre=None,iFun=None,theRest=None):
2253 """Handle normal input lines. Use as a template for handlers."""
2254 """Handle normal input lines. Use as a template for handlers."""
2254
2255
2255 # With autoindent on, we need some way to exit the input loop, and I
2256 # With autoindent on, we need some way to exit the input loop, and I
2256 # don't want to force the user to have to backspace all the way to
2257 # don't want to force the user to have to backspace all the way to
2257 # clear the line. The rule will be in this case, that either two
2258 # clear the line. The rule will be in this case, that either two
2258 # lines of pure whitespace in a row, or a line of pure whitespace but
2259 # lines of pure whitespace in a row, or a line of pure whitespace but
2259 # of a size different to the indent level, will exit the input loop.
2260 # of a size different to the indent level, will exit the input loop.
2260
2261
2261 if (continue_prompt and self.autoindent and line.isspace() and
2262 if (continue_prompt and self.autoindent and line.isspace() and
2262 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2263 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2263 (self.buffer[-1]).isspace() )):
2264 (self.buffer[-1]).isspace() )):
2264 line = ''
2265 line = ''
2265
2266
2266 self.log(line,line,continue_prompt)
2267 self.log(line,line,continue_prompt)
2267 return line
2268 return line
2268
2269
2269 def handle_alias(self,line,continue_prompt=None,
2270 def handle_alias(self,line,continue_prompt=None,
2270 pre=None,iFun=None,theRest=None):
2271 pre=None,iFun=None,theRest=None):
2271 """Handle alias input lines. """
2272 """Handle alias input lines. """
2272
2273
2273 # pre is needed, because it carries the leading whitespace. Otherwise
2274 # pre is needed, because it carries the leading whitespace. Otherwise
2274 # aliases won't work in indented sections.
2275 # aliases won't work in indented sections.
2275 transformed = self.expand_aliases(iFun, theRest)
2276 transformed = self.expand_aliases(iFun, theRest)
2276 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2277 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2277 self.log(line,line_out,continue_prompt)
2278 self.log(line,line_out,continue_prompt)
2278 #print 'line out:',line_out # dbg
2279 #print 'line out:',line_out # dbg
2279 return line_out
2280 return line_out
2280
2281
2281 def handle_shell_escape(self, line, continue_prompt=None,
2282 def handle_shell_escape(self, line, continue_prompt=None,
2282 pre=None,iFun=None,theRest=None):
2283 pre=None,iFun=None,theRest=None):
2283 """Execute the line in a shell, empty return value"""
2284 """Execute the line in a shell, empty return value"""
2284
2285
2285 #print 'line in :', `line` # dbg
2286 #print 'line in :', `line` # dbg
2286 # Example of a special handler. Others follow a similar pattern.
2287 # Example of a special handler. Others follow a similar pattern.
2287 if line.lstrip().startswith('!!'):
2288 if line.lstrip().startswith('!!'):
2288 # rewrite iFun/theRest to properly hold the call to %sx and
2289 # rewrite iFun/theRest to properly hold the call to %sx and
2289 # the actual command to be executed, so handle_magic can work
2290 # the actual command to be executed, so handle_magic can work
2290 # correctly
2291 # correctly
2291 theRest = '%s %s' % (iFun[2:],theRest)
2292 theRest = '%s %s' % (iFun[2:],theRest)
2292 iFun = 'sx'
2293 iFun = 'sx'
2293 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2294 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2294 line.lstrip()[2:]),
2295 line.lstrip()[2:]),
2295 continue_prompt,pre,iFun,theRest)
2296 continue_prompt,pre,iFun,theRest)
2296 else:
2297 else:
2297 cmd=line.lstrip().lstrip('!')
2298 cmd=line.lstrip().lstrip('!')
2298 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2299 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2299 # update cache/log and return
2300 # update cache/log and return
2300 self.log(line,line_out,continue_prompt)
2301 self.log(line,line_out,continue_prompt)
2301 return line_out
2302 return line_out
2302
2303
2303 def handle_magic(self, line, continue_prompt=None,
2304 def handle_magic(self, line, continue_prompt=None,
2304 pre=None,iFun=None,theRest=None):
2305 pre=None,iFun=None,theRest=None):
2305 """Execute magic functions."""
2306 """Execute magic functions."""
2306
2307
2307
2308
2308 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2309 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2309 self.log(line,cmd,continue_prompt)
2310 self.log(line,cmd,continue_prompt)
2310 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2311 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2311 return cmd
2312 return cmd
2312
2313
2313 def handle_auto(self, line, continue_prompt=None,
2314 def handle_auto(self, line, continue_prompt=None,
2314 pre=None,iFun=None,theRest=None,obj=None):
2315 pre=None,iFun=None,theRest=None,obj=None):
2315 """Hande lines which can be auto-executed, quoting if requested."""
2316 """Hande lines which can be auto-executed, quoting if requested."""
2316
2317
2317 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2318 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2318
2319
2319 # This should only be active for single-line input!
2320 # This should only be active for single-line input!
2320 if continue_prompt:
2321 if continue_prompt:
2321 self.log(line,line,continue_prompt)
2322 self.log(line,line,continue_prompt)
2322 return line
2323 return line
2323
2324
2324 auto_rewrite = True
2325 auto_rewrite = True
2325
2326
2326 if pre == self.ESC_QUOTE:
2327 if pre == self.ESC_QUOTE:
2327 # Auto-quote splitting on whitespace
2328 # Auto-quote splitting on whitespace
2328 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2329 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2329 elif pre == self.ESC_QUOTE2:
2330 elif pre == self.ESC_QUOTE2:
2330 # Auto-quote whole string
2331 # Auto-quote whole string
2331 newcmd = '%s("%s")' % (iFun,theRest)
2332 newcmd = '%s("%s")' % (iFun,theRest)
2332 elif pre == self.ESC_PAREN:
2333 elif pre == self.ESC_PAREN:
2333 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2334 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2334 else:
2335 else:
2335 # Auto-paren.
2336 # Auto-paren.
2336 # We only apply it to argument-less calls if the autocall
2337 # We only apply it to argument-less calls if the autocall
2337 # parameter is set to 2. We only need to check that autocall is <
2338 # parameter is set to 2. We only need to check that autocall is <
2338 # 2, since this function isn't called unless it's at least 1.
2339 # 2, since this function isn't called unless it's at least 1.
2339 if not theRest and (self.rc.autocall < 2):
2340 if not theRest and (self.rc.autocall < 2):
2340 newcmd = '%s %s' % (iFun,theRest)
2341 newcmd = '%s %s' % (iFun,theRest)
2341 auto_rewrite = False
2342 auto_rewrite = False
2342 else:
2343 else:
2343 if theRest.startswith('['):
2344 if theRest.startswith('['):
2344 if hasattr(obj,'__getitem__'):
2345 if hasattr(obj,'__getitem__'):
2345 # Don't autocall in this case: item access for an object
2346 # Don't autocall in this case: item access for an object
2346 # which is BOTH callable and implements __getitem__.
2347 # which is BOTH callable and implements __getitem__.
2347 newcmd = '%s %s' % (iFun,theRest)
2348 newcmd = '%s %s' % (iFun,theRest)
2348 auto_rewrite = False
2349 auto_rewrite = False
2349 else:
2350 else:
2350 # if the object doesn't support [] access, go ahead and
2351 # if the object doesn't support [] access, go ahead and
2351 # autocall
2352 # autocall
2352 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2353 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2353 elif theRest.endswith(';'):
2354 elif theRest.endswith(';'):
2354 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2355 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2355 else:
2356 else:
2356 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2357 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2357
2358
2358 if auto_rewrite:
2359 if auto_rewrite:
2359 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2360 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2360 # log what is now valid Python, not the actual user input (without the
2361 # log what is now valid Python, not the actual user input (without the
2361 # final newline)
2362 # final newline)
2362 self.log(line,newcmd,continue_prompt)
2363 self.log(line,newcmd,continue_prompt)
2363 return newcmd
2364 return newcmd
2364
2365
2365 def handle_help(self, line, continue_prompt=None,
2366 def handle_help(self, line, continue_prompt=None,
2366 pre=None,iFun=None,theRest=None):
2367 pre=None,iFun=None,theRest=None):
2367 """Try to get some help for the object.
2368 """Try to get some help for the object.
2368
2369
2369 obj? or ?obj -> basic information.
2370 obj? or ?obj -> basic information.
2370 obj?? or ??obj -> more details.
2371 obj?? or ??obj -> more details.
2371 """
2372 """
2372
2373
2373 # We need to make sure that we don't process lines which would be
2374 # We need to make sure that we don't process lines which would be
2374 # otherwise valid python, such as "x=1 # what?"
2375 # otherwise valid python, such as "x=1 # what?"
2375 try:
2376 try:
2376 codeop.compile_command(line)
2377 codeop.compile_command(line)
2377 except SyntaxError:
2378 except SyntaxError:
2378 # We should only handle as help stuff which is NOT valid syntax
2379 # We should only handle as help stuff which is NOT valid syntax
2379 if line[0]==self.ESC_HELP:
2380 if line[0]==self.ESC_HELP:
2380 line = line[1:]
2381 line = line[1:]
2381 elif line[-1]==self.ESC_HELP:
2382 elif line[-1]==self.ESC_HELP:
2382 line = line[:-1]
2383 line = line[:-1]
2383 self.log(line,'#?'+line,continue_prompt)
2384 self.log(line,'#?'+line,continue_prompt)
2384 if line:
2385 if line:
2385 #print 'line:<%r>' % line # dbg
2386 #print 'line:<%r>' % line # dbg
2386 self.magic_pinfo(line)
2387 self.magic_pinfo(line)
2387 else:
2388 else:
2388 page(self.usage,screen_lines=self.rc.screen_length)
2389 page(self.usage,screen_lines=self.rc.screen_length)
2389 return '' # Empty string is needed here!
2390 return '' # Empty string is needed here!
2390 except:
2391 except:
2391 # Pass any other exceptions through to the normal handler
2392 # Pass any other exceptions through to the normal handler
2392 return self.handle_normal(line,continue_prompt)
2393 return self.handle_normal(line,continue_prompt)
2393 else:
2394 else:
2394 # If the code compiles ok, we should handle it normally
2395 # If the code compiles ok, we should handle it normally
2395 return self.handle_normal(line,continue_prompt)
2396 return self.handle_normal(line,continue_prompt)
2396
2397
2397 def getapi(self):
2398 def getapi(self):
2398 """ Get an IPApi object for this shell instance
2399 """ Get an IPApi object for this shell instance
2399
2400
2400 Getting an IPApi object is always preferable to accessing the shell
2401 Getting an IPApi object is always preferable to accessing the shell
2401 directly, but this holds true especially for extensions.
2402 directly, but this holds true especially for extensions.
2402
2403
2403 It should always be possible to implement an extension with IPApi
2404 It should always be possible to implement an extension with IPApi
2404 alone. If not, contact maintainer to request an addition.
2405 alone. If not, contact maintainer to request an addition.
2405
2406
2406 """
2407 """
2407 return self.api
2408 return self.api
2408
2409
2409 def handle_emacs(self,line,continue_prompt=None,
2410 def handle_emacs(self,line,continue_prompt=None,
2410 pre=None,iFun=None,theRest=None):
2411 pre=None,iFun=None,theRest=None):
2411 """Handle input lines marked by python-mode."""
2412 """Handle input lines marked by python-mode."""
2412
2413
2413 # Currently, nothing is done. Later more functionality can be added
2414 # Currently, nothing is done. Later more functionality can be added
2414 # here if needed.
2415 # here if needed.
2415
2416
2416 # The input cache shouldn't be updated
2417 # The input cache shouldn't be updated
2417
2418
2418 return line
2419 return line
2419
2420
2420 def mktempfile(self,data=None):
2421 def mktempfile(self,data=None):
2421 """Make a new tempfile and return its filename.
2422 """Make a new tempfile and return its filename.
2422
2423
2423 This makes a call to tempfile.mktemp, but it registers the created
2424 This makes a call to tempfile.mktemp, but it registers the created
2424 filename internally so ipython cleans it up at exit time.
2425 filename internally so ipython cleans it up at exit time.
2425
2426
2426 Optional inputs:
2427 Optional inputs:
2427
2428
2428 - data(None): if data is given, it gets written out to the temp file
2429 - data(None): if data is given, it gets written out to the temp file
2429 immediately, and the file is closed again."""
2430 immediately, and the file is closed again."""
2430
2431
2431 filename = tempfile.mktemp('.py','ipython_edit_')
2432 filename = tempfile.mktemp('.py','ipython_edit_')
2432 self.tempfiles.append(filename)
2433 self.tempfiles.append(filename)
2433
2434
2434 if data:
2435 if data:
2435 tmp_file = open(filename,'w')
2436 tmp_file = open(filename,'w')
2436 tmp_file.write(data)
2437 tmp_file.write(data)
2437 tmp_file.close()
2438 tmp_file.close()
2438 return filename
2439 return filename
2439
2440
2440 def write(self,data):
2441 def write(self,data):
2441 """Write a string to the default output"""
2442 """Write a string to the default output"""
2442 Term.cout.write(data)
2443 Term.cout.write(data)
2443
2444
2444 def write_err(self,data):
2445 def write_err(self,data):
2445 """Write a string to the default error output"""
2446 """Write a string to the default error output"""
2446 Term.cerr.write(data)
2447 Term.cerr.write(data)
2447
2448
2448 def exit(self):
2449 def exit(self):
2449 """Handle interactive exit.
2450 """Handle interactive exit.
2450
2451
2451 This method sets the exit_now attribute."""
2452 This method sets the exit_now attribute."""
2452
2453
2453 if self.rc.confirm_exit:
2454 if self.rc.confirm_exit:
2454 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2455 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2455 self.exit_now = True
2456 self.exit_now = True
2456 else:
2457 else:
2457 self.exit_now = True
2458 self.exit_now = True
2458
2459
2459 def safe_execfile(self,fname,*where,**kw):
2460 def safe_execfile(self,fname,*where,**kw):
2460 """A safe version of the builtin execfile().
2461 """A safe version of the builtin execfile().
2461
2462
2462 This version will never throw an exception, and knows how to handle
2463 This version will never throw an exception, and knows how to handle
2463 ipython logs as well."""
2464 ipython logs as well."""
2464
2465
2465 def syspath_cleanup():
2466 def syspath_cleanup():
2466 """Internal cleanup routine for sys.path."""
2467 """Internal cleanup routine for sys.path."""
2467 if add_dname:
2468 if add_dname:
2468 try:
2469 try:
2469 sys.path.remove(dname)
2470 sys.path.remove(dname)
2470 except ValueError:
2471 except ValueError:
2471 # For some reason the user has already removed it, ignore.
2472 # For some reason the user has already removed it, ignore.
2472 pass
2473 pass
2473
2474
2474 fname = os.path.expanduser(fname)
2475 fname = os.path.expanduser(fname)
2475
2476
2476 # Find things also in current directory. This is needed to mimic the
2477 # Find things also in current directory. This is needed to mimic the
2477 # behavior of running a script from the system command line, where
2478 # behavior of running a script from the system command line, where
2478 # Python inserts the script's directory into sys.path
2479 # Python inserts the script's directory into sys.path
2479 dname = os.path.dirname(os.path.abspath(fname))
2480 dname = os.path.dirname(os.path.abspath(fname))
2480 add_dname = False
2481 add_dname = False
2481 if dname not in sys.path:
2482 if dname not in sys.path:
2482 sys.path.insert(0,dname)
2483 sys.path.insert(0,dname)
2483 add_dname = True
2484 add_dname = True
2484
2485
2485 try:
2486 try:
2486 xfile = open(fname)
2487 xfile = open(fname)
2487 except:
2488 except:
2488 print >> Term.cerr, \
2489 print >> Term.cerr, \
2489 'Could not open file <%s> for safe execution.' % fname
2490 'Could not open file <%s> for safe execution.' % fname
2490 syspath_cleanup()
2491 syspath_cleanup()
2491 return None
2492 return None
2492
2493
2493 kw.setdefault('islog',0)
2494 kw.setdefault('islog',0)
2494 kw.setdefault('quiet',1)
2495 kw.setdefault('quiet',1)
2495 kw.setdefault('exit_ignore',0)
2496 kw.setdefault('exit_ignore',0)
2496 first = xfile.readline()
2497 first = xfile.readline()
2497 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2498 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2498 xfile.close()
2499 xfile.close()
2499 # line by line execution
2500 # line by line execution
2500 if first.startswith(loghead) or kw['islog']:
2501 if first.startswith(loghead) or kw['islog']:
2501 print 'Loading log file <%s> one line at a time...' % fname
2502 print 'Loading log file <%s> one line at a time...' % fname
2502 if kw['quiet']:
2503 if kw['quiet']:
2503 stdout_save = sys.stdout
2504 stdout_save = sys.stdout
2504 sys.stdout = StringIO.StringIO()
2505 sys.stdout = StringIO.StringIO()
2505 try:
2506 try:
2506 globs,locs = where[0:2]
2507 globs,locs = where[0:2]
2507 except:
2508 except:
2508 try:
2509 try:
2509 globs = locs = where[0]
2510 globs = locs = where[0]
2510 except:
2511 except:
2511 globs = locs = globals()
2512 globs = locs = globals()
2512 badblocks = []
2513 badblocks = []
2513
2514
2514 # we also need to identify indented blocks of code when replaying
2515 # we also need to identify indented blocks of code when replaying
2515 # logs and put them together before passing them to an exec
2516 # logs and put them together before passing them to an exec
2516 # statement. This takes a bit of regexp and look-ahead work in the
2517 # statement. This takes a bit of regexp and look-ahead work in the
2517 # file. It's easiest if we swallow the whole thing in memory
2518 # file. It's easiest if we swallow the whole thing in memory
2518 # first, and manually walk through the lines list moving the
2519 # first, and manually walk through the lines list moving the
2519 # counter ourselves.
2520 # counter ourselves.
2520 indent_re = re.compile('\s+\S')
2521 indent_re = re.compile('\s+\S')
2521 xfile = open(fname)
2522 xfile = open(fname)
2522 filelines = xfile.readlines()
2523 filelines = xfile.readlines()
2523 xfile.close()
2524 xfile.close()
2524 nlines = len(filelines)
2525 nlines = len(filelines)
2525 lnum = 0
2526 lnum = 0
2526 while lnum < nlines:
2527 while lnum < nlines:
2527 line = filelines[lnum]
2528 line = filelines[lnum]
2528 lnum += 1
2529 lnum += 1
2529 # don't re-insert logger status info into cache
2530 # don't re-insert logger status info into cache
2530 if line.startswith('#log#'):
2531 if line.startswith('#log#'):
2531 continue
2532 continue
2532 else:
2533 else:
2533 # build a block of code (maybe a single line) for execution
2534 # build a block of code (maybe a single line) for execution
2534 block = line
2535 block = line
2535 try:
2536 try:
2536 next = filelines[lnum] # lnum has already incremented
2537 next = filelines[lnum] # lnum has already incremented
2537 except:
2538 except:
2538 next = None
2539 next = None
2539 while next and indent_re.match(next):
2540 while next and indent_re.match(next):
2540 block += next
2541 block += next
2541 lnum += 1
2542 lnum += 1
2542 try:
2543 try:
2543 next = filelines[lnum]
2544 next = filelines[lnum]
2544 except:
2545 except:
2545 next = None
2546 next = None
2546 # now execute the block of one or more lines
2547 # now execute the block of one or more lines
2547 try:
2548 try:
2548 exec block in globs,locs
2549 exec block in globs,locs
2549 except SystemExit:
2550 except SystemExit:
2550 pass
2551 pass
2551 except:
2552 except:
2552 badblocks.append(block.rstrip())
2553 badblocks.append(block.rstrip())
2553 if kw['quiet']: # restore stdout
2554 if kw['quiet']: # restore stdout
2554 sys.stdout.close()
2555 sys.stdout.close()
2555 sys.stdout = stdout_save
2556 sys.stdout = stdout_save
2556 print 'Finished replaying log file <%s>' % fname
2557 print 'Finished replaying log file <%s>' % fname
2557 if badblocks:
2558 if badblocks:
2558 print >> sys.stderr, ('\nThe following lines/blocks in file '
2559 print >> sys.stderr, ('\nThe following lines/blocks in file '
2559 '<%s> reported errors:' % fname)
2560 '<%s> reported errors:' % fname)
2560
2561
2561 for badline in badblocks:
2562 for badline in badblocks:
2562 print >> sys.stderr, badline
2563 print >> sys.stderr, badline
2563 else: # regular file execution
2564 else: # regular file execution
2564 try:
2565 try:
2565 execfile(fname,*where)
2566 execfile(fname,*where)
2566 except SyntaxError:
2567 except SyntaxError:
2567 self.showsyntaxerror()
2568 self.showsyntaxerror()
2568 warn('Failure executing file: <%s>' % fname)
2569 warn('Failure executing file: <%s>' % fname)
2569 except SystemExit,status:
2570 except SystemExit,status:
2570 if not kw['exit_ignore']:
2571 if not kw['exit_ignore']:
2571 self.showtraceback()
2572 self.showtraceback()
2572 warn('Failure executing file: <%s>' % fname)
2573 warn('Failure executing file: <%s>' % fname)
2573 except:
2574 except:
2574 self.showtraceback()
2575 self.showtraceback()
2575 warn('Failure executing file: <%s>' % fname)
2576 warn('Failure executing file: <%s>' % fname)
2576
2577
2577 syspath_cleanup()
2578 syspath_cleanup()
2578
2579
2579 #************************* end of file <iplib.py> *****************************
2580 #************************* end of file <iplib.py> *****************************
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