##// END OF EJS Templates
provide single readline config place through rlineimpl
vivainio -
Show More
@@ -0,0 +1,43 b''
1 # -*- coding: utf-8 -*-
2 """ Imports and provides the "correct" version of readline for the platform.
3
4 Readline is used throughout IPython as "import IPython.rlineimpl as readline.
5
6 In addition to normal readline stuff, this module provides have_readline boolean
7 and _outputfile variable used in genutils.
8
9 $Id: Magic.py 1096 2006-01-28 20:08:02Z vivainio $"""
10
11
12 import sys
13
14 have_readline = False
15
16 if sys.platform == 'win32':
17 try:
18 from pyreadline import *
19 print "Using the new pyreadline (thanks for participating in the testing!)"
20 have_readline = True
21 except ImportError:
22 print "The IPython team recommends the new pyreadline for Windows use, it wasn't found."
23 print "It's superior especially with non-US keyboard layouts."
24 print "Try installing it with 'easy_install pyreadline (ctypes is required) or"
25 print "svn co http://ipython.scipy.org/svn/ipython/pyreadline/trunk pyreadline"
26 print "Trying 'old' windows readline."
27
28 from readline import *
29 have_readline = True
30 else:
31 try:
32 from readline import *
33 have_readline = True
34 except ImportError:
35 pass
36
37
38 if have_readline:
39 try:
40 _outputfile=GetOutputFile()
41 except AttributeError:
42 have_readline = False
43
@@ -1,2872 +1,2859 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 1096 2006-01-28 20:08:02Z vivainio $"""
4 $Id: Magic.py 1099 2006-01-29 21:05:57Z vivainio $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import sys
29 import sys
30 import re
30 import re
31 import tempfile
31 import tempfile
32 import time
32 import time
33 import cPickle as pickle
33 import cPickle as pickle
34 import textwrap
34 import textwrap
35 from cStringIO import StringIO
35 from cStringIO import StringIO
36 from getopt import getopt,GetoptError
36 from getopt import getopt,GetoptError
37 from pprint import pprint, pformat
37 from pprint import pprint, pformat
38
38
39 # profile isn't bundled by default in Debian for license reasons
39 # profile isn't bundled by default in Debian for license reasons
40 try:
40 try:
41 import profile,pstats
41 import profile,pstats
42 except ImportError:
42 except ImportError:
43 profile = pstats = None
43 profile = pstats = None
44
44
45 # Homebrewed
45 # Homebrewed
46 from IPython import Debugger, OInspect, wildcard
46 from IPython import Debugger, OInspect, wildcard
47 from IPython.FakeModule import FakeModule
47 from IPython.FakeModule import FakeModule
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
49 from IPython.PyColorize import Parser
49 from IPython.PyColorize import Parser
50 from IPython.ipstruct import Struct
50 from IPython.ipstruct import Struct
51 from IPython.macro import Macro
51 from IPython.macro import Macro
52 from IPython.genutils import *
52 from IPython.genutils import *
53 from IPython import platutils
53 from IPython import platutils
54
54
55 #***************************************************************************
55 #***************************************************************************
56 # Utility functions
56 # Utility functions
57 def on_off(tag):
57 def on_off(tag):
58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
59 return ['OFF','ON'][tag]
59 return ['OFF','ON'][tag]
60
60
61 class Bunch: pass
61 class Bunch: pass
62
62
63 #***************************************************************************
63 #***************************************************************************
64 # Main class implementing Magic functionality
64 # Main class implementing Magic functionality
65 class Magic:
65 class Magic:
66 """Magic functions for InteractiveShell.
66 """Magic functions for InteractiveShell.
67
67
68 Shell functions which can be reached as %function_name. All magic
68 Shell functions which can be reached as %function_name. All magic
69 functions should accept a string, which they can parse for their own
69 functions should accept a string, which they can parse for their own
70 needs. This can make some functions easier to type, eg `%cd ../`
70 needs. This can make some functions easier to type, eg `%cd ../`
71 vs. `%cd("../")`
71 vs. `%cd("../")`
72
72
73 ALL definitions MUST begin with the prefix magic_. The user won't need it
73 ALL definitions MUST begin with the prefix magic_. The user won't need it
74 at the command line, but it is is needed in the definition. """
74 at the command line, but it is is needed in the definition. """
75
75
76 # class globals
76 # class globals
77 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
77 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
78 'Automagic is ON, % prefix NOT needed for magic functions.']
78 'Automagic is ON, % prefix NOT needed for magic functions.']
79
79
80 #......................................................................
80 #......................................................................
81 # some utility functions
81 # some utility functions
82
82
83 def __init__(self,shell):
83 def __init__(self,shell):
84
84
85 self.options_table = {}
85 self.options_table = {}
86 if profile is None:
86 if profile is None:
87 self.magic_prun = self.profile_missing_notice
87 self.magic_prun = self.profile_missing_notice
88 self.shell = shell
88 self.shell = shell
89
89
90 # namespace for holding state we may need
90 # namespace for holding state we may need
91 self._magic_state = Bunch()
91 self._magic_state = Bunch()
92
92
93 def profile_missing_notice(self, *args, **kwargs):
93 def profile_missing_notice(self, *args, **kwargs):
94 error("""\
94 error("""\
95 The profile module could not be found. If you are a Debian user,
95 The profile module could not be found. If you are a Debian user,
96 it has been removed from the standard Debian package because of its non-free
96 it has been removed from the standard Debian package because of its non-free
97 license. To use profiling, please install"python2.3-profiler" from non-free.""")
97 license. To use profiling, please install"python2.3-profiler" from non-free.""")
98
98
99 def default_option(self,fn,optstr):
99 def default_option(self,fn,optstr):
100 """Make an entry in the options_table for fn, with value optstr"""
100 """Make an entry in the options_table for fn, with value optstr"""
101
101
102 if fn not in self.lsmagic():
102 if fn not in self.lsmagic():
103 error("%s is not a magic function" % fn)
103 error("%s is not a magic function" % fn)
104 self.options_table[fn] = optstr
104 self.options_table[fn] = optstr
105
105
106 def lsmagic(self):
106 def lsmagic(self):
107 """Return a list of currently available magic functions.
107 """Return a list of currently available magic functions.
108
108
109 Gives a list of the bare names after mangling (['ls','cd', ...], not
109 Gives a list of the bare names after mangling (['ls','cd', ...], not
110 ['magic_ls','magic_cd',...]"""
110 ['magic_ls','magic_cd',...]"""
111
111
112 # FIXME. This needs a cleanup, in the way the magics list is built.
112 # FIXME. This needs a cleanup, in the way the magics list is built.
113
113
114 # magics in class definition
114 # magics in class definition
115 class_magic = lambda fn: fn.startswith('magic_') and \
115 class_magic = lambda fn: fn.startswith('magic_') and \
116 callable(Magic.__dict__[fn])
116 callable(Magic.__dict__[fn])
117 # in instance namespace (run-time user additions)
117 # in instance namespace (run-time user additions)
118 inst_magic = lambda fn: fn.startswith('magic_') and \
118 inst_magic = lambda fn: fn.startswith('magic_') and \
119 callable(self.__dict__[fn])
119 callable(self.__dict__[fn])
120 # and bound magics by user (so they can access self):
120 # and bound magics by user (so they can access self):
121 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
121 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
122 callable(self.__class__.__dict__[fn])
122 callable(self.__class__.__dict__[fn])
123 magics = filter(class_magic,Magic.__dict__.keys()) + \
123 magics = filter(class_magic,Magic.__dict__.keys()) + \
124 filter(inst_magic,self.__dict__.keys()) + \
124 filter(inst_magic,self.__dict__.keys()) + \
125 filter(inst_bound_magic,self.__class__.__dict__.keys())
125 filter(inst_bound_magic,self.__class__.__dict__.keys())
126 out = []
126 out = []
127 for fn in magics:
127 for fn in magics:
128 out.append(fn.replace('magic_','',1))
128 out.append(fn.replace('magic_','',1))
129 out.sort()
129 out.sort()
130 return out
130 return out
131
131
132 def extract_input_slices(self,slices):
132 def extract_input_slices(self,slices):
133 """Return as a string a set of input history slices.
133 """Return as a string a set of input history slices.
134
134
135 The set of slices is given as a list of strings (like ['1','4:8','9'],
135 The set of slices is given as a list of strings (like ['1','4:8','9'],
136 since this function is for use by magic functions which get their
136 since this function is for use by magic functions which get their
137 arguments as strings.
137 arguments as strings.
138
138
139 Note that slices can be called with two notations:
139 Note that slices can be called with two notations:
140
140
141 N:M -> standard python form, means including items N...(M-1).
141 N:M -> standard python form, means including items N...(M-1).
142
142
143 N-M -> include items N..M (closed endpoint)."""
143 N-M -> include items N..M (closed endpoint)."""
144
144
145 cmds = []
145 cmds = []
146 for chunk in slices:
146 for chunk in slices:
147 if ':' in chunk:
147 if ':' in chunk:
148 ini,fin = map(int,chunk.split(':'))
148 ini,fin = map(int,chunk.split(':'))
149 elif '-' in chunk:
149 elif '-' in chunk:
150 ini,fin = map(int,chunk.split('-'))
150 ini,fin = map(int,chunk.split('-'))
151 fin += 1
151 fin += 1
152 else:
152 else:
153 ini = int(chunk)
153 ini = int(chunk)
154 fin = ini+1
154 fin = ini+1
155 cmds.append(self.shell.input_hist[ini:fin])
155 cmds.append(self.shell.input_hist[ini:fin])
156 return cmds
156 return cmds
157
157
158 def _ofind(self,oname):
158 def _ofind(self,oname):
159 """Find an object in the available namespaces.
159 """Find an object in the available namespaces.
160
160
161 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
161 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
162
162
163 Has special code to detect magic functions.
163 Has special code to detect magic functions.
164 """
164 """
165
165
166 oname = oname.strip()
166 oname = oname.strip()
167
167
168 # Namespaces to search in:
168 # Namespaces to search in:
169 user_ns = self.shell.user_ns
169 user_ns = self.shell.user_ns
170 internal_ns = self.shell.internal_ns
170 internal_ns = self.shell.internal_ns
171 builtin_ns = __builtin__.__dict__
171 builtin_ns = __builtin__.__dict__
172 alias_ns = self.shell.alias_table
172 alias_ns = self.shell.alias_table
173
173
174 # Put them in a list. The order is important so that we find things in
174 # Put them in a list. The order is important so that we find things in
175 # the same order that Python finds them.
175 # the same order that Python finds them.
176 namespaces = [ ('Interactive',user_ns),
176 namespaces = [ ('Interactive',user_ns),
177 ('IPython internal',internal_ns),
177 ('IPython internal',internal_ns),
178 ('Python builtin',builtin_ns),
178 ('Python builtin',builtin_ns),
179 ('Alias',alias_ns),
179 ('Alias',alias_ns),
180 ]
180 ]
181
181
182 # initialize results to 'null'
182 # initialize results to 'null'
183 found = 0; obj = None; ospace = None; ds = None;
183 found = 0; obj = None; ospace = None; ds = None;
184 ismagic = 0; isalias = 0
184 ismagic = 0; isalias = 0
185
185
186 # Look for the given name by splitting it in parts. If the head is
186 # Look for the given name by splitting it in parts. If the head is
187 # found, then we look for all the remaining parts as members, and only
187 # found, then we look for all the remaining parts as members, and only
188 # declare success if we can find them all.
188 # declare success if we can find them all.
189 oname_parts = oname.split('.')
189 oname_parts = oname.split('.')
190 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
190 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
191 for nsname,ns in namespaces:
191 for nsname,ns in namespaces:
192 try:
192 try:
193 obj = ns[oname_head]
193 obj = ns[oname_head]
194 except KeyError:
194 except KeyError:
195 continue
195 continue
196 else:
196 else:
197 for part in oname_rest:
197 for part in oname_rest:
198 try:
198 try:
199 obj = getattr(obj,part)
199 obj = getattr(obj,part)
200 except:
200 except:
201 # Blanket except b/c some badly implemented objects
201 # Blanket except b/c some badly implemented objects
202 # allow __getattr__ to raise exceptions other than
202 # allow __getattr__ to raise exceptions other than
203 # AttributeError, which then crashes IPython.
203 # AttributeError, which then crashes IPython.
204 break
204 break
205 else:
205 else:
206 # If we finish the for loop (no break), we got all members
206 # If we finish the for loop (no break), we got all members
207 found = 1
207 found = 1
208 ospace = nsname
208 ospace = nsname
209 if ns == alias_ns:
209 if ns == alias_ns:
210 isalias = 1
210 isalias = 1
211 break # namespace loop
211 break # namespace loop
212
212
213 # Try to see if it's magic
213 # Try to see if it's magic
214 if not found:
214 if not found:
215 if oname.startswith(self.shell.ESC_MAGIC):
215 if oname.startswith(self.shell.ESC_MAGIC):
216 oname = oname[1:]
216 oname = oname[1:]
217 obj = getattr(self,'magic_'+oname,None)
217 obj = getattr(self,'magic_'+oname,None)
218 if obj is not None:
218 if obj is not None:
219 found = 1
219 found = 1
220 ospace = 'IPython internal'
220 ospace = 'IPython internal'
221 ismagic = 1
221 ismagic = 1
222
222
223 # Last try: special-case some literals like '', [], {}, etc:
223 # Last try: special-case some literals like '', [], {}, etc:
224 if not found and oname_head in ["''",'""','[]','{}','()']:
224 if not found and oname_head in ["''",'""','[]','{}','()']:
225 obj = eval(oname_head)
225 obj = eval(oname_head)
226 found = 1
226 found = 1
227 ospace = 'Interactive'
227 ospace = 'Interactive'
228
228
229 return {'found':found, 'obj':obj, 'namespace':ospace,
229 return {'found':found, 'obj':obj, 'namespace':ospace,
230 'ismagic':ismagic, 'isalias':isalias}
230 'ismagic':ismagic, 'isalias':isalias}
231
231
232 def arg_err(self,func):
232 def arg_err(self,func):
233 """Print docstring if incorrect arguments were passed"""
233 """Print docstring if incorrect arguments were passed"""
234 print 'Error in arguments:'
234 print 'Error in arguments:'
235 print OInspect.getdoc(func)
235 print OInspect.getdoc(func)
236
236
237 def format_latex(self,strng):
237 def format_latex(self,strng):
238 """Format a string for latex inclusion."""
238 """Format a string for latex inclusion."""
239
239
240 # Characters that need to be escaped for latex:
240 # Characters that need to be escaped for latex:
241 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
241 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
242 # Magic command names as headers:
242 # Magic command names as headers:
243 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
243 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
244 re.MULTILINE)
244 re.MULTILINE)
245 # Magic commands
245 # Magic commands
246 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
246 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
247 re.MULTILINE)
247 re.MULTILINE)
248 # Paragraph continue
248 # Paragraph continue
249 par_re = re.compile(r'\\$',re.MULTILINE)
249 par_re = re.compile(r'\\$',re.MULTILINE)
250
250
251 # The "\n" symbol
251 # The "\n" symbol
252 newline_re = re.compile(r'\\n')
252 newline_re = re.compile(r'\\n')
253
253
254 # Now build the string for output:
254 # Now build the string for output:
255 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
255 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
256 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
256 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
257 strng)
257 strng)
258 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
258 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
259 strng = par_re.sub(r'\\\\',strng)
259 strng = par_re.sub(r'\\\\',strng)
260 strng = escape_re.sub(r'\\\1',strng)
260 strng = escape_re.sub(r'\\\1',strng)
261 strng = newline_re.sub(r'\\textbackslash{}n',strng)
261 strng = newline_re.sub(r'\\textbackslash{}n',strng)
262 return strng
262 return strng
263
263
264 def format_screen(self,strng):
264 def format_screen(self,strng):
265 """Format a string for screen printing.
265 """Format a string for screen printing.
266
266
267 This removes some latex-type format codes."""
267 This removes some latex-type format codes."""
268 # Paragraph continue
268 # Paragraph continue
269 par_re = re.compile(r'\\$',re.MULTILINE)
269 par_re = re.compile(r'\\$',re.MULTILINE)
270 strng = par_re.sub('',strng)
270 strng = par_re.sub('',strng)
271 return strng
271 return strng
272
272
273 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
273 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
274 """Parse options passed to an argument string.
274 """Parse options passed to an argument string.
275
275
276 The interface is similar to that of getopt(), but it returns back a
276 The interface is similar to that of getopt(), but it returns back a
277 Struct with the options as keys and the stripped argument string still
277 Struct with the options as keys and the stripped argument string still
278 as a string.
278 as a string.
279
279
280 arg_str is quoted as a true sys.argv vector by using shlex.split.
280 arg_str is quoted as a true sys.argv vector by using shlex.split.
281 This allows us to easily expand variables, glob files, quote
281 This allows us to easily expand variables, glob files, quote
282 arguments, etc.
282 arguments, etc.
283
283
284 Options:
284 Options:
285 -mode: default 'string'. If given as 'list', the argument string is
285 -mode: default 'string'. If given as 'list', the argument string is
286 returned as a list (split on whitespace) instead of a string.
286 returned as a list (split on whitespace) instead of a string.
287
287
288 -list_all: put all option values in lists. Normally only options
288 -list_all: put all option values in lists. Normally only options
289 appearing more than once are put in a list."""
289 appearing more than once are put in a list."""
290
290
291 # inject default options at the beginning of the input line
291 # inject default options at the beginning of the input line
292 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
292 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
293 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
293 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
294
294
295 mode = kw.get('mode','string')
295 mode = kw.get('mode','string')
296 if mode not in ['string','list']:
296 if mode not in ['string','list']:
297 raise ValueError,'incorrect mode given: %s' % mode
297 raise ValueError,'incorrect mode given: %s' % mode
298 # Get options
298 # Get options
299 list_all = kw.get('list_all',0)
299 list_all = kw.get('list_all',0)
300
300
301 # Check if we have more than one argument to warrant extra processing:
301 # Check if we have more than one argument to warrant extra processing:
302 odict = {} # Dictionary with options
302 odict = {} # Dictionary with options
303 args = arg_str.split()
303 args = arg_str.split()
304 if len(args) >= 1:
304 if len(args) >= 1:
305 # If the list of inputs only has 0 or 1 thing in it, there's no
305 # If the list of inputs only has 0 or 1 thing in it, there's no
306 # need to look for options
306 # need to look for options
307 argv = shlex_split(arg_str)
307 argv = shlex_split(arg_str)
308 # Do regular option processing
308 # Do regular option processing
309 try:
309 try:
310 opts,args = getopt(argv,opt_str,*long_opts)
310 opts,args = getopt(argv,opt_str,*long_opts)
311 except GetoptError,e:
311 except GetoptError,e:
312 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
312 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
313 " ".join(long_opts)))
313 " ".join(long_opts)))
314 for o,a in opts:
314 for o,a in opts:
315 if o.startswith('--'):
315 if o.startswith('--'):
316 o = o[2:]
316 o = o[2:]
317 else:
317 else:
318 o = o[1:]
318 o = o[1:]
319 try:
319 try:
320 odict[o].append(a)
320 odict[o].append(a)
321 except AttributeError:
321 except AttributeError:
322 odict[o] = [odict[o],a]
322 odict[o] = [odict[o],a]
323 except KeyError:
323 except KeyError:
324 if list_all:
324 if list_all:
325 odict[o] = [a]
325 odict[o] = [a]
326 else:
326 else:
327 odict[o] = a
327 odict[o] = a
328
328
329 # Prepare opts,args for return
329 # Prepare opts,args for return
330 opts = Struct(odict)
330 opts = Struct(odict)
331 if mode == 'string':
331 if mode == 'string':
332 args = ' '.join(args)
332 args = ' '.join(args)
333
333
334 return opts,args
334 return opts,args
335
335
336 #......................................................................
336 #......................................................................
337 # And now the actual magic functions
337 # And now the actual magic functions
338
338
339 # Functions for IPython shell work (vars,funcs, config, etc)
339 # Functions for IPython shell work (vars,funcs, config, etc)
340 def magic_lsmagic(self, parameter_s = ''):
340 def magic_lsmagic(self, parameter_s = ''):
341 """List currently available magic functions."""
341 """List currently available magic functions."""
342 mesc = self.shell.ESC_MAGIC
342 mesc = self.shell.ESC_MAGIC
343 print 'Available magic functions:\n'+mesc+\
343 print 'Available magic functions:\n'+mesc+\
344 (' '+mesc).join(self.lsmagic())
344 (' '+mesc).join(self.lsmagic())
345 print '\n' + Magic.auto_status[self.shell.rc.automagic]
345 print '\n' + Magic.auto_status[self.shell.rc.automagic]
346 return None
346 return None
347
347
348 def magic_magic(self, parameter_s = ''):
348 def magic_magic(self, parameter_s = ''):
349 """Print information about the magic function system."""
349 """Print information about the magic function system."""
350
350
351 mode = ''
351 mode = ''
352 try:
352 try:
353 if parameter_s.split()[0] == '-latex':
353 if parameter_s.split()[0] == '-latex':
354 mode = 'latex'
354 mode = 'latex'
355 except:
355 except:
356 pass
356 pass
357
357
358 magic_docs = []
358 magic_docs = []
359 for fname in self.lsmagic():
359 for fname in self.lsmagic():
360 mname = 'magic_' + fname
360 mname = 'magic_' + fname
361 for space in (Magic,self,self.__class__):
361 for space in (Magic,self,self.__class__):
362 try:
362 try:
363 fn = space.__dict__[mname]
363 fn = space.__dict__[mname]
364 except KeyError:
364 except KeyError:
365 pass
365 pass
366 else:
366 else:
367 break
367 break
368 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
368 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
369 fname,fn.__doc__))
369 fname,fn.__doc__))
370 magic_docs = ''.join(magic_docs)
370 magic_docs = ''.join(magic_docs)
371
371
372 if mode == 'latex':
372 if mode == 'latex':
373 print self.format_latex(magic_docs)
373 print self.format_latex(magic_docs)
374 return
374 return
375 else:
375 else:
376 magic_docs = self.format_screen(magic_docs)
376 magic_docs = self.format_screen(magic_docs)
377
377
378 outmsg = """
378 outmsg = """
379 IPython's 'magic' functions
379 IPython's 'magic' functions
380 ===========================
380 ===========================
381
381
382 The magic function system provides a series of functions which allow you to
382 The magic function system provides a series of functions which allow you to
383 control the behavior of IPython itself, plus a lot of system-type
383 control the behavior of IPython itself, plus a lot of system-type
384 features. All these functions are prefixed with a % character, but parameters
384 features. All these functions are prefixed with a % character, but parameters
385 are given without parentheses or quotes.
385 are given without parentheses or quotes.
386
386
387 NOTE: If you have 'automagic' enabled (via the command line option or with the
387 NOTE: If you have 'automagic' enabled (via the command line option or with the
388 %automagic function), you don't need to type in the % explicitly. By default,
388 %automagic function), you don't need to type in the % explicitly. By default,
389 IPython ships with automagic on, so you should only rarely need the % escape.
389 IPython ships with automagic on, so you should only rarely need the % escape.
390
390
391 Example: typing '%cd mydir' (without the quotes) changes you working directory
391 Example: typing '%cd mydir' (without the quotes) changes you working directory
392 to 'mydir', if it exists.
392 to 'mydir', if it exists.
393
393
394 You can define your own magic functions to extend the system. See the supplied
394 You can define your own magic functions to extend the system. See the supplied
395 ipythonrc and example-magic.py files for details (in your ipython
395 ipythonrc and example-magic.py files for details (in your ipython
396 configuration directory, typically $HOME/.ipython/).
396 configuration directory, typically $HOME/.ipython/).
397
397
398 You can also define your own aliased names for magic functions. In your
398 You can also define your own aliased names for magic functions. In your
399 ipythonrc file, placing a line like:
399 ipythonrc file, placing a line like:
400
400
401 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
401 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
402
402
403 will define %pf as a new name for %profile.
403 will define %pf as a new name for %profile.
404
404
405 You can also call magics in code using the ipmagic() function, which IPython
405 You can also call magics in code using the ipmagic() function, which IPython
406 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
406 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
407
407
408 For a list of the available magic functions, use %lsmagic. For a description
408 For a list of the available magic functions, use %lsmagic. For a description
409 of any of them, type %magic_name?, e.g. '%cd?'.
409 of any of them, type %magic_name?, e.g. '%cd?'.
410
410
411 Currently the magic system has the following functions:\n"""
411 Currently the magic system has the following functions:\n"""
412
412
413 mesc = self.shell.ESC_MAGIC
413 mesc = self.shell.ESC_MAGIC
414 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
414 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
415 "\n\n%s%s\n\n%s" % (outmsg,
415 "\n\n%s%s\n\n%s" % (outmsg,
416 magic_docs,mesc,mesc,
416 magic_docs,mesc,mesc,
417 (' '+mesc).join(self.lsmagic()),
417 (' '+mesc).join(self.lsmagic()),
418 Magic.auto_status[self.shell.rc.automagic] ) )
418 Magic.auto_status[self.shell.rc.automagic] ) )
419
419
420 page(outmsg,screen_lines=self.shell.rc.screen_length)
420 page(outmsg,screen_lines=self.shell.rc.screen_length)
421
421
422 def magic_automagic(self, parameter_s = ''):
422 def magic_automagic(self, parameter_s = ''):
423 """Make magic functions callable without having to type the initial %.
423 """Make magic functions callable without having to type the initial %.
424
424
425 Toggles on/off (when off, you must call it as %automagic, of
425 Toggles on/off (when off, you must call it as %automagic, of
426 course). Note that magic functions have lowest priority, so if there's
426 course). Note that magic functions have lowest priority, so if there's
427 a variable whose name collides with that of a magic fn, automagic
427 a variable whose name collides with that of a magic fn, automagic
428 won't work for that function (you get the variable instead). However,
428 won't work for that function (you get the variable instead). However,
429 if you delete the variable (del var), the previously shadowed magic
429 if you delete the variable (del var), the previously shadowed magic
430 function becomes visible to automagic again."""
430 function becomes visible to automagic again."""
431
431
432 rc = self.shell.rc
432 rc = self.shell.rc
433 rc.automagic = not rc.automagic
433 rc.automagic = not rc.automagic
434 print '\n' + Magic.auto_status[rc.automagic]
434 print '\n' + Magic.auto_status[rc.automagic]
435
435
436 def magic_autocall(self, parameter_s = ''):
436 def magic_autocall(self, parameter_s = ''):
437 """Make functions callable without having to type parentheses.
437 """Make functions callable without having to type parentheses.
438
438
439 Usage:
439 Usage:
440
440
441 %autocall [mode]
441 %autocall [mode]
442
442
443 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
443 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
444 value is toggled on and off (remembering the previous state)."""
444 value is toggled on and off (remembering the previous state)."""
445
445
446 rc = self.shell.rc
446 rc = self.shell.rc
447
447
448 if parameter_s:
448 if parameter_s:
449 arg = int(parameter_s)
449 arg = int(parameter_s)
450 else:
450 else:
451 arg = 'toggle'
451 arg = 'toggle'
452
452
453 if not arg in (0,1,2,'toggle'):
453 if not arg in (0,1,2,'toggle'):
454 error('Valid modes: (0->Off, 1->Smart, 2->Full')
454 error('Valid modes: (0->Off, 1->Smart, 2->Full')
455 return
455 return
456
456
457 if arg in (0,1,2):
457 if arg in (0,1,2):
458 rc.autocall = arg
458 rc.autocall = arg
459 else: # toggle
459 else: # toggle
460 if rc.autocall:
460 if rc.autocall:
461 self._magic_state.autocall_save = rc.autocall
461 self._magic_state.autocall_save = rc.autocall
462 rc.autocall = 0
462 rc.autocall = 0
463 else:
463 else:
464 try:
464 try:
465 rc.autocall = self._magic_state.autocall_save
465 rc.autocall = self._magic_state.autocall_save
466 except AttributeError:
466 except AttributeError:
467 rc.autocall = self._magic_state.autocall_save = 1
467 rc.autocall = self._magic_state.autocall_save = 1
468
468
469 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
469 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
470
470
471 def magic_autoindent(self, parameter_s = ''):
471 def magic_autoindent(self, parameter_s = ''):
472 """Toggle autoindent on/off (if available)."""
472 """Toggle autoindent on/off (if available)."""
473
473
474 self.shell.set_autoindent()
474 self.shell.set_autoindent()
475 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
475 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
476
476
477 def magic_system_verbose(self, parameter_s = ''):
477 def magic_system_verbose(self, parameter_s = ''):
478 """Toggle verbose printing of system calls on/off."""
478 """Toggle verbose printing of system calls on/off."""
479
479
480 self.shell.rc_set_toggle('system_verbose')
480 self.shell.rc_set_toggle('system_verbose')
481 print "System verbose printing is:",\
481 print "System verbose printing is:",\
482 ['OFF','ON'][self.shell.rc.system_verbose]
482 ['OFF','ON'][self.shell.rc.system_verbose]
483
483
484 def magic_history(self, parameter_s = ''):
484 def magic_history(self, parameter_s = ''):
485 """Print input history (_i<n> variables), with most recent last.
485 """Print input history (_i<n> variables), with most recent last.
486
486
487 %history -> print at most 40 inputs (some may be multi-line)\\
487 %history -> print at most 40 inputs (some may be multi-line)\\
488 %history n -> print at most n inputs\\
488 %history n -> print at most n inputs\\
489 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
489 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
490
490
491 Each input's number <n> is shown, and is accessible as the
491 Each input's number <n> is shown, and is accessible as the
492 automatically generated variable _i<n>. Multi-line statements are
492 automatically generated variable _i<n>. Multi-line statements are
493 printed starting at a new line for easy copy/paste.
493 printed starting at a new line for easy copy/paste.
494
494
495
495
496 Options:
496 Options:
497
497
498 -n: do NOT print line numbers. This is useful if you want to get a
498 -n: do NOT print line numbers. This is useful if you want to get a
499 printout of many lines which can be directly pasted into a text
499 printout of many lines which can be directly pasted into a text
500 editor.
500 editor.
501
501
502 This feature is only available if numbered prompts are in use.
502 This feature is only available if numbered prompts are in use.
503
503
504 -r: print the 'raw' history. IPython filters your input and
504 -r: print the 'raw' history. IPython filters your input and
505 converts it all into valid Python source before executing it (things
505 converts it all into valid Python source before executing it (things
506 like magics or aliases are turned into function calls, for
506 like magics or aliases are turned into function calls, for
507 example). With this option, you'll see the unfiltered history
507 example). With this option, you'll see the unfiltered history
508 instead of the filtered version: '%cd /' will be seen as '%cd /'
508 instead of the filtered version: '%cd /' will be seen as '%cd /'
509 instead of '_ip.magic("%cd /")'.
509 instead of '_ip.magic("%cd /")'.
510 """
510 """
511
511
512 shell = self.shell
512 shell = self.shell
513 if not shell.outputcache.do_full_cache:
513 if not shell.outputcache.do_full_cache:
514 print 'This feature is only available if numbered prompts are in use.'
514 print 'This feature is only available if numbered prompts are in use.'
515 return
515 return
516 opts,args = self.parse_options(parameter_s,'nr',mode='list')
516 opts,args = self.parse_options(parameter_s,'nr',mode='list')
517
517
518 if opts.has_key('r'):
518 if opts.has_key('r'):
519 input_hist = shell.input_hist_raw
519 input_hist = shell.input_hist_raw
520 else:
520 else:
521 input_hist = shell.input_hist
521 input_hist = shell.input_hist
522
522
523 default_length = 40
523 default_length = 40
524 if len(args) == 0:
524 if len(args) == 0:
525 final = len(input_hist)
525 final = len(input_hist)
526 init = max(1,final-default_length)
526 init = max(1,final-default_length)
527 elif len(args) == 1:
527 elif len(args) == 1:
528 final = len(input_hist)
528 final = len(input_hist)
529 init = max(1,final-int(args[0]))
529 init = max(1,final-int(args[0]))
530 elif len(args) == 2:
530 elif len(args) == 2:
531 init,final = map(int,args)
531 init,final = map(int,args)
532 else:
532 else:
533 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
533 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
534 print self.magic_hist.__doc__
534 print self.magic_hist.__doc__
535 return
535 return
536 width = len(str(final))
536 width = len(str(final))
537 line_sep = ['','\n']
537 line_sep = ['','\n']
538 print_nums = not opts.has_key('n')
538 print_nums = not opts.has_key('n')
539 for in_num in range(init,final):
539 for in_num in range(init,final):
540 inline = input_hist[in_num]
540 inline = input_hist[in_num]
541 multiline = int(inline.count('\n') > 1)
541 multiline = int(inline.count('\n') > 1)
542 if print_nums:
542 if print_nums:
543 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
543 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
544 print inline,
544 print inline,
545
545
546 def magic_hist(self, parameter_s=''):
546 def magic_hist(self, parameter_s=''):
547 """Alternate name for %history."""
547 """Alternate name for %history."""
548 return self.magic_history(parameter_s)
548 return self.magic_history(parameter_s)
549
549
550 def magic_p(self, parameter_s=''):
550 def magic_p(self, parameter_s=''):
551 """Just a short alias for Python's 'print'."""
551 """Just a short alias for Python's 'print'."""
552 exec 'print ' + parameter_s in self.shell.user_ns
552 exec 'print ' + parameter_s in self.shell.user_ns
553
553
554 def magic_r(self, parameter_s=''):
554 def magic_r(self, parameter_s=''):
555 """Repeat previous input.
555 """Repeat previous input.
556
556
557 If given an argument, repeats the previous command which starts with
557 If given an argument, repeats the previous command which starts with
558 the same string, otherwise it just repeats the previous input.
558 the same string, otherwise it just repeats the previous input.
559
559
560 Shell escaped commands (with ! as first character) are not recognized
560 Shell escaped commands (with ! as first character) are not recognized
561 by this system, only pure python code and magic commands.
561 by this system, only pure python code and magic commands.
562 """
562 """
563
563
564 start = parameter_s.strip()
564 start = parameter_s.strip()
565 esc_magic = self.shell.ESC_MAGIC
565 esc_magic = self.shell.ESC_MAGIC
566 # Identify magic commands even if automagic is on (which means
566 # Identify magic commands even if automagic is on (which means
567 # the in-memory version is different from that typed by the user).
567 # the in-memory version is different from that typed by the user).
568 if self.shell.rc.automagic:
568 if self.shell.rc.automagic:
569 start_magic = esc_magic+start
569 start_magic = esc_magic+start
570 else:
570 else:
571 start_magic = start
571 start_magic = start
572 # Look through the input history in reverse
572 # Look through the input history in reverse
573 for n in range(len(self.shell.input_hist)-2,0,-1):
573 for n in range(len(self.shell.input_hist)-2,0,-1):
574 input = self.shell.input_hist[n]
574 input = self.shell.input_hist[n]
575 # skip plain 'r' lines so we don't recurse to infinity
575 # skip plain 'r' lines so we don't recurse to infinity
576 if input != '_ip.magic("r")\n' and \
576 if input != '_ip.magic("r")\n' and \
577 (input.startswith(start) or input.startswith(start_magic)):
577 (input.startswith(start) or input.startswith(start_magic)):
578 #print 'match',`input` # dbg
578 #print 'match',`input` # dbg
579 print 'Executing:',input,
579 print 'Executing:',input,
580 self.shell.runlines(input)
580 self.shell.runlines(input)
581 return
581 return
582 print 'No previous input matching `%s` found.' % start
582 print 'No previous input matching `%s` found.' % start
583
583
584 def magic_page(self, parameter_s=''):
584 def magic_page(self, parameter_s=''):
585 """Pretty print the object and display it through a pager.
585 """Pretty print the object and display it through a pager.
586
586
587 If no parameter is given, use _ (last output)."""
587 If no parameter is given, use _ (last output)."""
588 # After a function contributed by Olivier Aubert, slightly modified.
588 # After a function contributed by Olivier Aubert, slightly modified.
589
589
590 oname = parameter_s and parameter_s or '_'
590 oname = parameter_s and parameter_s or '_'
591 info = self._ofind(oname)
591 info = self._ofind(oname)
592 if info['found']:
592 if info['found']:
593 page(pformat(info['obj']))
593 page(pformat(info['obj']))
594 else:
594 else:
595 print 'Object `%s` not found' % oname
595 print 'Object `%s` not found' % oname
596
596
597 def magic_profile(self, parameter_s=''):
597 def magic_profile(self, parameter_s=''):
598 """Print your currently active IPyhton profile."""
598 """Print your currently active IPyhton profile."""
599 if self.shell.rc.profile:
599 if self.shell.rc.profile:
600 printpl('Current IPython profile: $self.shell.rc.profile.')
600 printpl('Current IPython profile: $self.shell.rc.profile.')
601 else:
601 else:
602 print 'No profile active.'
602 print 'No profile active.'
603
603
604 def _inspect(self,meth,oname,**kw):
604 def _inspect(self,meth,oname,**kw):
605 """Generic interface to the inspector system.
605 """Generic interface to the inspector system.
606
606
607 This function is meant to be called by pdef, pdoc & friends."""
607 This function is meant to be called by pdef, pdoc & friends."""
608
608
609 oname = oname.strip()
609 oname = oname.strip()
610 info = Struct(self._ofind(oname))
610 info = Struct(self._ofind(oname))
611 if info.found:
611 if info.found:
612 pmethod = getattr(self.shell.inspector,meth)
612 pmethod = getattr(self.shell.inspector,meth)
613 formatter = info.ismagic and self.format_screen or None
613 formatter = info.ismagic and self.format_screen or None
614 if meth == 'pdoc':
614 if meth == 'pdoc':
615 pmethod(info.obj,oname,formatter)
615 pmethod(info.obj,oname,formatter)
616 elif meth == 'pinfo':
616 elif meth == 'pinfo':
617 pmethod(info.obj,oname,formatter,info,**kw)
617 pmethod(info.obj,oname,formatter,info,**kw)
618 else:
618 else:
619 pmethod(info.obj,oname)
619 pmethod(info.obj,oname)
620 else:
620 else:
621 print 'Object `%s` not found.' % oname
621 print 'Object `%s` not found.' % oname
622 return 'not found' # so callers can take other action
622 return 'not found' # so callers can take other action
623
623
624 def magic_pdef(self, parameter_s=''):
624 def magic_pdef(self, parameter_s=''):
625 """Print the definition header for any callable object.
625 """Print the definition header for any callable object.
626
626
627 If the object is a class, print the constructor information."""
627 If the object is a class, print the constructor information."""
628 self._inspect('pdef',parameter_s)
628 self._inspect('pdef',parameter_s)
629
629
630 def magic_pdoc(self, parameter_s=''):
630 def magic_pdoc(self, parameter_s=''):
631 """Print the docstring for an object.
631 """Print the docstring for an object.
632
632
633 If the given object is a class, it will print both the class and the
633 If the given object is a class, it will print both the class and the
634 constructor docstrings."""
634 constructor docstrings."""
635 self._inspect('pdoc',parameter_s)
635 self._inspect('pdoc',parameter_s)
636
636
637 def magic_psource(self, parameter_s=''):
637 def magic_psource(self, parameter_s=''):
638 """Print (or run through pager) the source code for an object."""
638 """Print (or run through pager) the source code for an object."""
639 self._inspect('psource',parameter_s)
639 self._inspect('psource',parameter_s)
640
640
641 def magic_pfile(self, parameter_s=''):
641 def magic_pfile(self, parameter_s=''):
642 """Print (or run through pager) the file where an object is defined.
642 """Print (or run through pager) the file where an object is defined.
643
643
644 The file opens at the line where the object definition begins. IPython
644 The file opens at the line where the object definition begins. IPython
645 will honor the environment variable PAGER if set, and otherwise will
645 will honor the environment variable PAGER if set, and otherwise will
646 do its best to print the file in a convenient form.
646 do its best to print the file in a convenient form.
647
647
648 If the given argument is not an object currently defined, IPython will
648 If the given argument is not an object currently defined, IPython will
649 try to interpret it as a filename (automatically adding a .py extension
649 try to interpret it as a filename (automatically adding a .py extension
650 if needed). You can thus use %pfile as a syntax highlighting code
650 if needed). You can thus use %pfile as a syntax highlighting code
651 viewer."""
651 viewer."""
652
652
653 # first interpret argument as an object name
653 # first interpret argument as an object name
654 out = self._inspect('pfile',parameter_s)
654 out = self._inspect('pfile',parameter_s)
655 # if not, try the input as a filename
655 # if not, try the input as a filename
656 if out == 'not found':
656 if out == 'not found':
657 try:
657 try:
658 filename = get_py_filename(parameter_s)
658 filename = get_py_filename(parameter_s)
659 except IOError,msg:
659 except IOError,msg:
660 print msg
660 print msg
661 return
661 return
662 page(self.shell.inspector.format(file(filename).read()))
662 page(self.shell.inspector.format(file(filename).read()))
663
663
664 def magic_pinfo(self, parameter_s=''):
664 def magic_pinfo(self, parameter_s=''):
665 """Provide detailed information about an object.
665 """Provide detailed information about an object.
666
666
667 '%pinfo object' is just a synonym for object? or ?object."""
667 '%pinfo object' is just a synonym for object? or ?object."""
668
668
669 #print 'pinfo par: <%s>' % parameter_s # dbg
669 #print 'pinfo par: <%s>' % parameter_s # dbg
670
670
671 # detail_level: 0 -> obj? , 1 -> obj??
671 # detail_level: 0 -> obj? , 1 -> obj??
672 detail_level = 0
672 detail_level = 0
673 # We need to detect if we got called as 'pinfo pinfo foo', which can
673 # We need to detect if we got called as 'pinfo pinfo foo', which can
674 # happen if the user types 'pinfo foo?' at the cmd line.
674 # happen if the user types 'pinfo foo?' at the cmd line.
675 pinfo,qmark1,oname,qmark2 = \
675 pinfo,qmark1,oname,qmark2 = \
676 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
676 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
677 if pinfo or qmark1 or qmark2:
677 if pinfo or qmark1 or qmark2:
678 detail_level = 1
678 detail_level = 1
679 if "*" in oname:
679 if "*" in oname:
680 self.magic_psearch(oname)
680 self.magic_psearch(oname)
681 else:
681 else:
682 self._inspect('pinfo',oname,detail_level=detail_level)
682 self._inspect('pinfo',oname,detail_level=detail_level)
683
683
684 def magic_psearch(self, parameter_s=''):
684 def magic_psearch(self, parameter_s=''):
685 """Search for object in namespaces by wildcard.
685 """Search for object in namespaces by wildcard.
686
686
687 %psearch [options] PATTERN [OBJECT TYPE]
687 %psearch [options] PATTERN [OBJECT TYPE]
688
688
689 Note: ? can be used as a synonym for %psearch, at the beginning or at
689 Note: ? can be used as a synonym for %psearch, at the beginning or at
690 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
690 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
691 rest of the command line must be unchanged (options come first), so
691 rest of the command line must be unchanged (options come first), so
692 for example the following forms are equivalent
692 for example the following forms are equivalent
693
693
694 %psearch -i a* function
694 %psearch -i a* function
695 -i a* function?
695 -i a* function?
696 ?-i a* function
696 ?-i a* function
697
697
698 Arguments:
698 Arguments:
699
699
700 PATTERN
700 PATTERN
701
701
702 where PATTERN is a string containing * as a wildcard similar to its
702 where PATTERN is a string containing * as a wildcard similar to its
703 use in a shell. The pattern is matched in all namespaces on the
703 use in a shell. The pattern is matched in all namespaces on the
704 search path. By default objects starting with a single _ are not
704 search path. By default objects starting with a single _ are not
705 matched, many IPython generated objects have a single
705 matched, many IPython generated objects have a single
706 underscore. The default is case insensitive matching. Matching is
706 underscore. The default is case insensitive matching. Matching is
707 also done on the attributes of objects and not only on the objects
707 also done on the attributes of objects and not only on the objects
708 in a module.
708 in a module.
709
709
710 [OBJECT TYPE]
710 [OBJECT TYPE]
711
711
712 Is the name of a python type from the types module. The name is
712 Is the name of a python type from the types module. The name is
713 given in lowercase without the ending type, ex. StringType is
713 given in lowercase without the ending type, ex. StringType is
714 written string. By adding a type here only objects matching the
714 written string. By adding a type here only objects matching the
715 given type are matched. Using all here makes the pattern match all
715 given type are matched. Using all here makes the pattern match all
716 types (this is the default).
716 types (this is the default).
717
717
718 Options:
718 Options:
719
719
720 -a: makes the pattern match even objects whose names start with a
720 -a: makes the pattern match even objects whose names start with a
721 single underscore. These names are normally ommitted from the
721 single underscore. These names are normally ommitted from the
722 search.
722 search.
723
723
724 -i/-c: make the pattern case insensitive/sensitive. If neither of
724 -i/-c: make the pattern case insensitive/sensitive. If neither of
725 these options is given, the default is read from your ipythonrc
725 these options is given, the default is read from your ipythonrc
726 file. The option name which sets this value is
726 file. The option name which sets this value is
727 'wildcards_case_sensitive'. If this option is not specified in your
727 'wildcards_case_sensitive'. If this option is not specified in your
728 ipythonrc file, IPython's internal default is to do a case sensitive
728 ipythonrc file, IPython's internal default is to do a case sensitive
729 search.
729 search.
730
730
731 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
731 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
732 specifiy can be searched in any of the following namespaces:
732 specifiy can be searched in any of the following namespaces:
733 'builtin', 'user', 'user_global','internal', 'alias', where
733 'builtin', 'user', 'user_global','internal', 'alias', where
734 'builtin' and 'user' are the search defaults. Note that you should
734 'builtin' and 'user' are the search defaults. Note that you should
735 not use quotes when specifying namespaces.
735 not use quotes when specifying namespaces.
736
736
737 'Builtin' contains the python module builtin, 'user' contains all
737 'Builtin' contains the python module builtin, 'user' contains all
738 user data, 'alias' only contain the shell aliases and no python
738 user data, 'alias' only contain the shell aliases and no python
739 objects, 'internal' contains objects used by IPython. The
739 objects, 'internal' contains objects used by IPython. The
740 'user_global' namespace is only used by embedded IPython instances,
740 'user_global' namespace is only used by embedded IPython instances,
741 and it contains module-level globals. You can add namespaces to the
741 and it contains module-level globals. You can add namespaces to the
742 search with -s or exclude them with -e (these options can be given
742 search with -s or exclude them with -e (these options can be given
743 more than once).
743 more than once).
744
744
745 Examples:
745 Examples:
746
746
747 %psearch a* -> objects beginning with an a
747 %psearch a* -> objects beginning with an a
748 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
748 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
749 %psearch a* function -> all functions beginning with an a
749 %psearch a* function -> all functions beginning with an a
750 %psearch re.e* -> objects beginning with an e in module re
750 %psearch re.e* -> objects beginning with an e in module re
751 %psearch r*.e* -> objects that start with e in modules starting in r
751 %psearch r*.e* -> objects that start with e in modules starting in r
752 %psearch r*.* string -> all strings in modules beginning with r
752 %psearch r*.* string -> all strings in modules beginning with r
753
753
754 Case sensitve search:
754 Case sensitve search:
755
755
756 %psearch -c a* list all object beginning with lower case a
756 %psearch -c a* list all object beginning with lower case a
757
757
758 Show objects beginning with a single _:
758 Show objects beginning with a single _:
759
759
760 %psearch -a _* list objects beginning with a single underscore"""
760 %psearch -a _* list objects beginning with a single underscore"""
761
761
762 # default namespaces to be searched
762 # default namespaces to be searched
763 def_search = ['user','builtin']
763 def_search = ['user','builtin']
764
764
765 # Process options/args
765 # Process options/args
766 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
766 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
767 opt = opts.get
767 opt = opts.get
768 shell = self.shell
768 shell = self.shell
769 psearch = shell.inspector.psearch
769 psearch = shell.inspector.psearch
770
770
771 # select case options
771 # select case options
772 if opts.has_key('i'):
772 if opts.has_key('i'):
773 ignore_case = True
773 ignore_case = True
774 elif opts.has_key('c'):
774 elif opts.has_key('c'):
775 ignore_case = False
775 ignore_case = False
776 else:
776 else:
777 ignore_case = not shell.rc.wildcards_case_sensitive
777 ignore_case = not shell.rc.wildcards_case_sensitive
778
778
779 # Build list of namespaces to search from user options
779 # Build list of namespaces to search from user options
780 def_search.extend(opt('s',[]))
780 def_search.extend(opt('s',[]))
781 ns_exclude = ns_exclude=opt('e',[])
781 ns_exclude = ns_exclude=opt('e',[])
782 ns_search = [nm for nm in def_search if nm not in ns_exclude]
782 ns_search = [nm for nm in def_search if nm not in ns_exclude]
783
783
784 # Call the actual search
784 # Call the actual search
785 try:
785 try:
786 psearch(args,shell.ns_table,ns_search,
786 psearch(args,shell.ns_table,ns_search,
787 show_all=opt('a'),ignore_case=ignore_case)
787 show_all=opt('a'),ignore_case=ignore_case)
788 except:
788 except:
789 shell.showtraceback()
789 shell.showtraceback()
790
790
791 def magic_who_ls(self, parameter_s=''):
791 def magic_who_ls(self, parameter_s=''):
792 """Return a sorted list of all interactive variables.
792 """Return a sorted list of all interactive variables.
793
793
794 If arguments are given, only variables of types matching these
794 If arguments are given, only variables of types matching these
795 arguments are returned."""
795 arguments are returned."""
796
796
797 user_ns = self.shell.user_ns
797 user_ns = self.shell.user_ns
798 internal_ns = self.shell.internal_ns
798 internal_ns = self.shell.internal_ns
799 user_config_ns = self.shell.user_config_ns
799 user_config_ns = self.shell.user_config_ns
800 out = []
800 out = []
801 typelist = parameter_s.split()
801 typelist = parameter_s.split()
802
802
803 for i in user_ns:
803 for i in user_ns:
804 if not (i.startswith('_') or i.startswith('_i')) \
804 if not (i.startswith('_') or i.startswith('_i')) \
805 and not (i in internal_ns or i in user_config_ns):
805 and not (i in internal_ns or i in user_config_ns):
806 if typelist:
806 if typelist:
807 if type(user_ns[i]).__name__ in typelist:
807 if type(user_ns[i]).__name__ in typelist:
808 out.append(i)
808 out.append(i)
809 else:
809 else:
810 out.append(i)
810 out.append(i)
811 out.sort()
811 out.sort()
812 return out
812 return out
813
813
814 def magic_who(self, parameter_s=''):
814 def magic_who(self, parameter_s=''):
815 """Print all interactive variables, with some minimal formatting.
815 """Print all interactive variables, with some minimal formatting.
816
816
817 If any arguments are given, only variables whose type matches one of
817 If any arguments are given, only variables whose type matches one of
818 these are printed. For example:
818 these are printed. For example:
819
819
820 %who function str
820 %who function str
821
821
822 will only list functions and strings, excluding all other types of
822 will only list functions and strings, excluding all other types of
823 variables. To find the proper type names, simply use type(var) at a
823 variables. To find the proper type names, simply use type(var) at a
824 command line to see how python prints type names. For example:
824 command line to see how python prints type names. For example:
825
825
826 In [1]: type('hello')\\
826 In [1]: type('hello')\\
827 Out[1]: <type 'str'>
827 Out[1]: <type 'str'>
828
828
829 indicates that the type name for strings is 'str'.
829 indicates that the type name for strings is 'str'.
830
830
831 %who always excludes executed names loaded through your configuration
831 %who always excludes executed names loaded through your configuration
832 file and things which are internal to IPython.
832 file and things which are internal to IPython.
833
833
834 This is deliberate, as typically you may load many modules and the
834 This is deliberate, as typically you may load many modules and the
835 purpose of %who is to show you only what you've manually defined."""
835 purpose of %who is to show you only what you've manually defined."""
836
836
837 varlist = self.magic_who_ls(parameter_s)
837 varlist = self.magic_who_ls(parameter_s)
838 if not varlist:
838 if not varlist:
839 print 'Interactive namespace is empty.'
839 print 'Interactive namespace is empty.'
840 return
840 return
841
841
842 # if we have variables, move on...
842 # if we have variables, move on...
843
843
844 # stupid flushing problem: when prompts have no separators, stdout is
844 # stupid flushing problem: when prompts have no separators, stdout is
845 # getting lost. I'm starting to think this is a python bug. I'm having
845 # getting lost. I'm starting to think this is a python bug. I'm having
846 # to force a flush with a print because even a sys.stdout.flush
846 # to force a flush with a print because even a sys.stdout.flush
847 # doesn't seem to do anything!
847 # doesn't seem to do anything!
848
848
849 count = 0
849 count = 0
850 for i in varlist:
850 for i in varlist:
851 print i+'\t',
851 print i+'\t',
852 count += 1
852 count += 1
853 if count > 8:
853 if count > 8:
854 count = 0
854 count = 0
855 print
855 print
856 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
856 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
857
857
858 print # well, this does force a flush at the expense of an extra \n
858 print # well, this does force a flush at the expense of an extra \n
859
859
860 def magic_whos(self, parameter_s=''):
860 def magic_whos(self, parameter_s=''):
861 """Like %who, but gives some extra information about each variable.
861 """Like %who, but gives some extra information about each variable.
862
862
863 The same type filtering of %who can be applied here.
863 The same type filtering of %who can be applied here.
864
864
865 For all variables, the type is printed. Additionally it prints:
865 For all variables, the type is printed. Additionally it prints:
866
866
867 - For {},[],(): their length.
867 - For {},[],(): their length.
868
868
869 - For Numeric arrays, a summary with shape, number of elements,
869 - For Numeric arrays, a summary with shape, number of elements,
870 typecode and size in memory.
870 typecode and size in memory.
871
871
872 - Everything else: a string representation, snipping their middle if
872 - Everything else: a string representation, snipping their middle if
873 too long."""
873 too long."""
874
874
875 varnames = self.magic_who_ls(parameter_s)
875 varnames = self.magic_who_ls(parameter_s)
876 if not varnames:
876 if not varnames:
877 print 'Interactive namespace is empty.'
877 print 'Interactive namespace is empty.'
878 return
878 return
879
879
880 # if we have variables, move on...
880 # if we have variables, move on...
881
881
882 # for these types, show len() instead of data:
882 # for these types, show len() instead of data:
883 seq_types = [types.DictType,types.ListType,types.TupleType]
883 seq_types = [types.DictType,types.ListType,types.TupleType]
884
884
885 # for Numeric arrays, display summary info
885 # for Numeric arrays, display summary info
886 try:
886 try:
887 import Numeric
887 import Numeric
888 except ImportError:
888 except ImportError:
889 array_type = None
889 array_type = None
890 else:
890 else:
891 array_type = Numeric.ArrayType.__name__
891 array_type = Numeric.ArrayType.__name__
892
892
893 # Find all variable names and types so we can figure out column sizes
893 # Find all variable names and types so we can figure out column sizes
894 get_vars = lambda i: self.shell.user_ns[i]
894 get_vars = lambda i: self.shell.user_ns[i]
895 type_name = lambda v: type(v).__name__
895 type_name = lambda v: type(v).__name__
896 varlist = map(get_vars,varnames)
896 varlist = map(get_vars,varnames)
897
897
898 typelist = []
898 typelist = []
899 for vv in varlist:
899 for vv in varlist:
900 tt = type_name(vv)
900 tt = type_name(vv)
901 if tt=='instance':
901 if tt=='instance':
902 typelist.append(str(vv.__class__))
902 typelist.append(str(vv.__class__))
903 else:
903 else:
904 typelist.append(tt)
904 typelist.append(tt)
905
905
906 # column labels and # of spaces as separator
906 # column labels and # of spaces as separator
907 varlabel = 'Variable'
907 varlabel = 'Variable'
908 typelabel = 'Type'
908 typelabel = 'Type'
909 datalabel = 'Data/Info'
909 datalabel = 'Data/Info'
910 colsep = 3
910 colsep = 3
911 # variable format strings
911 # variable format strings
912 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
912 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
913 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
913 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
914 aformat = "%s: %s elems, type `%s`, %s bytes"
914 aformat = "%s: %s elems, type `%s`, %s bytes"
915 # find the size of the columns to format the output nicely
915 # find the size of the columns to format the output nicely
916 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
916 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
917 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
917 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
918 # table header
918 # table header
919 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
919 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
920 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
920 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
921 # and the table itself
921 # and the table itself
922 kb = 1024
922 kb = 1024
923 Mb = 1048576 # kb**2
923 Mb = 1048576 # kb**2
924 for vname,var,vtype in zip(varnames,varlist,typelist):
924 for vname,var,vtype in zip(varnames,varlist,typelist):
925 print itpl(vformat),
925 print itpl(vformat),
926 if vtype in seq_types:
926 if vtype in seq_types:
927 print len(var)
927 print len(var)
928 elif vtype==array_type:
928 elif vtype==array_type:
929 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
929 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
930 vsize = Numeric.size(var)
930 vsize = Numeric.size(var)
931 vbytes = vsize*var.itemsize()
931 vbytes = vsize*var.itemsize()
932 if vbytes < 100000:
932 if vbytes < 100000:
933 print aformat % (vshape,vsize,var.typecode(),vbytes)
933 print aformat % (vshape,vsize,var.typecode(),vbytes)
934 else:
934 else:
935 print aformat % (vshape,vsize,var.typecode(),vbytes),
935 print aformat % (vshape,vsize,var.typecode(),vbytes),
936 if vbytes < Mb:
936 if vbytes < Mb:
937 print '(%s kb)' % (vbytes/kb,)
937 print '(%s kb)' % (vbytes/kb,)
938 else:
938 else:
939 print '(%s Mb)' % (vbytes/Mb,)
939 print '(%s Mb)' % (vbytes/Mb,)
940 else:
940 else:
941 vstr = str(var).replace('\n','\\n')
941 vstr = str(var).replace('\n','\\n')
942 if len(vstr) < 50:
942 if len(vstr) < 50:
943 print vstr
943 print vstr
944 else:
944 else:
945 printpl(vfmt_short)
945 printpl(vfmt_short)
946
946
947 def magic_reset(self, parameter_s=''):
947 def magic_reset(self, parameter_s=''):
948 """Resets the namespace by removing all names defined by the user.
948 """Resets the namespace by removing all names defined by the user.
949
949
950 Input/Output history are left around in case you need them."""
950 Input/Output history are left around in case you need them."""
951
951
952 ans = raw_input(
952 ans = raw_input(
953 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
953 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
954 if not ans.lower() == 'y':
954 if not ans.lower() == 'y':
955 print 'Nothing done.'
955 print 'Nothing done.'
956 return
956 return
957 user_ns = self.shell.user_ns
957 user_ns = self.shell.user_ns
958 for i in self.magic_who_ls():
958 for i in self.magic_who_ls():
959 del(user_ns[i])
959 del(user_ns[i])
960
960
961 def magic_config(self,parameter_s=''):
961 def magic_config(self,parameter_s=''):
962 """Show IPython's internal configuration."""
962 """Show IPython's internal configuration."""
963
963
964 page('Current configuration structure:\n'+
964 page('Current configuration structure:\n'+
965 pformat(self.shell.rc.dict()))
965 pformat(self.shell.rc.dict()))
966
966
967 def magic_logstart(self,parameter_s=''):
967 def magic_logstart(self,parameter_s=''):
968 """Start logging anywhere in a session.
968 """Start logging anywhere in a session.
969
969
970 %logstart [-o|-t] [log_name [log_mode]]
970 %logstart [-o|-t] [log_name [log_mode]]
971
971
972 If no name is given, it defaults to a file named 'ipython_log.py' in your
972 If no name is given, it defaults to a file named 'ipython_log.py' in your
973 current directory, in 'rotate' mode (see below).
973 current directory, in 'rotate' mode (see below).
974
974
975 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
975 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
976 history up to that point and then continues logging.
976 history up to that point and then continues logging.
977
977
978 %logstart takes a second optional parameter: logging mode. This can be one
978 %logstart takes a second optional parameter: logging mode. This can be one
979 of (note that the modes are given unquoted):\\
979 of (note that the modes are given unquoted):\\
980 append: well, that says it.\\
980 append: well, that says it.\\
981 backup: rename (if exists) to name~ and start name.\\
981 backup: rename (if exists) to name~ and start name.\\
982 global: single logfile in your home dir, appended to.\\
982 global: single logfile in your home dir, appended to.\\
983 over : overwrite existing log.\\
983 over : overwrite existing log.\\
984 rotate: create rotating logs name.1~, name.2~, etc.
984 rotate: create rotating logs name.1~, name.2~, etc.
985
985
986 Options:
986 Options:
987
987
988 -o: log also IPython's output. In this mode, all commands which
988 -o: log also IPython's output. In this mode, all commands which
989 generate an Out[NN] prompt are recorded to the logfile, right after
989 generate an Out[NN] prompt are recorded to the logfile, right after
990 their corresponding input line. The output lines are always
990 their corresponding input line. The output lines are always
991 prepended with a '#[Out]# ' marker, so that the log remains valid
991 prepended with a '#[Out]# ' marker, so that the log remains valid
992 Python code.
992 Python code.
993
993
994 Since this marker is always the same, filtering only the output from
994 Since this marker is always the same, filtering only the output from
995 a log is very easy, using for example a simple awk call:
995 a log is very easy, using for example a simple awk call:
996
996
997 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
997 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
998
998
999 -t: put timestamps before each input line logged (these are put in
999 -t: put timestamps before each input line logged (these are put in
1000 comments)."""
1000 comments)."""
1001
1001
1002 opts,par = self.parse_options(parameter_s,'ot')
1002 opts,par = self.parse_options(parameter_s,'ot')
1003 log_output = 'o' in opts
1003 log_output = 'o' in opts
1004 timestamp = 't' in opts
1004 timestamp = 't' in opts
1005
1005
1006 rc = self.shell.rc
1006 rc = self.shell.rc
1007 logger = self.shell.logger
1007 logger = self.shell.logger
1008
1008
1009 # if no args are given, the defaults set in the logger constructor by
1009 # if no args are given, the defaults set in the logger constructor by
1010 # ipytohn remain valid
1010 # ipytohn remain valid
1011 if par:
1011 if par:
1012 try:
1012 try:
1013 logfname,logmode = par.split()
1013 logfname,logmode = par.split()
1014 except:
1014 except:
1015 logfname = par
1015 logfname = par
1016 logmode = 'backup'
1016 logmode = 'backup'
1017 else:
1017 else:
1018 logfname = logger.logfname
1018 logfname = logger.logfname
1019 logmode = logger.logmode
1019 logmode = logger.logmode
1020 # put logfname into rc struct as if it had been called on the command
1020 # put logfname into rc struct as if it had been called on the command
1021 # line, so it ends up saved in the log header Save it in case we need
1021 # line, so it ends up saved in the log header Save it in case we need
1022 # to restore it...
1022 # to restore it...
1023 old_logfile = rc.opts.get('logfile','')
1023 old_logfile = rc.opts.get('logfile','')
1024 if logfname:
1024 if logfname:
1025 logfname = os.path.expanduser(logfname)
1025 logfname = os.path.expanduser(logfname)
1026 rc.opts.logfile = logfname
1026 rc.opts.logfile = logfname
1027 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1027 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1028 try:
1028 try:
1029 started = logger.logstart(logfname,loghead,logmode,
1029 started = logger.logstart(logfname,loghead,logmode,
1030 log_output,timestamp)
1030 log_output,timestamp)
1031 except:
1031 except:
1032 rc.opts.logfile = old_logfile
1032 rc.opts.logfile = old_logfile
1033 warn("Couldn't start log: %s" % sys.exc_info()[1])
1033 warn("Couldn't start log: %s" % sys.exc_info()[1])
1034 else:
1034 else:
1035 # log input history up to this point, optionally interleaving
1035 # log input history up to this point, optionally interleaving
1036 # output if requested
1036 # output if requested
1037
1037
1038 if timestamp:
1038 if timestamp:
1039 # disable timestamping for the previous history, since we've
1039 # disable timestamping for the previous history, since we've
1040 # lost those already (no time machine here).
1040 # lost those already (no time machine here).
1041 logger.timestamp = False
1041 logger.timestamp = False
1042 if log_output:
1042 if log_output:
1043 log_write = logger.log_write
1043 log_write = logger.log_write
1044 input_hist = self.shell.input_hist
1044 input_hist = self.shell.input_hist
1045 output_hist = self.shell.output_hist
1045 output_hist = self.shell.output_hist
1046 for n in range(1,len(input_hist)-1):
1046 for n in range(1,len(input_hist)-1):
1047 log_write(input_hist[n].rstrip())
1047 log_write(input_hist[n].rstrip())
1048 if n in output_hist:
1048 if n in output_hist:
1049 log_write(repr(output_hist[n]),'output')
1049 log_write(repr(output_hist[n]),'output')
1050 else:
1050 else:
1051 logger.log_write(self.shell.input_hist[1:])
1051 logger.log_write(self.shell.input_hist[1:])
1052 if timestamp:
1052 if timestamp:
1053 # re-enable timestamping
1053 # re-enable timestamping
1054 logger.timestamp = True
1054 logger.timestamp = True
1055
1055
1056 print ('Activating auto-logging. '
1056 print ('Activating auto-logging. '
1057 'Current session state plus future input saved.')
1057 'Current session state plus future input saved.')
1058 logger.logstate()
1058 logger.logstate()
1059
1059
1060 def magic_logoff(self,parameter_s=''):
1060 def magic_logoff(self,parameter_s=''):
1061 """Temporarily stop logging.
1061 """Temporarily stop logging.
1062
1062
1063 You must have previously started logging."""
1063 You must have previously started logging."""
1064 self.shell.logger.switch_log(0)
1064 self.shell.logger.switch_log(0)
1065
1065
1066 def magic_logon(self,parameter_s=''):
1066 def magic_logon(self,parameter_s=''):
1067 """Restart logging.
1067 """Restart logging.
1068
1068
1069 This function is for restarting logging which you've temporarily
1069 This function is for restarting logging which you've temporarily
1070 stopped with %logoff. For starting logging for the first time, you
1070 stopped with %logoff. For starting logging for the first time, you
1071 must use the %logstart function, which allows you to specify an
1071 must use the %logstart function, which allows you to specify an
1072 optional log filename."""
1072 optional log filename."""
1073
1073
1074 self.shell.logger.switch_log(1)
1074 self.shell.logger.switch_log(1)
1075
1075
1076 def magic_logstate(self,parameter_s=''):
1076 def magic_logstate(self,parameter_s=''):
1077 """Print the status of the logging system."""
1077 """Print the status of the logging system."""
1078
1078
1079 self.shell.logger.logstate()
1079 self.shell.logger.logstate()
1080
1080
1081 def magic_pdb(self, parameter_s=''):
1081 def magic_pdb(self, parameter_s=''):
1082 """Control the calling of the pdb interactive debugger.
1082 """Control the calling of the pdb interactive debugger.
1083
1083
1084 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1084 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1085 argument it works as a toggle.
1085 argument it works as a toggle.
1086
1086
1087 When an exception is triggered, IPython can optionally call the
1087 When an exception is triggered, IPython can optionally call the
1088 interactive pdb debugger after the traceback printout. %pdb toggles
1088 interactive pdb debugger after the traceback printout. %pdb toggles
1089 this feature on and off."""
1089 this feature on and off."""
1090
1090
1091 par = parameter_s.strip().lower()
1091 par = parameter_s.strip().lower()
1092
1092
1093 if par:
1093 if par:
1094 try:
1094 try:
1095 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1095 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1096 except KeyError:
1096 except KeyError:
1097 print ('Incorrect argument. Use on/1, off/0, '
1097 print ('Incorrect argument. Use on/1, off/0, '
1098 'or nothing for a toggle.')
1098 'or nothing for a toggle.')
1099 return
1099 return
1100 else:
1100 else:
1101 # toggle
1101 # toggle
1102 new_pdb = not self.shell.InteractiveTB.call_pdb
1102 new_pdb = not self.shell.InteractiveTB.call_pdb
1103
1103
1104 # set on the shell
1104 # set on the shell
1105 self.shell.call_pdb = new_pdb
1105 self.shell.call_pdb = new_pdb
1106 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1106 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1107
1107
1108 def magic_prun(self, parameter_s ='',user_mode=1,
1108 def magic_prun(self, parameter_s ='',user_mode=1,
1109 opts=None,arg_lst=None,prog_ns=None):
1109 opts=None,arg_lst=None,prog_ns=None):
1110
1110
1111 """Run a statement through the python code profiler.
1111 """Run a statement through the python code profiler.
1112
1112
1113 Usage:\\
1113 Usage:\\
1114 %prun [options] statement
1114 %prun [options] statement
1115
1115
1116 The given statement (which doesn't require quote marks) is run via the
1116 The given statement (which doesn't require quote marks) is run via the
1117 python profiler in a manner similar to the profile.run() function.
1117 python profiler in a manner similar to the profile.run() function.
1118 Namespaces are internally managed to work correctly; profile.run
1118 Namespaces are internally managed to work correctly; profile.run
1119 cannot be used in IPython because it makes certain assumptions about
1119 cannot be used in IPython because it makes certain assumptions about
1120 namespaces which do not hold under IPython.
1120 namespaces which do not hold under IPython.
1121
1121
1122 Options:
1122 Options:
1123
1123
1124 -l <limit>: you can place restrictions on what or how much of the
1124 -l <limit>: you can place restrictions on what or how much of the
1125 profile gets printed. The limit value can be:
1125 profile gets printed. The limit value can be:
1126
1126
1127 * A string: only information for function names containing this string
1127 * A string: only information for function names containing this string
1128 is printed.
1128 is printed.
1129
1129
1130 * An integer: only these many lines are printed.
1130 * An integer: only these many lines are printed.
1131
1131
1132 * A float (between 0 and 1): this fraction of the report is printed
1132 * A float (between 0 and 1): this fraction of the report is printed
1133 (for example, use a limit of 0.4 to see the topmost 40% only).
1133 (for example, use a limit of 0.4 to see the topmost 40% only).
1134
1134
1135 You can combine several limits with repeated use of the option. For
1135 You can combine several limits with repeated use of the option. For
1136 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1136 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1137 information about class constructors.
1137 information about class constructors.
1138
1138
1139 -r: return the pstats.Stats object generated by the profiling. This
1139 -r: return the pstats.Stats object generated by the profiling. This
1140 object has all the information about the profile in it, and you can
1140 object has all the information about the profile in it, and you can
1141 later use it for further analysis or in other functions.
1141 later use it for further analysis or in other functions.
1142
1142
1143 Since magic functions have a particular form of calling which prevents
1143 Since magic functions have a particular form of calling which prevents
1144 you from writing something like:\\
1144 you from writing something like:\\
1145 In [1]: p = %prun -r print 4 # invalid!\\
1145 In [1]: p = %prun -r print 4 # invalid!\\
1146 you must instead use IPython's automatic variables to assign this:\\
1146 you must instead use IPython's automatic variables to assign this:\\
1147 In [1]: %prun -r print 4 \\
1147 In [1]: %prun -r print 4 \\
1148 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1148 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1149 In [2]: stats = _
1149 In [2]: stats = _
1150
1150
1151 If you really need to assign this value via an explicit function call,
1151 If you really need to assign this value via an explicit function call,
1152 you can always tap directly into the true name of the magic function
1152 you can always tap directly into the true name of the magic function
1153 by using the _ip.magic function:\\
1153 by using the _ip.magic function:\\
1154 In [3]: stats = _ip.magic('prun','-r print 4')
1154 In [3]: stats = _ip.magic('prun','-r print 4')
1155
1155
1156 You can type _ip.magic? for more details.
1156 You can type _ip.magic? for more details.
1157
1157
1158 -s <key>: sort profile by given key. You can provide more than one key
1158 -s <key>: sort profile by given key. You can provide more than one key
1159 by using the option several times: '-s key1 -s key2 -s key3...'. The
1159 by using the option several times: '-s key1 -s key2 -s key3...'. The
1160 default sorting key is 'time'.
1160 default sorting key is 'time'.
1161
1161
1162 The following is copied verbatim from the profile documentation
1162 The following is copied verbatim from the profile documentation
1163 referenced below:
1163 referenced below:
1164
1164
1165 When more than one key is provided, additional keys are used as
1165 When more than one key is provided, additional keys are used as
1166 secondary criteria when the there is equality in all keys selected
1166 secondary criteria when the there is equality in all keys selected
1167 before them.
1167 before them.
1168
1168
1169 Abbreviations can be used for any key names, as long as the
1169 Abbreviations can be used for any key names, as long as the
1170 abbreviation is unambiguous. The following are the keys currently
1170 abbreviation is unambiguous. The following are the keys currently
1171 defined:
1171 defined:
1172
1172
1173 Valid Arg Meaning\\
1173 Valid Arg Meaning\\
1174 "calls" call count\\
1174 "calls" call count\\
1175 "cumulative" cumulative time\\
1175 "cumulative" cumulative time\\
1176 "file" file name\\
1176 "file" file name\\
1177 "module" file name\\
1177 "module" file name\\
1178 "pcalls" primitive call count\\
1178 "pcalls" primitive call count\\
1179 "line" line number\\
1179 "line" line number\\
1180 "name" function name\\
1180 "name" function name\\
1181 "nfl" name/file/line\\
1181 "nfl" name/file/line\\
1182 "stdname" standard name\\
1182 "stdname" standard name\\
1183 "time" internal time
1183 "time" internal time
1184
1184
1185 Note that all sorts on statistics are in descending order (placing
1185 Note that all sorts on statistics are in descending order (placing
1186 most time consuming items first), where as name, file, and line number
1186 most time consuming items first), where as name, file, and line number
1187 searches are in ascending order (i.e., alphabetical). The subtle
1187 searches are in ascending order (i.e., alphabetical). The subtle
1188 distinction between "nfl" and "stdname" is that the standard name is a
1188 distinction between "nfl" and "stdname" is that the standard name is a
1189 sort of the name as printed, which means that the embedded line
1189 sort of the name as printed, which means that the embedded line
1190 numbers get compared in an odd way. For example, lines 3, 20, and 40
1190 numbers get compared in an odd way. For example, lines 3, 20, and 40
1191 would (if the file names were the same) appear in the string order
1191 would (if the file names were the same) appear in the string order
1192 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1192 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1193 line numbers. In fact, sort_stats("nfl") is the same as
1193 line numbers. In fact, sort_stats("nfl") is the same as
1194 sort_stats("name", "file", "line").
1194 sort_stats("name", "file", "line").
1195
1195
1196 -T <filename>: save profile results as shown on screen to a text
1196 -T <filename>: save profile results as shown on screen to a text
1197 file. The profile is still shown on screen.
1197 file. The profile is still shown on screen.
1198
1198
1199 -D <filename>: save (via dump_stats) profile statistics to given
1199 -D <filename>: save (via dump_stats) profile statistics to given
1200 filename. This data is in a format understod by the pstats module, and
1200 filename. This data is in a format understod by the pstats module, and
1201 is generated by a call to the dump_stats() method of profile
1201 is generated by a call to the dump_stats() method of profile
1202 objects. The profile is still shown on screen.
1202 objects. The profile is still shown on screen.
1203
1203
1204 If you want to run complete programs under the profiler's control, use
1204 If you want to run complete programs under the profiler's control, use
1205 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1205 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1206 contains profiler specific options as described here.
1206 contains profiler specific options as described here.
1207
1207
1208 You can read the complete documentation for the profile module with:\\
1208 You can read the complete documentation for the profile module with:\\
1209 In [1]: import profile; profile.help() """
1209 In [1]: import profile; profile.help() """
1210
1210
1211 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1211 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1212 # protect user quote marks
1212 # protect user quote marks
1213 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1213 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1214
1214
1215 if user_mode: # regular user call
1215 if user_mode: # regular user call
1216 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1216 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1217 list_all=1)
1217 list_all=1)
1218 namespace = self.shell.user_ns
1218 namespace = self.shell.user_ns
1219 else: # called to run a program by %run -p
1219 else: # called to run a program by %run -p
1220 try:
1220 try:
1221 filename = get_py_filename(arg_lst[0])
1221 filename = get_py_filename(arg_lst[0])
1222 except IOError,msg:
1222 except IOError,msg:
1223 error(msg)
1223 error(msg)
1224 return
1224 return
1225
1225
1226 arg_str = 'execfile(filename,prog_ns)'
1226 arg_str = 'execfile(filename,prog_ns)'
1227 namespace = locals()
1227 namespace = locals()
1228
1228
1229 opts.merge(opts_def)
1229 opts.merge(opts_def)
1230
1230
1231 prof = profile.Profile()
1231 prof = profile.Profile()
1232 try:
1232 try:
1233 prof = prof.runctx(arg_str,namespace,namespace)
1233 prof = prof.runctx(arg_str,namespace,namespace)
1234 sys_exit = ''
1234 sys_exit = ''
1235 except SystemExit:
1235 except SystemExit:
1236 sys_exit = """*** SystemExit exception caught in code being profiled."""
1236 sys_exit = """*** SystemExit exception caught in code being profiled."""
1237
1237
1238 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1238 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1239
1239
1240 lims = opts.l
1240 lims = opts.l
1241 if lims:
1241 if lims:
1242 lims = [] # rebuild lims with ints/floats/strings
1242 lims = [] # rebuild lims with ints/floats/strings
1243 for lim in opts.l:
1243 for lim in opts.l:
1244 try:
1244 try:
1245 lims.append(int(lim))
1245 lims.append(int(lim))
1246 except ValueError:
1246 except ValueError:
1247 try:
1247 try:
1248 lims.append(float(lim))
1248 lims.append(float(lim))
1249 except ValueError:
1249 except ValueError:
1250 lims.append(lim)
1250 lims.append(lim)
1251
1251
1252 # trap output
1252 # trap output
1253 sys_stdout = sys.stdout
1253 sys_stdout = sys.stdout
1254 stdout_trap = StringIO()
1254 stdout_trap = StringIO()
1255 try:
1255 try:
1256 sys.stdout = stdout_trap
1256 sys.stdout = stdout_trap
1257 stats.print_stats(*lims)
1257 stats.print_stats(*lims)
1258 finally:
1258 finally:
1259 sys.stdout = sys_stdout
1259 sys.stdout = sys_stdout
1260 output = stdout_trap.getvalue()
1260 output = stdout_trap.getvalue()
1261 output = output.rstrip()
1261 output = output.rstrip()
1262
1262
1263 page(output,screen_lines=self.shell.rc.screen_length)
1263 page(output,screen_lines=self.shell.rc.screen_length)
1264 print sys_exit,
1264 print sys_exit,
1265
1265
1266 dump_file = opts.D[0]
1266 dump_file = opts.D[0]
1267 text_file = opts.T[0]
1267 text_file = opts.T[0]
1268 if dump_file:
1268 if dump_file:
1269 prof.dump_stats(dump_file)
1269 prof.dump_stats(dump_file)
1270 print '\n*** Profile stats marshalled to file',\
1270 print '\n*** Profile stats marshalled to file',\
1271 `dump_file`+'.',sys_exit
1271 `dump_file`+'.',sys_exit
1272 if text_file:
1272 if text_file:
1273 file(text_file,'w').write(output)
1273 file(text_file,'w').write(output)
1274 print '\n*** Profile printout saved to text file',\
1274 print '\n*** Profile printout saved to text file',\
1275 `text_file`+'.',sys_exit
1275 `text_file`+'.',sys_exit
1276
1276
1277 if opts.has_key('r'):
1277 if opts.has_key('r'):
1278 return stats
1278 return stats
1279 else:
1279 else:
1280 return None
1280 return None
1281
1281
1282 def magic_run(self, parameter_s ='',runner=None):
1282 def magic_run(self, parameter_s ='',runner=None):
1283 """Run the named file inside IPython as a program.
1283 """Run the named file inside IPython as a program.
1284
1284
1285 Usage:\\
1285 Usage:\\
1286 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1286 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1287
1287
1288 Parameters after the filename are passed as command-line arguments to
1288 Parameters after the filename are passed as command-line arguments to
1289 the program (put in sys.argv). Then, control returns to IPython's
1289 the program (put in sys.argv). Then, control returns to IPython's
1290 prompt.
1290 prompt.
1291
1291
1292 This is similar to running at a system prompt:\\
1292 This is similar to running at a system prompt:\\
1293 $ python file args\\
1293 $ python file args\\
1294 but with the advantage of giving you IPython's tracebacks, and of
1294 but with the advantage of giving you IPython's tracebacks, and of
1295 loading all variables into your interactive namespace for further use
1295 loading all variables into your interactive namespace for further use
1296 (unless -p is used, see below).
1296 (unless -p is used, see below).
1297
1297
1298 The file is executed in a namespace initially consisting only of
1298 The file is executed in a namespace initially consisting only of
1299 __name__=='__main__' and sys.argv constructed as indicated. It thus
1299 __name__=='__main__' and sys.argv constructed as indicated. It thus
1300 sees its environment as if it were being run as a stand-alone
1300 sees its environment as if it were being run as a stand-alone
1301 program. But after execution, the IPython interactive namespace gets
1301 program. But after execution, the IPython interactive namespace gets
1302 updated with all variables defined in the program (except for __name__
1302 updated with all variables defined in the program (except for __name__
1303 and sys.argv). This allows for very convenient loading of code for
1303 and sys.argv). This allows for very convenient loading of code for
1304 interactive work, while giving each program a 'clean sheet' to run in.
1304 interactive work, while giving each program a 'clean sheet' to run in.
1305
1305
1306 Options:
1306 Options:
1307
1307
1308 -n: __name__ is NOT set to '__main__', but to the running file's name
1308 -n: __name__ is NOT set to '__main__', but to the running file's name
1309 without extension (as python does under import). This allows running
1309 without extension (as python does under import). This allows running
1310 scripts and reloading the definitions in them without calling code
1310 scripts and reloading the definitions in them without calling code
1311 protected by an ' if __name__ == "__main__" ' clause.
1311 protected by an ' if __name__ == "__main__" ' clause.
1312
1312
1313 -i: run the file in IPython's namespace instead of an empty one. This
1313 -i: run the file in IPython's namespace instead of an empty one. This
1314 is useful if you are experimenting with code written in a text editor
1314 is useful if you are experimenting with code written in a text editor
1315 which depends on variables defined interactively.
1315 which depends on variables defined interactively.
1316
1316
1317 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1317 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1318 being run. This is particularly useful if IPython is being used to
1318 being run. This is particularly useful if IPython is being used to
1319 run unittests, which always exit with a sys.exit() call. In such
1319 run unittests, which always exit with a sys.exit() call. In such
1320 cases you are interested in the output of the test results, not in
1320 cases you are interested in the output of the test results, not in
1321 seeing a traceback of the unittest module.
1321 seeing a traceback of the unittest module.
1322
1322
1323 -t: print timing information at the end of the run. IPython will give
1323 -t: print timing information at the end of the run. IPython will give
1324 you an estimated CPU time consumption for your script, which under
1324 you an estimated CPU time consumption for your script, which under
1325 Unix uses the resource module to avoid the wraparound problems of
1325 Unix uses the resource module to avoid the wraparound problems of
1326 time.clock(). Under Unix, an estimate of time spent on system tasks
1326 time.clock(). Under Unix, an estimate of time spent on system tasks
1327 is also given (for Windows platforms this is reported as 0.0).
1327 is also given (for Windows platforms this is reported as 0.0).
1328
1328
1329 If -t is given, an additional -N<N> option can be given, where <N>
1329 If -t is given, an additional -N<N> option can be given, where <N>
1330 must be an integer indicating how many times you want the script to
1330 must be an integer indicating how many times you want the script to
1331 run. The final timing report will include total and per run results.
1331 run. The final timing report will include total and per run results.
1332
1332
1333 For example (testing the script uniq_stable.py):
1333 For example (testing the script uniq_stable.py):
1334
1334
1335 In [1]: run -t uniq_stable
1335 In [1]: run -t uniq_stable
1336
1336
1337 IPython CPU timings (estimated):\\
1337 IPython CPU timings (estimated):\\
1338 User : 0.19597 s.\\
1338 User : 0.19597 s.\\
1339 System: 0.0 s.\\
1339 System: 0.0 s.\\
1340
1340
1341 In [2]: run -t -N5 uniq_stable
1341 In [2]: run -t -N5 uniq_stable
1342
1342
1343 IPython CPU timings (estimated):\\
1343 IPython CPU timings (estimated):\\
1344 Total runs performed: 5\\
1344 Total runs performed: 5\\
1345 Times : Total Per run\\
1345 Times : Total Per run\\
1346 User : 0.910862 s, 0.1821724 s.\\
1346 User : 0.910862 s, 0.1821724 s.\\
1347 System: 0.0 s, 0.0 s.
1347 System: 0.0 s, 0.0 s.
1348
1348
1349 -d: run your program under the control of pdb, the Python debugger.
1349 -d: run your program under the control of pdb, the Python debugger.
1350 This allows you to execute your program step by step, watch variables,
1350 This allows you to execute your program step by step, watch variables,
1351 etc. Internally, what IPython does is similar to calling:
1351 etc. Internally, what IPython does is similar to calling:
1352
1352
1353 pdb.run('execfile("YOURFILENAME")')
1353 pdb.run('execfile("YOURFILENAME")')
1354
1354
1355 with a breakpoint set on line 1 of your file. You can change the line
1355 with a breakpoint set on line 1 of your file. You can change the line
1356 number for this automatic breakpoint to be <N> by using the -bN option
1356 number for this automatic breakpoint to be <N> by using the -bN option
1357 (where N must be an integer). For example:
1357 (where N must be an integer). For example:
1358
1358
1359 %run -d -b40 myscript
1359 %run -d -b40 myscript
1360
1360
1361 will set the first breakpoint at line 40 in myscript.py. Note that
1361 will set the first breakpoint at line 40 in myscript.py. Note that
1362 the first breakpoint must be set on a line which actually does
1362 the first breakpoint must be set on a line which actually does
1363 something (not a comment or docstring) for it to stop execution.
1363 something (not a comment or docstring) for it to stop execution.
1364
1364
1365 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1365 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1366 first enter 'c' (without qoutes) to start execution up to the first
1366 first enter 'c' (without qoutes) to start execution up to the first
1367 breakpoint.
1367 breakpoint.
1368
1368
1369 Entering 'help' gives information about the use of the debugger. You
1369 Entering 'help' gives information about the use of the debugger. You
1370 can easily see pdb's full documentation with "import pdb;pdb.help()"
1370 can easily see pdb's full documentation with "import pdb;pdb.help()"
1371 at a prompt.
1371 at a prompt.
1372
1372
1373 -p: run program under the control of the Python profiler module (which
1373 -p: run program under the control of the Python profiler module (which
1374 prints a detailed report of execution times, function calls, etc).
1374 prints a detailed report of execution times, function calls, etc).
1375
1375
1376 You can pass other options after -p which affect the behavior of the
1376 You can pass other options after -p which affect the behavior of the
1377 profiler itself. See the docs for %prun for details.
1377 profiler itself. See the docs for %prun for details.
1378
1378
1379 In this mode, the program's variables do NOT propagate back to the
1379 In this mode, the program's variables do NOT propagate back to the
1380 IPython interactive namespace (because they remain in the namespace
1380 IPython interactive namespace (because they remain in the namespace
1381 where the profiler executes them).
1381 where the profiler executes them).
1382
1382
1383 Internally this triggers a call to %prun, see its documentation for
1383 Internally this triggers a call to %prun, see its documentation for
1384 details on the options available specifically for profiling."""
1384 details on the options available specifically for profiling."""
1385
1385
1386 # get arguments and set sys.argv for program to be run.
1386 # get arguments and set sys.argv for program to be run.
1387 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1387 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1388 mode='list',list_all=1)
1388 mode='list',list_all=1)
1389
1389
1390 try:
1390 try:
1391 filename = get_py_filename(arg_lst[0])
1391 filename = get_py_filename(arg_lst[0])
1392 except IndexError:
1392 except IndexError:
1393 warn('you must provide at least a filename.')
1393 warn('you must provide at least a filename.')
1394 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1394 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1395 return
1395 return
1396 except IOError,msg:
1396 except IOError,msg:
1397 error(msg)
1397 error(msg)
1398 return
1398 return
1399
1399
1400 # Control the response to exit() calls made by the script being run
1400 # Control the response to exit() calls made by the script being run
1401 exit_ignore = opts.has_key('e')
1401 exit_ignore = opts.has_key('e')
1402
1402
1403 # Make sure that the running script gets a proper sys.argv as if it
1403 # Make sure that the running script gets a proper sys.argv as if it
1404 # were run from a system shell.
1404 # were run from a system shell.
1405 save_argv = sys.argv # save it for later restoring
1405 save_argv = sys.argv # save it for later restoring
1406 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1406 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1407
1407
1408 if opts.has_key('i'):
1408 if opts.has_key('i'):
1409 prog_ns = self.shell.user_ns
1409 prog_ns = self.shell.user_ns
1410 __name__save = self.shell.user_ns['__name__']
1410 __name__save = self.shell.user_ns['__name__']
1411 prog_ns['__name__'] = '__main__'
1411 prog_ns['__name__'] = '__main__'
1412 else:
1412 else:
1413 if opts.has_key('n'):
1413 if opts.has_key('n'):
1414 name = os.path.splitext(os.path.basename(filename))[0]
1414 name = os.path.splitext(os.path.basename(filename))[0]
1415 else:
1415 else:
1416 name = '__main__'
1416 name = '__main__'
1417 prog_ns = {'__name__':name}
1417 prog_ns = {'__name__':name}
1418
1418
1419 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1419 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1420 # set the __file__ global in the script's namespace
1420 # set the __file__ global in the script's namespace
1421 prog_ns['__file__'] = filename
1421 prog_ns['__file__'] = filename
1422
1422
1423 # pickle fix. See iplib for an explanation. But we need to make sure
1423 # pickle fix. See iplib for an explanation. But we need to make sure
1424 # that, if we overwrite __main__, we replace it at the end
1424 # that, if we overwrite __main__, we replace it at the end
1425 if prog_ns['__name__'] == '__main__':
1425 if prog_ns['__name__'] == '__main__':
1426 restore_main = sys.modules['__main__']
1426 restore_main = sys.modules['__main__']
1427 else:
1427 else:
1428 restore_main = False
1428 restore_main = False
1429
1429
1430 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1430 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1431
1431
1432 stats = None
1432 stats = None
1433 try:
1433 try:
1434 if opts.has_key('p'):
1434 if opts.has_key('p'):
1435 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1435 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1436 else:
1436 else:
1437 if opts.has_key('d'):
1437 if opts.has_key('d'):
1438 deb = Debugger.Pdb(self.shell.rc.colors)
1438 deb = Debugger.Pdb(self.shell.rc.colors)
1439 # reset Breakpoint state, which is moronically kept
1439 # reset Breakpoint state, which is moronically kept
1440 # in a class
1440 # in a class
1441 bdb.Breakpoint.next = 1
1441 bdb.Breakpoint.next = 1
1442 bdb.Breakpoint.bplist = {}
1442 bdb.Breakpoint.bplist = {}
1443 bdb.Breakpoint.bpbynumber = [None]
1443 bdb.Breakpoint.bpbynumber = [None]
1444 # Set an initial breakpoint to stop execution
1444 # Set an initial breakpoint to stop execution
1445 maxtries = 10
1445 maxtries = 10
1446 bp = int(opts.get('b',[1])[0])
1446 bp = int(opts.get('b',[1])[0])
1447 checkline = deb.checkline(filename,bp)
1447 checkline = deb.checkline(filename,bp)
1448 if not checkline:
1448 if not checkline:
1449 for bp in range(bp+1,bp+maxtries+1):
1449 for bp in range(bp+1,bp+maxtries+1):
1450 if deb.checkline(filename,bp):
1450 if deb.checkline(filename,bp):
1451 break
1451 break
1452 else:
1452 else:
1453 msg = ("\nI failed to find a valid line to set "
1453 msg = ("\nI failed to find a valid line to set "
1454 "a breakpoint\n"
1454 "a breakpoint\n"
1455 "after trying up to line: %s.\n"
1455 "after trying up to line: %s.\n"
1456 "Please set a valid breakpoint manually "
1456 "Please set a valid breakpoint manually "
1457 "with the -b option." % bp)
1457 "with the -b option." % bp)
1458 error(msg)
1458 error(msg)
1459 return
1459 return
1460 # if we find a good linenumber, set the breakpoint
1460 # if we find a good linenumber, set the breakpoint
1461 deb.do_break('%s:%s' % (filename,bp))
1461 deb.do_break('%s:%s' % (filename,bp))
1462 # Start file run
1462 # Start file run
1463 print "NOTE: Enter 'c' at the",
1463 print "NOTE: Enter 'c' at the",
1464 print "ipdb> prompt to start your script."
1464 print "ipdb> prompt to start your script."
1465 try:
1465 try:
1466 deb.run('execfile("%s")' % filename,prog_ns)
1466 deb.run('execfile("%s")' % filename,prog_ns)
1467 except:
1467 except:
1468 etype, value, tb = sys.exc_info()
1468 etype, value, tb = sys.exc_info()
1469 # Skip three frames in the traceback: the %run one,
1469 # Skip three frames in the traceback: the %run one,
1470 # one inside bdb.py, and the command-line typed by the
1470 # one inside bdb.py, and the command-line typed by the
1471 # user (run by exec in pdb itself).
1471 # user (run by exec in pdb itself).
1472 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1472 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1473 else:
1473 else:
1474 if runner is None:
1474 if runner is None:
1475 runner = self.shell.safe_execfile
1475 runner = self.shell.safe_execfile
1476 if opts.has_key('t'):
1476 if opts.has_key('t'):
1477 try:
1477 try:
1478 nruns = int(opts['N'][0])
1478 nruns = int(opts['N'][0])
1479 if nruns < 1:
1479 if nruns < 1:
1480 error('Number of runs must be >=1')
1480 error('Number of runs must be >=1')
1481 return
1481 return
1482 except (KeyError):
1482 except (KeyError):
1483 nruns = 1
1483 nruns = 1
1484 if nruns == 1:
1484 if nruns == 1:
1485 t0 = clock2()
1485 t0 = clock2()
1486 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1486 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1487 t1 = clock2()
1487 t1 = clock2()
1488 t_usr = t1[0]-t0[0]
1488 t_usr = t1[0]-t0[0]
1489 t_sys = t1[1]-t1[1]
1489 t_sys = t1[1]-t1[1]
1490 print "\nIPython CPU timings (estimated):"
1490 print "\nIPython CPU timings (estimated):"
1491 print " User : %10s s." % t_usr
1491 print " User : %10s s." % t_usr
1492 print " System: %10s s." % t_sys
1492 print " System: %10s s." % t_sys
1493 else:
1493 else:
1494 runs = range(nruns)
1494 runs = range(nruns)
1495 t0 = clock2()
1495 t0 = clock2()
1496 for nr in runs:
1496 for nr in runs:
1497 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1497 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1498 t1 = clock2()
1498 t1 = clock2()
1499 t_usr = t1[0]-t0[0]
1499 t_usr = t1[0]-t0[0]
1500 t_sys = t1[1]-t1[1]
1500 t_sys = t1[1]-t1[1]
1501 print "\nIPython CPU timings (estimated):"
1501 print "\nIPython CPU timings (estimated):"
1502 print "Total runs performed:",nruns
1502 print "Total runs performed:",nruns
1503 print " Times : %10s %10s" % ('Total','Per run')
1503 print " Times : %10s %10s" % ('Total','Per run')
1504 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1504 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1505 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1505 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1506
1506
1507 else:
1507 else:
1508 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1508 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1509 if opts.has_key('i'):
1509 if opts.has_key('i'):
1510 self.shell.user_ns['__name__'] = __name__save
1510 self.shell.user_ns['__name__'] = __name__save
1511 else:
1511 else:
1512 # update IPython interactive namespace
1512 # update IPython interactive namespace
1513 del prog_ns['__name__']
1513 del prog_ns['__name__']
1514 self.shell.user_ns.update(prog_ns)
1514 self.shell.user_ns.update(prog_ns)
1515 finally:
1515 finally:
1516 sys.argv = save_argv
1516 sys.argv = save_argv
1517 if restore_main:
1517 if restore_main:
1518 sys.modules['__main__'] = restore_main
1518 sys.modules['__main__'] = restore_main
1519 return stats
1519 return stats
1520
1520
1521 def magic_runlog(self, parameter_s =''):
1521 def magic_runlog(self, parameter_s =''):
1522 """Run files as logs.
1522 """Run files as logs.
1523
1523
1524 Usage:\\
1524 Usage:\\
1525 %runlog file1 file2 ...
1525 %runlog file1 file2 ...
1526
1526
1527 Run the named files (treating them as log files) in sequence inside
1527 Run the named files (treating them as log files) in sequence inside
1528 the interpreter, and return to the prompt. This is much slower than
1528 the interpreter, and return to the prompt. This is much slower than
1529 %run because each line is executed in a try/except block, but it
1529 %run because each line is executed in a try/except block, but it
1530 allows running files with syntax errors in them.
1530 allows running files with syntax errors in them.
1531
1531
1532 Normally IPython will guess when a file is one of its own logfiles, so
1532 Normally IPython will guess when a file is one of its own logfiles, so
1533 you can typically use %run even for logs. This shorthand allows you to
1533 you can typically use %run even for logs. This shorthand allows you to
1534 force any file to be treated as a log file."""
1534 force any file to be treated as a log file."""
1535
1535
1536 for f in parameter_s.split():
1536 for f in parameter_s.split():
1537 self.shell.safe_execfile(f,self.shell.user_ns,
1537 self.shell.safe_execfile(f,self.shell.user_ns,
1538 self.shell.user_ns,islog=1)
1538 self.shell.user_ns,islog=1)
1539
1539
1540 def magic_time(self,parameter_s = ''):
1540 def magic_time(self,parameter_s = ''):
1541 """Time execution of a Python statement or expression.
1541 """Time execution of a Python statement or expression.
1542
1542
1543 The CPU and wall clock times are printed, and the value of the
1543 The CPU and wall clock times are printed, and the value of the
1544 expression (if any) is returned. Note that under Win32, system time
1544 expression (if any) is returned. Note that under Win32, system time
1545 is always reported as 0, since it can not be measured.
1545 is always reported as 0, since it can not be measured.
1546
1546
1547 This function provides very basic timing functionality. In Python
1547 This function provides very basic timing functionality. In Python
1548 2.3, the timeit module offers more control and sophistication, but for
1548 2.3, the timeit module offers more control and sophistication, but for
1549 now IPython supports Python 2.2, so we can not rely on timeit being
1549 now IPython supports Python 2.2, so we can not rely on timeit being
1550 present.
1550 present.
1551
1551
1552 Some examples:
1552 Some examples:
1553
1553
1554 In [1]: time 2**128
1554 In [1]: time 2**128
1555 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1555 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1556 Wall time: 0.00
1556 Wall time: 0.00
1557 Out[1]: 340282366920938463463374607431768211456L
1557 Out[1]: 340282366920938463463374607431768211456L
1558
1558
1559 In [2]: n = 1000000
1559 In [2]: n = 1000000
1560
1560
1561 In [3]: time sum(range(n))
1561 In [3]: time sum(range(n))
1562 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1562 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1563 Wall time: 1.37
1563 Wall time: 1.37
1564 Out[3]: 499999500000L
1564 Out[3]: 499999500000L
1565
1565
1566 In [4]: time print 'hello world'
1566 In [4]: time print 'hello world'
1567 hello world
1567 hello world
1568 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1568 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1569 Wall time: 0.00
1569 Wall time: 0.00
1570 """
1570 """
1571
1571
1572 # fail immediately if the given expression can't be compiled
1572 # fail immediately if the given expression can't be compiled
1573 try:
1573 try:
1574 mode = 'eval'
1574 mode = 'eval'
1575 code = compile(parameter_s,'<timed eval>',mode)
1575 code = compile(parameter_s,'<timed eval>',mode)
1576 except SyntaxError:
1576 except SyntaxError:
1577 mode = 'exec'
1577 mode = 'exec'
1578 code = compile(parameter_s,'<timed exec>',mode)
1578 code = compile(parameter_s,'<timed exec>',mode)
1579 # skew measurement as little as possible
1579 # skew measurement as little as possible
1580 glob = self.shell.user_ns
1580 glob = self.shell.user_ns
1581 clk = clock2
1581 clk = clock2
1582 wtime = time.time
1582 wtime = time.time
1583 # time execution
1583 # time execution
1584 wall_st = wtime()
1584 wall_st = wtime()
1585 if mode=='eval':
1585 if mode=='eval':
1586 st = clk()
1586 st = clk()
1587 out = eval(code,glob)
1587 out = eval(code,glob)
1588 end = clk()
1588 end = clk()
1589 else:
1589 else:
1590 st = clk()
1590 st = clk()
1591 exec code in glob
1591 exec code in glob
1592 end = clk()
1592 end = clk()
1593 out = None
1593 out = None
1594 wall_end = wtime()
1594 wall_end = wtime()
1595 # Compute actual times and report
1595 # Compute actual times and report
1596 wall_time = wall_end-wall_st
1596 wall_time = wall_end-wall_st
1597 cpu_user = end[0]-st[0]
1597 cpu_user = end[0]-st[0]
1598 cpu_sys = end[1]-st[1]
1598 cpu_sys = end[1]-st[1]
1599 cpu_tot = cpu_user+cpu_sys
1599 cpu_tot = cpu_user+cpu_sys
1600 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1600 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1601 (cpu_user,cpu_sys,cpu_tot)
1601 (cpu_user,cpu_sys,cpu_tot)
1602 print "Wall time: %.2f" % wall_time
1602 print "Wall time: %.2f" % wall_time
1603 return out
1603 return out
1604
1604
1605 def magic_macro(self,parameter_s = ''):
1605 def magic_macro(self,parameter_s = ''):
1606 """Define a set of input lines as a macro for future re-execution.
1606 """Define a set of input lines as a macro for future re-execution.
1607
1607
1608 Usage:\\
1608 Usage:\\
1609 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1609 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1610
1610
1611 This will define a global variable called `name` which is a string
1611 This will define a global variable called `name` which is a string
1612 made of joining the slices and lines you specify (n1,n2,... numbers
1612 made of joining the slices and lines you specify (n1,n2,... numbers
1613 above) from your input history into a single string. This variable
1613 above) from your input history into a single string. This variable
1614 acts like an automatic function which re-executes those lines as if
1614 acts like an automatic function which re-executes those lines as if
1615 you had typed them. You just type 'name' at the prompt and the code
1615 you had typed them. You just type 'name' at the prompt and the code
1616 executes.
1616 executes.
1617
1617
1618 The notation for indicating number ranges is: n1-n2 means 'use line
1618 The notation for indicating number ranges is: n1-n2 means 'use line
1619 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1619 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1620 using the lines numbered 5,6 and 7.
1620 using the lines numbered 5,6 and 7.
1621
1621
1622 Note: as a 'hidden' feature, you can also use traditional python slice
1622 Note: as a 'hidden' feature, you can also use traditional python slice
1623 notation, where N:M means numbers N through M-1.
1623 notation, where N:M means numbers N through M-1.
1624
1624
1625 For example, if your history contains (%hist prints it):
1625 For example, if your history contains (%hist prints it):
1626
1626
1627 44: x=1\\
1627 44: x=1\\
1628 45: y=3\\
1628 45: y=3\\
1629 46: z=x+y\\
1629 46: z=x+y\\
1630 47: print x\\
1630 47: print x\\
1631 48: a=5\\
1631 48: a=5\\
1632 49: print 'x',x,'y',y\\
1632 49: print 'x',x,'y',y\\
1633
1633
1634 you can create a macro with lines 44 through 47 (included) and line 49
1634 you can create a macro with lines 44 through 47 (included) and line 49
1635 called my_macro with:
1635 called my_macro with:
1636
1636
1637 In [51]: %macro my_macro 44-47 49
1637 In [51]: %macro my_macro 44-47 49
1638
1638
1639 Now, typing `my_macro` (without quotes) will re-execute all this code
1639 Now, typing `my_macro` (without quotes) will re-execute all this code
1640 in one pass.
1640 in one pass.
1641
1641
1642 You don't need to give the line-numbers in order, and any given line
1642 You don't need to give the line-numbers in order, and any given line
1643 number can appear multiple times. You can assemble macros with any
1643 number can appear multiple times. You can assemble macros with any
1644 lines from your input history in any order.
1644 lines from your input history in any order.
1645
1645
1646 The macro is a simple object which holds its value in an attribute,
1646 The macro is a simple object which holds its value in an attribute,
1647 but IPython's display system checks for macros and executes them as
1647 but IPython's display system checks for macros and executes them as
1648 code instead of printing them when you type their name.
1648 code instead of printing them when you type their name.
1649
1649
1650 You can view a macro's contents by explicitly printing it with:
1650 You can view a macro's contents by explicitly printing it with:
1651
1651
1652 'print macro_name'.
1652 'print macro_name'.
1653
1653
1654 For one-off cases which DON'T contain magic function calls in them you
1654 For one-off cases which DON'T contain magic function calls in them you
1655 can obtain similar results by explicitly executing slices from your
1655 can obtain similar results by explicitly executing slices from your
1656 input history with:
1656 input history with:
1657
1657
1658 In [60]: exec In[44:48]+In[49]"""
1658 In [60]: exec In[44:48]+In[49]"""
1659
1659
1660 args = parameter_s.split()
1660 args = parameter_s.split()
1661 name,ranges = args[0], args[1:]
1661 name,ranges = args[0], args[1:]
1662 #print 'rng',ranges # dbg
1662 #print 'rng',ranges # dbg
1663 lines = self.extract_input_slices(ranges)
1663 lines = self.extract_input_slices(ranges)
1664 macro = Macro(lines)
1664 macro = Macro(lines)
1665 self.shell.user_ns.update({name:macro})
1665 self.shell.user_ns.update({name:macro})
1666 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1666 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1667 print 'Macro contents:'
1667 print 'Macro contents:'
1668 print macro,
1668 print macro,
1669
1669
1670 def magic_save(self,parameter_s = ''):
1670 def magic_save(self,parameter_s = ''):
1671 """Save a set of lines to a given filename.
1671 """Save a set of lines to a given filename.
1672
1672
1673 Usage:\\
1673 Usage:\\
1674 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1674 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1675
1675
1676 This function uses the same syntax as %macro for line extraction, but
1676 This function uses the same syntax as %macro for line extraction, but
1677 instead of creating a macro it saves the resulting string to the
1677 instead of creating a macro it saves the resulting string to the
1678 filename you specify.
1678 filename you specify.
1679
1679
1680 It adds a '.py' extension to the file if you don't do so yourself, and
1680 It adds a '.py' extension to the file if you don't do so yourself, and
1681 it asks for confirmation before overwriting existing files."""
1681 it asks for confirmation before overwriting existing files."""
1682
1682
1683 args = parameter_s.split()
1683 args = parameter_s.split()
1684 fname,ranges = args[0], args[1:]
1684 fname,ranges = args[0], args[1:]
1685 if not fname.endswith('.py'):
1685 if not fname.endswith('.py'):
1686 fname += '.py'
1686 fname += '.py'
1687 if os.path.isfile(fname):
1687 if os.path.isfile(fname):
1688 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1688 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1689 if ans.lower() not in ['y','yes']:
1689 if ans.lower() not in ['y','yes']:
1690 print 'Operation cancelled.'
1690 print 'Operation cancelled.'
1691 return
1691 return
1692 cmds = ''.join(self.extract_input_slices(ranges))
1692 cmds = ''.join(self.extract_input_slices(ranges))
1693 f = file(fname,'w')
1693 f = file(fname,'w')
1694 f.write(cmds)
1694 f.write(cmds)
1695 f.close()
1695 f.close()
1696 print 'The following commands were written to file `%s`:' % fname
1696 print 'The following commands were written to file `%s`:' % fname
1697 print cmds
1697 print cmds
1698
1698
1699 def _edit_macro(self,mname,macro):
1699 def _edit_macro(self,mname,macro):
1700 """open an editor with the macro data in a file"""
1700 """open an editor with the macro data in a file"""
1701 filename = self.shell.mktempfile(macro.value)
1701 filename = self.shell.mktempfile(macro.value)
1702 self.shell.hooks.editor(filename)
1702 self.shell.hooks.editor(filename)
1703
1703
1704 # and make a new macro object, to replace the old one
1704 # and make a new macro object, to replace the old one
1705 mfile = open(filename)
1705 mfile = open(filename)
1706 mvalue = mfile.read()
1706 mvalue = mfile.read()
1707 mfile.close()
1707 mfile.close()
1708 self.shell.user_ns[mname] = Macro(mvalue)
1708 self.shell.user_ns[mname] = Macro(mvalue)
1709
1709
1710 def magic_ed(self,parameter_s=''):
1710 def magic_ed(self,parameter_s=''):
1711 """Alias to %edit."""
1711 """Alias to %edit."""
1712 return self.magic_edit(parameter_s)
1712 return self.magic_edit(parameter_s)
1713
1713
1714 def magic_edit(self,parameter_s='',last_call=['','']):
1714 def magic_edit(self,parameter_s='',last_call=['','']):
1715 """Bring up an editor and execute the resulting code.
1715 """Bring up an editor and execute the resulting code.
1716
1716
1717 Usage:
1717 Usage:
1718 %edit [options] [args]
1718 %edit [options] [args]
1719
1719
1720 %edit runs IPython's editor hook. The default version of this hook is
1720 %edit runs IPython's editor hook. The default version of this hook is
1721 set to call the __IPYTHON__.rc.editor command. This is read from your
1721 set to call the __IPYTHON__.rc.editor command. This is read from your
1722 environment variable $EDITOR. If this isn't found, it will default to
1722 environment variable $EDITOR. If this isn't found, it will default to
1723 vi under Linux/Unix and to notepad under Windows. See the end of this
1723 vi under Linux/Unix and to notepad under Windows. See the end of this
1724 docstring for how to change the editor hook.
1724 docstring for how to change the editor hook.
1725
1725
1726 You can also set the value of this editor via the command line option
1726 You can also set the value of this editor via the command line option
1727 '-editor' or in your ipythonrc file. This is useful if you wish to use
1727 '-editor' or in your ipythonrc file. This is useful if you wish to use
1728 specifically for IPython an editor different from your typical default
1728 specifically for IPython an editor different from your typical default
1729 (and for Windows users who typically don't set environment variables).
1729 (and for Windows users who typically don't set environment variables).
1730
1730
1731 This command allows you to conveniently edit multi-line code right in
1731 This command allows you to conveniently edit multi-line code right in
1732 your IPython session.
1732 your IPython session.
1733
1733
1734 If called without arguments, %edit opens up an empty editor with a
1734 If called without arguments, %edit opens up an empty editor with a
1735 temporary file and will execute the contents of this file when you
1735 temporary file and will execute the contents of this file when you
1736 close it (don't forget to save it!).
1736 close it (don't forget to save it!).
1737
1737
1738
1738
1739 Options:
1739 Options:
1740
1740
1741 -p: this will call the editor with the same data as the previous time
1741 -p: this will call the editor with the same data as the previous time
1742 it was used, regardless of how long ago (in your current session) it
1742 it was used, regardless of how long ago (in your current session) it
1743 was.
1743 was.
1744
1744
1745 -x: do not execute the edited code immediately upon exit. This is
1745 -x: do not execute the edited code immediately upon exit. This is
1746 mainly useful if you are editing programs which need to be called with
1746 mainly useful if you are editing programs which need to be called with
1747 command line arguments, which you can then do using %run.
1747 command line arguments, which you can then do using %run.
1748
1748
1749
1749
1750 Arguments:
1750 Arguments:
1751
1751
1752 If arguments are given, the following possibilites exist:
1752 If arguments are given, the following possibilites exist:
1753
1753
1754 - The arguments are numbers or pairs of colon-separated numbers (like
1754 - The arguments are numbers or pairs of colon-separated numbers (like
1755 1 4:8 9). These are interpreted as lines of previous input to be
1755 1 4:8 9). These are interpreted as lines of previous input to be
1756 loaded into the editor. The syntax is the same of the %macro command.
1756 loaded into the editor. The syntax is the same of the %macro command.
1757
1757
1758 - If the argument doesn't start with a number, it is evaluated as a
1758 - If the argument doesn't start with a number, it is evaluated as a
1759 variable and its contents loaded into the editor. You can thus edit
1759 variable and its contents loaded into the editor. You can thus edit
1760 any string which contains python code (including the result of
1760 any string which contains python code (including the result of
1761 previous edits).
1761 previous edits).
1762
1762
1763 - If the argument is the name of an object (other than a string),
1763 - If the argument is the name of an object (other than a string),
1764 IPython will try to locate the file where it was defined and open the
1764 IPython will try to locate the file where it was defined and open the
1765 editor at the point where it is defined. You can use `%edit function`
1765 editor at the point where it is defined. You can use `%edit function`
1766 to load an editor exactly at the point where 'function' is defined,
1766 to load an editor exactly at the point where 'function' is defined,
1767 edit it and have the file be executed automatically.
1767 edit it and have the file be executed automatically.
1768
1768
1769 If the object is a macro (see %macro for details), this opens up your
1769 If the object is a macro (see %macro for details), this opens up your
1770 specified editor with a temporary file containing the macro's data.
1770 specified editor with a temporary file containing the macro's data.
1771 Upon exit, the macro is reloaded with the contents of the file.
1771 Upon exit, the macro is reloaded with the contents of the file.
1772
1772
1773 Note: opening at an exact line is only supported under Unix, and some
1773 Note: opening at an exact line is only supported under Unix, and some
1774 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1774 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1775 '+NUMBER' parameter necessary for this feature. Good editors like
1775 '+NUMBER' parameter necessary for this feature. Good editors like
1776 (X)Emacs, vi, jed, pico and joe all do.
1776 (X)Emacs, vi, jed, pico and joe all do.
1777
1777
1778 - If the argument is not found as a variable, IPython will look for a
1778 - If the argument is not found as a variable, IPython will look for a
1779 file with that name (adding .py if necessary) and load it into the
1779 file with that name (adding .py if necessary) and load it into the
1780 editor. It will execute its contents with execfile() when you exit,
1780 editor. It will execute its contents with execfile() when you exit,
1781 loading any code in the file into your interactive namespace.
1781 loading any code in the file into your interactive namespace.
1782
1782
1783 After executing your code, %edit will return as output the code you
1783 After executing your code, %edit will return as output the code you
1784 typed in the editor (except when it was an existing file). This way
1784 typed in the editor (except when it was an existing file). This way
1785 you can reload the code in further invocations of %edit as a variable,
1785 you can reload the code in further invocations of %edit as a variable,
1786 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1786 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1787 the output.
1787 the output.
1788
1788
1789 Note that %edit is also available through the alias %ed.
1789 Note that %edit is also available through the alias %ed.
1790
1790
1791 This is an example of creating a simple function inside the editor and
1791 This is an example of creating a simple function inside the editor and
1792 then modifying it. First, start up the editor:
1792 then modifying it. First, start up the editor:
1793
1793
1794 In [1]: ed\\
1794 In [1]: ed\\
1795 Editing... done. Executing edited code...\\
1795 Editing... done. Executing edited code...\\
1796 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1796 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1797
1797
1798 We can then call the function foo():
1798 We can then call the function foo():
1799
1799
1800 In [2]: foo()\\
1800 In [2]: foo()\\
1801 foo() was defined in an editing session
1801 foo() was defined in an editing session
1802
1802
1803 Now we edit foo. IPython automatically loads the editor with the
1803 Now we edit foo. IPython automatically loads the editor with the
1804 (temporary) file where foo() was previously defined:
1804 (temporary) file where foo() was previously defined:
1805
1805
1806 In [3]: ed foo\\
1806 In [3]: ed foo\\
1807 Editing... done. Executing edited code...
1807 Editing... done. Executing edited code...
1808
1808
1809 And if we call foo() again we get the modified version:
1809 And if we call foo() again we get the modified version:
1810
1810
1811 In [4]: foo()\\
1811 In [4]: foo()\\
1812 foo() has now been changed!
1812 foo() has now been changed!
1813
1813
1814 Here is an example of how to edit a code snippet successive
1814 Here is an example of how to edit a code snippet successive
1815 times. First we call the editor:
1815 times. First we call the editor:
1816
1816
1817 In [8]: ed\\
1817 In [8]: ed\\
1818 Editing... done. Executing edited code...\\
1818 Editing... done. Executing edited code...\\
1819 hello\\
1819 hello\\
1820 Out[8]: "print 'hello'\\n"
1820 Out[8]: "print 'hello'\\n"
1821
1821
1822 Now we call it again with the previous output (stored in _):
1822 Now we call it again with the previous output (stored in _):
1823
1823
1824 In [9]: ed _\\
1824 In [9]: ed _\\
1825 Editing... done. Executing edited code...\\
1825 Editing... done. Executing edited code...\\
1826 hello world\\
1826 hello world\\
1827 Out[9]: "print 'hello world'\\n"
1827 Out[9]: "print 'hello world'\\n"
1828
1828
1829 Now we call it with the output #8 (stored in _8, also as Out[8]):
1829 Now we call it with the output #8 (stored in _8, also as Out[8]):
1830
1830
1831 In [10]: ed _8\\
1831 In [10]: ed _8\\
1832 Editing... done. Executing edited code...\\
1832 Editing... done. Executing edited code...\\
1833 hello again\\
1833 hello again\\
1834 Out[10]: "print 'hello again'\\n"
1834 Out[10]: "print 'hello again'\\n"
1835
1835
1836
1836
1837 Changing the default editor hook:
1837 Changing the default editor hook:
1838
1838
1839 If you wish to write your own editor hook, you can put it in a
1839 If you wish to write your own editor hook, you can put it in a
1840 configuration file which you load at startup time. The default hook
1840 configuration file which you load at startup time. The default hook
1841 is defined in the IPython.hooks module, and you can use that as a
1841 is defined in the IPython.hooks module, and you can use that as a
1842 starting example for further modifications. That file also has
1842 starting example for further modifications. That file also has
1843 general instructions on how to set a new hook for use once you've
1843 general instructions on how to set a new hook for use once you've
1844 defined it."""
1844 defined it."""
1845
1845
1846 # FIXME: This function has become a convoluted mess. It needs a
1846 # FIXME: This function has become a convoluted mess. It needs a
1847 # ground-up rewrite with clean, simple logic.
1847 # ground-up rewrite with clean, simple logic.
1848
1848
1849 def make_filename(arg):
1849 def make_filename(arg):
1850 "Make a filename from the given args"
1850 "Make a filename from the given args"
1851 try:
1851 try:
1852 filename = get_py_filename(arg)
1852 filename = get_py_filename(arg)
1853 except IOError:
1853 except IOError:
1854 if args.endswith('.py'):
1854 if args.endswith('.py'):
1855 filename = arg
1855 filename = arg
1856 else:
1856 else:
1857 filename = None
1857 filename = None
1858 return filename
1858 return filename
1859
1859
1860 # custom exceptions
1860 # custom exceptions
1861 class DataIsObject(Exception): pass
1861 class DataIsObject(Exception): pass
1862
1862
1863 opts,args = self.parse_options(parameter_s,'px')
1863 opts,args = self.parse_options(parameter_s,'px')
1864
1864
1865 # Default line number value
1865 # Default line number value
1866 lineno = None
1866 lineno = None
1867 if opts.has_key('p'):
1867 if opts.has_key('p'):
1868 args = '_%s' % last_call[0]
1868 args = '_%s' % last_call[0]
1869 if not self.shell.user_ns.has_key(args):
1869 if not self.shell.user_ns.has_key(args):
1870 args = last_call[1]
1870 args = last_call[1]
1871
1871
1872 # use last_call to remember the state of the previous call, but don't
1872 # use last_call to remember the state of the previous call, but don't
1873 # let it be clobbered by successive '-p' calls.
1873 # let it be clobbered by successive '-p' calls.
1874 try:
1874 try:
1875 last_call[0] = self.shell.outputcache.prompt_count
1875 last_call[0] = self.shell.outputcache.prompt_count
1876 if not opts.has_key('p'):
1876 if not opts.has_key('p'):
1877 last_call[1] = parameter_s
1877 last_call[1] = parameter_s
1878 except:
1878 except:
1879 pass
1879 pass
1880
1880
1881 # by default this is done with temp files, except when the given
1881 # by default this is done with temp files, except when the given
1882 # arg is a filename
1882 # arg is a filename
1883 use_temp = 1
1883 use_temp = 1
1884
1884
1885 if re.match(r'\d',args):
1885 if re.match(r'\d',args):
1886 # Mode where user specifies ranges of lines, like in %macro.
1886 # Mode where user specifies ranges of lines, like in %macro.
1887 # This means that you can't edit files whose names begin with
1887 # This means that you can't edit files whose names begin with
1888 # numbers this way. Tough.
1888 # numbers this way. Tough.
1889 ranges = args.split()
1889 ranges = args.split()
1890 data = ''.join(self.extract_input_slices(ranges))
1890 data = ''.join(self.extract_input_slices(ranges))
1891 elif args.endswith('.py'):
1891 elif args.endswith('.py'):
1892 filename = make_filename(args)
1892 filename = make_filename(args)
1893 data = ''
1893 data = ''
1894 use_temp = 0
1894 use_temp = 0
1895 elif args:
1895 elif args:
1896 try:
1896 try:
1897 # Load the parameter given as a variable. If not a string,
1897 # Load the parameter given as a variable. If not a string,
1898 # process it as an object instead (below)
1898 # process it as an object instead (below)
1899
1899
1900 #print '*** args',args,'type',type(args) # dbg
1900 #print '*** args',args,'type',type(args) # dbg
1901 data = eval(args,self.shell.user_ns)
1901 data = eval(args,self.shell.user_ns)
1902 if not type(data) in StringTypes:
1902 if not type(data) in StringTypes:
1903 raise DataIsObject
1903 raise DataIsObject
1904
1904
1905 except (NameError,SyntaxError):
1905 except (NameError,SyntaxError):
1906 # given argument is not a variable, try as a filename
1906 # given argument is not a variable, try as a filename
1907 filename = make_filename(args)
1907 filename = make_filename(args)
1908 if filename is None:
1908 if filename is None:
1909 warn("Argument given (%s) can't be found as a variable "
1909 warn("Argument given (%s) can't be found as a variable "
1910 "or as a filename." % args)
1910 "or as a filename." % args)
1911 return
1911 return
1912
1912
1913 data = ''
1913 data = ''
1914 use_temp = 0
1914 use_temp = 0
1915 except DataIsObject:
1915 except DataIsObject:
1916
1916
1917 # macros have a special edit function
1917 # macros have a special edit function
1918 if isinstance(data,Macro):
1918 if isinstance(data,Macro):
1919 self._edit_macro(args,data)
1919 self._edit_macro(args,data)
1920 return
1920 return
1921
1921
1922 # For objects, try to edit the file where they are defined
1922 # For objects, try to edit the file where they are defined
1923 try:
1923 try:
1924 filename = inspect.getabsfile(data)
1924 filename = inspect.getabsfile(data)
1925 datafile = 1
1925 datafile = 1
1926 except TypeError:
1926 except TypeError:
1927 filename = make_filename(args)
1927 filename = make_filename(args)
1928 datafile = 1
1928 datafile = 1
1929 warn('Could not find file where `%s` is defined.\n'
1929 warn('Could not find file where `%s` is defined.\n'
1930 'Opening a file named `%s`' % (args,filename))
1930 'Opening a file named `%s`' % (args,filename))
1931 # Now, make sure we can actually read the source (if it was in
1931 # Now, make sure we can actually read the source (if it was in
1932 # a temp file it's gone by now).
1932 # a temp file it's gone by now).
1933 if datafile:
1933 if datafile:
1934 try:
1934 try:
1935 lineno = inspect.getsourcelines(data)[1]
1935 lineno = inspect.getsourcelines(data)[1]
1936 except IOError:
1936 except IOError:
1937 filename = make_filename(args)
1937 filename = make_filename(args)
1938 if filename is None:
1938 if filename is None:
1939 warn('The file `%s` where `%s` was defined cannot '
1939 warn('The file `%s` where `%s` was defined cannot '
1940 'be read.' % (filename,data))
1940 'be read.' % (filename,data))
1941 return
1941 return
1942 use_temp = 0
1942 use_temp = 0
1943 else:
1943 else:
1944 data = ''
1944 data = ''
1945
1945
1946 if use_temp:
1946 if use_temp:
1947 filename = self.shell.mktempfile(data)
1947 filename = self.shell.mktempfile(data)
1948 print 'IPython will make a temporary file named:',filename
1948 print 'IPython will make a temporary file named:',filename
1949
1949
1950 # do actual editing here
1950 # do actual editing here
1951 print 'Editing...',
1951 print 'Editing...',
1952 sys.stdout.flush()
1952 sys.stdout.flush()
1953 self.shell.hooks.editor(filename,lineno)
1953 self.shell.hooks.editor(filename,lineno)
1954 if opts.has_key('x'): # -x prevents actual execution
1954 if opts.has_key('x'): # -x prevents actual execution
1955 print
1955 print
1956 else:
1956 else:
1957 print 'done. Executing edited code...'
1957 print 'done. Executing edited code...'
1958 self.shell.safe_execfile(filename,self.shell.user_ns)
1958 self.shell.safe_execfile(filename,self.shell.user_ns)
1959 if use_temp:
1959 if use_temp:
1960 try:
1960 try:
1961 return open(filename).read()
1961 return open(filename).read()
1962 except IOError,msg:
1962 except IOError,msg:
1963 if msg.filename == filename:
1963 if msg.filename == filename:
1964 warn('File not found. Did you forget to save?')
1964 warn('File not found. Did you forget to save?')
1965 return
1965 return
1966 else:
1966 else:
1967 self.shell.showtraceback()
1967 self.shell.showtraceback()
1968
1968
1969 def magic_xmode(self,parameter_s = ''):
1969 def magic_xmode(self,parameter_s = ''):
1970 """Switch modes for the exception handlers.
1970 """Switch modes for the exception handlers.
1971
1971
1972 Valid modes: Plain, Context and Verbose.
1972 Valid modes: Plain, Context and Verbose.
1973
1973
1974 If called without arguments, acts as a toggle."""
1974 If called without arguments, acts as a toggle."""
1975
1975
1976 def xmode_switch_err(name):
1976 def xmode_switch_err(name):
1977 warn('Error changing %s exception modes.\n%s' %
1977 warn('Error changing %s exception modes.\n%s' %
1978 (name,sys.exc_info()[1]))
1978 (name,sys.exc_info()[1]))
1979
1979
1980 shell = self.shell
1980 shell = self.shell
1981 new_mode = parameter_s.strip().capitalize()
1981 new_mode = parameter_s.strip().capitalize()
1982 try:
1982 try:
1983 shell.InteractiveTB.set_mode(mode=new_mode)
1983 shell.InteractiveTB.set_mode(mode=new_mode)
1984 print 'Exception reporting mode:',shell.InteractiveTB.mode
1984 print 'Exception reporting mode:',shell.InteractiveTB.mode
1985 except:
1985 except:
1986 xmode_switch_err('user')
1986 xmode_switch_err('user')
1987
1987
1988 # threaded shells use a special handler in sys.excepthook
1988 # threaded shells use a special handler in sys.excepthook
1989 if shell.isthreaded:
1989 if shell.isthreaded:
1990 try:
1990 try:
1991 shell.sys_excepthook.set_mode(mode=new_mode)
1991 shell.sys_excepthook.set_mode(mode=new_mode)
1992 except:
1992 except:
1993 xmode_switch_err('threaded')
1993 xmode_switch_err('threaded')
1994
1994
1995 def magic_colors(self,parameter_s = ''):
1995 def magic_colors(self,parameter_s = ''):
1996 """Switch color scheme for prompts, info system and exception handlers.
1996 """Switch color scheme for prompts, info system and exception handlers.
1997
1997
1998 Currently implemented schemes: NoColor, Linux, LightBG.
1998 Currently implemented schemes: NoColor, Linux, LightBG.
1999
1999
2000 Color scheme names are not case-sensitive."""
2000 Color scheme names are not case-sensitive."""
2001
2001
2002 def color_switch_err(name):
2002 def color_switch_err(name):
2003 warn('Error changing %s color schemes.\n%s' %
2003 warn('Error changing %s color schemes.\n%s' %
2004 (name,sys.exc_info()[1]))
2004 (name,sys.exc_info()[1]))
2005
2005
2006
2006
2007 new_scheme = parameter_s.strip()
2007 new_scheme = parameter_s.strip()
2008 if not new_scheme:
2008 if not new_scheme:
2009 print 'You must specify a color scheme.'
2009 print 'You must specify a color scheme.'
2010 return
2010 return
2011 # Under Windows, check for Gary Bishop's readline, which is necessary
2011 import IPython.rlineimpl as readline
2012 # for ANSI coloring
2012 if not readline.have_readline:
2013 if os.name in ['nt','dos']:
2013 msg = """\
2014 try:
2015 import readline
2016 except ImportError:
2017 has_readline = 0
2018 else:
2019 try:
2020 readline.GetOutputFile()
2021 except AttributeError:
2022 has_readline = 0
2023 else:
2024 has_readline = 1
2025 if not has_readline:
2026 msg = """\
2027 Proper color support under MS Windows requires Gary Bishop's readline library.
2014 Proper color support under MS Windows requires Gary Bishop's readline library.
2028 You can find it at:
2015 You can find it at:
2029 http://sourceforge.net/projects/uncpythontools
2016 http://sourceforge.net/projects/uncpythontools
2030 Gary's readline needs the ctypes module, from:
2017 Gary's readline needs the ctypes module, from:
2031 http://starship.python.net/crew/theller/ctypes
2018 http://starship.python.net/crew/theller/ctypes
2032
2019
2033 Defaulting color scheme to 'NoColor'"""
2020 Defaulting color scheme to 'NoColor'"""
2034 new_scheme = 'NoColor'
2021 new_scheme = 'NoColor'
2035 warn(msg)
2022 warn(msg)
2036 # local shortcut
2023 # local shortcut
2037 shell = self.shell
2024 shell = self.shell
2038
2025
2039 # Set prompt colors
2026 # Set prompt colors
2040 try:
2027 try:
2041 shell.outputcache.set_colors(new_scheme)
2028 shell.outputcache.set_colors(new_scheme)
2042 except:
2029 except:
2043 color_switch_err('prompt')
2030 color_switch_err('prompt')
2044 else:
2031 else:
2045 shell.rc.colors = \
2032 shell.rc.colors = \
2046 shell.outputcache.color_table.active_scheme_name
2033 shell.outputcache.color_table.active_scheme_name
2047 # Set exception colors
2034 # Set exception colors
2048 try:
2035 try:
2049 shell.InteractiveTB.set_colors(scheme = new_scheme)
2036 shell.InteractiveTB.set_colors(scheme = new_scheme)
2050 shell.SyntaxTB.set_colors(scheme = new_scheme)
2037 shell.SyntaxTB.set_colors(scheme = new_scheme)
2051 except:
2038 except:
2052 color_switch_err('exception')
2039 color_switch_err('exception')
2053
2040
2054 # threaded shells use a verbose traceback in sys.excepthook
2041 # threaded shells use a verbose traceback in sys.excepthook
2055 if shell.isthreaded:
2042 if shell.isthreaded:
2056 try:
2043 try:
2057 shell.sys_excepthook.set_colors(scheme=new_scheme)
2044 shell.sys_excepthook.set_colors(scheme=new_scheme)
2058 except:
2045 except:
2059 color_switch_err('system exception handler')
2046 color_switch_err('system exception handler')
2060
2047
2061 # Set info (for 'object?') colors
2048 # Set info (for 'object?') colors
2062 if shell.rc.color_info:
2049 if shell.rc.color_info:
2063 try:
2050 try:
2064 shell.inspector.set_active_scheme(new_scheme)
2051 shell.inspector.set_active_scheme(new_scheme)
2065 except:
2052 except:
2066 color_switch_err('object inspector')
2053 color_switch_err('object inspector')
2067 else:
2054 else:
2068 shell.inspector.set_active_scheme('NoColor')
2055 shell.inspector.set_active_scheme('NoColor')
2069
2056
2070 def magic_color_info(self,parameter_s = ''):
2057 def magic_color_info(self,parameter_s = ''):
2071 """Toggle color_info.
2058 """Toggle color_info.
2072
2059
2073 The color_info configuration parameter controls whether colors are
2060 The color_info configuration parameter controls whether colors are
2074 used for displaying object details (by things like %psource, %pfile or
2061 used for displaying object details (by things like %psource, %pfile or
2075 the '?' system). This function toggles this value with each call.
2062 the '?' system). This function toggles this value with each call.
2076
2063
2077 Note that unless you have a fairly recent pager (less works better
2064 Note that unless you have a fairly recent pager (less works better
2078 than more) in your system, using colored object information displays
2065 than more) in your system, using colored object information displays
2079 will not work properly. Test it and see."""
2066 will not work properly. Test it and see."""
2080
2067
2081 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2068 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2082 self.magic_colors(self.shell.rc.colors)
2069 self.magic_colors(self.shell.rc.colors)
2083 print 'Object introspection functions have now coloring:',
2070 print 'Object introspection functions have now coloring:',
2084 print ['OFF','ON'][self.shell.rc.color_info]
2071 print ['OFF','ON'][self.shell.rc.color_info]
2085
2072
2086 def magic_Pprint(self, parameter_s=''):
2073 def magic_Pprint(self, parameter_s=''):
2087 """Toggle pretty printing on/off."""
2074 """Toggle pretty printing on/off."""
2088
2075
2089 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2076 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2090 print 'Pretty printing has been turned', \
2077 print 'Pretty printing has been turned', \
2091 ['OFF','ON'][self.shell.outputcache.Pprint]
2078 ['OFF','ON'][self.shell.outputcache.Pprint]
2092
2079
2093 def magic_exit(self, parameter_s=''):
2080 def magic_exit(self, parameter_s=''):
2094 """Exit IPython, confirming if configured to do so.
2081 """Exit IPython, confirming if configured to do so.
2095
2082
2096 You can configure whether IPython asks for confirmation upon exit by
2083 You can configure whether IPython asks for confirmation upon exit by
2097 setting the confirm_exit flag in the ipythonrc file."""
2084 setting the confirm_exit flag in the ipythonrc file."""
2098
2085
2099 self.shell.exit()
2086 self.shell.exit()
2100
2087
2101 def magic_quit(self, parameter_s=''):
2088 def magic_quit(self, parameter_s=''):
2102 """Exit IPython, confirming if configured to do so (like %exit)"""
2089 """Exit IPython, confirming if configured to do so (like %exit)"""
2103
2090
2104 self.shell.exit()
2091 self.shell.exit()
2105
2092
2106 def magic_Exit(self, parameter_s=''):
2093 def magic_Exit(self, parameter_s=''):
2107 """Exit IPython without confirmation."""
2094 """Exit IPython without confirmation."""
2108
2095
2109 self.shell.exit_now = True
2096 self.shell.exit_now = True
2110
2097
2111 def magic_Quit(self, parameter_s=''):
2098 def magic_Quit(self, parameter_s=''):
2112 """Exit IPython without confirmation (like %Exit)."""
2099 """Exit IPython without confirmation (like %Exit)."""
2113
2100
2114 self.shell.exit_now = True
2101 self.shell.exit_now = True
2115
2102
2116 #......................................................................
2103 #......................................................................
2117 # Functions to implement unix shell-type things
2104 # Functions to implement unix shell-type things
2118
2105
2119 def magic_alias(self, parameter_s = ''):
2106 def magic_alias(self, parameter_s = ''):
2120 """Define an alias for a system command.
2107 """Define an alias for a system command.
2121
2108
2122 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2109 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2123
2110
2124 Then, typing 'alias_name params' will execute the system command 'cmd
2111 Then, typing 'alias_name params' will execute the system command 'cmd
2125 params' (from your underlying operating system).
2112 params' (from your underlying operating system).
2126
2113
2127 Aliases have lower precedence than magic functions and Python normal
2114 Aliases have lower precedence than magic functions and Python normal
2128 variables, so if 'foo' is both a Python variable and an alias, the
2115 variables, so if 'foo' is both a Python variable and an alias, the
2129 alias can not be executed until 'del foo' removes the Python variable.
2116 alias can not be executed until 'del foo' removes the Python variable.
2130
2117
2131 You can use the %l specifier in an alias definition to represent the
2118 You can use the %l specifier in an alias definition to represent the
2132 whole line when the alias is called. For example:
2119 whole line when the alias is called. For example:
2133
2120
2134 In [2]: alias all echo "Input in brackets: <%l>"\\
2121 In [2]: alias all echo "Input in brackets: <%l>"\\
2135 In [3]: all hello world\\
2122 In [3]: all hello world\\
2136 Input in brackets: <hello world>
2123 Input in brackets: <hello world>
2137
2124
2138 You can also define aliases with parameters using %s specifiers (one
2125 You can also define aliases with parameters using %s specifiers (one
2139 per parameter):
2126 per parameter):
2140
2127
2141 In [1]: alias parts echo first %s second %s\\
2128 In [1]: alias parts echo first %s second %s\\
2142 In [2]: %parts A B\\
2129 In [2]: %parts A B\\
2143 first A second B\\
2130 first A second B\\
2144 In [3]: %parts A\\
2131 In [3]: %parts A\\
2145 Incorrect number of arguments: 2 expected.\\
2132 Incorrect number of arguments: 2 expected.\\
2146 parts is an alias to: 'echo first %s second %s'
2133 parts is an alias to: 'echo first %s second %s'
2147
2134
2148 Note that %l and %s are mutually exclusive. You can only use one or
2135 Note that %l and %s are mutually exclusive. You can only use one or
2149 the other in your aliases.
2136 the other in your aliases.
2150
2137
2151 Aliases expand Python variables just like system calls using ! or !!
2138 Aliases expand Python variables just like system calls using ! or !!
2152 do: all expressions prefixed with '$' get expanded. For details of
2139 do: all expressions prefixed with '$' get expanded. For details of
2153 the semantic rules, see PEP-215:
2140 the semantic rules, see PEP-215:
2154 http://www.python.org/peps/pep-0215.html. This is the library used by
2141 http://www.python.org/peps/pep-0215.html. This is the library used by
2155 IPython for variable expansion. If you want to access a true shell
2142 IPython for variable expansion. If you want to access a true shell
2156 variable, an extra $ is necessary to prevent its expansion by IPython:
2143 variable, an extra $ is necessary to prevent its expansion by IPython:
2157
2144
2158 In [6]: alias show echo\\
2145 In [6]: alias show echo\\
2159 In [7]: PATH='A Python string'\\
2146 In [7]: PATH='A Python string'\\
2160 In [8]: show $PATH\\
2147 In [8]: show $PATH\\
2161 A Python string\\
2148 A Python string\\
2162 In [9]: show $$PATH\\
2149 In [9]: show $$PATH\\
2163 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2150 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2164
2151
2165 You can use the alias facility to acess all of $PATH. See the %rehash
2152 You can use the alias facility to acess all of $PATH. See the %rehash
2166 and %rehashx functions, which automatically create aliases for the
2153 and %rehashx functions, which automatically create aliases for the
2167 contents of your $PATH.
2154 contents of your $PATH.
2168
2155
2169 If called with no parameters, %alias prints the current alias table."""
2156 If called with no parameters, %alias prints the current alias table."""
2170
2157
2171 par = parameter_s.strip()
2158 par = parameter_s.strip()
2172 if not par:
2159 if not par:
2173 if self.shell.rc.automagic:
2160 if self.shell.rc.automagic:
2174 prechar = ''
2161 prechar = ''
2175 else:
2162 else:
2176 prechar = self.shell.ESC_MAGIC
2163 prechar = self.shell.ESC_MAGIC
2177 #print 'Alias\t\tSystem Command\n'+'-'*30
2164 #print 'Alias\t\tSystem Command\n'+'-'*30
2178 atab = self.shell.alias_table
2165 atab = self.shell.alias_table
2179 aliases = atab.keys()
2166 aliases = atab.keys()
2180 aliases.sort()
2167 aliases.sort()
2181 res = []
2168 res = []
2182 for alias in aliases:
2169 for alias in aliases:
2183 res.append((alias, atab[alias][1]))
2170 res.append((alias, atab[alias][1]))
2184 print "Total number of aliases:",len(aliases)
2171 print "Total number of aliases:",len(aliases)
2185 return res
2172 return res
2186 try:
2173 try:
2187 alias,cmd = par.split(None,1)
2174 alias,cmd = par.split(None,1)
2188 except:
2175 except:
2189 print OInspect.getdoc(self.magic_alias)
2176 print OInspect.getdoc(self.magic_alias)
2190 else:
2177 else:
2191 nargs = cmd.count('%s')
2178 nargs = cmd.count('%s')
2192 if nargs>0 and cmd.find('%l')>=0:
2179 if nargs>0 and cmd.find('%l')>=0:
2193 error('The %s and %l specifiers are mutually exclusive '
2180 error('The %s and %l specifiers are mutually exclusive '
2194 'in alias definitions.')
2181 'in alias definitions.')
2195 else: # all looks OK
2182 else: # all looks OK
2196 self.shell.alias_table[alias] = (nargs,cmd)
2183 self.shell.alias_table[alias] = (nargs,cmd)
2197 self.shell.alias_table_validate(verbose=1)
2184 self.shell.alias_table_validate(verbose=1)
2198 # end magic_alias
2185 # end magic_alias
2199
2186
2200 def magic_unalias(self, parameter_s = ''):
2187 def magic_unalias(self, parameter_s = ''):
2201 """Remove an alias"""
2188 """Remove an alias"""
2202
2189
2203 aname = parameter_s.strip()
2190 aname = parameter_s.strip()
2204 if aname in self.shell.alias_table:
2191 if aname in self.shell.alias_table:
2205 del self.shell.alias_table[aname]
2192 del self.shell.alias_table[aname]
2206
2193
2207 def magic_rehash(self, parameter_s = ''):
2194 def magic_rehash(self, parameter_s = ''):
2208 """Update the alias table with all entries in $PATH.
2195 """Update the alias table with all entries in $PATH.
2209
2196
2210 This version does no checks on execute permissions or whether the
2197 This version does no checks on execute permissions or whether the
2211 contents of $PATH are truly files (instead of directories or something
2198 contents of $PATH are truly files (instead of directories or something
2212 else). For such a safer (but slower) version, use %rehashx."""
2199 else). For such a safer (but slower) version, use %rehashx."""
2213
2200
2214 # This function (and rehashx) manipulate the alias_table directly
2201 # This function (and rehashx) manipulate the alias_table directly
2215 # rather than calling magic_alias, for speed reasons. A rehash on a
2202 # rather than calling magic_alias, for speed reasons. A rehash on a
2216 # typical Linux box involves several thousand entries, so efficiency
2203 # typical Linux box involves several thousand entries, so efficiency
2217 # here is a top concern.
2204 # here is a top concern.
2218
2205
2219 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2206 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2220 alias_table = self.shell.alias_table
2207 alias_table = self.shell.alias_table
2221 for pdir in path:
2208 for pdir in path:
2222 for ff in os.listdir(pdir):
2209 for ff in os.listdir(pdir):
2223 # each entry in the alias table must be (N,name), where
2210 # each entry in the alias table must be (N,name), where
2224 # N is the number of positional arguments of the alias.
2211 # N is the number of positional arguments of the alias.
2225 alias_table[ff] = (0,ff)
2212 alias_table[ff] = (0,ff)
2226 # Make sure the alias table doesn't contain keywords or builtins
2213 # Make sure the alias table doesn't contain keywords or builtins
2227 self.shell.alias_table_validate()
2214 self.shell.alias_table_validate()
2228 # Call again init_auto_alias() so we get 'rm -i' and other modified
2215 # Call again init_auto_alias() so we get 'rm -i' and other modified
2229 # aliases since %rehash will probably clobber them
2216 # aliases since %rehash will probably clobber them
2230 self.shell.init_auto_alias()
2217 self.shell.init_auto_alias()
2231
2218
2232 def magic_rehashx(self, parameter_s = ''):
2219 def magic_rehashx(self, parameter_s = ''):
2233 """Update the alias table with all executable files in $PATH.
2220 """Update the alias table with all executable files in $PATH.
2234
2221
2235 This version explicitly checks that every entry in $PATH is a file
2222 This version explicitly checks that every entry in $PATH is a file
2236 with execute access (os.X_OK), so it is much slower than %rehash.
2223 with execute access (os.X_OK), so it is much slower than %rehash.
2237
2224
2238 Under Windows, it checks executability as a match agains a
2225 Under Windows, it checks executability as a match agains a
2239 '|'-separated string of extensions, stored in the IPython config
2226 '|'-separated string of extensions, stored in the IPython config
2240 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2227 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2241
2228
2242 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2229 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2243 alias_table = self.shell.alias_table
2230 alias_table = self.shell.alias_table
2244
2231
2245 if os.name == 'posix':
2232 if os.name == 'posix':
2246 isexec = lambda fname:os.path.isfile(fname) and \
2233 isexec = lambda fname:os.path.isfile(fname) and \
2247 os.access(fname,os.X_OK)
2234 os.access(fname,os.X_OK)
2248 else:
2235 else:
2249
2236
2250 try:
2237 try:
2251 winext = os.environ['pathext'].replace(';','|').replace('.','')
2238 winext = os.environ['pathext'].replace(';','|').replace('.','')
2252 except KeyError:
2239 except KeyError:
2253 winext = 'exe|com|bat'
2240 winext = 'exe|com|bat'
2254
2241
2255 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2242 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2256 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2243 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2257 savedir = os.getcwd()
2244 savedir = os.getcwd()
2258 try:
2245 try:
2259 # write the whole loop for posix/Windows so we don't have an if in
2246 # write the whole loop for posix/Windows so we don't have an if in
2260 # the innermost part
2247 # the innermost part
2261 if os.name == 'posix':
2248 if os.name == 'posix':
2262 for pdir in path:
2249 for pdir in path:
2263 os.chdir(pdir)
2250 os.chdir(pdir)
2264 for ff in os.listdir(pdir):
2251 for ff in os.listdir(pdir):
2265 if isexec(ff):
2252 if isexec(ff):
2266 # each entry in the alias table must be (N,name),
2253 # each entry in the alias table must be (N,name),
2267 # where N is the number of positional arguments of the
2254 # where N is the number of positional arguments of the
2268 # alias.
2255 # alias.
2269 alias_table[ff] = (0,ff)
2256 alias_table[ff] = (0,ff)
2270 else:
2257 else:
2271 for pdir in path:
2258 for pdir in path:
2272 os.chdir(pdir)
2259 os.chdir(pdir)
2273 for ff in os.listdir(pdir):
2260 for ff in os.listdir(pdir):
2274 if isexec(ff):
2261 if isexec(ff):
2275 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2262 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2276 # Make sure the alias table doesn't contain keywords or builtins
2263 # Make sure the alias table doesn't contain keywords or builtins
2277 self.shell.alias_table_validate()
2264 self.shell.alias_table_validate()
2278 # Call again init_auto_alias() so we get 'rm -i' and other
2265 # Call again init_auto_alias() so we get 'rm -i' and other
2279 # modified aliases since %rehashx will probably clobber them
2266 # modified aliases since %rehashx will probably clobber them
2280 self.shell.init_auto_alias()
2267 self.shell.init_auto_alias()
2281 finally:
2268 finally:
2282 os.chdir(savedir)
2269 os.chdir(savedir)
2283
2270
2284 def magic_pwd(self, parameter_s = ''):
2271 def magic_pwd(self, parameter_s = ''):
2285 """Return the current working directory path."""
2272 """Return the current working directory path."""
2286 return os.getcwd()
2273 return os.getcwd()
2287
2274
2288 def magic_cd(self, parameter_s=''):
2275 def magic_cd(self, parameter_s=''):
2289 """Change the current working directory.
2276 """Change the current working directory.
2290
2277
2291 This command automatically maintains an internal list of directories
2278 This command automatically maintains an internal list of directories
2292 you visit during your IPython session, in the variable _dh. The
2279 you visit during your IPython session, in the variable _dh. The
2293 command %dhist shows this history nicely formatted.
2280 command %dhist shows this history nicely formatted.
2294
2281
2295 Usage:
2282 Usage:
2296
2283
2297 cd 'dir': changes to directory 'dir'.
2284 cd 'dir': changes to directory 'dir'.
2298
2285
2299 cd -: changes to the last visited directory.
2286 cd -: changes to the last visited directory.
2300
2287
2301 cd -<n>: changes to the n-th directory in the directory history.
2288 cd -<n>: changes to the n-th directory in the directory history.
2302
2289
2303 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2290 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2304 (note: cd <bookmark_name> is enough if there is no
2291 (note: cd <bookmark_name> is enough if there is no
2305 directory <bookmark_name>, but a bookmark with the name exists.)
2292 directory <bookmark_name>, but a bookmark with the name exists.)
2306
2293
2307 Options:
2294 Options:
2308
2295
2309 -q: quiet. Do not print the working directory after the cd command is
2296 -q: quiet. Do not print the working directory after the cd command is
2310 executed. By default IPython's cd command does print this directory,
2297 executed. By default IPython's cd command does print this directory,
2311 since the default prompts do not display path information.
2298 since the default prompts do not display path information.
2312
2299
2313 Note that !cd doesn't work for this purpose because the shell where
2300 Note that !cd doesn't work for this purpose because the shell where
2314 !command runs is immediately discarded after executing 'command'."""
2301 !command runs is immediately discarded after executing 'command'."""
2315
2302
2316 parameter_s = parameter_s.strip()
2303 parameter_s = parameter_s.strip()
2317 bkms = self.shell.persist.get("bookmarks",{})
2304 bkms = self.shell.persist.get("bookmarks",{})
2318
2305
2319 numcd = re.match(r'(-)(\d+)$',parameter_s)
2306 numcd = re.match(r'(-)(\d+)$',parameter_s)
2320 # jump in directory history by number
2307 # jump in directory history by number
2321 if numcd:
2308 if numcd:
2322 nn = int(numcd.group(2))
2309 nn = int(numcd.group(2))
2323 try:
2310 try:
2324 ps = self.shell.user_ns['_dh'][nn]
2311 ps = self.shell.user_ns['_dh'][nn]
2325 except IndexError:
2312 except IndexError:
2326 print 'The requested directory does not exist in history.'
2313 print 'The requested directory does not exist in history.'
2327 return
2314 return
2328 else:
2315 else:
2329 opts = {}
2316 opts = {}
2330 else:
2317 else:
2331 #turn all non-space-escaping backslashes to slashes,
2318 #turn all non-space-escaping backslashes to slashes,
2332 # for c:\windows\directory\names\
2319 # for c:\windows\directory\names\
2333 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2320 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2334 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2321 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2335 # jump to previous
2322 # jump to previous
2336 if ps == '-':
2323 if ps == '-':
2337 try:
2324 try:
2338 ps = self.shell.user_ns['_dh'][-2]
2325 ps = self.shell.user_ns['_dh'][-2]
2339 except IndexError:
2326 except IndexError:
2340 print 'No previous directory to change to.'
2327 print 'No previous directory to change to.'
2341 return
2328 return
2342 # jump to bookmark
2329 # jump to bookmark
2343 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2330 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2344 if bkms.has_key(ps):
2331 if bkms.has_key(ps):
2345 target = bkms[ps]
2332 target = bkms[ps]
2346 print '(bookmark:%s) -> %s' % (ps,target)
2333 print '(bookmark:%s) -> %s' % (ps,target)
2347 ps = target
2334 ps = target
2348 else:
2335 else:
2349 if bkms:
2336 if bkms:
2350 error("Bookmark '%s' not found. "
2337 error("Bookmark '%s' not found. "
2351 "Use '%%bookmark -l' to see your bookmarks." % ps)
2338 "Use '%%bookmark -l' to see your bookmarks." % ps)
2352 else:
2339 else:
2353 print "Bookmarks not set - use %bookmark <bookmarkname>"
2340 print "Bookmarks not set - use %bookmark <bookmarkname>"
2354 return
2341 return
2355
2342
2356 # at this point ps should point to the target dir
2343 # at this point ps should point to the target dir
2357 if ps:
2344 if ps:
2358 try:
2345 try:
2359 os.chdir(os.path.expanduser(ps))
2346 os.chdir(os.path.expanduser(ps))
2360 ttitle = ("IPy:" + (
2347 ttitle = ("IPy:" + (
2361 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2348 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2362 platutils.set_term_title(ttitle)
2349 platutils.set_term_title(ttitle)
2363 except OSError:
2350 except OSError:
2364 print sys.exc_info()[1]
2351 print sys.exc_info()[1]
2365 else:
2352 else:
2366 self.shell.user_ns['_dh'].append(os.getcwd())
2353 self.shell.user_ns['_dh'].append(os.getcwd())
2367 else:
2354 else:
2368 os.chdir(self.shell.home_dir)
2355 os.chdir(self.shell.home_dir)
2369 platutils.set_term_title("IPy:~")
2356 platutils.set_term_title("IPy:~")
2370 self.shell.user_ns['_dh'].append(os.getcwd())
2357 self.shell.user_ns['_dh'].append(os.getcwd())
2371 if not 'q' in opts:
2358 if not 'q' in opts:
2372 print self.shell.user_ns['_dh'][-1]
2359 print self.shell.user_ns['_dh'][-1]
2373
2360
2374 def magic_dhist(self, parameter_s=''):
2361 def magic_dhist(self, parameter_s=''):
2375 """Print your history of visited directories.
2362 """Print your history of visited directories.
2376
2363
2377 %dhist -> print full history\\
2364 %dhist -> print full history\\
2378 %dhist n -> print last n entries only\\
2365 %dhist n -> print last n entries only\\
2379 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2366 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2380
2367
2381 This history is automatically maintained by the %cd command, and
2368 This history is automatically maintained by the %cd command, and
2382 always available as the global list variable _dh. You can use %cd -<n>
2369 always available as the global list variable _dh. You can use %cd -<n>
2383 to go to directory number <n>."""
2370 to go to directory number <n>."""
2384
2371
2385 dh = self.shell.user_ns['_dh']
2372 dh = self.shell.user_ns['_dh']
2386 if parameter_s:
2373 if parameter_s:
2387 try:
2374 try:
2388 args = map(int,parameter_s.split())
2375 args = map(int,parameter_s.split())
2389 except:
2376 except:
2390 self.arg_err(Magic.magic_dhist)
2377 self.arg_err(Magic.magic_dhist)
2391 return
2378 return
2392 if len(args) == 1:
2379 if len(args) == 1:
2393 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2380 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2394 elif len(args) == 2:
2381 elif len(args) == 2:
2395 ini,fin = args
2382 ini,fin = args
2396 else:
2383 else:
2397 self.arg_err(Magic.magic_dhist)
2384 self.arg_err(Magic.magic_dhist)
2398 return
2385 return
2399 else:
2386 else:
2400 ini,fin = 0,len(dh)
2387 ini,fin = 0,len(dh)
2401 nlprint(dh,
2388 nlprint(dh,
2402 header = 'Directory history (kept in _dh)',
2389 header = 'Directory history (kept in _dh)',
2403 start=ini,stop=fin)
2390 start=ini,stop=fin)
2404
2391
2405 def magic_env(self, parameter_s=''):
2392 def magic_env(self, parameter_s=''):
2406 """List environment variables."""
2393 """List environment variables."""
2407
2394
2408 return os.environ.data
2395 return os.environ.data
2409
2396
2410 def magic_pushd(self, parameter_s=''):
2397 def magic_pushd(self, parameter_s=''):
2411 """Place the current dir on stack and change directory.
2398 """Place the current dir on stack and change directory.
2412
2399
2413 Usage:\\
2400 Usage:\\
2414 %pushd ['dirname']
2401 %pushd ['dirname']
2415
2402
2416 %pushd with no arguments does a %pushd to your home directory.
2403 %pushd with no arguments does a %pushd to your home directory.
2417 """
2404 """
2418 if parameter_s == '': parameter_s = '~'
2405 if parameter_s == '': parameter_s = '~'
2419 dir_s = self.shell.dir_stack
2406 dir_s = self.shell.dir_stack
2420 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2407 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2421 os.path.expanduser(self.shell.dir_stack[0]):
2408 os.path.expanduser(self.shell.dir_stack[0]):
2422 try:
2409 try:
2423 self.magic_cd(parameter_s)
2410 self.magic_cd(parameter_s)
2424 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2411 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2425 self.magic_dirs()
2412 self.magic_dirs()
2426 except:
2413 except:
2427 print 'Invalid directory'
2414 print 'Invalid directory'
2428 else:
2415 else:
2429 print 'You are already there!'
2416 print 'You are already there!'
2430
2417
2431 def magic_popd(self, parameter_s=''):
2418 def magic_popd(self, parameter_s=''):
2432 """Change to directory popped off the top of the stack.
2419 """Change to directory popped off the top of the stack.
2433 """
2420 """
2434 if len (self.shell.dir_stack) > 1:
2421 if len (self.shell.dir_stack) > 1:
2435 self.shell.dir_stack.pop(0)
2422 self.shell.dir_stack.pop(0)
2436 self.magic_cd(self.shell.dir_stack[0])
2423 self.magic_cd(self.shell.dir_stack[0])
2437 print self.shell.dir_stack[0]
2424 print self.shell.dir_stack[0]
2438 else:
2425 else:
2439 print "You can't remove the starting directory from the stack:",\
2426 print "You can't remove the starting directory from the stack:",\
2440 self.shell.dir_stack
2427 self.shell.dir_stack
2441
2428
2442 def magic_dirs(self, parameter_s=''):
2429 def magic_dirs(self, parameter_s=''):
2443 """Return the current directory stack."""
2430 """Return the current directory stack."""
2444
2431
2445 return self.shell.dir_stack[:]
2432 return self.shell.dir_stack[:]
2446
2433
2447 def magic_sc(self, parameter_s=''):
2434 def magic_sc(self, parameter_s=''):
2448 """Shell capture - execute a shell command and capture its output.
2435 """Shell capture - execute a shell command and capture its output.
2449
2436
2450 DEPRECATED. Suboptimal, retained for backwards compatibility.
2437 DEPRECATED. Suboptimal, retained for backwards compatibility.
2451
2438
2452 You should use the form 'var = !command' instead. Example:
2439 You should use the form 'var = !command' instead. Example:
2453
2440
2454 "%sc -l myfiles = ls ~" should now be written as
2441 "%sc -l myfiles = ls ~" should now be written as
2455
2442
2456 "myfiles = !ls ~"
2443 "myfiles = !ls ~"
2457
2444
2458 myfiles.s, myfiles.l and myfiles.n still apply as documented
2445 myfiles.s, myfiles.l and myfiles.n still apply as documented
2459 below.
2446 below.
2460
2447
2461 --
2448 --
2462 %sc [options] varname=command
2449 %sc [options] varname=command
2463
2450
2464 IPython will run the given command using commands.getoutput(), and
2451 IPython will run the given command using commands.getoutput(), and
2465 will then update the user's interactive namespace with a variable
2452 will then update the user's interactive namespace with a variable
2466 called varname, containing the value of the call. Your command can
2453 called varname, containing the value of the call. Your command can
2467 contain shell wildcards, pipes, etc.
2454 contain shell wildcards, pipes, etc.
2468
2455
2469 The '=' sign in the syntax is mandatory, and the variable name you
2456 The '=' sign in the syntax is mandatory, and the variable name you
2470 supply must follow Python's standard conventions for valid names.
2457 supply must follow Python's standard conventions for valid names.
2471
2458
2472 (A special format without variable name exists for internal use)
2459 (A special format without variable name exists for internal use)
2473
2460
2474 Options:
2461 Options:
2475
2462
2476 -l: list output. Split the output on newlines into a list before
2463 -l: list output. Split the output on newlines into a list before
2477 assigning it to the given variable. By default the output is stored
2464 assigning it to the given variable. By default the output is stored
2478 as a single string.
2465 as a single string.
2479
2466
2480 -v: verbose. Print the contents of the variable.
2467 -v: verbose. Print the contents of the variable.
2481
2468
2482 In most cases you should not need to split as a list, because the
2469 In most cases you should not need to split as a list, because the
2483 returned value is a special type of string which can automatically
2470 returned value is a special type of string which can automatically
2484 provide its contents either as a list (split on newlines) or as a
2471 provide its contents either as a list (split on newlines) or as a
2485 space-separated string. These are convenient, respectively, either
2472 space-separated string. These are convenient, respectively, either
2486 for sequential processing or to be passed to a shell command.
2473 for sequential processing or to be passed to a shell command.
2487
2474
2488 For example:
2475 For example:
2489
2476
2490 # Capture into variable a
2477 # Capture into variable a
2491 In [9]: sc a=ls *py
2478 In [9]: sc a=ls *py
2492
2479
2493 # a is a string with embedded newlines
2480 # a is a string with embedded newlines
2494 In [10]: a
2481 In [10]: a
2495 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2482 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2496
2483
2497 # which can be seen as a list:
2484 # which can be seen as a list:
2498 In [11]: a.l
2485 In [11]: a.l
2499 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2486 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2500
2487
2501 # or as a whitespace-separated string:
2488 # or as a whitespace-separated string:
2502 In [12]: a.s
2489 In [12]: a.s
2503 Out[12]: 'setup.py win32_manual_post_install.py'
2490 Out[12]: 'setup.py win32_manual_post_install.py'
2504
2491
2505 # a.s is useful to pass as a single command line:
2492 # a.s is useful to pass as a single command line:
2506 In [13]: !wc -l $a.s
2493 In [13]: !wc -l $a.s
2507 146 setup.py
2494 146 setup.py
2508 130 win32_manual_post_install.py
2495 130 win32_manual_post_install.py
2509 276 total
2496 276 total
2510
2497
2511 # while the list form is useful to loop over:
2498 # while the list form is useful to loop over:
2512 In [14]: for f in a.l:
2499 In [14]: for f in a.l:
2513 ....: !wc -l $f
2500 ....: !wc -l $f
2514 ....:
2501 ....:
2515 146 setup.py
2502 146 setup.py
2516 130 win32_manual_post_install.py
2503 130 win32_manual_post_install.py
2517
2504
2518 Similiarly, the lists returned by the -l option are also special, in
2505 Similiarly, the lists returned by the -l option are also special, in
2519 the sense that you can equally invoke the .s attribute on them to
2506 the sense that you can equally invoke the .s attribute on them to
2520 automatically get a whitespace-separated string from their contents:
2507 automatically get a whitespace-separated string from their contents:
2521
2508
2522 In [1]: sc -l b=ls *py
2509 In [1]: sc -l b=ls *py
2523
2510
2524 In [2]: b
2511 In [2]: b
2525 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2512 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2526
2513
2527 In [3]: b.s
2514 In [3]: b.s
2528 Out[3]: 'setup.py win32_manual_post_install.py'
2515 Out[3]: 'setup.py win32_manual_post_install.py'
2529
2516
2530 In summary, both the lists and strings used for ouptut capture have
2517 In summary, both the lists and strings used for ouptut capture have
2531 the following special attributes:
2518 the following special attributes:
2532
2519
2533 .l (or .list) : value as list.
2520 .l (or .list) : value as list.
2534 .n (or .nlstr): value as newline-separated string.
2521 .n (or .nlstr): value as newline-separated string.
2535 .s (or .spstr): value as space-separated string.
2522 .s (or .spstr): value as space-separated string.
2536 """
2523 """
2537
2524
2538 opts,args = self.parse_options(parameter_s,'lv')
2525 opts,args = self.parse_options(parameter_s,'lv')
2539 # Try to get a variable name and command to run
2526 # Try to get a variable name and command to run
2540 try:
2527 try:
2541 # the variable name must be obtained from the parse_options
2528 # the variable name must be obtained from the parse_options
2542 # output, which uses shlex.split to strip options out.
2529 # output, which uses shlex.split to strip options out.
2543 var,_ = args.split('=',1)
2530 var,_ = args.split('=',1)
2544 var = var.strip()
2531 var = var.strip()
2545 # But the the command has to be extracted from the original input
2532 # But the the command has to be extracted from the original input
2546 # parameter_s, not on what parse_options returns, to avoid the
2533 # parameter_s, not on what parse_options returns, to avoid the
2547 # quote stripping which shlex.split performs on it.
2534 # quote stripping which shlex.split performs on it.
2548 _,cmd = parameter_s.split('=',1)
2535 _,cmd = parameter_s.split('=',1)
2549 except ValueError:
2536 except ValueError:
2550 var,cmd = '',''
2537 var,cmd = '',''
2551 # If all looks ok, proceed
2538 # If all looks ok, proceed
2552 out,err = self.shell.getoutputerror(cmd)
2539 out,err = self.shell.getoutputerror(cmd)
2553 if err:
2540 if err:
2554 print >> Term.cerr,err
2541 print >> Term.cerr,err
2555 if opts.has_key('l'):
2542 if opts.has_key('l'):
2556 out = SList(out.split('\n'))
2543 out = SList(out.split('\n'))
2557 else:
2544 else:
2558 out = LSString(out)
2545 out = LSString(out)
2559 if opts.has_key('v'):
2546 if opts.has_key('v'):
2560 print '%s ==\n%s' % (var,pformat(out))
2547 print '%s ==\n%s' % (var,pformat(out))
2561 if var:
2548 if var:
2562 self.shell.user_ns.update({var:out})
2549 self.shell.user_ns.update({var:out})
2563 else:
2550 else:
2564 return out
2551 return out
2565
2552
2566 def magic_sx(self, parameter_s=''):
2553 def magic_sx(self, parameter_s=''):
2567 """Shell execute - run a shell command and capture its output.
2554 """Shell execute - run a shell command and capture its output.
2568
2555
2569 %sx command
2556 %sx command
2570
2557
2571 IPython will run the given command using commands.getoutput(), and
2558 IPython will run the given command using commands.getoutput(), and
2572 return the result formatted as a list (split on '\\n'). Since the
2559 return the result formatted as a list (split on '\\n'). Since the
2573 output is _returned_, it will be stored in ipython's regular output
2560 output is _returned_, it will be stored in ipython's regular output
2574 cache Out[N] and in the '_N' automatic variables.
2561 cache Out[N] and in the '_N' automatic variables.
2575
2562
2576 Notes:
2563 Notes:
2577
2564
2578 1) If an input line begins with '!!', then %sx is automatically
2565 1) If an input line begins with '!!', then %sx is automatically
2579 invoked. That is, while:
2566 invoked. That is, while:
2580 !ls
2567 !ls
2581 causes ipython to simply issue system('ls'), typing
2568 causes ipython to simply issue system('ls'), typing
2582 !!ls
2569 !!ls
2583 is a shorthand equivalent to:
2570 is a shorthand equivalent to:
2584 %sx ls
2571 %sx ls
2585
2572
2586 2) %sx differs from %sc in that %sx automatically splits into a list,
2573 2) %sx differs from %sc in that %sx automatically splits into a list,
2587 like '%sc -l'. The reason for this is to make it as easy as possible
2574 like '%sc -l'. The reason for this is to make it as easy as possible
2588 to process line-oriented shell output via further python commands.
2575 to process line-oriented shell output via further python commands.
2589 %sc is meant to provide much finer control, but requires more
2576 %sc is meant to provide much finer control, but requires more
2590 typing.
2577 typing.
2591
2578
2592 3) Just like %sc -l, this is a list with special attributes:
2579 3) Just like %sc -l, this is a list with special attributes:
2593
2580
2594 .l (or .list) : value as list.
2581 .l (or .list) : value as list.
2595 .n (or .nlstr): value as newline-separated string.
2582 .n (or .nlstr): value as newline-separated string.
2596 .s (or .spstr): value as whitespace-separated string.
2583 .s (or .spstr): value as whitespace-separated string.
2597
2584
2598 This is very useful when trying to use such lists as arguments to
2585 This is very useful when trying to use such lists as arguments to
2599 system commands."""
2586 system commands."""
2600
2587
2601 if parameter_s:
2588 if parameter_s:
2602 out,err = self.shell.getoutputerror(parameter_s)
2589 out,err = self.shell.getoutputerror(parameter_s)
2603 if err:
2590 if err:
2604 print >> Term.cerr,err
2591 print >> Term.cerr,err
2605 return SList(out.split('\n'))
2592 return SList(out.split('\n'))
2606
2593
2607 def magic_bg(self, parameter_s=''):
2594 def magic_bg(self, parameter_s=''):
2608 """Run a job in the background, in a separate thread.
2595 """Run a job in the background, in a separate thread.
2609
2596
2610 For example,
2597 For example,
2611
2598
2612 %bg myfunc(x,y,z=1)
2599 %bg myfunc(x,y,z=1)
2613
2600
2614 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2601 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2615 execution starts, a message will be printed indicating the job
2602 execution starts, a message will be printed indicating the job
2616 number. If your job number is 5, you can use
2603 number. If your job number is 5, you can use
2617
2604
2618 myvar = jobs.result(5) or myvar = jobs[5].result
2605 myvar = jobs.result(5) or myvar = jobs[5].result
2619
2606
2620 to assign this result to variable 'myvar'.
2607 to assign this result to variable 'myvar'.
2621
2608
2622 IPython has a job manager, accessible via the 'jobs' object. You can
2609 IPython has a job manager, accessible via the 'jobs' object. You can
2623 type jobs? to get more information about it, and use jobs.<TAB> to see
2610 type jobs? to get more information about it, and use jobs.<TAB> to see
2624 its attributes. All attributes not starting with an underscore are
2611 its attributes. All attributes not starting with an underscore are
2625 meant for public use.
2612 meant for public use.
2626
2613
2627 In particular, look at the jobs.new() method, which is used to create
2614 In particular, look at the jobs.new() method, which is used to create
2628 new jobs. This magic %bg function is just a convenience wrapper
2615 new jobs. This magic %bg function is just a convenience wrapper
2629 around jobs.new(), for expression-based jobs. If you want to create a
2616 around jobs.new(), for expression-based jobs. If you want to create a
2630 new job with an explicit function object and arguments, you must call
2617 new job with an explicit function object and arguments, you must call
2631 jobs.new() directly.
2618 jobs.new() directly.
2632
2619
2633 The jobs.new docstring also describes in detail several important
2620 The jobs.new docstring also describes in detail several important
2634 caveats associated with a thread-based model for background job
2621 caveats associated with a thread-based model for background job
2635 execution. Type jobs.new? for details.
2622 execution. Type jobs.new? for details.
2636
2623
2637 You can check the status of all jobs with jobs.status().
2624 You can check the status of all jobs with jobs.status().
2638
2625
2639 The jobs variable is set by IPython into the Python builtin namespace.
2626 The jobs variable is set by IPython into the Python builtin namespace.
2640 If you ever declare a variable named 'jobs', you will shadow this
2627 If you ever declare a variable named 'jobs', you will shadow this
2641 name. You can either delete your global jobs variable to regain
2628 name. You can either delete your global jobs variable to regain
2642 access to the job manager, or make a new name and assign it manually
2629 access to the job manager, or make a new name and assign it manually
2643 to the manager (stored in IPython's namespace). For example, to
2630 to the manager (stored in IPython's namespace). For example, to
2644 assign the job manager to the Jobs name, use:
2631 assign the job manager to the Jobs name, use:
2645
2632
2646 Jobs = __builtins__.jobs"""
2633 Jobs = __builtins__.jobs"""
2647
2634
2648 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2635 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2649
2636
2650 def magic_store(self, parameter_s=''):
2637 def magic_store(self, parameter_s=''):
2651 """Lightweight persistence for python variables.
2638 """Lightweight persistence for python variables.
2652
2639
2653 Example:
2640 Example:
2654
2641
2655 ville@badger[~]|1> A = ['hello',10,'world']\\
2642 ville@badger[~]|1> A = ['hello',10,'world']\\
2656 ville@badger[~]|2> %store A\\
2643 ville@badger[~]|2> %store A\\
2657 ville@badger[~]|3> Exit
2644 ville@badger[~]|3> Exit
2658
2645
2659 (IPython session is closed and started again...)
2646 (IPython session is closed and started again...)
2660
2647
2661 ville@badger:~$ ipython -p pysh\\
2648 ville@badger:~$ ipython -p pysh\\
2662 ville@badger[~]|1> print A
2649 ville@badger[~]|1> print A
2663
2650
2664 ['hello', 10, 'world']
2651 ['hello', 10, 'world']
2665
2652
2666 Usage:
2653 Usage:
2667
2654
2668 %store - Show list of all variables and their current values\\
2655 %store - Show list of all variables and their current values\\
2669 %store <var> - Store the *current* value of the variable to disk\\
2656 %store <var> - Store the *current* value of the variable to disk\\
2670 %store -d <var> - Remove the variable and its value from storage\\
2657 %store -d <var> - Remove the variable and its value from storage\\
2671 %store -r - Remove all variables from storage\\
2658 %store -r - Remove all variables from storage\\
2672 %store foo >a.txt - Store value of foo to new file a.txt\\
2659 %store foo >a.txt - Store value of foo to new file a.txt\\
2673 %store foo >>a.txt - Append value of foo to file a.txt\\
2660 %store foo >>a.txt - Append value of foo to file a.txt\\
2674
2661
2675 It should be noted that if you change the value of a variable, you
2662 It should be noted that if you change the value of a variable, you
2676 need to %store it again if you want to persist the new value.
2663 need to %store it again if you want to persist the new value.
2677
2664
2678 Note also that the variables will need to be pickleable; most basic
2665 Note also that the variables will need to be pickleable; most basic
2679 python types can be safely %stored.
2666 python types can be safely %stored.
2680 """
2667 """
2681
2668
2682 opts,argsl = self.parse_options(parameter_s,'dr',mode='string')
2669 opts,argsl = self.parse_options(parameter_s,'dr',mode='string')
2683 args = argsl.split(None,1)
2670 args = argsl.split(None,1)
2684 ip = self.getapi()
2671 ip = self.getapi()
2685 # delete
2672 # delete
2686 if opts.has_key('d'):
2673 if opts.has_key('d'):
2687 try:
2674 try:
2688 todel = args[0]
2675 todel = args[0]
2689 except IndexError:
2676 except IndexError:
2690 error('You must provide the variable to forget')
2677 error('You must provide the variable to forget')
2691 else:
2678 else:
2692 try:
2679 try:
2693 del self.shell.persist['S:' + todel]
2680 del self.shell.persist['S:' + todel]
2694 except:
2681 except:
2695 error("Can't delete variable '%s'" % todel)
2682 error("Can't delete variable '%s'" % todel)
2696 # reset
2683 # reset
2697 elif opts.has_key('r'):
2684 elif opts.has_key('r'):
2698 for k in self.shell.persist.keys():
2685 for k in self.shell.persist.keys():
2699 if k.startswith('S:'):
2686 if k.startswith('S:'):
2700 del self.shell.persist[k]
2687 del self.shell.persist[k]
2701
2688
2702 # run without arguments -> list variables & values
2689 # run without arguments -> list variables & values
2703 elif not args:
2690 elif not args:
2704 vars = [v[2:] for v in self.shell.persist.keys()
2691 vars = [v[2:] for v in self.shell.persist.keys()
2705 if v.startswith('S:')]
2692 if v.startswith('S:')]
2706 vars.sort()
2693 vars.sort()
2707 if vars:
2694 if vars:
2708 size = max(map(len,vars))
2695 size = max(map(len,vars))
2709 else:
2696 else:
2710 size = 0
2697 size = 0
2711
2698
2712 print 'Stored variables and their in-memory values:'
2699 print 'Stored variables and their in-memory values:'
2713 fmt = '%-'+str(size)+'s -> %s'
2700 fmt = '%-'+str(size)+'s -> %s'
2714 get = self.shell.user_ns.get
2701 get = self.shell.user_ns.get
2715 for var in vars:
2702 for var in vars:
2716 # print 30 first characters from every var
2703 # print 30 first characters from every var
2717 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2704 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2718
2705
2719 # default action - store the variable
2706 # default action - store the variable
2720 else:
2707 else:
2721 # %store foo >file.txt or >>file.txt
2708 # %store foo >file.txt or >>file.txt
2722 if len(args) > 1 and args[1].startswith('>'):
2709 if len(args) > 1 and args[1].startswith('>'):
2723 fnam = os.path.expanduser(args[1].lstrip('>').lstrip())
2710 fnam = os.path.expanduser(args[1].lstrip('>').lstrip())
2724 if args[1].startswith('>>'):
2711 if args[1].startswith('>>'):
2725 fil = open(fnam,'a')
2712 fil = open(fnam,'a')
2726 else:
2713 else:
2727 fil = open(fnam,'w')
2714 fil = open(fnam,'w')
2728 obj = ip.ev(args[0])
2715 obj = ip.ev(args[0])
2729 print "Writing '%s' (%s) to file '%s'." % (args[0],
2716 print "Writing '%s' (%s) to file '%s'." % (args[0],
2730 obj.__class__.__name__, fnam)
2717 obj.__class__.__name__, fnam)
2731
2718
2732
2719
2733 if not isinstance (obj,basestring):
2720 if not isinstance (obj,basestring):
2734 pprint(obj,fil)
2721 pprint(obj,fil)
2735 else:
2722 else:
2736 fil.write(obj)
2723 fil.write(obj)
2737 if not obj.endswith('\n'):
2724 if not obj.endswith('\n'):
2738 fil.write('\n')
2725 fil.write('\n')
2739
2726
2740 fil.close()
2727 fil.close()
2741 return
2728 return
2742
2729
2743 # %store foo
2730 # %store foo
2744 obj = self.shell.user_ns[args[0] ]
2731 obj = self.shell.user_ns[args[0] ]
2745 if isinstance(inspect.getmodule(obj), FakeModule):
2732 if isinstance(inspect.getmodule(obj), FakeModule):
2746 print textwrap.dedent("""\
2733 print textwrap.dedent("""\
2747 Warning:%s is %s
2734 Warning:%s is %s
2748 Proper storage of interactively declared classes (or instances
2735 Proper storage of interactively declared classes (or instances
2749 of those classes) is not possible! Only instances
2736 of those classes) is not possible! Only instances
2750 of classes in real modules on file system can be %%store'd.
2737 of classes in real modules on file system can be %%store'd.
2751 """ % (args[0], obj) )
2738 """ % (args[0], obj) )
2752 return
2739 return
2753 pickled = pickle.dumps(obj)
2740 pickled = pickle.dumps(obj)
2754 self.shell.persist[ 'S:' + args[0] ] = pickled
2741 self.shell.persist[ 'S:' + args[0] ] = pickled
2755 print "Stored '%s' (%s, %d bytes)" % (args[0], obj.__class__.__name__,len(pickled))
2742 print "Stored '%s' (%s, %d bytes)" % (args[0], obj.__class__.__name__,len(pickled))
2756
2743
2757 def magic_bookmark(self, parameter_s=''):
2744 def magic_bookmark(self, parameter_s=''):
2758 """Manage IPython's bookmark system.
2745 """Manage IPython's bookmark system.
2759
2746
2760 %bookmark <name> - set bookmark to current dir
2747 %bookmark <name> - set bookmark to current dir
2761 %bookmark <name> <dir> - set bookmark to <dir>
2748 %bookmark <name> <dir> - set bookmark to <dir>
2762 %bookmark -l - list all bookmarks
2749 %bookmark -l - list all bookmarks
2763 %bookmark -d <name> - remove bookmark
2750 %bookmark -d <name> - remove bookmark
2764 %bookmark -r - remove all bookmarks
2751 %bookmark -r - remove all bookmarks
2765
2752
2766 You can later on access a bookmarked folder with:
2753 You can later on access a bookmarked folder with:
2767 %cd -b <name>
2754 %cd -b <name>
2768 or simply '%cd <name>' if there is no directory called <name> AND
2755 or simply '%cd <name>' if there is no directory called <name> AND
2769 there is such a bookmark defined.
2756 there is such a bookmark defined.
2770
2757
2771 Your bookmarks persist through IPython sessions, but they are
2758 Your bookmarks persist through IPython sessions, but they are
2772 associated with each profile."""
2759 associated with each profile."""
2773
2760
2774 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2761 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2775 if len(args) > 2:
2762 if len(args) > 2:
2776 error('You can only give at most two arguments')
2763 error('You can only give at most two arguments')
2777 return
2764 return
2778
2765
2779 bkms = self.shell.persist.get('bookmarks',{})
2766 bkms = self.shell.persist.get('bookmarks',{})
2780
2767
2781 if opts.has_key('d'):
2768 if opts.has_key('d'):
2782 try:
2769 try:
2783 todel = args[0]
2770 todel = args[0]
2784 except IndexError:
2771 except IndexError:
2785 error('You must provide a bookmark to delete')
2772 error('You must provide a bookmark to delete')
2786 else:
2773 else:
2787 try:
2774 try:
2788 del bkms[todel]
2775 del bkms[todel]
2789 except:
2776 except:
2790 error("Can't delete bookmark '%s'" % todel)
2777 error("Can't delete bookmark '%s'" % todel)
2791 elif opts.has_key('r'):
2778 elif opts.has_key('r'):
2792 bkms = {}
2779 bkms = {}
2793 elif opts.has_key('l'):
2780 elif opts.has_key('l'):
2794 bks = bkms.keys()
2781 bks = bkms.keys()
2795 bks.sort()
2782 bks.sort()
2796 if bks:
2783 if bks:
2797 size = max(map(len,bks))
2784 size = max(map(len,bks))
2798 else:
2785 else:
2799 size = 0
2786 size = 0
2800 fmt = '%-'+str(size)+'s -> %s'
2787 fmt = '%-'+str(size)+'s -> %s'
2801 print 'Current bookmarks:'
2788 print 'Current bookmarks:'
2802 for bk in bks:
2789 for bk in bks:
2803 print fmt % (bk,bkms[bk])
2790 print fmt % (bk,bkms[bk])
2804 else:
2791 else:
2805 if not args:
2792 if not args:
2806 error("You must specify the bookmark name")
2793 error("You must specify the bookmark name")
2807 elif len(args)==1:
2794 elif len(args)==1:
2808 bkms[args[0]] = os.getcwd()
2795 bkms[args[0]] = os.getcwd()
2809 elif len(args)==2:
2796 elif len(args)==2:
2810 bkms[args[0]] = args[1]
2797 bkms[args[0]] = args[1]
2811 self.shell.persist['bookmarks'] = bkms
2798 self.shell.persist['bookmarks'] = bkms
2812
2799
2813 def magic_pycat(self, parameter_s=''):
2800 def magic_pycat(self, parameter_s=''):
2814 """Show a syntax-highlighted file through a pager.
2801 """Show a syntax-highlighted file through a pager.
2815
2802
2816 This magic is similar to the cat utility, but it will assume the file
2803 This magic is similar to the cat utility, but it will assume the file
2817 to be Python source and will show it with syntax highlighting. """
2804 to be Python source and will show it with syntax highlighting. """
2818
2805
2819 filename = get_py_filename(parameter_s)
2806 filename = get_py_filename(parameter_s)
2820 page(self.shell.pycolorize(file_read(filename)),
2807 page(self.shell.pycolorize(file_read(filename)),
2821 screen_lines=self.shell.rc.screen_length)
2808 screen_lines=self.shell.rc.screen_length)
2822
2809
2823 def magic_cpaste(self, parameter_s=''):
2810 def magic_cpaste(self, parameter_s=''):
2824 """Allows you to paste & execute a pre-formatted code block from
2811 """Allows you to paste & execute a pre-formatted code block from
2825 clipboard.
2812 clipboard.
2826
2813
2827 You must terminate the block with '--' (two minus-signs) alone on the
2814 You must terminate the block with '--' (two minus-signs) alone on the
2828 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2815 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2829 is the new sentinel for this operation)
2816 is the new sentinel for this operation)
2830
2817
2831 The block is dedented prior to execution to enable execution of
2818 The block is dedented prior to execution to enable execution of
2832 method definitions. The executed block is also assigned to variable
2819 method definitions. The executed block is also assigned to variable
2833 named 'pasted_block' for later editing with '%edit pasted_block'.
2820 named 'pasted_block' for later editing with '%edit pasted_block'.
2834
2821
2835 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2822 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2836 This assigns the pasted block to variable 'foo' as string, without
2823 This assigns the pasted block to variable 'foo' as string, without
2837 dedenting or executing it.
2824 dedenting or executing it.
2838
2825
2839 Do not be alarmed by garbled output on Windows (it's a readline bug).
2826 Do not be alarmed by garbled output on Windows (it's a readline bug).
2840 Just press enter and type -- (and press enter again) and the block
2827 Just press enter and type -- (and press enter again) and the block
2841 will be what was just pasted.
2828 will be what was just pasted.
2842
2829
2843 IPython statements (magics, shell escapes) are not supported (yet).
2830 IPython statements (magics, shell escapes) are not supported (yet).
2844 """
2831 """
2845 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2832 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2846 par = args.strip()
2833 par = args.strip()
2847 sentinel = opts.get('s','--')
2834 sentinel = opts.get('s','--')
2848
2835
2849 from IPython import iplib
2836 from IPython import iplib
2850 lines = []
2837 lines = []
2851 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2838 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2852 while 1:
2839 while 1:
2853 l = iplib.raw_input_original(':')
2840 l = iplib.raw_input_original(':')
2854 if l ==sentinel:
2841 if l ==sentinel:
2855 break
2842 break
2856 lines.append(l)
2843 lines.append(l)
2857 block = "\n".join(lines) + '\n'
2844 block = "\n".join(lines) + '\n'
2858 #print "block:\n",block
2845 #print "block:\n",block
2859 if not par:
2846 if not par:
2860 b = textwrap.dedent(block)
2847 b = textwrap.dedent(block)
2861 exec b in self.user_ns
2848 exec b in self.user_ns
2862 self.user_ns['pasted_block'] = b
2849 self.user_ns['pasted_block'] = b
2863 else:
2850 else:
2864 self.user_ns[par] = block
2851 self.user_ns[par] = block
2865 print "Block assigned to '%s'" % par
2852 print "Block assigned to '%s'" % par
2866 def magic_quickref(self,arg):
2853 def magic_quickref(self,arg):
2867 import IPython.usage
2854 import IPython.usage
2868 page(IPython.usage.quick_reference)
2855 page(IPython.usage.quick_reference)
2869 del IPython.usage
2856 del IPython.usage
2870
2857
2871
2858
2872 # end Magic
2859 # end Magic
@@ -1,66 +1,66 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 One of Python's nicest features is its interactive interpreter. This allows
5 One of Python's nicest features is its interactive interpreter. This allows
6 very fast testing of ideas without the overhead of creating test files as is
6 very fast testing of ideas without the overhead of creating test files as is
7 typical in most programming languages. However, the interpreter supplied with
7 typical in most programming languages. However, the interpreter supplied with
8 the standard Python distribution is fairly primitive (and IDLE isn't really
8 the standard Python distribution is fairly primitive (and IDLE isn't really
9 much better).
9 much better).
10
10
11 IPython tries to:
11 IPython tries to:
12
12
13 i - provide an efficient environment for interactive work in Python
13 i - provide an efficient environment for interactive work in Python
14 programming. It tries to address what we see as shortcomings of the standard
14 programming. It tries to address what we see as shortcomings of the standard
15 Python prompt, and adds many features to make interactive work much more
15 Python prompt, and adds many features to make interactive work much more
16 efficient.
16 efficient.
17
17
18 ii - offer a flexible framework so that it can be used as the base
18 ii - offer a flexible framework so that it can be used as the base
19 environment for other projects and problems where Python can be the
19 environment for other projects and problems where Python can be the
20 underlying language. Specifically scientific environments like Mathematica,
20 underlying language. Specifically scientific environments like Mathematica,
21 IDL and Mathcad inspired its design, but similar ideas can be useful in many
21 IDL and Mathcad inspired its design, but similar ideas can be useful in many
22 fields. Python is a fabulous language for implementing this kind of system
22 fields. Python is a fabulous language for implementing this kind of system
23 (due to its dynamic and introspective features), and with suitable libraries
23 (due to its dynamic and introspective features), and with suitable libraries
24 entire systems could be built leveraging Python's power.
24 entire systems could be built leveraging Python's power.
25
25
26 iii - serve as an embeddable, ready to go interpreter for your own programs.
26 iii - serve as an embeddable, ready to go interpreter for your own programs.
27
27
28 IPython requires Python 2.2 or newer.
28 IPython requires Python 2.2 or newer.
29
29
30 $Id: __init__.py 1025 2006-01-16 20:22:21Z vivainio $"""
30 $Id: __init__.py 1099 2006-01-29 21:05:57Z vivainio $"""
31
31
32 #*****************************************************************************
32 #*****************************************************************************
33 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
33 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
34 #
34 #
35 # Distributed under the terms of the BSD License. The full license is in
35 # Distributed under the terms of the BSD License. The full license is in
36 # the file COPYING, distributed as part of this software.
36 # the file COPYING, distributed as part of this software.
37 #*****************************************************************************
37 #*****************************************************************************
38
38
39 # Enforce proper version requirements
39 # Enforce proper version requirements
40 import sys
40 import sys
41 if sys.version[0:3] < '2.3':
41 if sys.version[0:3] < '2.3':
42 raise ImportError, 'Python Version 2.3 or above is required.'
42 raise ImportError, 'Python Version 2.3 or above is required.'
43
43
44 # Define what gets imported with a 'from IPython import *'
44 # Define what gets imported with a 'from IPython import *'
45 __all__ = ['deep_reload','genutils','ipstruct','ultraTB','DPyGetOpt',
45 __all__ = ['deep_reload','genutils','ipstruct','ultraTB','DPyGetOpt',
46 'Itpl','hooks','ConfigLoader','OutputTrap','Release','Shell',
46 'Itpl','hooks','ConfigLoader','OutputTrap','Release','Shell',
47 'platutils','platutils_win32','platutils_posix','platutils_dummy',
47 'platutils','platutils_win32','platutils_posix','platutils_dummy',
48 'ipapi','path']
48 'ipapi','path','rlineimpl']
49
49
50 # Load __all__ in IPython namespace so that a simple 'import IPython' gives
50 # Load __all__ in IPython namespace so that a simple 'import IPython' gives
51 # access to them via IPython.<name>
51 # access to them via IPython.<name>
52 glob,loc = globals(),locals()
52 glob,loc = globals(),locals()
53 for name in __all__:
53 for name in __all__:
54 __import__(name,glob,loc,[])
54 __import__(name,glob,loc,[])
55
55
56 # Release data
56 # Release data
57 from IPython import Release # do it explicitly so pydoc can see it - pydoc bug
57 from IPython import Release # do it explicitly so pydoc can see it - pydoc bug
58 __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \
58 __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \
59 ( Release.authors['Fernando'] + Release.authors['Janko'] + \
59 ( Release.authors['Fernando'] + Release.authors['Janko'] + \
60 Release.authors['Nathan'] )
60 Release.authors['Nathan'] )
61 __license__ = Release.license
61 __license__ = Release.license
62 __version__ = Release.version
62 __version__ = Release.version
63 __revision__ = Release.revision
63 __revision__ = Release.revision
64
64
65 # Namespace cleanup
65 # Namespace cleanup
66 del name,glob,loc
66 del name,glob,loc
@@ -1,562 +1,563 b''
1 """Word completion for IPython.
1 """Word completion for IPython.
2
2
3 This module is a fork of the rlcompleter module in the Python standard
3 This module is a fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3, but we need a lot more
5 upstream and were accepted as of Python 2.3, but we need a lot more
6 functionality specific to IPython, so this module will continue to live as an
6 functionality specific to IPython, so this module will continue to live as an
7 IPython-specific utility.
7 IPython-specific utility.
8
8
9 ---------------------------------------------------------------------------
9 ---------------------------------------------------------------------------
10 Original rlcompleter documentation:
10 Original rlcompleter documentation:
11
11
12 This requires the latest extension to the readline module (the
12 This requires the latest extension to the readline module (the
13 completes keywords, built-ins and globals in __main__; when completing
13 completes keywords, built-ins and globals in __main__; when completing
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 completes its attributes.
15 completes its attributes.
16
16
17 It's very cool to do "import string" type "string.", hit the
17 It's very cool to do "import string" type "string.", hit the
18 completion key (twice), and see the list of names defined by the
18 completion key (twice), and see the list of names defined by the
19 string module!
19 string module!
20
20
21 Tip: to use the tab key as the completion key, call
21 Tip: to use the tab key as the completion key, call
22
22
23 readline.parse_and_bind("tab: complete")
23 readline.parse_and_bind("tab: complete")
24
24
25 Notes:
25 Notes:
26
26
27 - Exceptions raised by the completer function are *ignored* (and
27 - Exceptions raised by the completer function are *ignored* (and
28 generally cause the completion to fail). This is a feature -- since
28 generally cause the completion to fail). This is a feature -- since
29 readline sets the tty device in raw (or cbreak) mode, printing a
29 readline sets the tty device in raw (or cbreak) mode, printing a
30 traceback wouldn't work well without some complicated hoopla to save,
30 traceback wouldn't work well without some complicated hoopla to save,
31 reset and restore the tty state.
31 reset and restore the tty state.
32
32
33 - The evaluation of the NAME.NAME... form may cause arbitrary
33 - The evaluation of the NAME.NAME... form may cause arbitrary
34 application defined code to be executed if an object with a
34 application defined code to be executed if an object with a
35 __getattr__ hook is found. Since it is the responsibility of the
35 __getattr__ hook is found. Since it is the responsibility of the
36 application (or the user) to enable this feature, I consider this an
36 application (or the user) to enable this feature, I consider this an
37 acceptable risk. More complicated expressions (e.g. function calls or
37 acceptable risk. More complicated expressions (e.g. function calls or
38 indexing operations) are *not* evaluated.
38 indexing operations) are *not* evaluated.
39
39
40 - GNU readline is also used by the built-in functions input() and
40 - GNU readline is also used by the built-in functions input() and
41 raw_input(), and thus these also benefit/suffer from the completer
41 raw_input(), and thus these also benefit/suffer from the completer
42 features. Clearly an interactive application can benefit by
42 features. Clearly an interactive application can benefit by
43 specifying its own completer function and using raw_input() for all
43 specifying its own completer function and using raw_input() for all
44 its input.
44 its input.
45
45
46 - When the original stdin is not a tty device, GNU readline is never
46 - When the original stdin is not a tty device, GNU readline is never
47 used, and this module (and the readline module) are silently inactive.
47 used, and this module (and the readline module) are silently inactive.
48
48
49 """
49 """
50
50
51 #*****************************************************************************
51 #*****************************************************************************
52 #
52 #
53 # Since this file is essentially a minimally modified copy of the rlcompleter
53 # Since this file is essentially a minimally modified copy of the rlcompleter
54 # module which is part of the standard Python distribution, I assume that the
54 # module which is part of the standard Python distribution, I assume that the
55 # proper procedure is to maintain its copyright as belonging to the Python
55 # proper procedure is to maintain its copyright as belonging to the Python
56 # Software Foundation (in addition to my own, for all new code).
56 # Software Foundation (in addition to my own, for all new code).
57 #
57 #
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
59 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
60 #
60 #
61 # Distributed under the terms of the BSD License. The full license is in
61 # Distributed under the terms of the BSD License. The full license is in
62 # the file COPYING, distributed as part of this software.
62 # the file COPYING, distributed as part of this software.
63 #
63 #
64 #*****************************************************************************
64 #*****************************************************************************
65
65
66 import __builtin__
66 import __builtin__
67 import __main__
67 import __main__
68 import glob
68 import glob
69 import keyword
69 import keyword
70 import os
70 import os
71 import re
71 import re
72 import readline
73 import sys
72 import sys
73 import IPython.rlineimpl as readline
74
74 import types
75 import types
75
76
76 # Python 2.4 offers sets as a builtin
77 # Python 2.4 offers sets as a builtin
77 try:
78 try:
78 set([1,2])
79 set([1,2])
79 except NameError:
80 except NameError:
80 from sets import Set as set
81 from sets import Set as set
81
82
82
83
83 from IPython.genutils import shlex_split,debugx
84 from IPython.genutils import shlex_split,debugx
84
85
85 __all__ = ['Completer','IPCompleter']
86 __all__ = ['Completer','IPCompleter']
86
87
87 def get_class_members(cls):
88 def get_class_members(cls):
88 ret = dir(cls)
89 ret = dir(cls)
89 if hasattr(cls,'__bases__'):
90 if hasattr(cls,'__bases__'):
90 for base in cls.__bases__:
91 for base in cls.__bases__:
91 ret.extend(get_class_members(base))
92 ret.extend(get_class_members(base))
92 return ret
93 return ret
93
94
94 class Completer:
95 class Completer:
95 def __init__(self,namespace=None,global_namespace=None):
96 def __init__(self,namespace=None,global_namespace=None):
96 """Create a new completer for the command line.
97 """Create a new completer for the command line.
97
98
98 Completer([namespace,global_namespace]) -> completer instance.
99 Completer([namespace,global_namespace]) -> completer instance.
99
100
100 If unspecified, the default namespace where completions are performed
101 If unspecified, the default namespace where completions are performed
101 is __main__ (technically, __main__.__dict__). Namespaces should be
102 is __main__ (technically, __main__.__dict__). Namespaces should be
102 given as dictionaries.
103 given as dictionaries.
103
104
104 An optional second namespace can be given. This allows the completer
105 An optional second namespace can be given. This allows the completer
105 to handle cases where both the local and global scopes need to be
106 to handle cases where both the local and global scopes need to be
106 distinguished.
107 distinguished.
107
108
108 Completer instances should be used as the completion mechanism of
109 Completer instances should be used as the completion mechanism of
109 readline via the set_completer() call:
110 readline via the set_completer() call:
110
111
111 readline.set_completer(Completer(my_namespace).complete)
112 readline.set_completer(Completer(my_namespace).complete)
112 """
113 """
113
114
114 # some minimal strict typechecks. For some core data structures, I
115 # some minimal strict typechecks. For some core data structures, I
115 # want actual basic python types, not just anything that looks like
116 # want actual basic python types, not just anything that looks like
116 # one. This is especially true for namespaces.
117 # one. This is especially true for namespaces.
117 for ns in (namespace,global_namespace):
118 for ns in (namespace,global_namespace):
118 if ns is not None and type(ns) != types.DictType:
119 if ns is not None and type(ns) != types.DictType:
119 raise TypeError,'namespace must be a dictionary'
120 raise TypeError,'namespace must be a dictionary'
120
121
121 # Don't bind to namespace quite yet, but flag whether the user wants a
122 # Don't bind to namespace quite yet, but flag whether the user wants a
122 # specific namespace or to use __main__.__dict__. This will allow us
123 # specific namespace or to use __main__.__dict__. This will allow us
123 # to bind to __main__.__dict__ at completion time, not now.
124 # to bind to __main__.__dict__ at completion time, not now.
124 if namespace is None:
125 if namespace is None:
125 self.use_main_ns = 1
126 self.use_main_ns = 1
126 else:
127 else:
127 self.use_main_ns = 0
128 self.use_main_ns = 0
128 self.namespace = namespace
129 self.namespace = namespace
129
130
130 # The global namespace, if given, can be bound directly
131 # The global namespace, if given, can be bound directly
131 if global_namespace is None:
132 if global_namespace is None:
132 self.global_namespace = {}
133 self.global_namespace = {}
133 else:
134 else:
134 self.global_namespace = global_namespace
135 self.global_namespace = global_namespace
135
136
136 def complete(self, text, state):
137 def complete(self, text, state):
137 """Return the next possible completion for 'text'.
138 """Return the next possible completion for 'text'.
138
139
139 This is called successively with state == 0, 1, 2, ... until it
140 This is called successively with state == 0, 1, 2, ... until it
140 returns None. The completion should begin with 'text'.
141 returns None. The completion should begin with 'text'.
141
142
142 """
143 """
143 if self.use_main_ns:
144 if self.use_main_ns:
144 self.namespace = __main__.__dict__
145 self.namespace = __main__.__dict__
145
146
146 if state == 0:
147 if state == 0:
147 if "." in text:
148 if "." in text:
148 self.matches = self.attr_matches(text)
149 self.matches = self.attr_matches(text)
149 else:
150 else:
150 self.matches = self.global_matches(text)
151 self.matches = self.global_matches(text)
151 try:
152 try:
152 return self.matches[state]
153 return self.matches[state]
153 except IndexError:
154 except IndexError:
154 return None
155 return None
155
156
156 def global_matches(self, text):
157 def global_matches(self, text):
157 """Compute matches when text is a simple name.
158 """Compute matches when text is a simple name.
158
159
159 Return a list of all keywords, built-in functions and names currently
160 Return a list of all keywords, built-in functions and names currently
160 defined in self.namespace or self.global_namespace that match.
161 defined in self.namespace or self.global_namespace that match.
161
162
162 """
163 """
163 matches = []
164 matches = []
164 match_append = matches.append
165 match_append = matches.append
165 n = len(text)
166 n = len(text)
166 for lst in [keyword.kwlist,
167 for lst in [keyword.kwlist,
167 __builtin__.__dict__.keys(),
168 __builtin__.__dict__.keys(),
168 self.namespace.keys(),
169 self.namespace.keys(),
169 self.global_namespace.keys()]:
170 self.global_namespace.keys()]:
170 for word in lst:
171 for word in lst:
171 if word[:n] == text and word != "__builtins__":
172 if word[:n] == text and word != "__builtins__":
172 match_append(word)
173 match_append(word)
173 return matches
174 return matches
174
175
175 def attr_matches(self, text):
176 def attr_matches(self, text):
176 """Compute matches when text contains a dot.
177 """Compute matches when text contains a dot.
177
178
178 Assuming the text is of the form NAME.NAME....[NAME], and is
179 Assuming the text is of the form NAME.NAME....[NAME], and is
179 evaluatable in self.namespace or self.global_namespace, it will be
180 evaluatable in self.namespace or self.global_namespace, it will be
180 evaluated and its attributes (as revealed by dir()) are used as
181 evaluated and its attributes (as revealed by dir()) are used as
181 possible completions. (For class instances, class members are are
182 possible completions. (For class instances, class members are are
182 also considered.)
183 also considered.)
183
184
184 WARNING: this can still invoke arbitrary C code, if an object
185 WARNING: this can still invoke arbitrary C code, if an object
185 with a __getattr__ hook is evaluated.
186 with a __getattr__ hook is evaluated.
186
187
187 """
188 """
188 import re
189 import re
189
190
190 # Another option, seems to work great. Catches things like ''.<tab>
191 # Another option, seems to work great. Catches things like ''.<tab>
191 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
192 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
192
193
193 if not m:
194 if not m:
194 return []
195 return []
195
196
196 expr, attr = m.group(1, 3)
197 expr, attr = m.group(1, 3)
197 try:
198 try:
198 object = eval(expr, self.namespace)
199 object = eval(expr, self.namespace)
199 except:
200 except:
200 object = eval(expr, self.global_namespace)
201 object = eval(expr, self.global_namespace)
201
202
202 # Start building the attribute list via dir(), and then complete it
203 # Start building the attribute list via dir(), and then complete it
203 # with a few extra special-purpose calls.
204 # with a few extra special-purpose calls.
204 words = dir(object)
205 words = dir(object)
205
206
206 if hasattr(object,'__class__'):
207 if hasattr(object,'__class__'):
207 words.append('__class__')
208 words.append('__class__')
208 words.extend(get_class_members(object.__class__))
209 words.extend(get_class_members(object.__class__))
209
210
210 # this is the 'dir' function for objects with Enthought's traits
211 # this is the 'dir' function for objects with Enthought's traits
211 if hasattr(object, 'trait_names'):
212 if hasattr(object, 'trait_names'):
212 try:
213 try:
213 words.extend(object.trait_names())
214 words.extend(object.trait_names())
214 # eliminate possible duplicates, as some traits may also
215 # eliminate possible duplicates, as some traits may also
215 # appear as normal attributes in the dir() call.
216 # appear as normal attributes in the dir() call.
216 words = set(words)
217 words = set(words)
217 except TypeError:
218 except TypeError:
218 # This will happen if `object` is a class and not an instance.
219 # This will happen if `object` is a class and not an instance.
219 pass
220 pass
220
221
221 # filter out non-string attributes which may be stuffed by dir() calls
222 # filter out non-string attributes which may be stuffed by dir() calls
222 # and poor coding in third-party modules
223 # and poor coding in third-party modules
223 words = [w for w in words
224 words = [w for w in words
224 if isinstance(w, basestring) and w != "__builtins__"]
225 if isinstance(w, basestring) and w != "__builtins__"]
225 # Build match list to return
226 # Build match list to return
226 n = len(attr)
227 n = len(attr)
227 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
228 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
228
229
229 class IPCompleter(Completer):
230 class IPCompleter(Completer):
230 """Extension of the completer class with IPython-specific features"""
231 """Extension of the completer class with IPython-specific features"""
231
232
232 def __init__(self,shell,namespace=None,global_namespace=None,
233 def __init__(self,shell,namespace=None,global_namespace=None,
233 omit__names=0,alias_table=None):
234 omit__names=0,alias_table=None):
234 """IPCompleter() -> completer
235 """IPCompleter() -> completer
235
236
236 Return a completer object suitable for use by the readline library
237 Return a completer object suitable for use by the readline library
237 via readline.set_completer().
238 via readline.set_completer().
238
239
239 Inputs:
240 Inputs:
240
241
241 - shell: a pointer to the ipython shell itself. This is needed
242 - shell: a pointer to the ipython shell itself. This is needed
242 because this completer knows about magic functions, and those can
243 because this completer knows about magic functions, and those can
243 only be accessed via the ipython instance.
244 only be accessed via the ipython instance.
244
245
245 - namespace: an optional dict where completions are performed.
246 - namespace: an optional dict where completions are performed.
246
247
247 - global_namespace: secondary optional dict for completions, to
248 - global_namespace: secondary optional dict for completions, to
248 handle cases (such as IPython embedded inside functions) where
249 handle cases (such as IPython embedded inside functions) where
249 both Python scopes are visible.
250 both Python scopes are visible.
250
251
251 - The optional omit__names parameter sets the completer to omit the
252 - The optional omit__names parameter sets the completer to omit the
252 'magic' names (__magicname__) for python objects unless the text
253 'magic' names (__magicname__) for python objects unless the text
253 to be completed explicitly starts with one or more underscores.
254 to be completed explicitly starts with one or more underscores.
254
255
255 - If alias_table is supplied, it should be a dictionary of aliases
256 - If alias_table is supplied, it should be a dictionary of aliases
256 to complete. """
257 to complete. """
257
258
258 Completer.__init__(self,namespace,global_namespace)
259 Completer.__init__(self,namespace,global_namespace)
259 self.magic_prefix = shell.name+'.magic_'
260 self.magic_prefix = shell.name+'.magic_'
260 self.magic_escape = shell.ESC_MAGIC
261 self.magic_escape = shell.ESC_MAGIC
261 self.readline = readline
262 self.readline = readline
262 delims = self.readline.get_completer_delims()
263 delims = self.readline.get_completer_delims()
263 delims = delims.replace(self.magic_escape,'')
264 delims = delims.replace(self.magic_escape,'')
264 self.readline.set_completer_delims(delims)
265 self.readline.set_completer_delims(delims)
265 self.get_line_buffer = self.readline.get_line_buffer
266 self.get_line_buffer = self.readline.get_line_buffer
266 self.omit__names = omit__names
267 self.omit__names = omit__names
267 self.merge_completions = shell.rc.readline_merge_completions
268 self.merge_completions = shell.rc.readline_merge_completions
268
269
269 if alias_table is None:
270 if alias_table is None:
270 alias_table = {}
271 alias_table = {}
271 self.alias_table = alias_table
272 self.alias_table = alias_table
272 # Regexp to split filenames with spaces in them
273 # Regexp to split filenames with spaces in them
273 self.space_name_re = re.compile(r'([^\\] )')
274 self.space_name_re = re.compile(r'([^\\] )')
274 # Hold a local ref. to glob.glob for speed
275 # Hold a local ref. to glob.glob for speed
275 self.glob = glob.glob
276 self.glob = glob.glob
276
277
277 # Determine if we are running on 'dumb' terminals, like (X)Emacs
278 # Determine if we are running on 'dumb' terminals, like (X)Emacs
278 # buffers, to avoid completion problems.
279 # buffers, to avoid completion problems.
279 term = os.environ.get('TERM','xterm')
280 term = os.environ.get('TERM','xterm')
280 self.dumb_terminal = term in ['dumb','emacs']
281 self.dumb_terminal = term in ['dumb','emacs']
281
282
282 # Special handling of backslashes needed in win32 platforms
283 # Special handling of backslashes needed in win32 platforms
283 if sys.platform == "win32":
284 if sys.platform == "win32":
284 self.clean_glob = self._clean_glob_win32
285 self.clean_glob = self._clean_glob_win32
285 else:
286 else:
286 self.clean_glob = self._clean_glob
287 self.clean_glob = self._clean_glob
287 self.matchers = [self.python_matches,
288 self.matchers = [self.python_matches,
288 self.file_matches,
289 self.file_matches,
289 self.alias_matches,
290 self.alias_matches,
290 self.python_func_kw_matches]
291 self.python_func_kw_matches]
291
292
292 # Code contributed by Alex Schmolck, for ipython/emacs integration
293 # Code contributed by Alex Schmolck, for ipython/emacs integration
293 def all_completions(self, text):
294 def all_completions(self, text):
294 """Return all possible completions for the benefit of emacs."""
295 """Return all possible completions for the benefit of emacs."""
295
296
296 completions = []
297 completions = []
297 comp_append = completions.append
298 comp_append = completions.append
298 try:
299 try:
299 for i in xrange(sys.maxint):
300 for i in xrange(sys.maxint):
300 res = self.complete(text, i)
301 res = self.complete(text, i)
301
302
302 if not res: break
303 if not res: break
303
304
304 comp_append(res)
305 comp_append(res)
305 #XXX workaround for ``notDefined.<tab>``
306 #XXX workaround for ``notDefined.<tab>``
306 except NameError:
307 except NameError:
307 pass
308 pass
308 return completions
309 return completions
309 # /end Alex Schmolck code.
310 # /end Alex Schmolck code.
310
311
311 def _clean_glob(self,text):
312 def _clean_glob(self,text):
312 return self.glob("%s*" % text)
313 return self.glob("%s*" % text)
313
314
314 def _clean_glob_win32(self,text):
315 def _clean_glob_win32(self,text):
315 return [f.replace("\\","/")
316 return [f.replace("\\","/")
316 for f in self.glob("%s*" % text)]
317 for f in self.glob("%s*" % text)]
317
318
318 def file_matches(self, text):
319 def file_matches(self, text):
319 """Match filneames, expanding ~USER type strings.
320 """Match filneames, expanding ~USER type strings.
320
321
321 Most of the seemingly convoluted logic in this completer is an
322 Most of the seemingly convoluted logic in this completer is an
322 attempt to handle filenames with spaces in them. And yet it's not
323 attempt to handle filenames with spaces in them. And yet it's not
323 quite perfect, because Python's readline doesn't expose all of the
324 quite perfect, because Python's readline doesn't expose all of the
324 GNU readline details needed for this to be done correctly.
325 GNU readline details needed for this to be done correctly.
325
326
326 For a filename with a space in it, the printed completions will be
327 For a filename with a space in it, the printed completions will be
327 only the parts after what's already been typed (instead of the
328 only the parts after what's already been typed (instead of the
328 full completions, as is normally done). I don't think with the
329 full completions, as is normally done). I don't think with the
329 current (as of Python 2.3) Python readline it's possible to do
330 current (as of Python 2.3) Python readline it's possible to do
330 better."""
331 better."""
331
332
332 #print 'Completer->file_matches: <%s>' % text # dbg
333 #print 'Completer->file_matches: <%s>' % text # dbg
333
334
334 # chars that require escaping with backslash - i.e. chars
335 # chars that require escaping with backslash - i.e. chars
335 # that readline treats incorrectly as delimiters, but we
336 # that readline treats incorrectly as delimiters, but we
336 # don't want to treat as delimiters in filename matching
337 # don't want to treat as delimiters in filename matching
337 # when escaped with backslash
338 # when escaped with backslash
338
339
339 protectables = ' ()[]{}'
340 protectables = ' ()[]{}'
340
341
341 def protect_filename(s):
342 def protect_filename(s):
342 return "".join([(ch in protectables and '\\' + ch or ch)
343 return "".join([(ch in protectables and '\\' + ch or ch)
343 for ch in s])
344 for ch in s])
344
345
345 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
346 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
346 open_quotes = 0 # track strings with open quotes
347 open_quotes = 0 # track strings with open quotes
347 try:
348 try:
348 lsplit = shlex_split(lbuf)[-1]
349 lsplit = shlex_split(lbuf)[-1]
349 except ValueError:
350 except ValueError:
350 # typically an unmatched ", or backslash without escaped char.
351 # typically an unmatched ", or backslash without escaped char.
351 if lbuf.count('"')==1:
352 if lbuf.count('"')==1:
352 open_quotes = 1
353 open_quotes = 1
353 lsplit = lbuf.split('"')[-1]
354 lsplit = lbuf.split('"')[-1]
354 elif lbuf.count("'")==1:
355 elif lbuf.count("'")==1:
355 open_quotes = 1
356 open_quotes = 1
356 lsplit = lbuf.split("'")[-1]
357 lsplit = lbuf.split("'")[-1]
357 else:
358 else:
358 return None
359 return None
359 except IndexError:
360 except IndexError:
360 # tab pressed on empty line
361 # tab pressed on empty line
361 lsplit = ""
362 lsplit = ""
362
363
363 if lsplit != protect_filename(lsplit):
364 if lsplit != protect_filename(lsplit):
364 # if protectables are found, do matching on the whole escaped
365 # if protectables are found, do matching on the whole escaped
365 # name
366 # name
366 has_protectables = 1
367 has_protectables = 1
367 text0,text = text,lsplit
368 text0,text = text,lsplit
368 else:
369 else:
369 has_protectables = 0
370 has_protectables = 0
370 text = os.path.expanduser(text)
371 text = os.path.expanduser(text)
371
372
372 if text == "":
373 if text == "":
373 return [protect_filename(f) for f in self.glob("*")]
374 return [protect_filename(f) for f in self.glob("*")]
374
375
375 m0 = self.clean_glob(text.replace('\\',''))
376 m0 = self.clean_glob(text.replace('\\',''))
376 if has_protectables:
377 if has_protectables:
377 # If we had protectables, we need to revert our changes to the
378 # If we had protectables, we need to revert our changes to the
378 # beginning of filename so that we don't double-write the part
379 # beginning of filename so that we don't double-write the part
379 # of the filename we have so far
380 # of the filename we have so far
380 len_lsplit = len(lsplit)
381 len_lsplit = len(lsplit)
381 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
382 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
382 else:
383 else:
383 if open_quotes:
384 if open_quotes:
384 # if we have a string with an open quote, we don't need to
385 # if we have a string with an open quote, we don't need to
385 # protect the names at all (and we _shouldn't_, as it
386 # protect the names at all (and we _shouldn't_, as it
386 # would cause bugs when the filesystem call is made).
387 # would cause bugs when the filesystem call is made).
387 matches = m0
388 matches = m0
388 else:
389 else:
389 matches = [protect_filename(f) for f in m0]
390 matches = [protect_filename(f) for f in m0]
390 if len(matches) == 1 and os.path.isdir(matches[0]):
391 if len(matches) == 1 and os.path.isdir(matches[0]):
391 # Takes care of links to directories also. Use '/'
392 # Takes care of links to directories also. Use '/'
392 # explicitly, even under Windows, so that name completions
393 # explicitly, even under Windows, so that name completions
393 # don't end up escaped.
394 # don't end up escaped.
394 matches[0] += '/'
395 matches[0] += '/'
395 return matches
396 return matches
396
397
397 def alias_matches(self, text):
398 def alias_matches(self, text):
398 """Match internal system aliases"""
399 """Match internal system aliases"""
399
400
400 #print 'Completer->alias_matches:',text # dbg
401 #print 'Completer->alias_matches:',text # dbg
401 text = os.path.expanduser(text)
402 text = os.path.expanduser(text)
402 aliases = self.alias_table.keys()
403 aliases = self.alias_table.keys()
403 if text == "":
404 if text == "":
404 return aliases
405 return aliases
405 else:
406 else:
406 return [alias for alias in aliases if alias.startswith(text)]
407 return [alias for alias in aliases if alias.startswith(text)]
407
408
408 def python_matches(self,text):
409 def python_matches(self,text):
409 """Match attributes or global python names"""
410 """Match attributes or global python names"""
410
411
411 #print 'Completer->python_matches, txt=<%s>' % text # dbg
412 #print 'Completer->python_matches, txt=<%s>' % text # dbg
412 if "." in text:
413 if "." in text:
413 try:
414 try:
414 matches = self.attr_matches(text)
415 matches = self.attr_matches(text)
415 if text.endswith('.') and self.omit__names:
416 if text.endswith('.') and self.omit__names:
416 if self.omit__names == 1:
417 if self.omit__names == 1:
417 # true if txt is _not_ a __ name, false otherwise:
418 # true if txt is _not_ a __ name, false otherwise:
418 no__name = (lambda txt:
419 no__name = (lambda txt:
419 re.match(r'.*\.__.*?__',txt) is None)
420 re.match(r'.*\.__.*?__',txt) is None)
420 else:
421 else:
421 # true if txt is _not_ a _ name, false otherwise:
422 # true if txt is _not_ a _ name, false otherwise:
422 no__name = (lambda txt:
423 no__name = (lambda txt:
423 re.match(r'.*\._.*?',txt) is None)
424 re.match(r'.*\._.*?',txt) is None)
424 matches = filter(no__name, matches)
425 matches = filter(no__name, matches)
425 except NameError:
426 except NameError:
426 # catches <undefined attributes>.<tab>
427 # catches <undefined attributes>.<tab>
427 matches = []
428 matches = []
428 else:
429 else:
429 matches = self.global_matches(text)
430 matches = self.global_matches(text)
430 # this is so completion finds magics when automagic is on:
431 # this is so completion finds magics when automagic is on:
431 if matches == [] and not text.startswith(os.sep):
432 if matches == [] and not text.startswith(os.sep):
432 matches = self.attr_matches(self.magic_prefix+text)
433 matches = self.attr_matches(self.magic_prefix+text)
433 return matches
434 return matches
434
435
435 def _default_arguments(self, obj):
436 def _default_arguments(self, obj):
436 """Return the list of default arguments of obj if it is callable,
437 """Return the list of default arguments of obj if it is callable,
437 or empty list otherwise."""
438 or empty list otherwise."""
438
439
439 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
440 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
440 # for classes, check for __init__,__new__
441 # for classes, check for __init__,__new__
441 if inspect.isclass(obj):
442 if inspect.isclass(obj):
442 obj = (getattr(obj,'__init__',None) or
443 obj = (getattr(obj,'__init__',None) or
443 getattr(obj,'__new__',None))
444 getattr(obj,'__new__',None))
444 # for all others, check if they are __call__able
445 # for all others, check if they are __call__able
445 elif hasattr(obj, '__call__'):
446 elif hasattr(obj, '__call__'):
446 obj = obj.__call__
447 obj = obj.__call__
447 # XXX: is there a way to handle the builtins ?
448 # XXX: is there a way to handle the builtins ?
448 try:
449 try:
449 args,_,_1,defaults = inspect.getargspec(obj)
450 args,_,_1,defaults = inspect.getargspec(obj)
450 if defaults:
451 if defaults:
451 return args[-len(defaults):]
452 return args[-len(defaults):]
452 except TypeError: pass
453 except TypeError: pass
453 return []
454 return []
454
455
455 def python_func_kw_matches(self,text):
456 def python_func_kw_matches(self,text):
456 """Match named parameters (kwargs) of the last open function"""
457 """Match named parameters (kwargs) of the last open function"""
457
458
458 if "." in text: # a parameter cannot be dotted
459 if "." in text: # a parameter cannot be dotted
459 return []
460 return []
460 try: regexp = self.__funcParamsRegex
461 try: regexp = self.__funcParamsRegex
461 except AttributeError:
462 except AttributeError:
462 regexp = self.__funcParamsRegex = re.compile(r'''
463 regexp = self.__funcParamsRegex = re.compile(r'''
463 '.*?' | # single quoted strings or
464 '.*?' | # single quoted strings or
464 ".*?" | # double quoted strings or
465 ".*?" | # double quoted strings or
465 \w+ | # identifier
466 \w+ | # identifier
466 \S # other characters
467 \S # other characters
467 ''', re.VERBOSE | re.DOTALL)
468 ''', re.VERBOSE | re.DOTALL)
468 # 1. find the nearest identifier that comes before an unclosed
469 # 1. find the nearest identifier that comes before an unclosed
469 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
470 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
470 tokens = regexp.findall(self.get_line_buffer())
471 tokens = regexp.findall(self.get_line_buffer())
471 tokens.reverse()
472 tokens.reverse()
472 iterTokens = iter(tokens); openPar = 0
473 iterTokens = iter(tokens); openPar = 0
473 for token in iterTokens:
474 for token in iterTokens:
474 if token == ')':
475 if token == ')':
475 openPar -= 1
476 openPar -= 1
476 elif token == '(':
477 elif token == '(':
477 openPar += 1
478 openPar += 1
478 if openPar > 0:
479 if openPar > 0:
479 # found the last unclosed parenthesis
480 # found the last unclosed parenthesis
480 break
481 break
481 else:
482 else:
482 return []
483 return []
483 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
484 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
484 ids = []
485 ids = []
485 isId = re.compile(r'\w+$').match
486 isId = re.compile(r'\w+$').match
486 while True:
487 while True:
487 try:
488 try:
488 ids.append(iterTokens.next())
489 ids.append(iterTokens.next())
489 if not isId(ids[-1]):
490 if not isId(ids[-1]):
490 ids.pop(); break
491 ids.pop(); break
491 if not iterTokens.next() == '.':
492 if not iterTokens.next() == '.':
492 break
493 break
493 except StopIteration:
494 except StopIteration:
494 break
495 break
495 # lookup the candidate callable matches either using global_matches
496 # lookup the candidate callable matches either using global_matches
496 # or attr_matches for dotted names
497 # or attr_matches for dotted names
497 if len(ids) == 1:
498 if len(ids) == 1:
498 callableMatches = self.global_matches(ids[0])
499 callableMatches = self.global_matches(ids[0])
499 else:
500 else:
500 callableMatches = self.attr_matches('.'.join(ids[::-1]))
501 callableMatches = self.attr_matches('.'.join(ids[::-1]))
501 argMatches = []
502 argMatches = []
502 for callableMatch in callableMatches:
503 for callableMatch in callableMatches:
503 try: namedArgs = self._default_arguments(eval(callableMatch,
504 try: namedArgs = self._default_arguments(eval(callableMatch,
504 self.namespace))
505 self.namespace))
505 except: continue
506 except: continue
506 for namedArg in namedArgs:
507 for namedArg in namedArgs:
507 if namedArg.startswith(text):
508 if namedArg.startswith(text):
508 argMatches.append("%s=" %namedArg)
509 argMatches.append("%s=" %namedArg)
509 return argMatches
510 return argMatches
510
511
511 def complete(self, text, state):
512 def complete(self, text, state):
512 """Return the next possible completion for 'text'.
513 """Return the next possible completion for 'text'.
513
514
514 This is called successively with state == 0, 1, 2, ... until it
515 This is called successively with state == 0, 1, 2, ... until it
515 returns None. The completion should begin with 'text'. """
516 returns None. The completion should begin with 'text'. """
516
517
517 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
518 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
518
519
519 # if there is only a tab on a line with only whitespace, instead
520 # if there is only a tab on a line with only whitespace, instead
520 # of the mostly useless 'do you want to see all million
521 # of the mostly useless 'do you want to see all million
521 # completions' message, just do the right thing and give the user
522 # completions' message, just do the right thing and give the user
522 # his tab! Incidentally, this enables pasting of tabbed text from
523 # his tab! Incidentally, this enables pasting of tabbed text from
523 # an editor (as long as autoindent is off).
524 # an editor (as long as autoindent is off).
524
525
525 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
526 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
526 # don't interfere with their own tab-completion mechanism.
527 # don't interfere with their own tab-completion mechanism.
527 if not (self.dumb_terminal or self.get_line_buffer().strip()):
528 if not (self.dumb_terminal or self.get_line_buffer().strip()):
528 self.readline.insert_text('\t')
529 self.readline.insert_text('\t')
529 return None
530 return None
530
531
531 magic_escape = self.magic_escape
532 magic_escape = self.magic_escape
532 magic_prefix = self.magic_prefix
533 magic_prefix = self.magic_prefix
533
534
534 try:
535 try:
535 if text.startswith(magic_escape):
536 if text.startswith(magic_escape):
536 text = text.replace(magic_escape,magic_prefix)
537 text = text.replace(magic_escape,magic_prefix)
537 elif text.startswith('~'):
538 elif text.startswith('~'):
538 text = os.path.expanduser(text)
539 text = os.path.expanduser(text)
539 if state == 0:
540 if state == 0:
540 # Extend the list of completions with the results of each
541 # Extend the list of completions with the results of each
541 # matcher, so we return results to the user from all
542 # matcher, so we return results to the user from all
542 # namespaces.
543 # namespaces.
543 if self.merge_completions:
544 if self.merge_completions:
544 self.matches = []
545 self.matches = []
545 for matcher in self.matchers:
546 for matcher in self.matchers:
546 self.matches.extend(matcher(text))
547 self.matches.extend(matcher(text))
547 else:
548 else:
548 for matcher in self.matchers:
549 for matcher in self.matchers:
549 self.matches = matcher(text)
550 self.matches = matcher(text)
550 if self.matches:
551 if self.matches:
551 break
552 break
552
553
553 try:
554 try:
554 return self.matches[state].replace(magic_prefix,magic_escape)
555 return self.matches[state].replace(magic_prefix,magic_escape)
555 except IndexError:
556 except IndexError:
556 return None
557 return None
557 except:
558 except:
558 #from IPython.ultraTB import AutoFormattedTB; # dbg
559 #from IPython.ultraTB import AutoFormattedTB; # dbg
559 #tb=AutoFormattedTB('Verbose');tb() #dbg
560 #tb=AutoFormattedTB('Verbose');tb() #dbg
560
561
561 # If completion fails, don't annoy the user.
562 # If completion fails, don't annoy the user.
562 return None
563 return None
@@ -1,1773 +1,1761 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 1077 2006-01-24 18:15:27Z vivainio $"""
8 $Id: genutils.py 1099 2006-01-29 21:05:57Z vivainio $"""
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 from __future__ import generators # 2.2 compatibility
17 from __future__ import generators # 2.2 compatibility
18
18
19 from IPython import Release
19 from IPython import Release
20 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 __license__ = Release.license
21 __license__ = Release.license
22
22
23 #****************************************************************************
23 #****************************************************************************
24 # required modules from the Python standard library
24 # required modules from the Python standard library
25 import __main__
25 import __main__
26 import commands
26 import commands
27 import os
27 import os
28 import re
28 import re
29 import shlex
29 import shlex
30 import shutil
30 import shutil
31 import sys
31 import sys
32 import tempfile
32 import tempfile
33 import time
33 import time
34 import types
34 import types
35
35
36 # Other IPython utilities
36 # Other IPython utilities
37 from IPython.Itpl import Itpl,itpl,printpl
37 from IPython.Itpl import Itpl,itpl,printpl
38 from IPython import DPyGetOpt
38 from IPython import DPyGetOpt
39 from IPython.path import path
39 from IPython.path import path
40 if os.name == "nt":
40 if os.name == "nt":
41 from IPython.winconsole import get_console_size
41 from IPython.winconsole import get_console_size
42
42
43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
44 # 2.2-friendly
44 # 2.2-friendly
45 try:
45 try:
46 basestring
46 basestring
47 except NameError:
47 except NameError:
48 import types
48 import types
49 basestring = (types.StringType, types.UnicodeType)
49 basestring = (types.StringType, types.UnicodeType)
50 True = 1==1
50 True = 1==1
51 False = 1==0
51 False = 1==0
52
52
53 def enumerate(obj):
53 def enumerate(obj):
54 i = -1
54 i = -1
55 for item in obj:
55 for item in obj:
56 i += 1
56 i += 1
57 yield i, item
57 yield i, item
58
58
59 # add these to the builtin namespace, so that all modules find them
59 # add these to the builtin namespace, so that all modules find them
60 import __builtin__
60 import __builtin__
61 __builtin__.basestring = basestring
61 __builtin__.basestring = basestring
62 __builtin__.True = True
62 __builtin__.True = True
63 __builtin__.False = False
63 __builtin__.False = False
64 __builtin__.enumerate = enumerate
64 __builtin__.enumerate = enumerate
65
65
66 # Try to use shlex.split for converting an input string into a sys.argv-type
66 # Try to use shlex.split for converting an input string into a sys.argv-type
67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
68 try:
68 try:
69 shlex_split = shlex.split
69 shlex_split = shlex.split
70 except AttributeError:
70 except AttributeError:
71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
75 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
75 'À�ÂÃÄÅÆÇÈÉÊËÌ�Î��ÑÒÓÔÕÖØÙÚÛÜ�Þ%s'
76 % os.sep)
76 % os.sep)
77
77
78 def shlex_split(s):
78 def shlex_split(s):
79 """Simplified backport to Python 2.2 of shlex.split().
79 """Simplified backport to Python 2.2 of shlex.split().
80
80
81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
82 several of the features needed to really match the functionality of
82 several of the features needed to really match the functionality of
83 shlex.split() in 2.3."""
83 shlex.split() in 2.3."""
84
84
85 lex = shlex.shlex(StringIO(s))
85 lex = shlex.shlex(StringIO(s))
86 # Try to get options, extensions and path separators as characters
86 # Try to get options, extensions and path separators as characters
87 lex.wordchars = _wordchars
87 lex.wordchars = _wordchars
88 lex.commenters = ''
88 lex.commenters = ''
89 # Make a list out of the lexer by hand, since in 2.2 it's not an
89 # Make a list out of the lexer by hand, since in 2.2 it's not an
90 # iterator.
90 # iterator.
91 lout = []
91 lout = []
92 while 1:
92 while 1:
93 token = lex.get_token()
93 token = lex.get_token()
94 if token == '':
94 if token == '':
95 break
95 break
96 # Try to handle quoted tokens correctly
96 # Try to handle quoted tokens correctly
97 quotes = _quotesre.match(token)
97 quotes = _quotesre.match(token)
98 if quotes:
98 if quotes:
99 token = quotes.group(1)
99 token = quotes.group(1)
100 lout.append(token)
100 lout.append(token)
101 return lout
101 return lout
102
102
103 #****************************************************************************
103 #****************************************************************************
104 # Exceptions
104 # Exceptions
105 class Error(Exception):
105 class Error(Exception):
106 """Base class for exceptions in this module."""
106 """Base class for exceptions in this module."""
107 pass
107 pass
108
108
109 #----------------------------------------------------------------------------
109 #----------------------------------------------------------------------------
110 class IOStream:
110 class IOStream:
111 def __init__(self,stream,fallback):
111 def __init__(self,stream,fallback):
112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
113 stream = fallback
113 stream = fallback
114 self.stream = stream
114 self.stream = stream
115 self._swrite = stream.write
115 self._swrite = stream.write
116 self.flush = stream.flush
116 self.flush = stream.flush
117
117
118 def write(self,data):
118 def write(self,data):
119 try:
119 try:
120 self._swrite(data)
120 self._swrite(data)
121 except:
121 except:
122 try:
122 try:
123 # print handles some unicode issues which may trip a plain
123 # print handles some unicode issues which may trip a plain
124 # write() call. Attempt to emulate write() by using a
124 # write() call. Attempt to emulate write() by using a
125 # trailing comma
125 # trailing comma
126 print >> self.stream, data,
126 print >> self.stream, data,
127 except:
127 except:
128 # if we get here, something is seriously broken.
128 # if we get here, something is seriously broken.
129 print >> sys.stderr, \
129 print >> sys.stderr, \
130 'ERROR - failed to write data to stream:', stream
130 'ERROR - failed to write data to stream:', stream
131
131
132 class IOTerm:
132 class IOTerm:
133 """ Term holds the file or file-like objects for handling I/O operations.
133 """ Term holds the file or file-like objects for handling I/O operations.
134
134
135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
136 Windows they can can replaced to allow editing the strings before they are
136 Windows they can can replaced to allow editing the strings before they are
137 displayed."""
137 displayed."""
138
138
139 # In the future, having IPython channel all its I/O operations through
139 # In the future, having IPython channel all its I/O operations through
140 # this class will make it easier to embed it into other environments which
140 # this class will make it easier to embed it into other environments which
141 # are not a normal terminal (such as a GUI-based shell)
141 # are not a normal terminal (such as a GUI-based shell)
142 def __init__(self,cin=None,cout=None,cerr=None):
142 def __init__(self,cin=None,cout=None,cerr=None):
143 self.cin = IOStream(cin,sys.stdin)
143 self.cin = IOStream(cin,sys.stdin)
144 self.cout = IOStream(cout,sys.stdout)
144 self.cout = IOStream(cout,sys.stdout)
145 self.cerr = IOStream(cerr,sys.stderr)
145 self.cerr = IOStream(cerr,sys.stderr)
146
146
147 # Global variable to be used for all I/O
147 # Global variable to be used for all I/O
148 Term = IOTerm()
148 Term = IOTerm()
149
149
150 # Windows-specific code to load Gary Bishop's readline and configure it
150 import IPython.rlineimpl as readline
151 # automatically for the users
151 # Remake Term to use the readline i/o facilities
152 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
152 if readline.have_readline:
153 # windows. Cygwin returns 'cygwin' for sys.platform.
153
154 if os.name == 'nt':
154 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
155 try:
155
156 import readline
157 except ImportError:
158 pass
159 else:
160 try:
161 _out = readline.GetOutputFile()
162 except AttributeError:
163 pass
164 else:
165 # Remake Term to use the readline i/o facilities
166 Term = IOTerm(cout=_out,cerr=_out)
167 del _out
168
156
169 #****************************************************************************
157 #****************************************************************************
170 # Generic warning/error printer, used by everything else
158 # Generic warning/error printer, used by everything else
171 def warn(msg,level=2,exit_val=1):
159 def warn(msg,level=2,exit_val=1):
172 """Standard warning printer. Gives formatting consistency.
160 """Standard warning printer. Gives formatting consistency.
173
161
174 Output is sent to Term.cerr (sys.stderr by default).
162 Output is sent to Term.cerr (sys.stderr by default).
175
163
176 Options:
164 Options:
177
165
178 -level(2): allows finer control:
166 -level(2): allows finer control:
179 0 -> Do nothing, dummy function.
167 0 -> Do nothing, dummy function.
180 1 -> Print message.
168 1 -> Print message.
181 2 -> Print 'WARNING:' + message. (Default level).
169 2 -> Print 'WARNING:' + message. (Default level).
182 3 -> Print 'ERROR:' + message.
170 3 -> Print 'ERROR:' + message.
183 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
171 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
184
172
185 -exit_val (1): exit value returned by sys.exit() for a level 4
173 -exit_val (1): exit value returned by sys.exit() for a level 4
186 warning. Ignored for all other levels."""
174 warning. Ignored for all other levels."""
187
175
188 if level>0:
176 if level>0:
189 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
177 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
190 print >> Term.cerr, '%s%s' % (header[level],msg)
178 print >> Term.cerr, '%s%s' % (header[level],msg)
191 if level == 4:
179 if level == 4:
192 print >> Term.cerr,'Exiting.\n'
180 print >> Term.cerr,'Exiting.\n'
193 sys.exit(exit_val)
181 sys.exit(exit_val)
194
182
195 def info(msg):
183 def info(msg):
196 """Equivalent to warn(msg,level=1)."""
184 """Equivalent to warn(msg,level=1)."""
197
185
198 warn(msg,level=1)
186 warn(msg,level=1)
199
187
200 def error(msg):
188 def error(msg):
201 """Equivalent to warn(msg,level=3)."""
189 """Equivalent to warn(msg,level=3)."""
202
190
203 warn(msg,level=3)
191 warn(msg,level=3)
204
192
205 def fatal(msg,exit_val=1):
193 def fatal(msg,exit_val=1):
206 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
194 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
207
195
208 warn(msg,exit_val=exit_val,level=4)
196 warn(msg,exit_val=exit_val,level=4)
209
197
210 #---------------------------------------------------------------------------
198 #---------------------------------------------------------------------------
211 # Debugging routines
199 # Debugging routines
212 #
200 #
213 def debugx(expr,pre_msg=''):
201 def debugx(expr,pre_msg=''):
214 """Print the value of an expression from the caller's frame.
202 """Print the value of an expression from the caller's frame.
215
203
216 Takes an expression, evaluates it in the caller's frame and prints both
204 Takes an expression, evaluates it in the caller's frame and prints both
217 the given expression and the resulting value (as well as a debug mark
205 the given expression and the resulting value (as well as a debug mark
218 indicating the name of the calling function. The input must be of a form
206 indicating the name of the calling function. The input must be of a form
219 suitable for eval().
207 suitable for eval().
220
208
221 An optional message can be passed, which will be prepended to the printed
209 An optional message can be passed, which will be prepended to the printed
222 expr->value pair."""
210 expr->value pair."""
223
211
224 cf = sys._getframe(1)
212 cf = sys._getframe(1)
225 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
213 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
226 eval(expr,cf.f_globals,cf.f_locals))
214 eval(expr,cf.f_globals,cf.f_locals))
227
215
228 # deactivate it by uncommenting the following line, which makes it a no-op
216 # deactivate it by uncommenting the following line, which makes it a no-op
229 #def debugx(expr,pre_msg=''): pass
217 #def debugx(expr,pre_msg=''): pass
230
218
231 #----------------------------------------------------------------------------
219 #----------------------------------------------------------------------------
232 StringTypes = types.StringTypes
220 StringTypes = types.StringTypes
233
221
234 # Basic timing functionality
222 # Basic timing functionality
235
223
236 # If possible (Unix), use the resource module instead of time.clock()
224 # If possible (Unix), use the resource module instead of time.clock()
237 try:
225 try:
238 import resource
226 import resource
239 def clock():
227 def clock():
240 """clock() -> floating point number
228 """clock() -> floating point number
241
229
242 Return the CPU time in seconds (user time only, system time is
230 Return the CPU time in seconds (user time only, system time is
243 ignored) since the start of the process. This is done via a call to
231 ignored) since the start of the process. This is done via a call to
244 resource.getrusage, so it avoids the wraparound problems in
232 resource.getrusage, so it avoids the wraparound problems in
245 time.clock()."""
233 time.clock()."""
246
234
247 return resource.getrusage(resource.RUSAGE_SELF)[0]
235 return resource.getrusage(resource.RUSAGE_SELF)[0]
248
236
249 def clock2():
237 def clock2():
250 """clock2() -> (t_user,t_system)
238 """clock2() -> (t_user,t_system)
251
239
252 Similar to clock(), but return a tuple of user/system times."""
240 Similar to clock(), but return a tuple of user/system times."""
253 return resource.getrusage(resource.RUSAGE_SELF)[:2]
241 return resource.getrusage(resource.RUSAGE_SELF)[:2]
254
242
255 except ImportError:
243 except ImportError:
256 clock = time.clock
244 clock = time.clock
257 def clock2():
245 def clock2():
258 """Under windows, system CPU time can't be measured.
246 """Under windows, system CPU time can't be measured.
259
247
260 This just returns clock() and zero."""
248 This just returns clock() and zero."""
261 return time.clock(),0.0
249 return time.clock(),0.0
262
250
263 def timings_out(reps,func,*args,**kw):
251 def timings_out(reps,func,*args,**kw):
264 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
252 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
265
253
266 Execute a function reps times, return a tuple with the elapsed total
254 Execute a function reps times, return a tuple with the elapsed total
267 CPU time in seconds, the time per call and the function's output.
255 CPU time in seconds, the time per call and the function's output.
268
256
269 Under Unix, the return value is the sum of user+system time consumed by
257 Under Unix, the return value is the sum of user+system time consumed by
270 the process, computed via the resource module. This prevents problems
258 the process, computed via the resource module. This prevents problems
271 related to the wraparound effect which the time.clock() function has.
259 related to the wraparound effect which the time.clock() function has.
272
260
273 Under Windows the return value is in wall clock seconds. See the
261 Under Windows the return value is in wall clock seconds. See the
274 documentation for the time module for more details."""
262 documentation for the time module for more details."""
275
263
276 reps = int(reps)
264 reps = int(reps)
277 assert reps >=1, 'reps must be >= 1'
265 assert reps >=1, 'reps must be >= 1'
278 if reps==1:
266 if reps==1:
279 start = clock()
267 start = clock()
280 out = func(*args,**kw)
268 out = func(*args,**kw)
281 tot_time = clock()-start
269 tot_time = clock()-start
282 else:
270 else:
283 rng = xrange(reps-1) # the last time is executed separately to store output
271 rng = xrange(reps-1) # the last time is executed separately to store output
284 start = clock()
272 start = clock()
285 for dummy in rng: func(*args,**kw)
273 for dummy in rng: func(*args,**kw)
286 out = func(*args,**kw) # one last time
274 out = func(*args,**kw) # one last time
287 tot_time = clock()-start
275 tot_time = clock()-start
288 av_time = tot_time / reps
276 av_time = tot_time / reps
289 return tot_time,av_time,out
277 return tot_time,av_time,out
290
278
291 def timings(reps,func,*args,**kw):
279 def timings(reps,func,*args,**kw):
292 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
280 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
293
281
294 Execute a function reps times, return a tuple with the elapsed total CPU
282 Execute a function reps times, return a tuple with the elapsed total CPU
295 time in seconds and the time per call. These are just the first two values
283 time in seconds and the time per call. These are just the first two values
296 in timings_out()."""
284 in timings_out()."""
297
285
298 return timings_out(reps,func,*args,**kw)[0:2]
286 return timings_out(reps,func,*args,**kw)[0:2]
299
287
300 def timing(func,*args,**kw):
288 def timing(func,*args,**kw):
301 """timing(func,*args,**kw) -> t_total
289 """timing(func,*args,**kw) -> t_total
302
290
303 Execute a function once, return the elapsed total CPU time in
291 Execute a function once, return the elapsed total CPU time in
304 seconds. This is just the first value in timings_out()."""
292 seconds. This is just the first value in timings_out()."""
305
293
306 return timings_out(1,func,*args,**kw)[0]
294 return timings_out(1,func,*args,**kw)[0]
307
295
308 #****************************************************************************
296 #****************************************************************************
309 # file and system
297 # file and system
310
298
311 def system(cmd,verbose=0,debug=0,header=''):
299 def system(cmd,verbose=0,debug=0,header=''):
312 """Execute a system command, return its exit status.
300 """Execute a system command, return its exit status.
313
301
314 Options:
302 Options:
315
303
316 - verbose (0): print the command to be executed.
304 - verbose (0): print the command to be executed.
317
305
318 - debug (0): only print, do not actually execute.
306 - debug (0): only print, do not actually execute.
319
307
320 - header (''): Header to print on screen prior to the executed command (it
308 - header (''): Header to print on screen prior to the executed command (it
321 is only prepended to the command, no newlines are added).
309 is only prepended to the command, no newlines are added).
322
310
323 Note: a stateful version of this function is available through the
311 Note: a stateful version of this function is available through the
324 SystemExec class."""
312 SystemExec class."""
325
313
326 stat = 0
314 stat = 0
327 if verbose or debug: print header+cmd
315 if verbose or debug: print header+cmd
328 sys.stdout.flush()
316 sys.stdout.flush()
329 if not debug: stat = os.system(cmd)
317 if not debug: stat = os.system(cmd)
330 return stat
318 return stat
331
319
332 # This function is used by ipython in a lot of places to make system calls.
320 # This function is used by ipython in a lot of places to make system calls.
333 # We need it to be slightly different under win32, due to the vagaries of
321 # We need it to be slightly different under win32, due to the vagaries of
334 # 'network shares'. A win32 override is below.
322 # 'network shares'. A win32 override is below.
335
323
336 def shell(cmd,verbose=0,debug=0,header=''):
324 def shell(cmd,verbose=0,debug=0,header=''):
337 """Execute a command in the system shell, always return None.
325 """Execute a command in the system shell, always return None.
338
326
339 Options:
327 Options:
340
328
341 - verbose (0): print the command to be executed.
329 - verbose (0): print the command to be executed.
342
330
343 - debug (0): only print, do not actually execute.
331 - debug (0): only print, do not actually execute.
344
332
345 - header (''): Header to print on screen prior to the executed command (it
333 - header (''): Header to print on screen prior to the executed command (it
346 is only prepended to the command, no newlines are added).
334 is only prepended to the command, no newlines are added).
347
335
348 Note: this is similar to genutils.system(), but it returns None so it can
336 Note: this is similar to genutils.system(), but it returns None so it can
349 be conveniently used in interactive loops without getting the return value
337 be conveniently used in interactive loops without getting the return value
350 (typically 0) printed many times."""
338 (typically 0) printed many times."""
351
339
352 stat = 0
340 stat = 0
353 if verbose or debug: print header+cmd
341 if verbose or debug: print header+cmd
354 # flush stdout so we don't mangle python's buffering
342 # flush stdout so we don't mangle python's buffering
355 sys.stdout.flush()
343 sys.stdout.flush()
356 if not debug:
344 if not debug:
357 os.system(cmd)
345 os.system(cmd)
358
346
359 # override shell() for win32 to deal with network shares
347 # override shell() for win32 to deal with network shares
360 if os.name in ('nt','dos'):
348 if os.name in ('nt','dos'):
361
349
362 shell_ori = shell
350 shell_ori = shell
363
351
364 def shell(cmd,verbose=0,debug=0,header=''):
352 def shell(cmd,verbose=0,debug=0,header=''):
365 if os.getcwd().startswith(r"\\"):
353 if os.getcwd().startswith(r"\\"):
366 path = os.getcwd()
354 path = os.getcwd()
367 # change to c drive (cannot be on UNC-share when issuing os.system,
355 # change to c drive (cannot be on UNC-share when issuing os.system,
368 # as cmd.exe cannot handle UNC addresses)
356 # as cmd.exe cannot handle UNC addresses)
369 os.chdir("c:")
357 os.chdir("c:")
370 # issue pushd to the UNC-share and then run the command
358 # issue pushd to the UNC-share and then run the command
371 try:
359 try:
372 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
360 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
373 finally:
361 finally:
374 os.chdir(path)
362 os.chdir(path)
375 else:
363 else:
376 shell_ori(cmd,verbose,debug,header)
364 shell_ori(cmd,verbose,debug,header)
377
365
378 shell.__doc__ = shell_ori.__doc__
366 shell.__doc__ = shell_ori.__doc__
379
367
380 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
368 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
381 """Dummy substitute for perl's backquotes.
369 """Dummy substitute for perl's backquotes.
382
370
383 Executes a command and returns the output.
371 Executes a command and returns the output.
384
372
385 Accepts the same arguments as system(), plus:
373 Accepts the same arguments as system(), plus:
386
374
387 - split(0): if true, the output is returned as a list split on newlines.
375 - split(0): if true, the output is returned as a list split on newlines.
388
376
389 Note: a stateful version of this function is available through the
377 Note: a stateful version of this function is available through the
390 SystemExec class."""
378 SystemExec class."""
391
379
392 if verbose or debug: print header+cmd
380 if verbose or debug: print header+cmd
393 if not debug:
381 if not debug:
394 output = commands.getoutput(cmd)
382 output = commands.getoutput(cmd)
395 if split:
383 if split:
396 return output.split('\n')
384 return output.split('\n')
397 else:
385 else:
398 return output
386 return output
399
387
400 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
388 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
401 """Return (standard output,standard error) of executing cmd in a shell.
389 """Return (standard output,standard error) of executing cmd in a shell.
402
390
403 Accepts the same arguments as system(), plus:
391 Accepts the same arguments as system(), plus:
404
392
405 - split(0): if true, each of stdout/err is returned as a list split on
393 - split(0): if true, each of stdout/err is returned as a list split on
406 newlines.
394 newlines.
407
395
408 Note: a stateful version of this function is available through the
396 Note: a stateful version of this function is available through the
409 SystemExec class."""
397 SystemExec class."""
410
398
411 if verbose or debug: print header+cmd
399 if verbose or debug: print header+cmd
412 if not cmd:
400 if not cmd:
413 if split:
401 if split:
414 return [],[]
402 return [],[]
415 else:
403 else:
416 return '',''
404 return '',''
417 if not debug:
405 if not debug:
418 pin,pout,perr = os.popen3(cmd)
406 pin,pout,perr = os.popen3(cmd)
419 tout = pout.read().rstrip()
407 tout = pout.read().rstrip()
420 terr = perr.read().rstrip()
408 terr = perr.read().rstrip()
421 pin.close()
409 pin.close()
422 pout.close()
410 pout.close()
423 perr.close()
411 perr.close()
424 if split:
412 if split:
425 return tout.split('\n'),terr.split('\n')
413 return tout.split('\n'),terr.split('\n')
426 else:
414 else:
427 return tout,terr
415 return tout,terr
428
416
429 # for compatibility with older naming conventions
417 # for compatibility with older naming conventions
430 xsys = system
418 xsys = system
431 bq = getoutput
419 bq = getoutput
432
420
433 class SystemExec:
421 class SystemExec:
434 """Access the system and getoutput functions through a stateful interface.
422 """Access the system and getoutput functions through a stateful interface.
435
423
436 Note: here we refer to the system and getoutput functions from this
424 Note: here we refer to the system and getoutput functions from this
437 library, not the ones from the standard python library.
425 library, not the ones from the standard python library.
438
426
439 This class offers the system and getoutput functions as methods, but the
427 This class offers the system and getoutput functions as methods, but the
440 verbose, debug and header parameters can be set for the instance (at
428 verbose, debug and header parameters can be set for the instance (at
441 creation time or later) so that they don't need to be specified on each
429 creation time or later) so that they don't need to be specified on each
442 call.
430 call.
443
431
444 For efficiency reasons, there's no way to override the parameters on a
432 For efficiency reasons, there's no way to override the parameters on a
445 per-call basis other than by setting instance attributes. If you need
433 per-call basis other than by setting instance attributes. If you need
446 local overrides, it's best to directly call system() or getoutput().
434 local overrides, it's best to directly call system() or getoutput().
447
435
448 The following names are provided as alternate options:
436 The following names are provided as alternate options:
449 - xsys: alias to system
437 - xsys: alias to system
450 - bq: alias to getoutput
438 - bq: alias to getoutput
451
439
452 An instance can then be created as:
440 An instance can then be created as:
453 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
441 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
454
442
455 And used as:
443 And used as:
456 >>> sysexec.xsys('pwd')
444 >>> sysexec.xsys('pwd')
457 >>> dirlist = sysexec.bq('ls -l')
445 >>> dirlist = sysexec.bq('ls -l')
458 """
446 """
459
447
460 def __init__(self,verbose=0,debug=0,header='',split=0):
448 def __init__(self,verbose=0,debug=0,header='',split=0):
461 """Specify the instance's values for verbose, debug and header."""
449 """Specify the instance's values for verbose, debug and header."""
462 setattr_list(self,'verbose debug header split')
450 setattr_list(self,'verbose debug header split')
463
451
464 def system(self,cmd):
452 def system(self,cmd):
465 """Stateful interface to system(), with the same keyword parameters."""
453 """Stateful interface to system(), with the same keyword parameters."""
466
454
467 system(cmd,self.verbose,self.debug,self.header)
455 system(cmd,self.verbose,self.debug,self.header)
468
456
469 def shell(self,cmd):
457 def shell(self,cmd):
470 """Stateful interface to shell(), with the same keyword parameters."""
458 """Stateful interface to shell(), with the same keyword parameters."""
471
459
472 shell(cmd,self.verbose,self.debug,self.header)
460 shell(cmd,self.verbose,self.debug,self.header)
473
461
474 xsys = system # alias
462 xsys = system # alias
475
463
476 def getoutput(self,cmd):
464 def getoutput(self,cmd):
477 """Stateful interface to getoutput()."""
465 """Stateful interface to getoutput()."""
478
466
479 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
467 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
480
468
481 def getoutputerror(self,cmd):
469 def getoutputerror(self,cmd):
482 """Stateful interface to getoutputerror()."""
470 """Stateful interface to getoutputerror()."""
483
471
484 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
472 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
485
473
486 bq = getoutput # alias
474 bq = getoutput # alias
487
475
488 #-----------------------------------------------------------------------------
476 #-----------------------------------------------------------------------------
489 def mutex_opts(dict,ex_op):
477 def mutex_opts(dict,ex_op):
490 """Check for presence of mutually exclusive keys in a dict.
478 """Check for presence of mutually exclusive keys in a dict.
491
479
492 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
480 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
493 for op1,op2 in ex_op:
481 for op1,op2 in ex_op:
494 if op1 in dict and op2 in dict:
482 if op1 in dict and op2 in dict:
495 raise ValueError,'\n*** ERROR in Arguments *** '\
483 raise ValueError,'\n*** ERROR in Arguments *** '\
496 'Options '+op1+' and '+op2+' are mutually exclusive.'
484 'Options '+op1+' and '+op2+' are mutually exclusive.'
497
485
498 #-----------------------------------------------------------------------------
486 #-----------------------------------------------------------------------------
499 def get_py_filename(name):
487 def get_py_filename(name):
500 """Return a valid python filename in the current directory.
488 """Return a valid python filename in the current directory.
501
489
502 If the given name is not a file, it adds '.py' and searches again.
490 If the given name is not a file, it adds '.py' and searches again.
503 Raises IOError with an informative message if the file isn't found."""
491 Raises IOError with an informative message if the file isn't found."""
504
492
505 name = os.path.expanduser(name)
493 name = os.path.expanduser(name)
506 if not os.path.isfile(name) and not name.endswith('.py'):
494 if not os.path.isfile(name) and not name.endswith('.py'):
507 name += '.py'
495 name += '.py'
508 if os.path.isfile(name):
496 if os.path.isfile(name):
509 return name
497 return name
510 else:
498 else:
511 raise IOError,'File `%s` not found.' % name
499 raise IOError,'File `%s` not found.' % name
512
500
513 #-----------------------------------------------------------------------------
501 #-----------------------------------------------------------------------------
514 def filefind(fname,alt_dirs = None):
502 def filefind(fname,alt_dirs = None):
515 """Return the given filename either in the current directory, if it
503 """Return the given filename either in the current directory, if it
516 exists, or in a specified list of directories.
504 exists, or in a specified list of directories.
517
505
518 ~ expansion is done on all file and directory names.
506 ~ expansion is done on all file and directory names.
519
507
520 Upon an unsuccessful search, raise an IOError exception."""
508 Upon an unsuccessful search, raise an IOError exception."""
521
509
522 if alt_dirs is None:
510 if alt_dirs is None:
523 try:
511 try:
524 alt_dirs = get_home_dir()
512 alt_dirs = get_home_dir()
525 except HomeDirError:
513 except HomeDirError:
526 alt_dirs = os.getcwd()
514 alt_dirs = os.getcwd()
527 search = [fname] + list_strings(alt_dirs)
515 search = [fname] + list_strings(alt_dirs)
528 search = map(os.path.expanduser,search)
516 search = map(os.path.expanduser,search)
529 #print 'search list for',fname,'list:',search # dbg
517 #print 'search list for',fname,'list:',search # dbg
530 fname = search[0]
518 fname = search[0]
531 if os.path.isfile(fname):
519 if os.path.isfile(fname):
532 return fname
520 return fname
533 for direc in search[1:]:
521 for direc in search[1:]:
534 testname = os.path.join(direc,fname)
522 testname = os.path.join(direc,fname)
535 #print 'testname',testname # dbg
523 #print 'testname',testname # dbg
536 if os.path.isfile(testname):
524 if os.path.isfile(testname):
537 return testname
525 return testname
538 raise IOError,'File' + `fname` + \
526 raise IOError,'File' + `fname` + \
539 ' not found in current or supplied directories:' + `alt_dirs`
527 ' not found in current or supplied directories:' + `alt_dirs`
540
528
541 #----------------------------------------------------------------------------
529 #----------------------------------------------------------------------------
542 def file_read(filename):
530 def file_read(filename):
543 """Read a file and close it. Returns the file source."""
531 """Read a file and close it. Returns the file source."""
544 fobj=open(filename,'r');
532 fobj=open(filename,'r');
545 source = fobj.read();
533 source = fobj.read();
546 fobj.close()
534 fobj.close()
547 return source
535 return source
548
536
549 #----------------------------------------------------------------------------
537 #----------------------------------------------------------------------------
550 def target_outdated(target,deps):
538 def target_outdated(target,deps):
551 """Determine whether a target is out of date.
539 """Determine whether a target is out of date.
552
540
553 target_outdated(target,deps) -> 1/0
541 target_outdated(target,deps) -> 1/0
554
542
555 deps: list of filenames which MUST exist.
543 deps: list of filenames which MUST exist.
556 target: single filename which may or may not exist.
544 target: single filename which may or may not exist.
557
545
558 If target doesn't exist or is older than any file listed in deps, return
546 If target doesn't exist or is older than any file listed in deps, return
559 true, otherwise return false.
547 true, otherwise return false.
560 """
548 """
561 try:
549 try:
562 target_time = os.path.getmtime(target)
550 target_time = os.path.getmtime(target)
563 except os.error:
551 except os.error:
564 return 1
552 return 1
565 for dep in deps:
553 for dep in deps:
566 dep_time = os.path.getmtime(dep)
554 dep_time = os.path.getmtime(dep)
567 if dep_time > target_time:
555 if dep_time > target_time:
568 #print "For target",target,"Dep failed:",dep # dbg
556 #print "For target",target,"Dep failed:",dep # dbg
569 #print "times (dep,tar):",dep_time,target_time # dbg
557 #print "times (dep,tar):",dep_time,target_time # dbg
570 return 1
558 return 1
571 return 0
559 return 0
572
560
573 #-----------------------------------------------------------------------------
561 #-----------------------------------------------------------------------------
574 def target_update(target,deps,cmd):
562 def target_update(target,deps,cmd):
575 """Update a target with a given command given a list of dependencies.
563 """Update a target with a given command given a list of dependencies.
576
564
577 target_update(target,deps,cmd) -> runs cmd if target is outdated.
565 target_update(target,deps,cmd) -> runs cmd if target is outdated.
578
566
579 This is just a wrapper around target_outdated() which calls the given
567 This is just a wrapper around target_outdated() which calls the given
580 command if target is outdated."""
568 command if target is outdated."""
581
569
582 if target_outdated(target,deps):
570 if target_outdated(target,deps):
583 xsys(cmd)
571 xsys(cmd)
584
572
585 #----------------------------------------------------------------------------
573 #----------------------------------------------------------------------------
586 def unquote_ends(istr):
574 def unquote_ends(istr):
587 """Remove a single pair of quotes from the endpoints of a string."""
575 """Remove a single pair of quotes from the endpoints of a string."""
588
576
589 if not istr:
577 if not istr:
590 return istr
578 return istr
591 if (istr[0]=="'" and istr[-1]=="'") or \
579 if (istr[0]=="'" and istr[-1]=="'") or \
592 (istr[0]=='"' and istr[-1]=='"'):
580 (istr[0]=='"' and istr[-1]=='"'):
593 return istr[1:-1]
581 return istr[1:-1]
594 else:
582 else:
595 return istr
583 return istr
596
584
597 #----------------------------------------------------------------------------
585 #----------------------------------------------------------------------------
598 def process_cmdline(argv,names=[],defaults={},usage=''):
586 def process_cmdline(argv,names=[],defaults={},usage=''):
599 """ Process command-line options and arguments.
587 """ Process command-line options and arguments.
600
588
601 Arguments:
589 Arguments:
602
590
603 - argv: list of arguments, typically sys.argv.
591 - argv: list of arguments, typically sys.argv.
604
592
605 - names: list of option names. See DPyGetOpt docs for details on options
593 - names: list of option names. See DPyGetOpt docs for details on options
606 syntax.
594 syntax.
607
595
608 - defaults: dict of default values.
596 - defaults: dict of default values.
609
597
610 - usage: optional usage notice to print if a wrong argument is passed.
598 - usage: optional usage notice to print if a wrong argument is passed.
611
599
612 Return a dict of options and a list of free arguments."""
600 Return a dict of options and a list of free arguments."""
613
601
614 getopt = DPyGetOpt.DPyGetOpt()
602 getopt = DPyGetOpt.DPyGetOpt()
615 getopt.setIgnoreCase(0)
603 getopt.setIgnoreCase(0)
616 getopt.parseConfiguration(names)
604 getopt.parseConfiguration(names)
617
605
618 try:
606 try:
619 getopt.processArguments(argv)
607 getopt.processArguments(argv)
620 except:
608 except:
621 print usage
609 print usage
622 warn(`sys.exc_value`,level=4)
610 warn(`sys.exc_value`,level=4)
623
611
624 defaults.update(getopt.optionValues)
612 defaults.update(getopt.optionValues)
625 args = getopt.freeValues
613 args = getopt.freeValues
626
614
627 return defaults,args
615 return defaults,args
628
616
629 #----------------------------------------------------------------------------
617 #----------------------------------------------------------------------------
630 def optstr2types(ostr):
618 def optstr2types(ostr):
631 """Convert a string of option names to a dict of type mappings.
619 """Convert a string of option names to a dict of type mappings.
632
620
633 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
621 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
634
622
635 This is used to get the types of all the options in a string formatted
623 This is used to get the types of all the options in a string formatted
636 with the conventions of DPyGetOpt. The 'type' None is used for options
624 with the conventions of DPyGetOpt. The 'type' None is used for options
637 which are strings (they need no further conversion). This function's main
625 which are strings (they need no further conversion). This function's main
638 use is to get a typemap for use with read_dict().
626 use is to get a typemap for use with read_dict().
639 """
627 """
640
628
641 typeconv = {None:'',int:'',float:''}
629 typeconv = {None:'',int:'',float:''}
642 typemap = {'s':None,'i':int,'f':float}
630 typemap = {'s':None,'i':int,'f':float}
643 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
631 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
644
632
645 for w in ostr.split():
633 for w in ostr.split():
646 oname,alias,otype = opt_re.match(w).groups()
634 oname,alias,otype = opt_re.match(w).groups()
647 if otype == '' or alias == '!': # simple switches are integers too
635 if otype == '' or alias == '!': # simple switches are integers too
648 otype = 'i'
636 otype = 'i'
649 typeconv[typemap[otype]] += oname + ' '
637 typeconv[typemap[otype]] += oname + ' '
650 return typeconv
638 return typeconv
651
639
652 #----------------------------------------------------------------------------
640 #----------------------------------------------------------------------------
653 def read_dict(filename,type_conv=None,**opt):
641 def read_dict(filename,type_conv=None,**opt):
654
642
655 """Read a dictionary of key=value pairs from an input file, optionally
643 """Read a dictionary of key=value pairs from an input file, optionally
656 performing conversions on the resulting values.
644 performing conversions on the resulting values.
657
645
658 read_dict(filename,type_conv,**opt) -> dict
646 read_dict(filename,type_conv,**opt) -> dict
659
647
660 Only one value per line is accepted, the format should be
648 Only one value per line is accepted, the format should be
661 # optional comments are ignored
649 # optional comments are ignored
662 key value\n
650 key value\n
663
651
664 Args:
652 Args:
665
653
666 - type_conv: A dictionary specifying which keys need to be converted to
654 - type_conv: A dictionary specifying which keys need to be converted to
667 which types. By default all keys are read as strings. This dictionary
655 which types. By default all keys are read as strings. This dictionary
668 should have as its keys valid conversion functions for strings
656 should have as its keys valid conversion functions for strings
669 (int,long,float,complex, or your own). The value for each key
657 (int,long,float,complex, or your own). The value for each key
670 (converter) should be a whitespace separated string containing the names
658 (converter) should be a whitespace separated string containing the names
671 of all the entries in the file to be converted using that function. For
659 of all the entries in the file to be converted using that function. For
672 keys to be left alone, use None as the conversion function (only needed
660 keys to be left alone, use None as the conversion function (only needed
673 with purge=1, see below).
661 with purge=1, see below).
674
662
675 - opt: dictionary with extra options as below (default in parens)
663 - opt: dictionary with extra options as below (default in parens)
676
664
677 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
665 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
678 of the dictionary to be returned. If purge is going to be used, the
666 of the dictionary to be returned. If purge is going to be used, the
679 set of keys to be left as strings also has to be explicitly specified
667 set of keys to be left as strings also has to be explicitly specified
680 using the (non-existent) conversion function None.
668 using the (non-existent) conversion function None.
681
669
682 fs(None): field separator. This is the key/value separator to be used
670 fs(None): field separator. This is the key/value separator to be used
683 when parsing the file. The None default means any whitespace [behavior
671 when parsing the file. The None default means any whitespace [behavior
684 of string.split()].
672 of string.split()].
685
673
686 strip(0): if 1, strip string values of leading/trailinig whitespace.
674 strip(0): if 1, strip string values of leading/trailinig whitespace.
687
675
688 warn(1): warning level if requested keys are not found in file.
676 warn(1): warning level if requested keys are not found in file.
689 - 0: silently ignore.
677 - 0: silently ignore.
690 - 1: inform but proceed.
678 - 1: inform but proceed.
691 - 2: raise KeyError exception.
679 - 2: raise KeyError exception.
692
680
693 no_empty(0): if 1, remove keys with whitespace strings as a value.
681 no_empty(0): if 1, remove keys with whitespace strings as a value.
694
682
695 unique([]): list of keys (or space separated string) which can't be
683 unique([]): list of keys (or space separated string) which can't be
696 repeated. If one such key is found in the file, each new instance
684 repeated. If one such key is found in the file, each new instance
697 overwrites the previous one. For keys not listed here, the behavior is
685 overwrites the previous one. For keys not listed here, the behavior is
698 to make a list of all appearances.
686 to make a list of all appearances.
699
687
700 Example:
688 Example:
701 If the input file test.ini has:
689 If the input file test.ini has:
702 i 3
690 i 3
703 x 4.5
691 x 4.5
704 y 5.5
692 y 5.5
705 s hi ho
693 s hi ho
706 Then:
694 Then:
707
695
708 >>> type_conv={int:'i',float:'x',None:'s'}
696 >>> type_conv={int:'i',float:'x',None:'s'}
709 >>> read_dict('test.ini')
697 >>> read_dict('test.ini')
710 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
698 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
711 >>> read_dict('test.ini',type_conv)
699 >>> read_dict('test.ini',type_conv)
712 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
700 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
713 >>> read_dict('test.ini',type_conv,purge=1)
701 >>> read_dict('test.ini',type_conv,purge=1)
714 {'i': 3, 's': 'hi ho', 'x': 4.5}
702 {'i': 3, 's': 'hi ho', 'x': 4.5}
715 """
703 """
716
704
717 # starting config
705 # starting config
718 opt.setdefault('purge',0)
706 opt.setdefault('purge',0)
719 opt.setdefault('fs',None) # field sep defaults to any whitespace
707 opt.setdefault('fs',None) # field sep defaults to any whitespace
720 opt.setdefault('strip',0)
708 opt.setdefault('strip',0)
721 opt.setdefault('warn',1)
709 opt.setdefault('warn',1)
722 opt.setdefault('no_empty',0)
710 opt.setdefault('no_empty',0)
723 opt.setdefault('unique','')
711 opt.setdefault('unique','')
724 if type(opt['unique']) in StringTypes:
712 if type(opt['unique']) in StringTypes:
725 unique_keys = qw(opt['unique'])
713 unique_keys = qw(opt['unique'])
726 elif type(opt['unique']) in (types.TupleType,types.ListType):
714 elif type(opt['unique']) in (types.TupleType,types.ListType):
727 unique_keys = opt['unique']
715 unique_keys = opt['unique']
728 else:
716 else:
729 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
717 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
730
718
731 dict = {}
719 dict = {}
732 # first read in table of values as strings
720 # first read in table of values as strings
733 file = open(filename,'r')
721 file = open(filename,'r')
734 for line in file.readlines():
722 for line in file.readlines():
735 line = line.strip()
723 line = line.strip()
736 if len(line) and line[0]=='#': continue
724 if len(line) and line[0]=='#': continue
737 if len(line)>0:
725 if len(line)>0:
738 lsplit = line.split(opt['fs'],1)
726 lsplit = line.split(opt['fs'],1)
739 try:
727 try:
740 key,val = lsplit
728 key,val = lsplit
741 except ValueError:
729 except ValueError:
742 key,val = lsplit[0],''
730 key,val = lsplit[0],''
743 key = key.strip()
731 key = key.strip()
744 if opt['strip']: val = val.strip()
732 if opt['strip']: val = val.strip()
745 if val == "''" or val == '""': val = ''
733 if val == "''" or val == '""': val = ''
746 if opt['no_empty'] and (val=='' or val.isspace()):
734 if opt['no_empty'] and (val=='' or val.isspace()):
747 continue
735 continue
748 # if a key is found more than once in the file, build a list
736 # if a key is found more than once in the file, build a list
749 # unless it's in the 'unique' list. In that case, last found in file
737 # unless it's in the 'unique' list. In that case, last found in file
750 # takes precedence. User beware.
738 # takes precedence. User beware.
751 try:
739 try:
752 if dict[key] and key in unique_keys:
740 if dict[key] and key in unique_keys:
753 dict[key] = val
741 dict[key] = val
754 elif type(dict[key]) is types.ListType:
742 elif type(dict[key]) is types.ListType:
755 dict[key].append(val)
743 dict[key].append(val)
756 else:
744 else:
757 dict[key] = [dict[key],val]
745 dict[key] = [dict[key],val]
758 except KeyError:
746 except KeyError:
759 dict[key] = val
747 dict[key] = val
760 # purge if requested
748 # purge if requested
761 if opt['purge']:
749 if opt['purge']:
762 accepted_keys = qwflat(type_conv.values())
750 accepted_keys = qwflat(type_conv.values())
763 for key in dict.keys():
751 for key in dict.keys():
764 if key in accepted_keys: continue
752 if key in accepted_keys: continue
765 del(dict[key])
753 del(dict[key])
766 # now convert if requested
754 # now convert if requested
767 if type_conv==None: return dict
755 if type_conv==None: return dict
768 conversions = type_conv.keys()
756 conversions = type_conv.keys()
769 try: conversions.remove(None)
757 try: conversions.remove(None)
770 except: pass
758 except: pass
771 for convert in conversions:
759 for convert in conversions:
772 for val in qw(type_conv[convert]):
760 for val in qw(type_conv[convert]):
773 try:
761 try:
774 dict[val] = convert(dict[val])
762 dict[val] = convert(dict[val])
775 except KeyError,e:
763 except KeyError,e:
776 if opt['warn'] == 0:
764 if opt['warn'] == 0:
777 pass
765 pass
778 elif opt['warn'] == 1:
766 elif opt['warn'] == 1:
779 print >>sys.stderr, 'Warning: key',val,\
767 print >>sys.stderr, 'Warning: key',val,\
780 'not found in file',filename
768 'not found in file',filename
781 elif opt['warn'] == 2:
769 elif opt['warn'] == 2:
782 raise KeyError,e
770 raise KeyError,e
783 else:
771 else:
784 raise ValueError,'Warning level must be 0,1 or 2'
772 raise ValueError,'Warning level must be 0,1 or 2'
785
773
786 return dict
774 return dict
787
775
788 #----------------------------------------------------------------------------
776 #----------------------------------------------------------------------------
789 def flag_calls(func):
777 def flag_calls(func):
790 """Wrap a function to detect and flag when it gets called.
778 """Wrap a function to detect and flag when it gets called.
791
779
792 This is a decorator which takes a function and wraps it in a function with
780 This is a decorator which takes a function and wraps it in a function with
793 a 'called' attribute. wrapper.called is initialized to False.
781 a 'called' attribute. wrapper.called is initialized to False.
794
782
795 The wrapper.called attribute is set to False right before each call to the
783 The wrapper.called attribute is set to False right before each call to the
796 wrapped function, so if the call fails it remains False. After the call
784 wrapped function, so if the call fails it remains False. After the call
797 completes, wrapper.called is set to True and the output is returned.
785 completes, wrapper.called is set to True and the output is returned.
798
786
799 Testing for truth in wrapper.called allows you to determine if a call to
787 Testing for truth in wrapper.called allows you to determine if a call to
800 func() was attempted and succeeded."""
788 func() was attempted and succeeded."""
801
789
802 def wrapper(*args,**kw):
790 def wrapper(*args,**kw):
803 wrapper.called = False
791 wrapper.called = False
804 out = func(*args,**kw)
792 out = func(*args,**kw)
805 wrapper.called = True
793 wrapper.called = True
806 return out
794 return out
807
795
808 wrapper.called = False
796 wrapper.called = False
809 wrapper.__doc__ = func.__doc__
797 wrapper.__doc__ = func.__doc__
810 return wrapper
798 return wrapper
811
799
812 #----------------------------------------------------------------------------
800 #----------------------------------------------------------------------------
813 class HomeDirError(Error):
801 class HomeDirError(Error):
814 pass
802 pass
815
803
816 def get_home_dir():
804 def get_home_dir():
817 """Return the closest possible equivalent to a 'home' directory.
805 """Return the closest possible equivalent to a 'home' directory.
818
806
819 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
807 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
820
808
821 Currently only Posix and NT are implemented, a HomeDirError exception is
809 Currently only Posix and NT are implemented, a HomeDirError exception is
822 raised for all other OSes. """
810 raised for all other OSes. """
823
811
824 isdir = os.path.isdir
812 isdir = os.path.isdir
825 env = os.environ
813 env = os.environ
826 try:
814 try:
827 homedir = env['HOME']
815 homedir = env['HOME']
828 if not isdir(homedir):
816 if not isdir(homedir):
829 # in case a user stuck some string which does NOT resolve to a
817 # in case a user stuck some string which does NOT resolve to a
830 # valid path, it's as good as if we hadn't foud it
818 # valid path, it's as good as if we hadn't foud it
831 raise KeyError
819 raise KeyError
832 return homedir
820 return homedir
833 except KeyError:
821 except KeyError:
834 if os.name == 'posix':
822 if os.name == 'posix':
835 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
823 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
836 elif os.name == 'nt':
824 elif os.name == 'nt':
837 # For some strange reason, win9x returns 'nt' for os.name.
825 # For some strange reason, win9x returns 'nt' for os.name.
838 try:
826 try:
839 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
827 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
840 if not isdir(homedir):
828 if not isdir(homedir):
841 homedir = os.path.join(env['USERPROFILE'])
829 homedir = os.path.join(env['USERPROFILE'])
842 if not isdir(homedir):
830 if not isdir(homedir):
843 raise HomeDirError
831 raise HomeDirError
844 return homedir
832 return homedir
845 except:
833 except:
846 try:
834 try:
847 # Use the registry to get the 'My Documents' folder.
835 # Use the registry to get the 'My Documents' folder.
848 import _winreg as wreg
836 import _winreg as wreg
849 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
837 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
850 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
838 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
851 homedir = wreg.QueryValueEx(key,'Personal')[0]
839 homedir = wreg.QueryValueEx(key,'Personal')[0]
852 key.Close()
840 key.Close()
853 if not isdir(homedir):
841 if not isdir(homedir):
854 e = ('Invalid "Personal" folder registry key '
842 e = ('Invalid "Personal" folder registry key '
855 'typically "My Documents".\n'
843 'typically "My Documents".\n'
856 'Value: %s\n'
844 'Value: %s\n'
857 'This is not a valid directory on your system.' %
845 'This is not a valid directory on your system.' %
858 homedir)
846 homedir)
859 raise HomeDirError(e)
847 raise HomeDirError(e)
860 return homedir
848 return homedir
861 except HomeDirError:
849 except HomeDirError:
862 raise
850 raise
863 except:
851 except:
864 return 'C:\\'
852 return 'C:\\'
865 elif os.name == 'dos':
853 elif os.name == 'dos':
866 # Desperate, may do absurd things in classic MacOS. May work under DOS.
854 # Desperate, may do absurd things in classic MacOS. May work under DOS.
867 return 'C:\\'
855 return 'C:\\'
868 else:
856 else:
869 raise HomeDirError,'support for your operating system not implemented.'
857 raise HomeDirError,'support for your operating system not implemented.'
870
858
871 #****************************************************************************
859 #****************************************************************************
872 # strings and text
860 # strings and text
873
861
874 class LSString(str):
862 class LSString(str):
875 """String derivative with a special access attributes.
863 """String derivative with a special access attributes.
876
864
877 These are normal strings, but with the special attributes:
865 These are normal strings, but with the special attributes:
878
866
879 .l (or .list) : value as list (split on newlines).
867 .l (or .list) : value as list (split on newlines).
880 .n (or .nlstr): original value (the string itself).
868 .n (or .nlstr): original value (the string itself).
881 .s (or .spstr): value as whitespace-separated string.
869 .s (or .spstr): value as whitespace-separated string.
882
870
883 Any values which require transformations are computed only once and
871 Any values which require transformations are computed only once and
884 cached.
872 cached.
885
873
886 Such strings are very useful to efficiently interact with the shell, which
874 Such strings are very useful to efficiently interact with the shell, which
887 typically only understands whitespace-separated options for commands."""
875 typically only understands whitespace-separated options for commands."""
888
876
889 def get_list(self):
877 def get_list(self):
890 try:
878 try:
891 return self.__list
879 return self.__list
892 except AttributeError:
880 except AttributeError:
893 self.__list = self.split('\n')
881 self.__list = self.split('\n')
894 return self.__list
882 return self.__list
895
883
896 l = list = property(get_list)
884 l = list = property(get_list)
897
885
898 def get_spstr(self):
886 def get_spstr(self):
899 try:
887 try:
900 return self.__spstr
888 return self.__spstr
901 except AttributeError:
889 except AttributeError:
902 self.__spstr = self.replace('\n',' ')
890 self.__spstr = self.replace('\n',' ')
903 return self.__spstr
891 return self.__spstr
904
892
905 s = spstr = property(get_spstr)
893 s = spstr = property(get_spstr)
906
894
907 def get_nlstr(self):
895 def get_nlstr(self):
908 return self
896 return self
909
897
910 n = nlstr = property(get_nlstr)
898 n = nlstr = property(get_nlstr)
911
899
912 def get_paths(self):
900 def get_paths(self):
913 try:
901 try:
914 return self.__paths
902 return self.__paths
915 except AttributeError:
903 except AttributeError:
916 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
904 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
917 return self.__paths
905 return self.__paths
918
906
919 p = paths = property(get_paths)
907 p = paths = property(get_paths)
920
908
921
909
922 #----------------------------------------------------------------------------
910 #----------------------------------------------------------------------------
923 class SList(list):
911 class SList(list):
924 """List derivative with a special access attributes.
912 """List derivative with a special access attributes.
925
913
926 These are normal lists, but with the special attributes:
914 These are normal lists, but with the special attributes:
927
915
928 .l (or .list) : value as list (the list itself).
916 .l (or .list) : value as list (the list itself).
929 .n (or .nlstr): value as a string, joined on newlines.
917 .n (or .nlstr): value as a string, joined on newlines.
930 .s (or .spstr): value as a string, joined on spaces.
918 .s (or .spstr): value as a string, joined on spaces.
931
919
932 Any values which require transformations are computed only once and
920 Any values which require transformations are computed only once and
933 cached."""
921 cached."""
934
922
935 def get_list(self):
923 def get_list(self):
936 return self
924 return self
937
925
938 l = list = property(get_list)
926 l = list = property(get_list)
939
927
940 def get_spstr(self):
928 def get_spstr(self):
941 try:
929 try:
942 return self.__spstr
930 return self.__spstr
943 except AttributeError:
931 except AttributeError:
944 self.__spstr = ' '.join(self)
932 self.__spstr = ' '.join(self)
945 return self.__spstr
933 return self.__spstr
946
934
947 s = spstr = property(get_spstr)
935 s = spstr = property(get_spstr)
948
936
949 def get_nlstr(self):
937 def get_nlstr(self):
950 try:
938 try:
951 return self.__nlstr
939 return self.__nlstr
952 except AttributeError:
940 except AttributeError:
953 self.__nlstr = '\n'.join(self)
941 self.__nlstr = '\n'.join(self)
954 return self.__nlstr
942 return self.__nlstr
955
943
956 n = nlstr = property(get_nlstr)
944 n = nlstr = property(get_nlstr)
957
945
958 def get_paths(self):
946 def get_paths(self):
959 try:
947 try:
960 return self.__paths
948 return self.__paths
961 except AttributeError:
949 except AttributeError:
962 self.__paths = [path(p) for p in self if os.path.exists(p)]
950 self.__paths = [path(p) for p in self if os.path.exists(p)]
963 return self.__paths
951 return self.__paths
964
952
965 p = paths = property(get_paths)
953 p = paths = property(get_paths)
966
954
967 #----------------------------------------------------------------------------
955 #----------------------------------------------------------------------------
968 def esc_quotes(strng):
956 def esc_quotes(strng):
969 """Return the input string with single and double quotes escaped out"""
957 """Return the input string with single and double quotes escaped out"""
970
958
971 return strng.replace('"','\\"').replace("'","\\'")
959 return strng.replace('"','\\"').replace("'","\\'")
972
960
973 #----------------------------------------------------------------------------
961 #----------------------------------------------------------------------------
974 def make_quoted_expr(s):
962 def make_quoted_expr(s):
975 """Return string s in appropriate quotes, using raw string if possible.
963 """Return string s in appropriate quotes, using raw string if possible.
976
964
977 Effectively this turns string: cd \ao\ao\
965 Effectively this turns string: cd \ao\ao\
978 to: r"cd \ao\ao\_"[:-1]
966 to: r"cd \ao\ao\_"[:-1]
979
967
980 Note the use of raw string and padding at the end to allow trailing backslash.
968 Note the use of raw string and padding at the end to allow trailing backslash.
981
969
982 """
970 """
983
971
984 tail = ''
972 tail = ''
985 tailpadding = ''
973 tailpadding = ''
986 raw = ''
974 raw = ''
987 if "\\" in s:
975 if "\\" in s:
988 raw = 'r'
976 raw = 'r'
989 if s.endswith('\\'):
977 if s.endswith('\\'):
990 tail = '[:-1]'
978 tail = '[:-1]'
991 tailpadding = '_'
979 tailpadding = '_'
992 if '"' not in s:
980 if '"' not in s:
993 quote = '"'
981 quote = '"'
994 elif "'" not in s:
982 elif "'" not in s:
995 quote = "'"
983 quote = "'"
996 elif '"""' not in s and not s.endswith('"'):
984 elif '"""' not in s and not s.endswith('"'):
997 quote = '"""'
985 quote = '"""'
998 elif "'''" not in s and not s.endswith("'"):
986 elif "'''" not in s and not s.endswith("'"):
999 quote = "'''"
987 quote = "'''"
1000 else:
988 else:
1001 # give up, backslash-escaped string will do
989 # give up, backslash-escaped string will do
1002 return '"%s"' % esc_quotes(s)
990 return '"%s"' % esc_quotes(s)
1003 res = itpl("$raw$quote$s$tailpadding$quote$tail")
991 res = itpl("$raw$quote$s$tailpadding$quote$tail")
1004 return res
992 return res
1005
993
1006
994
1007 #----------------------------------------------------------------------------
995 #----------------------------------------------------------------------------
1008 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
996 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
1009 """Take multiple lines of input.
997 """Take multiple lines of input.
1010
998
1011 A list with each line of input as a separate element is returned when a
999 A list with each line of input as a separate element is returned when a
1012 termination string is entered (defaults to a single '.'). Input can also
1000 termination string is entered (defaults to a single '.'). Input can also
1013 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1001 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1014
1002
1015 Lines of input which end in \\ are joined into single entries (and a
1003 Lines of input which end in \\ are joined into single entries (and a
1016 secondary continuation prompt is issued as long as the user terminates
1004 secondary continuation prompt is issued as long as the user terminates
1017 lines with \\). This allows entering very long strings which are still
1005 lines with \\). This allows entering very long strings which are still
1018 meant to be treated as single entities.
1006 meant to be treated as single entities.
1019 """
1007 """
1020
1008
1021 try:
1009 try:
1022 if header:
1010 if header:
1023 header += '\n'
1011 header += '\n'
1024 lines = [raw_input(header + ps1)]
1012 lines = [raw_input(header + ps1)]
1025 except EOFError:
1013 except EOFError:
1026 return []
1014 return []
1027 terminate = [terminate_str]
1015 terminate = [terminate_str]
1028 try:
1016 try:
1029 while lines[-1:] != terminate:
1017 while lines[-1:] != terminate:
1030 new_line = raw_input(ps1)
1018 new_line = raw_input(ps1)
1031 while new_line.endswith('\\'):
1019 while new_line.endswith('\\'):
1032 new_line = new_line[:-1] + raw_input(ps2)
1020 new_line = new_line[:-1] + raw_input(ps2)
1033 lines.append(new_line)
1021 lines.append(new_line)
1034
1022
1035 return lines[:-1] # don't return the termination command
1023 return lines[:-1] # don't return the termination command
1036 except EOFError:
1024 except EOFError:
1037 print
1025 print
1038 return lines
1026 return lines
1039
1027
1040 #----------------------------------------------------------------------------
1028 #----------------------------------------------------------------------------
1041 def raw_input_ext(prompt='', ps2='... '):
1029 def raw_input_ext(prompt='', ps2='... '):
1042 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1030 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1043
1031
1044 line = raw_input(prompt)
1032 line = raw_input(prompt)
1045 while line.endswith('\\'):
1033 while line.endswith('\\'):
1046 line = line[:-1] + raw_input(ps2)
1034 line = line[:-1] + raw_input(ps2)
1047 return line
1035 return line
1048
1036
1049 #----------------------------------------------------------------------------
1037 #----------------------------------------------------------------------------
1050 def ask_yes_no(prompt,default=None):
1038 def ask_yes_no(prompt,default=None):
1051 """Asks a question and returns an integer 1/0 (y/n) answer.
1039 """Asks a question and returns an integer 1/0 (y/n) answer.
1052
1040
1053 If default is given (one of 'y','n'), it is used if the user input is
1041 If default is given (one of 'y','n'), it is used if the user input is
1054 empty. Otherwise the question is repeated until an answer is given.
1042 empty. Otherwise the question is repeated until an answer is given.
1055 If EOF occurs 20 times consecutively, the default answer is assumed,
1043 If EOF occurs 20 times consecutively, the default answer is assumed,
1056 or if there is no default, an exception is raised to prevent infinite
1044 or if there is no default, an exception is raised to prevent infinite
1057 loops.
1045 loops.
1058
1046
1059 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1047 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1060
1048
1061 answers = {'y':True,'n':False,'yes':True,'no':False}
1049 answers = {'y':True,'n':False,'yes':True,'no':False}
1062 ans = None
1050 ans = None
1063 eofs, max_eofs = 0, 20
1051 eofs, max_eofs = 0, 20
1064 while ans not in answers.keys():
1052 while ans not in answers.keys():
1065 try:
1053 try:
1066 ans = raw_input(prompt+' ').lower()
1054 ans = raw_input(prompt+' ').lower()
1067 if not ans: # response was an empty string
1055 if not ans: # response was an empty string
1068 ans = default
1056 ans = default
1069 eofs = 0
1057 eofs = 0
1070 except (EOFError,KeyboardInterrupt):
1058 except (EOFError,KeyboardInterrupt):
1071 eofs = eofs + 1
1059 eofs = eofs + 1
1072 if eofs >= max_eofs:
1060 if eofs >= max_eofs:
1073 if default in answers.keys():
1061 if default in answers.keys():
1074 ans = default
1062 ans = default
1075 else:
1063 else:
1076 raise
1064 raise
1077
1065
1078 return answers[ans]
1066 return answers[ans]
1079
1067
1080 #----------------------------------------------------------------------------
1068 #----------------------------------------------------------------------------
1081 def marquee(txt='',width=78,mark='*'):
1069 def marquee(txt='',width=78,mark='*'):
1082 """Return the input string centered in a 'marquee'."""
1070 """Return the input string centered in a 'marquee'."""
1083 if not txt:
1071 if not txt:
1084 return (mark*width)[:width]
1072 return (mark*width)[:width]
1085 nmark = (width-len(txt)-2)/len(mark)/2
1073 nmark = (width-len(txt)-2)/len(mark)/2
1086 if nmark < 0: nmark =0
1074 if nmark < 0: nmark =0
1087 marks = mark*nmark
1075 marks = mark*nmark
1088 return '%s %s %s' % (marks,txt,marks)
1076 return '%s %s %s' % (marks,txt,marks)
1089
1077
1090 #----------------------------------------------------------------------------
1078 #----------------------------------------------------------------------------
1091 class EvalDict:
1079 class EvalDict:
1092 """
1080 """
1093 Emulate a dict which evaluates its contents in the caller's frame.
1081 Emulate a dict which evaluates its contents in the caller's frame.
1094
1082
1095 Usage:
1083 Usage:
1096 >>>number = 19
1084 >>>number = 19
1097 >>>text = "python"
1085 >>>text = "python"
1098 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1086 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1099 """
1087 """
1100
1088
1101 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1089 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1102 # modified (shorter) version of:
1090 # modified (shorter) version of:
1103 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1091 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1104 # Skip Montanaro (skip@pobox.com).
1092 # Skip Montanaro (skip@pobox.com).
1105
1093
1106 def __getitem__(self, name):
1094 def __getitem__(self, name):
1107 frame = sys._getframe(1)
1095 frame = sys._getframe(1)
1108 return eval(name, frame.f_globals, frame.f_locals)
1096 return eval(name, frame.f_globals, frame.f_locals)
1109
1097
1110 EvalString = EvalDict # for backwards compatibility
1098 EvalString = EvalDict # for backwards compatibility
1111 #----------------------------------------------------------------------------
1099 #----------------------------------------------------------------------------
1112 def qw(words,flat=0,sep=None,maxsplit=-1):
1100 def qw(words,flat=0,sep=None,maxsplit=-1):
1113 """Similar to Perl's qw() operator, but with some more options.
1101 """Similar to Perl's qw() operator, but with some more options.
1114
1102
1115 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1103 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1116
1104
1117 words can also be a list itself, and with flat=1, the output will be
1105 words can also be a list itself, and with flat=1, the output will be
1118 recursively flattened. Examples:
1106 recursively flattened. Examples:
1119
1107
1120 >>> qw('1 2')
1108 >>> qw('1 2')
1121 ['1', '2']
1109 ['1', '2']
1122 >>> qw(['a b','1 2',['m n','p q']])
1110 >>> qw(['a b','1 2',['m n','p q']])
1123 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1111 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1124 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1112 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1125 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1113 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1126
1114
1127 if type(words) in StringTypes:
1115 if type(words) in StringTypes:
1128 return [word.strip() for word in words.split(sep,maxsplit)
1116 return [word.strip() for word in words.split(sep,maxsplit)
1129 if word and not word.isspace() ]
1117 if word and not word.isspace() ]
1130 if flat:
1118 if flat:
1131 return flatten(map(qw,words,[1]*len(words)))
1119 return flatten(map(qw,words,[1]*len(words)))
1132 return map(qw,words)
1120 return map(qw,words)
1133
1121
1134 #----------------------------------------------------------------------------
1122 #----------------------------------------------------------------------------
1135 def qwflat(words,sep=None,maxsplit=-1):
1123 def qwflat(words,sep=None,maxsplit=-1):
1136 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1124 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1137 return qw(words,1,sep,maxsplit)
1125 return qw(words,1,sep,maxsplit)
1138
1126
1139 #----------------------------------------------------------------------------
1127 #----------------------------------------------------------------------------
1140 def qw_lol(indata):
1128 def qw_lol(indata):
1141 """qw_lol('a b') -> [['a','b']],
1129 """qw_lol('a b') -> [['a','b']],
1142 otherwise it's just a call to qw().
1130 otherwise it's just a call to qw().
1143
1131
1144 We need this to make sure the modules_some keys *always* end up as a
1132 We need this to make sure the modules_some keys *always* end up as a
1145 list of lists."""
1133 list of lists."""
1146
1134
1147 if type(indata) in StringTypes:
1135 if type(indata) in StringTypes:
1148 return [qw(indata)]
1136 return [qw(indata)]
1149 else:
1137 else:
1150 return qw(indata)
1138 return qw(indata)
1151
1139
1152 #-----------------------------------------------------------------------------
1140 #-----------------------------------------------------------------------------
1153 def list_strings(arg):
1141 def list_strings(arg):
1154 """Always return a list of strings, given a string or list of strings
1142 """Always return a list of strings, given a string or list of strings
1155 as input."""
1143 as input."""
1156
1144
1157 if type(arg) in StringTypes: return [arg]
1145 if type(arg) in StringTypes: return [arg]
1158 else: return arg
1146 else: return arg
1159
1147
1160 #----------------------------------------------------------------------------
1148 #----------------------------------------------------------------------------
1161 def grep(pat,list,case=1):
1149 def grep(pat,list,case=1):
1162 """Simple minded grep-like function.
1150 """Simple minded grep-like function.
1163 grep(pat,list) returns occurrences of pat in list, None on failure.
1151 grep(pat,list) returns occurrences of pat in list, None on failure.
1164
1152
1165 It only does simple string matching, with no support for regexps. Use the
1153 It only does simple string matching, with no support for regexps. Use the
1166 option case=0 for case-insensitive matching."""
1154 option case=0 for case-insensitive matching."""
1167
1155
1168 # This is pretty crude. At least it should implement copying only references
1156 # This is pretty crude. At least it should implement copying only references
1169 # to the original data in case it's big. Now it copies the data for output.
1157 # to the original data in case it's big. Now it copies the data for output.
1170 out=[]
1158 out=[]
1171 if case:
1159 if case:
1172 for term in list:
1160 for term in list:
1173 if term.find(pat)>-1: out.append(term)
1161 if term.find(pat)>-1: out.append(term)
1174 else:
1162 else:
1175 lpat=pat.lower()
1163 lpat=pat.lower()
1176 for term in list:
1164 for term in list:
1177 if term.lower().find(lpat)>-1: out.append(term)
1165 if term.lower().find(lpat)>-1: out.append(term)
1178
1166
1179 if len(out): return out
1167 if len(out): return out
1180 else: return None
1168 else: return None
1181
1169
1182 #----------------------------------------------------------------------------
1170 #----------------------------------------------------------------------------
1183 def dgrep(pat,*opts):
1171 def dgrep(pat,*opts):
1184 """Return grep() on dir()+dir(__builtins__).
1172 """Return grep() on dir()+dir(__builtins__).
1185
1173
1186 A very common use of grep() when working interactively."""
1174 A very common use of grep() when working interactively."""
1187
1175
1188 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1176 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1189
1177
1190 #----------------------------------------------------------------------------
1178 #----------------------------------------------------------------------------
1191 def idgrep(pat):
1179 def idgrep(pat):
1192 """Case-insensitive dgrep()"""
1180 """Case-insensitive dgrep()"""
1193
1181
1194 return dgrep(pat,0)
1182 return dgrep(pat,0)
1195
1183
1196 #----------------------------------------------------------------------------
1184 #----------------------------------------------------------------------------
1197 def igrep(pat,list):
1185 def igrep(pat,list):
1198 """Synonym for case-insensitive grep."""
1186 """Synonym for case-insensitive grep."""
1199
1187
1200 return grep(pat,list,case=0)
1188 return grep(pat,list,case=0)
1201
1189
1202 #----------------------------------------------------------------------------
1190 #----------------------------------------------------------------------------
1203 def indent(str,nspaces=4,ntabs=0):
1191 def indent(str,nspaces=4,ntabs=0):
1204 """Indent a string a given number of spaces or tabstops.
1192 """Indent a string a given number of spaces or tabstops.
1205
1193
1206 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1194 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1207 """
1195 """
1208 if str is None:
1196 if str is None:
1209 return
1197 return
1210 ind = '\t'*ntabs+' '*nspaces
1198 ind = '\t'*ntabs+' '*nspaces
1211 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1199 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1212 if outstr.endswith(os.linesep+ind):
1200 if outstr.endswith(os.linesep+ind):
1213 return outstr[:-len(ind)]
1201 return outstr[:-len(ind)]
1214 else:
1202 else:
1215 return outstr
1203 return outstr
1216
1204
1217 #-----------------------------------------------------------------------------
1205 #-----------------------------------------------------------------------------
1218 def native_line_ends(filename,backup=1):
1206 def native_line_ends(filename,backup=1):
1219 """Convert (in-place) a file to line-ends native to the current OS.
1207 """Convert (in-place) a file to line-ends native to the current OS.
1220
1208
1221 If the optional backup argument is given as false, no backup of the
1209 If the optional backup argument is given as false, no backup of the
1222 original file is left. """
1210 original file is left. """
1223
1211
1224 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1212 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1225
1213
1226 bak_filename = filename + backup_suffixes[os.name]
1214 bak_filename = filename + backup_suffixes[os.name]
1227
1215
1228 original = open(filename).read()
1216 original = open(filename).read()
1229 shutil.copy2(filename,bak_filename)
1217 shutil.copy2(filename,bak_filename)
1230 try:
1218 try:
1231 new = open(filename,'wb')
1219 new = open(filename,'wb')
1232 new.write(os.linesep.join(original.splitlines()))
1220 new.write(os.linesep.join(original.splitlines()))
1233 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1221 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1234 new.close()
1222 new.close()
1235 except:
1223 except:
1236 os.rename(bak_filename,filename)
1224 os.rename(bak_filename,filename)
1237 if not backup:
1225 if not backup:
1238 try:
1226 try:
1239 os.remove(bak_filename)
1227 os.remove(bak_filename)
1240 except:
1228 except:
1241 pass
1229 pass
1242
1230
1243 #----------------------------------------------------------------------------
1231 #----------------------------------------------------------------------------
1244 def get_pager_cmd(pager_cmd = None):
1232 def get_pager_cmd(pager_cmd = None):
1245 """Return a pager command.
1233 """Return a pager command.
1246
1234
1247 Makes some attempts at finding an OS-correct one."""
1235 Makes some attempts at finding an OS-correct one."""
1248
1236
1249 if os.name == 'posix':
1237 if os.name == 'posix':
1250 default_pager_cmd = 'less -r' # -r for color control sequences
1238 default_pager_cmd = 'less -r' # -r for color control sequences
1251 elif os.name in ['nt','dos']:
1239 elif os.name in ['nt','dos']:
1252 default_pager_cmd = 'type'
1240 default_pager_cmd = 'type'
1253
1241
1254 if pager_cmd is None:
1242 if pager_cmd is None:
1255 try:
1243 try:
1256 pager_cmd = os.environ['PAGER']
1244 pager_cmd = os.environ['PAGER']
1257 except:
1245 except:
1258 pager_cmd = default_pager_cmd
1246 pager_cmd = default_pager_cmd
1259 return pager_cmd
1247 return pager_cmd
1260
1248
1261 #-----------------------------------------------------------------------------
1249 #-----------------------------------------------------------------------------
1262 def get_pager_start(pager,start):
1250 def get_pager_start(pager,start):
1263 """Return the string for paging files with an offset.
1251 """Return the string for paging files with an offset.
1264
1252
1265 This is the '+N' argument which less and more (under Unix) accept.
1253 This is the '+N' argument which less and more (under Unix) accept.
1266 """
1254 """
1267
1255
1268 if pager in ['less','more']:
1256 if pager in ['less','more']:
1269 if start:
1257 if start:
1270 start_string = '+' + str(start)
1258 start_string = '+' + str(start)
1271 else:
1259 else:
1272 start_string = ''
1260 start_string = ''
1273 else:
1261 else:
1274 start_string = ''
1262 start_string = ''
1275 return start_string
1263 return start_string
1276
1264
1277 #----------------------------------------------------------------------------
1265 #----------------------------------------------------------------------------
1278 if os.name == "nt":
1266 if os.name == "nt":
1279 import msvcrt
1267 import msvcrt
1280 def page_more():
1268 def page_more():
1281 """ Smart pausing between pages
1269 """ Smart pausing between pages
1282
1270
1283 @return: True if need print more lines, False if quit
1271 @return: True if need print more lines, False if quit
1284 """
1272 """
1285 Term.cout.write('---Return to continue, q to quit--- ')
1273 Term.cout.write('---Return to continue, q to quit--- ')
1286 ans = msvcrt.getch()
1274 ans = msvcrt.getch()
1287 if ans in ("q", "Q"):
1275 if ans in ("q", "Q"):
1288 result = False
1276 result = False
1289 else:
1277 else:
1290 result = True
1278 result = True
1291 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1279 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1292 return result
1280 return result
1293 else:
1281 else:
1294 def page_more():
1282 def page_more():
1295 ans = raw_input('---Return to continue, q to quit--- ')
1283 ans = raw_input('---Return to continue, q to quit--- ')
1296 if ans.lower().startswith('q'):
1284 if ans.lower().startswith('q'):
1297 return False
1285 return False
1298 else:
1286 else:
1299 return True
1287 return True
1300
1288
1301 esc_re = re.compile(r"(\x1b[^m]+m)")
1289 esc_re = re.compile(r"(\x1b[^m]+m)")
1302
1290
1303 def page_dumb(strng,start=0,screen_lines=25):
1291 def page_dumb(strng,start=0,screen_lines=25):
1304 """Very dumb 'pager' in Python, for when nothing else works.
1292 """Very dumb 'pager' in Python, for when nothing else works.
1305
1293
1306 Only moves forward, same interface as page(), except for pager_cmd and
1294 Only moves forward, same interface as page(), except for pager_cmd and
1307 mode."""
1295 mode."""
1308
1296
1309 out_ln = strng.splitlines()[start:]
1297 out_ln = strng.splitlines()[start:]
1310 screens = chop(out_ln,screen_lines-1)
1298 screens = chop(out_ln,screen_lines-1)
1311 if len(screens) == 1:
1299 if len(screens) == 1:
1312 print >>Term.cout, os.linesep.join(screens[0])
1300 print >>Term.cout, os.linesep.join(screens[0])
1313 else:
1301 else:
1314 last_escape = ""
1302 last_escape = ""
1315 for scr in screens[0:-1]:
1303 for scr in screens[0:-1]:
1316 hunk = os.linesep.join(scr)
1304 hunk = os.linesep.join(scr)
1317 print >>Term.cout, last_escape + hunk
1305 print >>Term.cout, last_escape + hunk
1318 if not page_more():
1306 if not page_more():
1319 return
1307 return
1320 esc_list = esc_re.findall(hunk)
1308 esc_list = esc_re.findall(hunk)
1321 if len(esc_list) > 0:
1309 if len(esc_list) > 0:
1322 last_escape = esc_list[-1]
1310 last_escape = esc_list[-1]
1323 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1311 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1324
1312
1325 #----------------------------------------------------------------------------
1313 #----------------------------------------------------------------------------
1326 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1314 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1327 """Print a string, piping through a pager after a certain length.
1315 """Print a string, piping through a pager after a certain length.
1328
1316
1329 The screen_lines parameter specifies the number of *usable* lines of your
1317 The screen_lines parameter specifies the number of *usable* lines of your
1330 terminal screen (total lines minus lines you need to reserve to show other
1318 terminal screen (total lines minus lines you need to reserve to show other
1331 information).
1319 information).
1332
1320
1333 If you set screen_lines to a number <=0, page() will try to auto-determine
1321 If you set screen_lines to a number <=0, page() will try to auto-determine
1334 your screen size and will only use up to (screen_size+screen_lines) for
1322 your screen size and will only use up to (screen_size+screen_lines) for
1335 printing, paging after that. That is, if you want auto-detection but need
1323 printing, paging after that. That is, if you want auto-detection but need
1336 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1324 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1337 auto-detection without any lines reserved simply use screen_lines = 0.
1325 auto-detection without any lines reserved simply use screen_lines = 0.
1338
1326
1339 If a string won't fit in the allowed lines, it is sent through the
1327 If a string won't fit in the allowed lines, it is sent through the
1340 specified pager command. If none given, look for PAGER in the environment,
1328 specified pager command. If none given, look for PAGER in the environment,
1341 and ultimately default to less.
1329 and ultimately default to less.
1342
1330
1343 If no system pager works, the string is sent through a 'dumb pager'
1331 If no system pager works, the string is sent through a 'dumb pager'
1344 written in python, very simplistic.
1332 written in python, very simplistic.
1345 """
1333 """
1346
1334
1347 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1335 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1348 TERM = os.environ.get('TERM','dumb')
1336 TERM = os.environ.get('TERM','dumb')
1349 if TERM in ['dumb','emacs'] and os.name != 'nt':
1337 if TERM in ['dumb','emacs'] and os.name != 'nt':
1350 print strng
1338 print strng
1351 return
1339 return
1352 # chop off the topmost part of the string we don't want to see
1340 # chop off the topmost part of the string we don't want to see
1353 str_lines = strng.split(os.linesep)[start:]
1341 str_lines = strng.split(os.linesep)[start:]
1354 str_toprint = os.linesep.join(str_lines)
1342 str_toprint = os.linesep.join(str_lines)
1355 num_newlines = len(str_lines)
1343 num_newlines = len(str_lines)
1356 len_str = len(str_toprint)
1344 len_str = len(str_toprint)
1357
1345
1358 # Dumb heuristics to guesstimate number of on-screen lines the string
1346 # Dumb heuristics to guesstimate number of on-screen lines the string
1359 # takes. Very basic, but good enough for docstrings in reasonable
1347 # takes. Very basic, but good enough for docstrings in reasonable
1360 # terminals. If someone later feels like refining it, it's not hard.
1348 # terminals. If someone later feels like refining it, it's not hard.
1361 numlines = max(num_newlines,int(len_str/80)+1)
1349 numlines = max(num_newlines,int(len_str/80)+1)
1362
1350
1363 if os.name == "nt":
1351 if os.name == "nt":
1364 screen_lines_def = get_console_size(defaulty=25)[1]
1352 screen_lines_def = get_console_size(defaulty=25)[1]
1365 else:
1353 else:
1366 screen_lines_def = 25 # default value if we can't auto-determine
1354 screen_lines_def = 25 # default value if we can't auto-determine
1367
1355
1368 # auto-determine screen size
1356 # auto-determine screen size
1369 if screen_lines <= 0:
1357 if screen_lines <= 0:
1370 if TERM=='xterm':
1358 if TERM=='xterm':
1371 try:
1359 try:
1372 import curses
1360 import curses
1373 if hasattr(curses,'initscr'):
1361 if hasattr(curses,'initscr'):
1374 use_curses = 1
1362 use_curses = 1
1375 else:
1363 else:
1376 use_curses = 0
1364 use_curses = 0
1377 except ImportError:
1365 except ImportError:
1378 use_curses = 0
1366 use_curses = 0
1379 else:
1367 else:
1380 # curses causes problems on many terminals other than xterm.
1368 # curses causes problems on many terminals other than xterm.
1381 use_curses = 0
1369 use_curses = 0
1382 if use_curses:
1370 if use_curses:
1383 scr = curses.initscr()
1371 scr = curses.initscr()
1384 screen_lines_real,screen_cols = scr.getmaxyx()
1372 screen_lines_real,screen_cols = scr.getmaxyx()
1385 curses.endwin()
1373 curses.endwin()
1386 screen_lines += screen_lines_real
1374 screen_lines += screen_lines_real
1387 #print '***Screen size:',screen_lines_real,'lines x',\
1375 #print '***Screen size:',screen_lines_real,'lines x',\
1388 #screen_cols,'columns.' # dbg
1376 #screen_cols,'columns.' # dbg
1389 else:
1377 else:
1390 screen_lines += screen_lines_def
1378 screen_lines += screen_lines_def
1391
1379
1392 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1380 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1393 if numlines <= screen_lines :
1381 if numlines <= screen_lines :
1394 #print '*** normal print' # dbg
1382 #print '*** normal print' # dbg
1395 print >>Term.cout, str_toprint
1383 print >>Term.cout, str_toprint
1396 else:
1384 else:
1397 # Try to open pager and default to internal one if that fails.
1385 # Try to open pager and default to internal one if that fails.
1398 # All failure modes are tagged as 'retval=1', to match the return
1386 # All failure modes are tagged as 'retval=1', to match the return
1399 # value of a failed system command. If any intermediate attempt
1387 # value of a failed system command. If any intermediate attempt
1400 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1388 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1401 pager_cmd = get_pager_cmd(pager_cmd)
1389 pager_cmd = get_pager_cmd(pager_cmd)
1402 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1390 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1403 if os.name == 'nt':
1391 if os.name == 'nt':
1404 if pager_cmd.startswith('type'):
1392 if pager_cmd.startswith('type'):
1405 # The default WinXP 'type' command is failing on complex strings.
1393 # The default WinXP 'type' command is failing on complex strings.
1406 retval = 1
1394 retval = 1
1407 else:
1395 else:
1408 tmpname = tempfile.mktemp('.txt')
1396 tmpname = tempfile.mktemp('.txt')
1409 tmpfile = file(tmpname,'wt')
1397 tmpfile = file(tmpname,'wt')
1410 tmpfile.write(strng)
1398 tmpfile.write(strng)
1411 tmpfile.close()
1399 tmpfile.close()
1412 cmd = "%s < %s" % (pager_cmd,tmpname)
1400 cmd = "%s < %s" % (pager_cmd,tmpname)
1413 if os.system(cmd):
1401 if os.system(cmd):
1414 retval = 1
1402 retval = 1
1415 else:
1403 else:
1416 retval = None
1404 retval = None
1417 os.remove(tmpname)
1405 os.remove(tmpname)
1418 else:
1406 else:
1419 try:
1407 try:
1420 retval = None
1408 retval = None
1421 # if I use popen4, things hang. No idea why.
1409 # if I use popen4, things hang. No idea why.
1422 #pager,shell_out = os.popen4(pager_cmd)
1410 #pager,shell_out = os.popen4(pager_cmd)
1423 pager = os.popen(pager_cmd,'w')
1411 pager = os.popen(pager_cmd,'w')
1424 pager.write(strng)
1412 pager.write(strng)
1425 pager.close()
1413 pager.close()
1426 retval = pager.close() # success returns None
1414 retval = pager.close() # success returns None
1427 except IOError,msg: # broken pipe when user quits
1415 except IOError,msg: # broken pipe when user quits
1428 if msg.args == (32,'Broken pipe'):
1416 if msg.args == (32,'Broken pipe'):
1429 retval = None
1417 retval = None
1430 else:
1418 else:
1431 retval = 1
1419 retval = 1
1432 except OSError:
1420 except OSError:
1433 # Other strange problems, sometimes seen in Win2k/cygwin
1421 # Other strange problems, sometimes seen in Win2k/cygwin
1434 retval = 1
1422 retval = 1
1435 if retval is not None:
1423 if retval is not None:
1436 page_dumb(strng,screen_lines=screen_lines)
1424 page_dumb(strng,screen_lines=screen_lines)
1437
1425
1438 #----------------------------------------------------------------------------
1426 #----------------------------------------------------------------------------
1439 def page_file(fname,start = 0, pager_cmd = None):
1427 def page_file(fname,start = 0, pager_cmd = None):
1440 """Page a file, using an optional pager command and starting line.
1428 """Page a file, using an optional pager command and starting line.
1441 """
1429 """
1442
1430
1443 pager_cmd = get_pager_cmd(pager_cmd)
1431 pager_cmd = get_pager_cmd(pager_cmd)
1444 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1432 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1445
1433
1446 try:
1434 try:
1447 if os.environ['TERM'] in ['emacs','dumb']:
1435 if os.environ['TERM'] in ['emacs','dumb']:
1448 raise EnvironmentError
1436 raise EnvironmentError
1449 xsys(pager_cmd + ' ' + fname)
1437 xsys(pager_cmd + ' ' + fname)
1450 except:
1438 except:
1451 try:
1439 try:
1452 if start > 0:
1440 if start > 0:
1453 start -= 1
1441 start -= 1
1454 page(open(fname).read(),start)
1442 page(open(fname).read(),start)
1455 except:
1443 except:
1456 print 'Unable to show file',`fname`
1444 print 'Unable to show file',`fname`
1457
1445
1458 #----------------------------------------------------------------------------
1446 #----------------------------------------------------------------------------
1459 def snip_print(str,width = 75,print_full = 0,header = ''):
1447 def snip_print(str,width = 75,print_full = 0,header = ''):
1460 """Print a string snipping the midsection to fit in width.
1448 """Print a string snipping the midsection to fit in width.
1461
1449
1462 print_full: mode control:
1450 print_full: mode control:
1463 - 0: only snip long strings
1451 - 0: only snip long strings
1464 - 1: send to page() directly.
1452 - 1: send to page() directly.
1465 - 2: snip long strings and ask for full length viewing with page()
1453 - 2: snip long strings and ask for full length viewing with page()
1466 Return 1 if snipping was necessary, 0 otherwise."""
1454 Return 1 if snipping was necessary, 0 otherwise."""
1467
1455
1468 if print_full == 1:
1456 if print_full == 1:
1469 page(header+str)
1457 page(header+str)
1470 return 0
1458 return 0
1471
1459
1472 print header,
1460 print header,
1473 if len(str) < width:
1461 if len(str) < width:
1474 print str
1462 print str
1475 snip = 0
1463 snip = 0
1476 else:
1464 else:
1477 whalf = int((width -5)/2)
1465 whalf = int((width -5)/2)
1478 print str[:whalf] + ' <...> ' + str[-whalf:]
1466 print str[:whalf] + ' <...> ' + str[-whalf:]
1479 snip = 1
1467 snip = 1
1480 if snip and print_full == 2:
1468 if snip and print_full == 2:
1481 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1469 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1482 page(str)
1470 page(str)
1483 return snip
1471 return snip
1484
1472
1485 #****************************************************************************
1473 #****************************************************************************
1486 # lists, dicts and structures
1474 # lists, dicts and structures
1487
1475
1488 def belong(candidates,checklist):
1476 def belong(candidates,checklist):
1489 """Check whether a list of items appear in a given list of options.
1477 """Check whether a list of items appear in a given list of options.
1490
1478
1491 Returns a list of 1 and 0, one for each candidate given."""
1479 Returns a list of 1 and 0, one for each candidate given."""
1492
1480
1493 return [x in checklist for x in candidates]
1481 return [x in checklist for x in candidates]
1494
1482
1495 #----------------------------------------------------------------------------
1483 #----------------------------------------------------------------------------
1496 def uniq_stable(elems):
1484 def uniq_stable(elems):
1497 """uniq_stable(elems) -> list
1485 """uniq_stable(elems) -> list
1498
1486
1499 Return from an iterable, a list of all the unique elements in the input,
1487 Return from an iterable, a list of all the unique elements in the input,
1500 but maintaining the order in which they first appear.
1488 but maintaining the order in which they first appear.
1501
1489
1502 A naive solution to this problem which just makes a dictionary with the
1490 A naive solution to this problem which just makes a dictionary with the
1503 elements as keys fails to respect the stability condition, since
1491 elements as keys fails to respect the stability condition, since
1504 dictionaries are unsorted by nature.
1492 dictionaries are unsorted by nature.
1505
1493
1506 Note: All elements in the input must be valid dictionary keys for this
1494 Note: All elements in the input must be valid dictionary keys for this
1507 routine to work, as it internally uses a dictionary for efficiency
1495 routine to work, as it internally uses a dictionary for efficiency
1508 reasons."""
1496 reasons."""
1509
1497
1510 unique = []
1498 unique = []
1511 unique_dict = {}
1499 unique_dict = {}
1512 for nn in elems:
1500 for nn in elems:
1513 if nn not in unique_dict:
1501 if nn not in unique_dict:
1514 unique.append(nn)
1502 unique.append(nn)
1515 unique_dict[nn] = None
1503 unique_dict[nn] = None
1516 return unique
1504 return unique
1517
1505
1518 #----------------------------------------------------------------------------
1506 #----------------------------------------------------------------------------
1519 class NLprinter:
1507 class NLprinter:
1520 """Print an arbitrarily nested list, indicating index numbers.
1508 """Print an arbitrarily nested list, indicating index numbers.
1521
1509
1522 An instance of this class called nlprint is available and callable as a
1510 An instance of this class called nlprint is available and callable as a
1523 function.
1511 function.
1524
1512
1525 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1513 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1526 and using 'sep' to separate the index from the value. """
1514 and using 'sep' to separate the index from the value. """
1527
1515
1528 def __init__(self):
1516 def __init__(self):
1529 self.depth = 0
1517 self.depth = 0
1530
1518
1531 def __call__(self,lst,pos='',**kw):
1519 def __call__(self,lst,pos='',**kw):
1532 """Prints the nested list numbering levels."""
1520 """Prints the nested list numbering levels."""
1533 kw.setdefault('indent',' ')
1521 kw.setdefault('indent',' ')
1534 kw.setdefault('sep',': ')
1522 kw.setdefault('sep',': ')
1535 kw.setdefault('start',0)
1523 kw.setdefault('start',0)
1536 kw.setdefault('stop',len(lst))
1524 kw.setdefault('stop',len(lst))
1537 # we need to remove start and stop from kw so they don't propagate
1525 # we need to remove start and stop from kw so they don't propagate
1538 # into a recursive call for a nested list.
1526 # into a recursive call for a nested list.
1539 start = kw['start']; del kw['start']
1527 start = kw['start']; del kw['start']
1540 stop = kw['stop']; del kw['stop']
1528 stop = kw['stop']; del kw['stop']
1541 if self.depth == 0 and 'header' in kw.keys():
1529 if self.depth == 0 and 'header' in kw.keys():
1542 print kw['header']
1530 print kw['header']
1543
1531
1544 for idx in range(start,stop):
1532 for idx in range(start,stop):
1545 elem = lst[idx]
1533 elem = lst[idx]
1546 if type(elem)==type([]):
1534 if type(elem)==type([]):
1547 self.depth += 1
1535 self.depth += 1
1548 self.__call__(elem,itpl('$pos$idx,'),**kw)
1536 self.__call__(elem,itpl('$pos$idx,'),**kw)
1549 self.depth -= 1
1537 self.depth -= 1
1550 else:
1538 else:
1551 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1539 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1552
1540
1553 nlprint = NLprinter()
1541 nlprint = NLprinter()
1554 #----------------------------------------------------------------------------
1542 #----------------------------------------------------------------------------
1555 def all_belong(candidates,checklist):
1543 def all_belong(candidates,checklist):
1556 """Check whether a list of items ALL appear in a given list of options.
1544 """Check whether a list of items ALL appear in a given list of options.
1557
1545
1558 Returns a single 1 or 0 value."""
1546 Returns a single 1 or 0 value."""
1559
1547
1560 return 1-(0 in [x in checklist for x in candidates])
1548 return 1-(0 in [x in checklist for x in candidates])
1561
1549
1562 #----------------------------------------------------------------------------
1550 #----------------------------------------------------------------------------
1563 def sort_compare(lst1,lst2,inplace = 1):
1551 def sort_compare(lst1,lst2,inplace = 1):
1564 """Sort and compare two lists.
1552 """Sort and compare two lists.
1565
1553
1566 By default it does it in place, thus modifying the lists. Use inplace = 0
1554 By default it does it in place, thus modifying the lists. Use inplace = 0
1567 to avoid that (at the cost of temporary copy creation)."""
1555 to avoid that (at the cost of temporary copy creation)."""
1568 if not inplace:
1556 if not inplace:
1569 lst1 = lst1[:]
1557 lst1 = lst1[:]
1570 lst2 = lst2[:]
1558 lst2 = lst2[:]
1571 lst1.sort(); lst2.sort()
1559 lst1.sort(); lst2.sort()
1572 return lst1 == lst2
1560 return lst1 == lst2
1573
1561
1574 #----------------------------------------------------------------------------
1562 #----------------------------------------------------------------------------
1575 def mkdict(**kwargs):
1563 def mkdict(**kwargs):
1576 """Return a dict from a keyword list.
1564 """Return a dict from a keyword list.
1577
1565
1578 It's just syntactic sugar for making ditcionary creation more convenient:
1566 It's just syntactic sugar for making ditcionary creation more convenient:
1579 # the standard way
1567 # the standard way
1580 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1568 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1581 # a cleaner way
1569 # a cleaner way
1582 >>>data = dict(red=1, green=2, blue=3)
1570 >>>data = dict(red=1, green=2, blue=3)
1583
1571
1584 If you need more than this, look at the Struct() class."""
1572 If you need more than this, look at the Struct() class."""
1585
1573
1586 return kwargs
1574 return kwargs
1587
1575
1588 #----------------------------------------------------------------------------
1576 #----------------------------------------------------------------------------
1589 def list2dict(lst):
1577 def list2dict(lst):
1590 """Takes a list of (key,value) pairs and turns it into a dict."""
1578 """Takes a list of (key,value) pairs and turns it into a dict."""
1591
1579
1592 dic = {}
1580 dic = {}
1593 for k,v in lst: dic[k] = v
1581 for k,v in lst: dic[k] = v
1594 return dic
1582 return dic
1595
1583
1596 #----------------------------------------------------------------------------
1584 #----------------------------------------------------------------------------
1597 def list2dict2(lst,default=''):
1585 def list2dict2(lst,default=''):
1598 """Takes a list and turns it into a dict.
1586 """Takes a list and turns it into a dict.
1599 Much slower than list2dict, but more versatile. This version can take
1587 Much slower than list2dict, but more versatile. This version can take
1600 lists with sublists of arbitrary length (including sclars)."""
1588 lists with sublists of arbitrary length (including sclars)."""
1601
1589
1602 dic = {}
1590 dic = {}
1603 for elem in lst:
1591 for elem in lst:
1604 if type(elem) in (types.ListType,types.TupleType):
1592 if type(elem) in (types.ListType,types.TupleType):
1605 size = len(elem)
1593 size = len(elem)
1606 if size == 0:
1594 if size == 0:
1607 pass
1595 pass
1608 elif size == 1:
1596 elif size == 1:
1609 dic[elem] = default
1597 dic[elem] = default
1610 else:
1598 else:
1611 k,v = elem[0], elem[1:]
1599 k,v = elem[0], elem[1:]
1612 if len(v) == 1: v = v[0]
1600 if len(v) == 1: v = v[0]
1613 dic[k] = v
1601 dic[k] = v
1614 else:
1602 else:
1615 dic[elem] = default
1603 dic[elem] = default
1616 return dic
1604 return dic
1617
1605
1618 #----------------------------------------------------------------------------
1606 #----------------------------------------------------------------------------
1619 def flatten(seq):
1607 def flatten(seq):
1620 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1608 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1621
1609
1622 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1610 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1623
1611
1624 # if the x=0 isn't made, a *global* variable x is left over after calling
1612 # if the x=0 isn't made, a *global* variable x is left over after calling
1625 # this function, with the value of the last element in the return
1613 # this function, with the value of the last element in the return
1626 # list. This does seem like a bug big time to me.
1614 # list. This does seem like a bug big time to me.
1627
1615
1628 # the problem is fixed with the x=0, which seems to force the creation of
1616 # the problem is fixed with the x=0, which seems to force the creation of
1629 # a local name
1617 # a local name
1630
1618
1631 x = 0
1619 x = 0
1632 return [x for subseq in seq for x in subseq]
1620 return [x for subseq in seq for x in subseq]
1633
1621
1634 #----------------------------------------------------------------------------
1622 #----------------------------------------------------------------------------
1635 def get_slice(seq,start=0,stop=None,step=1):
1623 def get_slice(seq,start=0,stop=None,step=1):
1636 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1624 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1637 if stop == None:
1625 if stop == None:
1638 stop = len(seq)
1626 stop = len(seq)
1639 item = lambda i: seq[i]
1627 item = lambda i: seq[i]
1640 return map(item,xrange(start,stop,step))
1628 return map(item,xrange(start,stop,step))
1641
1629
1642 #----------------------------------------------------------------------------
1630 #----------------------------------------------------------------------------
1643 def chop(seq,size):
1631 def chop(seq,size):
1644 """Chop a sequence into chunks of the given size."""
1632 """Chop a sequence into chunks of the given size."""
1645 chunk = lambda i: seq[i:i+size]
1633 chunk = lambda i: seq[i:i+size]
1646 return map(chunk,xrange(0,len(seq),size))
1634 return map(chunk,xrange(0,len(seq),size))
1647
1635
1648 #----------------------------------------------------------------------------
1636 #----------------------------------------------------------------------------
1649 def with(object, **args):
1637 def with(object, **args):
1650 """Set multiple attributes for an object, similar to Pascal's with.
1638 """Set multiple attributes for an object, similar to Pascal's with.
1651
1639
1652 Example:
1640 Example:
1653 with(jim,
1641 with(jim,
1654 born = 1960,
1642 born = 1960,
1655 haircolour = 'Brown',
1643 haircolour = 'Brown',
1656 eyecolour = 'Green')
1644 eyecolour = 'Green')
1657
1645
1658 Credit: Greg Ewing, in
1646 Credit: Greg Ewing, in
1659 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1647 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1660
1648
1661 object.__dict__.update(args)
1649 object.__dict__.update(args)
1662
1650
1663 #----------------------------------------------------------------------------
1651 #----------------------------------------------------------------------------
1664 def setattr_list(obj,alist,nspace = None):
1652 def setattr_list(obj,alist,nspace = None):
1665 """Set a list of attributes for an object taken from a namespace.
1653 """Set a list of attributes for an object taken from a namespace.
1666
1654
1667 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1655 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1668 alist with their values taken from nspace, which must be a dict (something
1656 alist with their values taken from nspace, which must be a dict (something
1669 like locals() will often do) If nspace isn't given, locals() of the
1657 like locals() will often do) If nspace isn't given, locals() of the
1670 *caller* is used, so in most cases you can omit it.
1658 *caller* is used, so in most cases you can omit it.
1671
1659
1672 Note that alist can be given as a string, which will be automatically
1660 Note that alist can be given as a string, which will be automatically
1673 split into a list on whitespace. If given as a list, it must be a list of
1661 split into a list on whitespace. If given as a list, it must be a list of
1674 *strings* (the variable names themselves), not of variables."""
1662 *strings* (the variable names themselves), not of variables."""
1675
1663
1676 # this grabs the local variables from the *previous* call frame -- that is
1664 # this grabs the local variables from the *previous* call frame -- that is
1677 # the locals from the function that called setattr_list().
1665 # the locals from the function that called setattr_list().
1678 # - snipped from weave.inline()
1666 # - snipped from weave.inline()
1679 if nspace is None:
1667 if nspace is None:
1680 call_frame = sys._getframe().f_back
1668 call_frame = sys._getframe().f_back
1681 nspace = call_frame.f_locals
1669 nspace = call_frame.f_locals
1682
1670
1683 if type(alist) in StringTypes:
1671 if type(alist) in StringTypes:
1684 alist = alist.split()
1672 alist = alist.split()
1685 for attr in alist:
1673 for attr in alist:
1686 val = eval(attr,nspace)
1674 val = eval(attr,nspace)
1687 setattr(obj,attr,val)
1675 setattr(obj,attr,val)
1688
1676
1689 #----------------------------------------------------------------------------
1677 #----------------------------------------------------------------------------
1690 def getattr_list(obj,alist,*args):
1678 def getattr_list(obj,alist,*args):
1691 """getattr_list(obj,alist[, default]) -> attribute list.
1679 """getattr_list(obj,alist[, default]) -> attribute list.
1692
1680
1693 Get a list of named attributes for an object. When a default argument is
1681 Get a list of named attributes for an object. When a default argument is
1694 given, it is returned when the attribute doesn't exist; without it, an
1682 given, it is returned when the attribute doesn't exist; without it, an
1695 exception is raised in that case.
1683 exception is raised in that case.
1696
1684
1697 Note that alist can be given as a string, which will be automatically
1685 Note that alist can be given as a string, which will be automatically
1698 split into a list on whitespace. If given as a list, it must be a list of
1686 split into a list on whitespace. If given as a list, it must be a list of
1699 *strings* (the variable names themselves), not of variables."""
1687 *strings* (the variable names themselves), not of variables."""
1700
1688
1701 if type(alist) in StringTypes:
1689 if type(alist) in StringTypes:
1702 alist = alist.split()
1690 alist = alist.split()
1703 if args:
1691 if args:
1704 if len(args)==1:
1692 if len(args)==1:
1705 default = args[0]
1693 default = args[0]
1706 return map(lambda attr: getattr(obj,attr,default),alist)
1694 return map(lambda attr: getattr(obj,attr,default),alist)
1707 else:
1695 else:
1708 raise ValueError,'getattr_list() takes only one optional argument'
1696 raise ValueError,'getattr_list() takes only one optional argument'
1709 else:
1697 else:
1710 return map(lambda attr: getattr(obj,attr),alist)
1698 return map(lambda attr: getattr(obj,attr),alist)
1711
1699
1712 #----------------------------------------------------------------------------
1700 #----------------------------------------------------------------------------
1713 def map_method(method,object_list,*argseq,**kw):
1701 def map_method(method,object_list,*argseq,**kw):
1714 """map_method(method,object_list,*args,**kw) -> list
1702 """map_method(method,object_list,*args,**kw) -> list
1715
1703
1716 Return a list of the results of applying the methods to the items of the
1704 Return a list of the results of applying the methods to the items of the
1717 argument sequence(s). If more than one sequence is given, the method is
1705 argument sequence(s). If more than one sequence is given, the method is
1718 called with an argument list consisting of the corresponding item of each
1706 called with an argument list consisting of the corresponding item of each
1719 sequence. All sequences must be of the same length.
1707 sequence. All sequences must be of the same length.
1720
1708
1721 Keyword arguments are passed verbatim to all objects called.
1709 Keyword arguments are passed verbatim to all objects called.
1722
1710
1723 This is Python code, so it's not nearly as fast as the builtin map()."""
1711 This is Python code, so it's not nearly as fast as the builtin map()."""
1724
1712
1725 out_list = []
1713 out_list = []
1726 idx = 0
1714 idx = 0
1727 for object in object_list:
1715 for object in object_list:
1728 try:
1716 try:
1729 handler = getattr(object, method)
1717 handler = getattr(object, method)
1730 except AttributeError:
1718 except AttributeError:
1731 out_list.append(None)
1719 out_list.append(None)
1732 else:
1720 else:
1733 if argseq:
1721 if argseq:
1734 args = map(lambda lst:lst[idx],argseq)
1722 args = map(lambda lst:lst[idx],argseq)
1735 #print 'ob',object,'hand',handler,'ar',args # dbg
1723 #print 'ob',object,'hand',handler,'ar',args # dbg
1736 out_list.append(handler(args,**kw))
1724 out_list.append(handler(args,**kw))
1737 else:
1725 else:
1738 out_list.append(handler(**kw))
1726 out_list.append(handler(**kw))
1739 idx += 1
1727 idx += 1
1740 return out_list
1728 return out_list
1741
1729
1742 #----------------------------------------------------------------------------
1730 #----------------------------------------------------------------------------
1743 def import_fail_info(mod_name,fns=None):
1731 def import_fail_info(mod_name,fns=None):
1744 """Inform load failure for a module."""
1732 """Inform load failure for a module."""
1745
1733
1746 if fns == None:
1734 if fns == None:
1747 warn("Loading of %s failed.\n" % (mod_name,))
1735 warn("Loading of %s failed.\n" % (mod_name,))
1748 else:
1736 else:
1749 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1737 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1750
1738
1751 #----------------------------------------------------------------------------
1739 #----------------------------------------------------------------------------
1752 # Proposed popitem() extension, written as a method
1740 # Proposed popitem() extension, written as a method
1753
1741
1754 class NotGiven: pass
1742 class NotGiven: pass
1755
1743
1756 def popkey(dct,key,default=NotGiven):
1744 def popkey(dct,key,default=NotGiven):
1757 """Return dct[key] and delete dct[key].
1745 """Return dct[key] and delete dct[key].
1758
1746
1759 If default is given, return it if dct[key] doesn't exist, otherwise raise
1747 If default is given, return it if dct[key] doesn't exist, otherwise raise
1760 KeyError. """
1748 KeyError. """
1761
1749
1762 try:
1750 try:
1763 val = dct[key]
1751 val = dct[key]
1764 except KeyError:
1752 except KeyError:
1765 if default is NotGiven:
1753 if default is NotGiven:
1766 raise
1754 raise
1767 else:
1755 else:
1768 return default
1756 return default
1769 else:
1757 else:
1770 del dct[key]
1758 del dct[key]
1771 return val
1759 return val
1772 #*************************** end of file <genutils.py> **********************
1760 #*************************** end of file <genutils.py> **********************
1773
1761
@@ -1,2285 +1,2271 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 1098 2006-01-29 16:14:21Z vivainio $
9 $Id: iplib.py 1099 2006-01-29 21:05:57Z vivainio $
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 __future__ import generators # for 2.2 backwards-compatibility
31 from __future__ import generators # for 2.2 backwards-compatibility
32
32
33 from IPython import Release
33 from IPython import Release
34 __author__ = '%s <%s>\n%s <%s>' % \
34 __author__ = '%s <%s>\n%s <%s>' % \
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 __license__ = Release.license
36 __license__ = Release.license
37 __version__ = Release.version
37 __version__ = Release.version
38
38
39 # Python standard modules
39 # Python standard modules
40 import __main__
40 import __main__
41 import __builtin__
41 import __builtin__
42 import StringIO
42 import StringIO
43 import bdb
43 import bdb
44 import cPickle as pickle
44 import cPickle as pickle
45 import codeop
45 import codeop
46 import exceptions
46 import exceptions
47 import glob
47 import glob
48 import inspect
48 import inspect
49 import keyword
49 import keyword
50 import new
50 import new
51 import os
51 import os
52 import pdb
52 import pdb
53 import pydoc
53 import pydoc
54 import re
54 import re
55 import shutil
55 import shutil
56 import string
56 import string
57 import sys
57 import sys
58 import tempfile
58 import tempfile
59 import traceback
59 import traceback
60 import types
60 import types
61
61
62 from pprint import pprint, pformat
62 from pprint import pprint, pformat
63
63
64 # IPython's own modules
64 # IPython's own modules
65 import IPython
65 import IPython
66 from IPython import OInspect,PyColorize,ultraTB
66 from IPython import OInspect,PyColorize,ultraTB
67 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
68 from IPython.FakeModule import FakeModule
68 from IPython.FakeModule import FakeModule
69 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
70 from IPython.Logger import Logger
70 from IPython.Logger import Logger
71 from IPython.Magic import Magic
71 from IPython.Magic import Magic
72 from IPython.Prompts import CachedOutput
72 from IPython.Prompts import CachedOutput
73 from IPython.ipstruct import Struct
73 from IPython.ipstruct import Struct
74 from IPython.background_jobs import BackgroundJobManager
74 from IPython.background_jobs import BackgroundJobManager
75 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.usage import cmd_line_usage,interactive_usage
76 from IPython.genutils import *
76 from IPython.genutils import *
77 import IPython.ipapi
77 import IPython.ipapi
78
78
79 # Globals
79 # Globals
80
80
81 # store the builtin raw_input globally, and use this always, in case user code
81 # store the builtin raw_input globally, and use this always, in case user code
82 # overwrites it (like wx.py.PyShell does)
82 # overwrites it (like wx.py.PyShell does)
83 raw_input_original = raw_input
83 raw_input_original = raw_input
84
84
85 # compiled regexps for autoindent management
85 # compiled regexps for autoindent management
86 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87
87
88
88
89 #****************************************************************************
89 #****************************************************************************
90 # Some utility function definitions
90 # Some utility function definitions
91
91
92 ini_spaces_re = re.compile(r'^(\s+)')
92 ini_spaces_re = re.compile(r'^(\s+)')
93
93
94 def num_ini_spaces(strng):
94 def num_ini_spaces(strng):
95 """Return the number of initial spaces in a string"""
95 """Return the number of initial spaces in a string"""
96
96
97 ini_spaces = ini_spaces_re.match(strng)
97 ini_spaces = ini_spaces_re.match(strng)
98 if ini_spaces:
98 if ini_spaces:
99 return ini_spaces.end()
99 return ini_spaces.end()
100 else:
100 else:
101 return 0
101 return 0
102
102
103 def softspace(file, newvalue):
103 def softspace(file, newvalue):
104 """Copied from code.py, to remove the dependency"""
104 """Copied from code.py, to remove the dependency"""
105
105
106 oldvalue = 0
106 oldvalue = 0
107 try:
107 try:
108 oldvalue = file.softspace
108 oldvalue = file.softspace
109 except AttributeError:
109 except AttributeError:
110 pass
110 pass
111 try:
111 try:
112 file.softspace = newvalue
112 file.softspace = newvalue
113 except (AttributeError, TypeError):
113 except (AttributeError, TypeError):
114 # "attribute-less object" or "read-only attributes"
114 # "attribute-less object" or "read-only attributes"
115 pass
115 pass
116 return oldvalue
116 return oldvalue
117
117
118
118
119 #****************************************************************************
119 #****************************************************************************
120 # Local use exceptions
120 # Local use exceptions
121 class SpaceInInput(exceptions.Exception): pass
121 class SpaceInInput(exceptions.Exception): pass
122
122
123
123
124 #****************************************************************************
124 #****************************************************************************
125 # Local use classes
125 # Local use classes
126 class Bunch: pass
126 class Bunch: pass
127
127
128 class Undefined: pass
128 class Undefined: pass
129
129
130 class InputList(list):
130 class InputList(list):
131 """Class to store user input.
131 """Class to store user input.
132
132
133 It's basically a list, but slices return a string instead of a list, thus
133 It's basically a list, but slices return a string instead of a list, thus
134 allowing things like (assuming 'In' is an instance):
134 allowing things like (assuming 'In' is an instance):
135
135
136 exec In[4:7]
136 exec In[4:7]
137
137
138 or
138 or
139
139
140 exec In[5:9] + In[14] + In[21:25]"""
140 exec In[5:9] + In[14] + In[21:25]"""
141
141
142 def __getslice__(self,i,j):
142 def __getslice__(self,i,j):
143 return ''.join(list.__getslice__(self,i,j))
143 return ''.join(list.__getslice__(self,i,j))
144
144
145 class SyntaxTB(ultraTB.ListTB):
145 class SyntaxTB(ultraTB.ListTB):
146 """Extension which holds some state: the last exception value"""
146 """Extension which holds some state: the last exception value"""
147
147
148 def __init__(self,color_scheme = 'NoColor'):
148 def __init__(self,color_scheme = 'NoColor'):
149 ultraTB.ListTB.__init__(self,color_scheme)
149 ultraTB.ListTB.__init__(self,color_scheme)
150 self.last_syntax_error = None
150 self.last_syntax_error = None
151
151
152 def __call__(self, etype, value, elist):
152 def __call__(self, etype, value, elist):
153 self.last_syntax_error = value
153 self.last_syntax_error = value
154 ultraTB.ListTB.__call__(self,etype,value,elist)
154 ultraTB.ListTB.__call__(self,etype,value,elist)
155
155
156 def clear_err_state(self):
156 def clear_err_state(self):
157 """Return the current error state and clear it"""
157 """Return the current error state and clear it"""
158 e = self.last_syntax_error
158 e = self.last_syntax_error
159 self.last_syntax_error = None
159 self.last_syntax_error = None
160 return e
160 return e
161
161
162 #****************************************************************************
162 #****************************************************************************
163 # Main IPython class
163 # Main IPython class
164
164
165 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
165 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
166 # until a full rewrite is made. I've cleaned all cross-class uses of
166 # until a full rewrite is made. I've cleaned all cross-class uses of
167 # attributes and methods, but too much user code out there relies on the
167 # attributes and methods, but too much user code out there relies on the
168 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
168 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
169 #
169 #
170 # But at least now, all the pieces have been separated and we could, in
170 # But at least now, all the pieces have been separated and we could, in
171 # principle, stop using the mixin. This will ease the transition to the
171 # principle, stop using the mixin. This will ease the transition to the
172 # chainsaw branch.
172 # chainsaw branch.
173
173
174 # For reference, the following is the list of 'self.foo' uses in the Magic
174 # For reference, the following is the list of 'self.foo' uses in the Magic
175 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
175 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
176 # class, to prevent clashes.
176 # class, to prevent clashes.
177
177
178 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
178 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
179 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
179 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
180 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
180 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
181 # 'self.value']
181 # 'self.value']
182
182
183 class InteractiveShell(object,Magic):
183 class InteractiveShell(object,Magic):
184 """An enhanced console for Python."""
184 """An enhanced console for Python."""
185
185
186 # class attribute to indicate whether the class supports threads or not.
186 # class attribute to indicate whether the class supports threads or not.
187 # Subclasses with thread support should override this as needed.
187 # Subclasses with thread support should override this as needed.
188 isthreaded = False
188 isthreaded = False
189
189
190 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
190 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
191 user_ns = None,user_global_ns=None,banner2='',
191 user_ns = None,user_global_ns=None,banner2='',
192 custom_exceptions=((),None),embedded=False):
192 custom_exceptions=((),None),embedded=False):
193
193
194 # log system
194 # log system
195 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
195 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
196
196
197 # Produce a public API instance
197 # Produce a public API instance
198
198
199 self.api = IPython.ipapi.IPApi(self)
199 self.api = IPython.ipapi.IPApi(self)
200
200
201 # some minimal strict typechecks. For some core data structures, I
201 # some minimal strict typechecks. For some core data structures, I
202 # want actual basic python types, not just anything that looks like
202 # want actual basic python types, not just anything that looks like
203 # one. This is especially true for namespaces.
203 # one. This is especially true for namespaces.
204 for ns in (user_ns,user_global_ns):
204 for ns in (user_ns,user_global_ns):
205 if ns is not None and type(ns) != types.DictType:
205 if ns is not None and type(ns) != types.DictType:
206 raise TypeError,'namespace must be a dictionary'
206 raise TypeError,'namespace must be a dictionary'
207
207
208 # Job manager (for jobs run as background threads)
208 # Job manager (for jobs run as background threads)
209 self.jobs = BackgroundJobManager()
209 self.jobs = BackgroundJobManager()
210
210
211 # track which builtins we add, so we can clean up later
211 # track which builtins we add, so we can clean up later
212 self.builtins_added = {}
212 self.builtins_added = {}
213 # This method will add the necessary builtins for operation, but
213 # This method will add the necessary builtins for operation, but
214 # tracking what it did via the builtins_added dict.
214 # tracking what it did via the builtins_added dict.
215 self.add_builtins()
215 self.add_builtins()
216
216
217 # Do the intuitively correct thing for quit/exit: we remove the
217 # Do the intuitively correct thing for quit/exit: we remove the
218 # builtins if they exist, and our own magics will deal with this
218 # builtins if they exist, and our own magics will deal with this
219 try:
219 try:
220 del __builtin__.exit, __builtin__.quit
220 del __builtin__.exit, __builtin__.quit
221 except AttributeError:
221 except AttributeError:
222 pass
222 pass
223
223
224 # Store the actual shell's name
224 # Store the actual shell's name
225 self.name = name
225 self.name = name
226
226
227 # We need to know whether the instance is meant for embedding, since
227 # We need to know whether the instance is meant for embedding, since
228 # global/local namespaces need to be handled differently in that case
228 # global/local namespaces need to be handled differently in that case
229 self.embedded = embedded
229 self.embedded = embedded
230
230
231 # command compiler
231 # command compiler
232 self.compile = codeop.CommandCompiler()
232 self.compile = codeop.CommandCompiler()
233
233
234 # User input buffer
234 # User input buffer
235 self.buffer = []
235 self.buffer = []
236
236
237 # Default name given in compilation of code
237 # Default name given in compilation of code
238 self.filename = '<ipython console>'
238 self.filename = '<ipython console>'
239
239
240 # Make an empty namespace, which extension writers can rely on both
240 # Make an empty namespace, which extension writers can rely on both
241 # existing and NEVER being used by ipython itself. This gives them a
241 # existing and NEVER being used by ipython itself. This gives them a
242 # convenient location for storing additional information and state
242 # convenient location for storing additional information and state
243 # their extensions may require, without fear of collisions with other
243 # their extensions may require, without fear of collisions with other
244 # ipython names that may develop later.
244 # ipython names that may develop later.
245 self.meta = Struct()
245 self.meta = Struct()
246
246
247 # Create the namespace where the user will operate. user_ns is
247 # Create the namespace where the user will operate. user_ns is
248 # normally the only one used, and it is passed to the exec calls as
248 # normally the only one used, and it is passed to the exec calls as
249 # the locals argument. But we do carry a user_global_ns namespace
249 # the locals argument. But we do carry a user_global_ns namespace
250 # given as the exec 'globals' argument, This is useful in embedding
250 # given as the exec 'globals' argument, This is useful in embedding
251 # situations where the ipython shell opens in a context where the
251 # situations where the ipython shell opens in a context where the
252 # distinction between locals and globals is meaningful.
252 # distinction between locals and globals is meaningful.
253
253
254 # FIXME. For some strange reason, __builtins__ is showing up at user
254 # FIXME. For some strange reason, __builtins__ is showing up at user
255 # level as a dict instead of a module. This is a manual fix, but I
255 # level as a dict instead of a module. This is a manual fix, but I
256 # should really track down where the problem is coming from. Alex
256 # should really track down where the problem is coming from. Alex
257 # Schmolck reported this problem first.
257 # Schmolck reported this problem first.
258
258
259 # A useful post by Alex Martelli on this topic:
259 # A useful post by Alex Martelli on this topic:
260 # Re: inconsistent value from __builtins__
260 # Re: inconsistent value from __builtins__
261 # Von: Alex Martelli <aleaxit@yahoo.com>
261 # Von: Alex Martelli <aleaxit@yahoo.com>
262 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
262 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
263 # Gruppen: comp.lang.python
263 # Gruppen: comp.lang.python
264
264
265 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
265 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
266 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
266 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
267 # > <type 'dict'>
267 # > <type 'dict'>
268 # > >>> print type(__builtins__)
268 # > >>> print type(__builtins__)
269 # > <type 'module'>
269 # > <type 'module'>
270 # > Is this difference in return value intentional?
270 # > Is this difference in return value intentional?
271
271
272 # Well, it's documented that '__builtins__' can be either a dictionary
272 # Well, it's documented that '__builtins__' can be either a dictionary
273 # or a module, and it's been that way for a long time. Whether it's
273 # or a module, and it's been that way for a long time. Whether it's
274 # intentional (or sensible), I don't know. In any case, the idea is
274 # intentional (or sensible), I don't know. In any case, the idea is
275 # that if you need to access the built-in namespace directly, you
275 # that if you need to access the built-in namespace directly, you
276 # should start with "import __builtin__" (note, no 's') which will
276 # should start with "import __builtin__" (note, no 's') which will
277 # definitely give you a module. Yeah, it's somewhat confusing:-(.
277 # definitely give you a module. Yeah, it's somewhat confusing:-(.
278
278
279 if user_ns is None:
279 if user_ns is None:
280 # Set __name__ to __main__ to better match the behavior of the
280 # Set __name__ to __main__ to better match the behavior of the
281 # normal interpreter.
281 # normal interpreter.
282 user_ns = {'__name__' :'__main__',
282 user_ns = {'__name__' :'__main__',
283 '__builtins__' : __builtin__,
283 '__builtins__' : __builtin__,
284 }
284 }
285
285
286 if user_global_ns is None:
286 if user_global_ns is None:
287 user_global_ns = {}
287 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 # Set all default hooks, defined in the IPython.hooks module.
408 # Set all default hooks, defined in the IPython.hooks module.
409 hooks = IPython.hooks
409 hooks = IPython.hooks
410 for hook_name in hooks.__all__:
410 for hook_name in hooks.__all__:
411 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
411 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
412 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
412 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
413 #print "bound hook",hook_name
413 #print "bound hook",hook_name
414
414
415 # Flag to mark unconditional exit
415 # Flag to mark unconditional exit
416 self.exit_now = False
416 self.exit_now = False
417
417
418 self.usage_min = """\
418 self.usage_min = """\
419 An enhanced console for Python.
419 An enhanced console for Python.
420 Some of its features are:
420 Some of its features are:
421 - Readline support if the readline library is present.
421 - Readline support if the readline library is present.
422 - Tab completion in the local namespace.
422 - Tab completion in the local namespace.
423 - Logging of input, see command-line options.
423 - Logging of input, see command-line options.
424 - System shell escape via ! , eg !ls.
424 - System shell escape via ! , eg !ls.
425 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
425 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
426 - Keeps track of locally defined variables via %who, %whos.
426 - Keeps track of locally defined variables via %who, %whos.
427 - Show object information with a ? eg ?x or x? (use ?? for more info).
427 - Show object information with a ? eg ?x or x? (use ?? for more info).
428 """
428 """
429 if usage: self.usage = usage
429 if usage: self.usage = usage
430 else: self.usage = self.usage_min
430 else: self.usage = self.usage_min
431
431
432 # Storage
432 # Storage
433 self.rc = rc # This will hold all configuration information
433 self.rc = rc # This will hold all configuration information
434 self.pager = 'less'
434 self.pager = 'less'
435 # temporary files used for various purposes. Deleted at exit.
435 # temporary files used for various purposes. Deleted at exit.
436 self.tempfiles = []
436 self.tempfiles = []
437
437
438 # Keep track of readline usage (later set by init_readline)
438 # Keep track of readline usage (later set by init_readline)
439 self.has_readline = False
439 self.has_readline = False
440
440
441 # template for logfile headers. It gets resolved at runtime by the
441 # template for logfile headers. It gets resolved at runtime by the
442 # logstart method.
442 # logstart method.
443 self.loghead_tpl = \
443 self.loghead_tpl = \
444 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
444 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
445 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
445 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
446 #log# opts = %s
446 #log# opts = %s
447 #log# args = %s
447 #log# args = %s
448 #log# It is safe to make manual edits below here.
448 #log# It is safe to make manual edits below here.
449 #log#-----------------------------------------------------------------------
449 #log#-----------------------------------------------------------------------
450 """
450 """
451 # for pushd/popd management
451 # for pushd/popd management
452 try:
452 try:
453 self.home_dir = get_home_dir()
453 self.home_dir = get_home_dir()
454 except HomeDirError,msg:
454 except HomeDirError,msg:
455 fatal(msg)
455 fatal(msg)
456
456
457 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
457 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
458
458
459 # Functions to call the underlying shell.
459 # Functions to call the underlying shell.
460
460
461 # utility to expand user variables via Itpl
461 # utility to expand user variables via Itpl
462 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
462 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
463 self.user_ns))
463 self.user_ns))
464 # The first is similar to os.system, but it doesn't return a value,
464 # The first is similar to os.system, but it doesn't return a value,
465 # and it allows interpolation of variables in the user's namespace.
465 # and it allows interpolation of variables in the user's namespace.
466 self.system = lambda cmd: shell(self.var_expand(cmd),
466 self.system = lambda cmd: shell(self.var_expand(cmd),
467 header='IPython system call: ',
467 header='IPython system call: ',
468 verbose=self.rc.system_verbose)
468 verbose=self.rc.system_verbose)
469 # These are for getoutput and getoutputerror:
469 # These are for getoutput and getoutputerror:
470 self.getoutput = lambda cmd: \
470 self.getoutput = lambda cmd: \
471 getoutput(self.var_expand(cmd),
471 getoutput(self.var_expand(cmd),
472 header='IPython system call: ',
472 header='IPython system call: ',
473 verbose=self.rc.system_verbose)
473 verbose=self.rc.system_verbose)
474 self.getoutputerror = lambda cmd: \
474 self.getoutputerror = lambda cmd: \
475 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
475 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
476 self.user_ns)),
476 self.user_ns)),
477 header='IPython system call: ',
477 header='IPython system call: ',
478 verbose=self.rc.system_verbose)
478 verbose=self.rc.system_verbose)
479
479
480 # RegExp for splitting line contents into pre-char//first
480 # RegExp for splitting line contents into pre-char//first
481 # word-method//rest. For clarity, each group in on one line.
481 # word-method//rest. For clarity, each group in on one line.
482
482
483 # WARNING: update the regexp if the above escapes are changed, as they
483 # WARNING: update the regexp if the above escapes are changed, as they
484 # are hardwired in.
484 # are hardwired in.
485
485
486 # Don't get carried away with trying to make the autocalling catch too
486 # Don't get carried away with trying to make the autocalling catch too
487 # much: it's better to be conservative rather than to trigger hidden
487 # much: it's better to be conservative rather than to trigger hidden
488 # evals() somewhere and end up causing side effects.
488 # evals() somewhere and end up causing side effects.
489
489
490 self.line_split = re.compile(r'^([\s*,;/])'
490 self.line_split = re.compile(r'^([\s*,;/])'
491 r'([\?\w\.]+\w*\s*)'
491 r'([\?\w\.]+\w*\s*)'
492 r'(\(?.*$)')
492 r'(\(?.*$)')
493
493
494 # Original re, keep around for a while in case changes break something
494 # Original re, keep around for a while in case changes break something
495 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
495 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
496 # r'(\s*[\?\w\.]+\w*\s*)'
496 # r'(\s*[\?\w\.]+\w*\s*)'
497 # r'(\(?.*$)')
497 # r'(\(?.*$)')
498
498
499 # RegExp to identify potential function names
499 # RegExp to identify potential function names
500 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
500 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
501
501
502 # RegExp to exclude strings with this start from autocalling. In
502 # RegExp to exclude strings with this start from autocalling. In
503 # particular, all binary operators should be excluded, so that if foo
503 # particular, all binary operators should be excluded, so that if foo
504 # is callable, foo OP bar doesn't become foo(OP bar), which is
504 # is callable, foo OP bar doesn't become foo(OP bar), which is
505 # invalid. The characters '!=()' don't need to be checked for, as the
505 # invalid. The characters '!=()' don't need to be checked for, as the
506 # _prefilter routine explicitely does so, to catch direct calls and
506 # _prefilter routine explicitely does so, to catch direct calls and
507 # rebindings of existing names.
507 # rebindings of existing names.
508
508
509 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
509 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
510 # it affects the rest of the group in square brackets.
510 # it affects the rest of the group in square brackets.
511 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
511 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
512 '|^is |^not |^in |^and |^or ')
512 '|^is |^not |^in |^and |^or ')
513
513
514 # try to catch also methods for stuff in lists/tuples/dicts: off
514 # try to catch also methods for stuff in lists/tuples/dicts: off
515 # (experimental). For this to work, the line_split regexp would need
515 # (experimental). For this to work, the line_split regexp would need
516 # to be modified so it wouldn't break things at '['. That line is
516 # to be modified so it wouldn't break things at '['. That line is
517 # nasty enough that I shouldn't change it until I can test it _well_.
517 # nasty enough that I shouldn't change it until I can test it _well_.
518 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
518 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
519
519
520 # keep track of where we started running (mainly for crash post-mortem)
520 # keep track of where we started running (mainly for crash post-mortem)
521 self.starting_dir = os.getcwd()
521 self.starting_dir = os.getcwd()
522
522
523 # Various switches which can be set
523 # Various switches which can be set
524 self.CACHELENGTH = 5000 # this is cheap, it's just text
524 self.CACHELENGTH = 5000 # this is cheap, it's just text
525 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
525 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
526 self.banner2 = banner2
526 self.banner2 = banner2
527
527
528 # TraceBack handlers:
528 # TraceBack handlers:
529
529
530 # Syntax error handler.
530 # Syntax error handler.
531 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
531 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
532
532
533 # The interactive one is initialized with an offset, meaning we always
533 # The interactive one is initialized with an offset, meaning we always
534 # want to remove the topmost item in the traceback, which is our own
534 # want to remove the topmost item in the traceback, which is our own
535 # internal code. Valid modes: ['Plain','Context','Verbose']
535 # internal code. Valid modes: ['Plain','Context','Verbose']
536 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
536 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
537 color_scheme='NoColor',
537 color_scheme='NoColor',
538 tb_offset = 1)
538 tb_offset = 1)
539
539
540 # IPython itself shouldn't crash. This will produce a detailed
540 # IPython itself shouldn't crash. This will produce a detailed
541 # post-mortem if it does. But we only install the crash handler for
541 # post-mortem if it does. But we only install the crash handler for
542 # non-threaded shells, the threaded ones use a normal verbose reporter
542 # non-threaded shells, the threaded ones use a normal verbose reporter
543 # and lose the crash handler. This is because exceptions in the main
543 # and lose the crash handler. This is because exceptions in the main
544 # thread (such as in GUI code) propagate directly to sys.excepthook,
544 # thread (such as in GUI code) propagate directly to sys.excepthook,
545 # and there's no point in printing crash dumps for every user exception.
545 # and there's no point in printing crash dumps for every user exception.
546 if self.isthreaded:
546 if self.isthreaded:
547 sys.excepthook = ultraTB.FormattedTB()
547 sys.excepthook = ultraTB.FormattedTB()
548 else:
548 else:
549 from IPython import CrashHandler
549 from IPython import CrashHandler
550 sys.excepthook = CrashHandler.CrashHandler(self)
550 sys.excepthook = CrashHandler.CrashHandler(self)
551
551
552 # The instance will store a pointer to this, so that runtime code
552 # The instance will store a pointer to this, so that runtime code
553 # (such as magics) can access it. This is because during the
553 # (such as magics) can access it. This is because during the
554 # read-eval loop, it gets temporarily overwritten (to deal with GUI
554 # read-eval loop, it gets temporarily overwritten (to deal with GUI
555 # frameworks).
555 # frameworks).
556 self.sys_excepthook = sys.excepthook
556 self.sys_excepthook = sys.excepthook
557
557
558 # and add any custom exception handlers the user may have specified
558 # and add any custom exception handlers the user may have specified
559 self.set_custom_exc(*custom_exceptions)
559 self.set_custom_exc(*custom_exceptions)
560
560
561 # Object inspector
561 # Object inspector
562 self.inspector = OInspect.Inspector(OInspect.InspectColors,
562 self.inspector = OInspect.Inspector(OInspect.InspectColors,
563 PyColorize.ANSICodeColors,
563 PyColorize.ANSICodeColors,
564 'NoColor')
564 'NoColor')
565 # indentation management
565 # indentation management
566 self.autoindent = False
566 self.autoindent = False
567 self.indent_current_nsp = 0
567 self.indent_current_nsp = 0
568
568
569 # Make some aliases automatically
569 # Make some aliases automatically
570 # Prepare list of shell aliases to auto-define
570 # Prepare list of shell aliases to auto-define
571 if os.name == 'posix':
571 if os.name == 'posix':
572 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
572 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
573 'mv mv -i','rm rm -i','cp cp -i',
573 'mv mv -i','rm rm -i','cp cp -i',
574 'cat cat','less less','clear clear',
574 'cat cat','less less','clear clear',
575 # a better ls
575 # a better ls
576 'ls ls -F',
576 'ls ls -F',
577 # long ls
577 # long ls
578 'll ls -lF',
578 'll ls -lF',
579 # color ls
579 # color ls
580 'lc ls -F -o --color',
580 'lc ls -F -o --color',
581 # ls normal files only
581 # ls normal files only
582 'lf ls -F -o --color %l | grep ^-',
582 'lf ls -F -o --color %l | grep ^-',
583 # ls symbolic links
583 # ls symbolic links
584 'lk ls -F -o --color %l | grep ^l',
584 'lk ls -F -o --color %l | grep ^l',
585 # directories or links to directories,
585 # directories or links to directories,
586 'ldir ls -F -o --color %l | grep /$',
586 'ldir ls -F -o --color %l | grep /$',
587 # things which are executable
587 # things which are executable
588 'lx ls -F -o --color %l | grep ^-..x',
588 'lx ls -F -o --color %l | grep ^-..x',
589 )
589 )
590 elif os.name in ['nt','dos']:
590 elif os.name in ['nt','dos']:
591 auto_alias = ('dir dir /on', 'ls dir /on',
591 auto_alias = ('dir dir /on', 'ls dir /on',
592 'ddir dir /ad /on', 'ldir dir /ad /on',
592 'ddir dir /ad /on', 'ldir dir /ad /on',
593 'mkdir mkdir','rmdir rmdir','echo echo',
593 'mkdir mkdir','rmdir rmdir','echo echo',
594 'ren ren','cls cls','copy copy')
594 'ren ren','cls cls','copy copy')
595 else:
595 else:
596 auto_alias = ()
596 auto_alias = ()
597 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
597 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
598 # Call the actual (public) initializer
598 # Call the actual (public) initializer
599 self.init_auto_alias()
599 self.init_auto_alias()
600 # end __init__
600 # end __init__
601
601
602 def post_config_initialization(self):
602 def post_config_initialization(self):
603 """Post configuration init method
603 """Post configuration init method
604
604
605 This is called after the configuration files have been processed to
605 This is called after the configuration files have been processed to
606 'finalize' the initialization."""
606 'finalize' the initialization."""
607
607
608 rc = self.rc
608 rc = self.rc
609
609
610 # Load readline proper
610 # Load readline proper
611 if rc.readline:
611 if rc.readline:
612 self.init_readline()
612 self.init_readline()
613
613
614 # local shortcut, this is used a LOT
614 # local shortcut, this is used a LOT
615 self.log = self.logger.log
615 self.log = self.logger.log
616
616
617 # Initialize cache, set in/out prompts and printing system
617 # Initialize cache, set in/out prompts and printing system
618 self.outputcache = CachedOutput(self,
618 self.outputcache = CachedOutput(self,
619 rc.cache_size,
619 rc.cache_size,
620 rc.pprint,
620 rc.pprint,
621 input_sep = rc.separate_in,
621 input_sep = rc.separate_in,
622 output_sep = rc.separate_out,
622 output_sep = rc.separate_out,
623 output_sep2 = rc.separate_out2,
623 output_sep2 = rc.separate_out2,
624 ps1 = rc.prompt_in1,
624 ps1 = rc.prompt_in1,
625 ps2 = rc.prompt_in2,
625 ps2 = rc.prompt_in2,
626 ps_out = rc.prompt_out,
626 ps_out = rc.prompt_out,
627 pad_left = rc.prompts_pad_left)
627 pad_left = rc.prompts_pad_left)
628
628
629 # user may have over-ridden the default print hook:
629 # user may have over-ridden the default print hook:
630 try:
630 try:
631 self.outputcache.__class__.display = self.hooks.display
631 self.outputcache.__class__.display = self.hooks.display
632 except AttributeError:
632 except AttributeError:
633 pass
633 pass
634
634
635 # I don't like assigning globally to sys, because it means when embedding
635 # I don't like assigning globally to sys, because it means when embedding
636 # instances, each embedded instance overrides the previous choice. But
636 # instances, each embedded instance overrides the previous choice. But
637 # sys.displayhook seems to be called internally by exec, so I don't see a
637 # sys.displayhook seems to be called internally by exec, so I don't see a
638 # way around it.
638 # way around it.
639 sys.displayhook = self.outputcache
639 sys.displayhook = self.outputcache
640
640
641 # Set user colors (don't do it in the constructor above so that it
641 # Set user colors (don't do it in the constructor above so that it
642 # doesn't crash if colors option is invalid)
642 # doesn't crash if colors option is invalid)
643 self.magic_colors(rc.colors)
643 self.magic_colors(rc.colors)
644
644
645 # Set calling of pdb on exceptions
645 # Set calling of pdb on exceptions
646 self.call_pdb = rc.pdb
646 self.call_pdb = rc.pdb
647
647
648 # Load user aliases
648 # Load user aliases
649 for alias in rc.alias:
649 for alias in rc.alias:
650 self.magic_alias(alias)
650 self.magic_alias(alias)
651
651
652 # dynamic data that survives through sessions
652 # dynamic data that survives through sessions
653 # XXX make the filename a config option?
653 # XXX make the filename a config option?
654 persist_base = 'persist'
654 persist_base = 'persist'
655 if rc.profile:
655 if rc.profile:
656 persist_base += '_%s' % rc.profile
656 persist_base += '_%s' % rc.profile
657 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
657 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
658
658
659 try:
659 try:
660 self.persist = pickle.load(file(self.persist_fname))
660 self.persist = pickle.load(file(self.persist_fname))
661 except:
661 except:
662 self.persist = {}
662 self.persist = {}
663
663
664
664
665 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
665 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
666 try:
666 try:
667 obj = pickle.loads(value)
667 obj = pickle.loads(value)
668 except:
668 except:
669
669
670 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
670 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
671 print "The error was:",sys.exc_info()[0]
671 print "The error was:",sys.exc_info()[0]
672 continue
672 continue
673
673
674
674
675 self.user_ns[key] = obj
675 self.user_ns[key] = obj
676
676
677 def add_builtins(self):
677 def add_builtins(self):
678 """Store ipython references into the builtin namespace.
678 """Store ipython references into the builtin namespace.
679
679
680 Some parts of ipython operate via builtins injected here, which hold a
680 Some parts of ipython operate via builtins injected here, which hold a
681 reference to IPython itself."""
681 reference to IPython itself."""
682
682
683 # TODO: deprecate all except _ip; 'jobs' should be installed
683 # TODO: deprecate all except _ip; 'jobs' should be installed
684 # by an extension and the rest are under _ip
684 # by an extension and the rest are under _ip
685 builtins_new = dict(__IPYTHON__ = self,
685 builtins_new = dict(__IPYTHON__ = self,
686 ip_set_hook = self.set_hook,
686 ip_set_hook = self.set_hook,
687 jobs = self.jobs,
687 jobs = self.jobs,
688 ipmagic = self.ipmagic,
688 ipmagic = self.ipmagic,
689 ipalias = self.ipalias,
689 ipalias = self.ipalias,
690 ipsystem = self.ipsystem,
690 ipsystem = self.ipsystem,
691 _ip = self.api
691 _ip = self.api
692 )
692 )
693 for biname,bival in builtins_new.items():
693 for biname,bival in builtins_new.items():
694 try:
694 try:
695 # store the orignal value so we can restore it
695 # store the orignal value so we can restore it
696 self.builtins_added[biname] = __builtin__.__dict__[biname]
696 self.builtins_added[biname] = __builtin__.__dict__[biname]
697 except KeyError:
697 except KeyError:
698 # or mark that it wasn't defined, and we'll just delete it at
698 # or mark that it wasn't defined, and we'll just delete it at
699 # cleanup
699 # cleanup
700 self.builtins_added[biname] = Undefined
700 self.builtins_added[biname] = Undefined
701 __builtin__.__dict__[biname] = bival
701 __builtin__.__dict__[biname] = bival
702
702
703 # Keep in the builtins a flag for when IPython is active. We set it
703 # Keep in the builtins a flag for when IPython is active. We set it
704 # with setdefault so that multiple nested IPythons don't clobber one
704 # with setdefault so that multiple nested IPythons don't clobber one
705 # another. Each will increase its value by one upon being activated,
705 # another. Each will increase its value by one upon being activated,
706 # which also gives us a way to determine the nesting level.
706 # which also gives us a way to determine the nesting level.
707 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
707 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
708
708
709 def clean_builtins(self):
709 def clean_builtins(self):
710 """Remove any builtins which might have been added by add_builtins, or
710 """Remove any builtins which might have been added by add_builtins, or
711 restore overwritten ones to their previous values."""
711 restore overwritten ones to their previous values."""
712 for biname,bival in self.builtins_added.items():
712 for biname,bival in self.builtins_added.items():
713 if bival is Undefined:
713 if bival is Undefined:
714 del __builtin__.__dict__[biname]
714 del __builtin__.__dict__[biname]
715 else:
715 else:
716 __builtin__.__dict__[biname] = bival
716 __builtin__.__dict__[biname] = bival
717 self.builtins_added.clear()
717 self.builtins_added.clear()
718
718
719 def set_hook(self,name,hook, priority = 50):
719 def set_hook(self,name,hook, priority = 50):
720 """set_hook(name,hook) -> sets an internal IPython hook.
720 """set_hook(name,hook) -> sets an internal IPython hook.
721
721
722 IPython exposes some of its internal API as user-modifiable hooks. By
722 IPython exposes some of its internal API as user-modifiable hooks. By
723 adding your function to one of these hooks, you can modify IPython's
723 adding your function to one of these hooks, you can modify IPython's
724 behavior to call at runtime your own routines."""
724 behavior to call at runtime your own routines."""
725
725
726 # At some point in the future, this should validate the hook before it
726 # At some point in the future, this should validate the hook before it
727 # accepts it. Probably at least check that the hook takes the number
727 # accepts it. Probably at least check that the hook takes the number
728 # of args it's supposed to.
728 # of args it's supposed to.
729 dp = getattr(self.hooks, name, None)
729 dp = getattr(self.hooks, name, None)
730 if name not in IPython.hooks.__all__:
730 if name not in IPython.hooks.__all__:
731 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
731 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
732 if not dp:
732 if not dp:
733 dp = IPython.hooks.CommandChainDispatcher()
733 dp = IPython.hooks.CommandChainDispatcher()
734
734
735 f = new.instancemethod(hook,self,self.__class__)
735 f = new.instancemethod(hook,self,self.__class__)
736 try:
736 try:
737 dp.add(f,priority)
737 dp.add(f,priority)
738 except AttributeError:
738 except AttributeError:
739 # it was not commandchain, plain old func - replace
739 # it was not commandchain, plain old func - replace
740 dp = f
740 dp = f
741
741
742 setattr(self.hooks,name, dp)
742 setattr(self.hooks,name, dp)
743
743
744
744
745 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
745 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
746
746
747 def set_custom_exc(self,exc_tuple,handler):
747 def set_custom_exc(self,exc_tuple,handler):
748 """set_custom_exc(exc_tuple,handler)
748 """set_custom_exc(exc_tuple,handler)
749
749
750 Set a custom exception handler, which will be called if any of the
750 Set a custom exception handler, which will be called if any of the
751 exceptions in exc_tuple occur in the mainloop (specifically, in the
751 exceptions in exc_tuple occur in the mainloop (specifically, in the
752 runcode() method.
752 runcode() method.
753
753
754 Inputs:
754 Inputs:
755
755
756 - exc_tuple: a *tuple* of valid exceptions to call the defined
756 - exc_tuple: a *tuple* of valid exceptions to call the defined
757 handler for. It is very important that you use a tuple, and NOT A
757 handler for. It is very important that you use a tuple, and NOT A
758 LIST here, because of the way Python's except statement works. If
758 LIST here, because of the way Python's except statement works. If
759 you only want to trap a single exception, use a singleton tuple:
759 you only want to trap a single exception, use a singleton tuple:
760
760
761 exc_tuple == (MyCustomException,)
761 exc_tuple == (MyCustomException,)
762
762
763 - handler: this must be defined as a function with the following
763 - handler: this must be defined as a function with the following
764 basic interface: def my_handler(self,etype,value,tb).
764 basic interface: def my_handler(self,etype,value,tb).
765
765
766 This will be made into an instance method (via new.instancemethod)
766 This will be made into an instance method (via new.instancemethod)
767 of IPython itself, and it will be called if any of the exceptions
767 of IPython itself, and it will be called if any of the exceptions
768 listed in the exc_tuple are caught. If the handler is None, an
768 listed in the exc_tuple are caught. If the handler is None, an
769 internal basic one is used, which just prints basic info.
769 internal basic one is used, which just prints basic info.
770
770
771 WARNING: by putting in your own exception handler into IPython's main
771 WARNING: by putting in your own exception handler into IPython's main
772 execution loop, you run a very good chance of nasty crashes. This
772 execution loop, you run a very good chance of nasty crashes. This
773 facility should only be used if you really know what you are doing."""
773 facility should only be used if you really know what you are doing."""
774
774
775 assert type(exc_tuple)==type(()) , \
775 assert type(exc_tuple)==type(()) , \
776 "The custom exceptions must be given AS A TUPLE."
776 "The custom exceptions must be given AS A TUPLE."
777
777
778 def dummy_handler(self,etype,value,tb):
778 def dummy_handler(self,etype,value,tb):
779 print '*** Simple custom exception handler ***'
779 print '*** Simple custom exception handler ***'
780 print 'Exception type :',etype
780 print 'Exception type :',etype
781 print 'Exception value:',value
781 print 'Exception value:',value
782 print 'Traceback :',tb
782 print 'Traceback :',tb
783 print 'Source code :','\n'.join(self.buffer)
783 print 'Source code :','\n'.join(self.buffer)
784
784
785 if handler is None: handler = dummy_handler
785 if handler is None: handler = dummy_handler
786
786
787 self.CustomTB = new.instancemethod(handler,self,self.__class__)
787 self.CustomTB = new.instancemethod(handler,self,self.__class__)
788 self.custom_exceptions = exc_tuple
788 self.custom_exceptions = exc_tuple
789
789
790 def set_custom_completer(self,completer,pos=0):
790 def set_custom_completer(self,completer,pos=0):
791 """set_custom_completer(completer,pos=0)
791 """set_custom_completer(completer,pos=0)
792
792
793 Adds a new custom completer function.
793 Adds a new custom completer function.
794
794
795 The position argument (defaults to 0) is the index in the completers
795 The position argument (defaults to 0) is the index in the completers
796 list where you want the completer to be inserted."""
796 list where you want the completer to be inserted."""
797
797
798 newcomp = new.instancemethod(completer,self.Completer,
798 newcomp = new.instancemethod(completer,self.Completer,
799 self.Completer.__class__)
799 self.Completer.__class__)
800 self.Completer.matchers.insert(pos,newcomp)
800 self.Completer.matchers.insert(pos,newcomp)
801
801
802 def _get_call_pdb(self):
802 def _get_call_pdb(self):
803 return self._call_pdb
803 return self._call_pdb
804
804
805 def _set_call_pdb(self,val):
805 def _set_call_pdb(self,val):
806
806
807 if val not in (0,1,False,True):
807 if val not in (0,1,False,True):
808 raise ValueError,'new call_pdb value must be boolean'
808 raise ValueError,'new call_pdb value must be boolean'
809
809
810 # store value in instance
810 # store value in instance
811 self._call_pdb = val
811 self._call_pdb = val
812
812
813 # notify the actual exception handlers
813 # notify the actual exception handlers
814 self.InteractiveTB.call_pdb = val
814 self.InteractiveTB.call_pdb = val
815 if self.isthreaded:
815 if self.isthreaded:
816 try:
816 try:
817 self.sys_excepthook.call_pdb = val
817 self.sys_excepthook.call_pdb = val
818 except:
818 except:
819 warn('Failed to activate pdb for threaded exception handler')
819 warn('Failed to activate pdb for threaded exception handler')
820
820
821 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
821 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
822 'Control auto-activation of pdb at exceptions')
822 'Control auto-activation of pdb at exceptions')
823
823
824
824
825 # These special functions get installed in the builtin namespace, to
825 # These special functions get installed in the builtin namespace, to
826 # provide programmatic (pure python) access to magics, aliases and system
826 # provide programmatic (pure python) access to magics, aliases and system
827 # calls. This is important for logging, user scripting, and more.
827 # calls. This is important for logging, user scripting, and more.
828
828
829 # We are basically exposing, via normal python functions, the three
829 # We are basically exposing, via normal python functions, the three
830 # mechanisms in which ipython offers special call modes (magics for
830 # mechanisms in which ipython offers special call modes (magics for
831 # internal control, aliases for direct system access via pre-selected
831 # internal control, aliases for direct system access via pre-selected
832 # names, and !cmd for calling arbitrary system commands).
832 # names, and !cmd for calling arbitrary system commands).
833
833
834 def ipmagic(self,arg_s):
834 def ipmagic(self,arg_s):
835 """Call a magic function by name.
835 """Call a magic function by name.
836
836
837 Input: a string containing the name of the magic function to call and any
837 Input: a string containing the name of the magic function to call and any
838 additional arguments to be passed to the magic.
838 additional arguments to be passed to the magic.
839
839
840 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
840 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
841 prompt:
841 prompt:
842
842
843 In[1]: %name -opt foo bar
843 In[1]: %name -opt foo bar
844
844
845 To call a magic without arguments, simply use ipmagic('name').
845 To call a magic without arguments, simply use ipmagic('name').
846
846
847 This provides a proper Python function to call IPython's magics in any
847 This provides a proper Python function to call IPython's magics in any
848 valid Python code you can type at the interpreter, including loops and
848 valid Python code you can type at the interpreter, including loops and
849 compound statements. It is added by IPython to the Python builtin
849 compound statements. It is added by IPython to the Python builtin
850 namespace upon initialization."""
850 namespace upon initialization."""
851
851
852 args = arg_s.split(' ',1)
852 args = arg_s.split(' ',1)
853 magic_name = args[0]
853 magic_name = args[0]
854 magic_name = magic_name.lstrip(self.ESC_MAGIC)
854 magic_name = magic_name.lstrip(self.ESC_MAGIC)
855
855
856 try:
856 try:
857 magic_args = args[1]
857 magic_args = args[1]
858 except IndexError:
858 except IndexError:
859 magic_args = ''
859 magic_args = ''
860 fn = getattr(self,'magic_'+magic_name,None)
860 fn = getattr(self,'magic_'+magic_name,None)
861 if fn is None:
861 if fn is None:
862 error("Magic function `%s` not found." % magic_name)
862 error("Magic function `%s` not found." % magic_name)
863 else:
863 else:
864 magic_args = self.var_expand(magic_args)
864 magic_args = self.var_expand(magic_args)
865 return fn(magic_args)
865 return fn(magic_args)
866
866
867 def ipalias(self,arg_s):
867 def ipalias(self,arg_s):
868 """Call an alias by name.
868 """Call an alias by name.
869
869
870 Input: a string containing the name of the alias to call and any
870 Input: a string containing the name of the alias to call and any
871 additional arguments to be passed to the magic.
871 additional arguments to be passed to the magic.
872
872
873 ipalias('name -opt foo bar') is equivalent to typing at the ipython
873 ipalias('name -opt foo bar') is equivalent to typing at the ipython
874 prompt:
874 prompt:
875
875
876 In[1]: name -opt foo bar
876 In[1]: name -opt foo bar
877
877
878 To call an alias without arguments, simply use ipalias('name').
878 To call an alias without arguments, simply use ipalias('name').
879
879
880 This provides a proper Python function to call IPython's aliases in any
880 This provides a proper Python function to call IPython's aliases in any
881 valid Python code you can type at the interpreter, including loops and
881 valid Python code you can type at the interpreter, including loops and
882 compound statements. It is added by IPython to the Python builtin
882 compound statements. It is added by IPython to the Python builtin
883 namespace upon initialization."""
883 namespace upon initialization."""
884
884
885 args = arg_s.split(' ',1)
885 args = arg_s.split(' ',1)
886 alias_name = args[0]
886 alias_name = args[0]
887 try:
887 try:
888 alias_args = args[1]
888 alias_args = args[1]
889 except IndexError:
889 except IndexError:
890 alias_args = ''
890 alias_args = ''
891 if alias_name in self.alias_table:
891 if alias_name in self.alias_table:
892 self.call_alias(alias_name,alias_args)
892 self.call_alias(alias_name,alias_args)
893 else:
893 else:
894 error("Alias `%s` not found." % alias_name)
894 error("Alias `%s` not found." % alias_name)
895
895
896 def ipsystem(self,arg_s):
896 def ipsystem(self,arg_s):
897 """Make a system call, using IPython."""
897 """Make a system call, using IPython."""
898
898
899 self.system(arg_s)
899 self.system(arg_s)
900
900
901 def complete(self,text):
901 def complete(self,text):
902 """Return a sorted list of all possible completions on text.
902 """Return a sorted list of all possible completions on text.
903
903
904 Inputs:
904 Inputs:
905
905
906 - text: a string of text to be completed on.
906 - text: a string of text to be completed on.
907
907
908 This is a wrapper around the completion mechanism, similar to what
908 This is a wrapper around the completion mechanism, similar to what
909 readline does at the command line when the TAB key is hit. By
909 readline does at the command line when the TAB key is hit. By
910 exposing it as a method, it can be used by other non-readline
910 exposing it as a method, it can be used by other non-readline
911 environments (such as GUIs) for text completion.
911 environments (such as GUIs) for text completion.
912
912
913 Simple usage example:
913 Simple usage example:
914
914
915 In [1]: x = 'hello'
915 In [1]: x = 'hello'
916
916
917 In [2]: __IP.complete('x.l')
917 In [2]: __IP.complete('x.l')
918 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
918 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
919
919
920 complete = self.Completer.complete
920 complete = self.Completer.complete
921 state = 0
921 state = 0
922 # use a dict so we get unique keys, since ipyhton's multiple
922 # use a dict so we get unique keys, since ipyhton's multiple
923 # completers can return duplicates.
923 # completers can return duplicates.
924 comps = {}
924 comps = {}
925 while True:
925 while True:
926 newcomp = complete(text,state)
926 newcomp = complete(text,state)
927 if newcomp is None:
927 if newcomp is None:
928 break
928 break
929 comps[newcomp] = 1
929 comps[newcomp] = 1
930 state += 1
930 state += 1
931 outcomps = comps.keys()
931 outcomps = comps.keys()
932 outcomps.sort()
932 outcomps.sort()
933 return outcomps
933 return outcomps
934
934
935 def set_completer_frame(self, frame=None):
935 def set_completer_frame(self, frame=None):
936 if frame:
936 if frame:
937 self.Completer.namespace = frame.f_locals
937 self.Completer.namespace = frame.f_locals
938 self.Completer.global_namespace = frame.f_globals
938 self.Completer.global_namespace = frame.f_globals
939 else:
939 else:
940 self.Completer.namespace = self.user_ns
940 self.Completer.namespace = self.user_ns
941 self.Completer.global_namespace = self.user_global_ns
941 self.Completer.global_namespace = self.user_global_ns
942
942
943 def init_auto_alias(self):
943 def init_auto_alias(self):
944 """Define some aliases automatically.
944 """Define some aliases automatically.
945
945
946 These are ALL parameter-less aliases"""
946 These are ALL parameter-less aliases"""
947
947
948 for alias,cmd in self.auto_alias:
948 for alias,cmd in self.auto_alias:
949 self.alias_table[alias] = (0,cmd)
949 self.alias_table[alias] = (0,cmd)
950
950
951 def alias_table_validate(self,verbose=0):
951 def alias_table_validate(self,verbose=0):
952 """Update information about the alias table.
952 """Update information about the alias table.
953
953
954 In particular, make sure no Python keywords/builtins are in it."""
954 In particular, make sure no Python keywords/builtins are in it."""
955
955
956 no_alias = self.no_alias
956 no_alias = self.no_alias
957 for k in self.alias_table.keys():
957 for k in self.alias_table.keys():
958 if k in no_alias:
958 if k in no_alias:
959 del self.alias_table[k]
959 del self.alias_table[k]
960 if verbose:
960 if verbose:
961 print ("Deleting alias <%s>, it's a Python "
961 print ("Deleting alias <%s>, it's a Python "
962 "keyword or builtin." % k)
962 "keyword or builtin." % k)
963
963
964 def set_autoindent(self,value=None):
964 def set_autoindent(self,value=None):
965 """Set the autoindent flag, checking for readline support.
965 """Set the autoindent flag, checking for readline support.
966
966
967 If called with no arguments, it acts as a toggle."""
967 If called with no arguments, it acts as a toggle."""
968
968
969 if not self.has_readline:
969 if not self.has_readline:
970 if os.name == 'posix':
970 if os.name == 'posix':
971 warn("The auto-indent feature requires the readline library")
971 warn("The auto-indent feature requires the readline library")
972 self.autoindent = 0
972 self.autoindent = 0
973 return
973 return
974 if value is None:
974 if value is None:
975 self.autoindent = not self.autoindent
975 self.autoindent = not self.autoindent
976 else:
976 else:
977 self.autoindent = value
977 self.autoindent = value
978
978
979 def rc_set_toggle(self,rc_field,value=None):
979 def rc_set_toggle(self,rc_field,value=None):
980 """Set or toggle a field in IPython's rc config. structure.
980 """Set or toggle a field in IPython's rc config. structure.
981
981
982 If called with no arguments, it acts as a toggle.
982 If called with no arguments, it acts as a toggle.
983
983
984 If called with a non-existent field, the resulting AttributeError
984 If called with a non-existent field, the resulting AttributeError
985 exception will propagate out."""
985 exception will propagate out."""
986
986
987 rc_val = getattr(self.rc,rc_field)
987 rc_val = getattr(self.rc,rc_field)
988 if value is None:
988 if value is None:
989 value = not rc_val
989 value = not rc_val
990 setattr(self.rc,rc_field,value)
990 setattr(self.rc,rc_field,value)
991
991
992 def user_setup(self,ipythondir,rc_suffix,mode='install'):
992 def user_setup(self,ipythondir,rc_suffix,mode='install'):
993 """Install the user configuration directory.
993 """Install the user configuration directory.
994
994
995 Can be called when running for the first time or to upgrade the user's
995 Can be called when running for the first time or to upgrade the user's
996 .ipython/ directory with the mode parameter. Valid modes are 'install'
996 .ipython/ directory with the mode parameter. Valid modes are 'install'
997 and 'upgrade'."""
997 and 'upgrade'."""
998
998
999 def wait():
999 def wait():
1000 try:
1000 try:
1001 raw_input("Please press <RETURN> to start IPython.")
1001 raw_input("Please press <RETURN> to start IPython.")
1002 except EOFError:
1002 except EOFError:
1003 print >> Term.cout
1003 print >> Term.cout
1004 print '*'*70
1004 print '*'*70
1005
1005
1006 cwd = os.getcwd() # remember where we started
1006 cwd = os.getcwd() # remember where we started
1007 glb = glob.glob
1007 glb = glob.glob
1008 print '*'*70
1008 print '*'*70
1009 if mode == 'install':
1009 if mode == 'install':
1010 print \
1010 print \
1011 """Welcome to IPython. I will try to create a personal configuration directory
1011 """Welcome to IPython. I will try to create a personal configuration directory
1012 where you can customize many aspects of IPython's functionality in:\n"""
1012 where you can customize many aspects of IPython's functionality in:\n"""
1013 else:
1013 else:
1014 print 'I am going to upgrade your configuration in:'
1014 print 'I am going to upgrade your configuration in:'
1015
1015
1016 print ipythondir
1016 print ipythondir
1017
1017
1018 rcdirend = os.path.join('IPython','UserConfig')
1018 rcdirend = os.path.join('IPython','UserConfig')
1019 cfg = lambda d: os.path.join(d,rcdirend)
1019 cfg = lambda d: os.path.join(d,rcdirend)
1020 try:
1020 try:
1021 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1021 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1022 except IOError:
1022 except IOError:
1023 warning = """
1023 warning = """
1024 Installation error. IPython's directory was not found.
1024 Installation error. IPython's directory was not found.
1025
1025
1026 Check the following:
1026 Check the following:
1027
1027
1028 The ipython/IPython directory should be in a directory belonging to your
1028 The ipython/IPython directory should be in a directory belonging to your
1029 PYTHONPATH environment variable (that is, it should be in a directory
1029 PYTHONPATH environment variable (that is, it should be in a directory
1030 belonging to sys.path). You can copy it explicitly there or just link to it.
1030 belonging to sys.path). You can copy it explicitly there or just link to it.
1031
1031
1032 IPython will proceed with builtin defaults.
1032 IPython will proceed with builtin defaults.
1033 """
1033 """
1034 warn(warning)
1034 warn(warning)
1035 wait()
1035 wait()
1036 return
1036 return
1037
1037
1038 if mode == 'install':
1038 if mode == 'install':
1039 try:
1039 try:
1040 shutil.copytree(rcdir,ipythondir)
1040 shutil.copytree(rcdir,ipythondir)
1041 os.chdir(ipythondir)
1041 os.chdir(ipythondir)
1042 rc_files = glb("ipythonrc*")
1042 rc_files = glb("ipythonrc*")
1043 for rc_file in rc_files:
1043 for rc_file in rc_files:
1044 os.rename(rc_file,rc_file+rc_suffix)
1044 os.rename(rc_file,rc_file+rc_suffix)
1045 except:
1045 except:
1046 warning = """
1046 warning = """
1047
1047
1048 There was a problem with the installation:
1048 There was a problem with the installation:
1049 %s
1049 %s
1050 Try to correct it or contact the developers if you think it's a bug.
1050 Try to correct it or contact the developers if you think it's a bug.
1051 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1051 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1052 warn(warning)
1052 warn(warning)
1053 wait()
1053 wait()
1054 return
1054 return
1055
1055
1056 elif mode == 'upgrade':
1056 elif mode == 'upgrade':
1057 try:
1057 try:
1058 os.chdir(ipythondir)
1058 os.chdir(ipythondir)
1059 except:
1059 except:
1060 print """
1060 print """
1061 Can not upgrade: changing to directory %s failed. Details:
1061 Can not upgrade: changing to directory %s failed. Details:
1062 %s
1062 %s
1063 """ % (ipythondir,sys.exc_info()[1])
1063 """ % (ipythondir,sys.exc_info()[1])
1064 wait()
1064 wait()
1065 return
1065 return
1066 else:
1066 else:
1067 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1067 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1068 for new_full_path in sources:
1068 for new_full_path in sources:
1069 new_filename = os.path.basename(new_full_path)
1069 new_filename = os.path.basename(new_full_path)
1070 if new_filename.startswith('ipythonrc'):
1070 if new_filename.startswith('ipythonrc'):
1071 new_filename = new_filename + rc_suffix
1071 new_filename = new_filename + rc_suffix
1072 # The config directory should only contain files, skip any
1072 # The config directory should only contain files, skip any
1073 # directories which may be there (like CVS)
1073 # directories which may be there (like CVS)
1074 if os.path.isdir(new_full_path):
1074 if os.path.isdir(new_full_path):
1075 continue
1075 continue
1076 if os.path.exists(new_filename):
1076 if os.path.exists(new_filename):
1077 old_file = new_filename+'.old'
1077 old_file = new_filename+'.old'
1078 if os.path.exists(old_file):
1078 if os.path.exists(old_file):
1079 os.remove(old_file)
1079 os.remove(old_file)
1080 os.rename(new_filename,old_file)
1080 os.rename(new_filename,old_file)
1081 shutil.copy(new_full_path,new_filename)
1081 shutil.copy(new_full_path,new_filename)
1082 else:
1082 else:
1083 raise ValueError,'unrecognized mode for install:',`mode`
1083 raise ValueError,'unrecognized mode for install:',`mode`
1084
1084
1085 # Fix line-endings to those native to each platform in the config
1085 # Fix line-endings to those native to each platform in the config
1086 # directory.
1086 # directory.
1087 try:
1087 try:
1088 os.chdir(ipythondir)
1088 os.chdir(ipythondir)
1089 except:
1089 except:
1090 print """
1090 print """
1091 Problem: changing to directory %s failed.
1091 Problem: changing to directory %s failed.
1092 Details:
1092 Details:
1093 %s
1093 %s
1094
1094
1095 Some configuration files may have incorrect line endings. This should not
1095 Some configuration files may have incorrect line endings. This should not
1096 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1096 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1097 wait()
1097 wait()
1098 else:
1098 else:
1099 for fname in glb('ipythonrc*'):
1099 for fname in glb('ipythonrc*'):
1100 try:
1100 try:
1101 native_line_ends(fname,backup=0)
1101 native_line_ends(fname,backup=0)
1102 except IOError:
1102 except IOError:
1103 pass
1103 pass
1104
1104
1105 if mode == 'install':
1105 if mode == 'install':
1106 print """
1106 print """
1107 Successful installation!
1107 Successful installation!
1108
1108
1109 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1109 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1110 IPython manual (there are both HTML and PDF versions supplied with the
1110 IPython manual (there are both HTML and PDF versions supplied with the
1111 distribution) to make sure that your system environment is properly configured
1111 distribution) to make sure that your system environment is properly configured
1112 to take advantage of IPython's features.
1112 to take advantage of IPython's features.
1113
1113
1114 Important note: the configuration system has changed! The old system is
1114 Important note: the configuration system has changed! The old system is
1115 still in place, but its setting may be partly overridden by the settings in
1115 still in place, but its setting may be partly overridden by the settings in
1116 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1116 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1117 if some of the new settings bother you.
1117 if some of the new settings bother you.
1118
1118
1119 """
1119 """
1120 else:
1120 else:
1121 print """
1121 print """
1122 Successful upgrade!
1122 Successful upgrade!
1123
1123
1124 All files in your directory:
1124 All files in your directory:
1125 %(ipythondir)s
1125 %(ipythondir)s
1126 which would have been overwritten by the upgrade were backed up with a .old
1126 which would have been overwritten by the upgrade were backed up with a .old
1127 extension. If you had made particular customizations in those files you may
1127 extension. If you had made particular customizations in those files you may
1128 want to merge them back into the new files.""" % locals()
1128 want to merge them back into the new files.""" % locals()
1129 wait()
1129 wait()
1130 os.chdir(cwd)
1130 os.chdir(cwd)
1131 # end user_setup()
1131 # end user_setup()
1132
1132
1133 def atexit_operations(self):
1133 def atexit_operations(self):
1134 """This will be executed at the time of exit.
1134 """This will be executed at the time of exit.
1135
1135
1136 Saving of persistent data should be performed here. """
1136 Saving of persistent data should be performed here. """
1137
1137
1138 #print '*** IPython exit cleanup ***' # dbg
1138 #print '*** IPython exit cleanup ***' # dbg
1139 # input history
1139 # input history
1140 self.savehist()
1140 self.savehist()
1141
1141
1142 # Cleanup all tempfiles left around
1142 # Cleanup all tempfiles left around
1143 for tfile in self.tempfiles:
1143 for tfile in self.tempfiles:
1144 try:
1144 try:
1145 os.unlink(tfile)
1145 os.unlink(tfile)
1146 except OSError:
1146 except OSError:
1147 pass
1147 pass
1148
1148
1149 # save the "persistent data" catch-all dictionary
1149 # save the "persistent data" catch-all dictionary
1150 try:
1150 try:
1151 pickle.dump(self.persist, open(self.persist_fname,"w"))
1151 pickle.dump(self.persist, open(self.persist_fname,"w"))
1152 except:
1152 except:
1153 print "*** ERROR *** persistent data saving failed."
1153 print "*** ERROR *** persistent data saving failed."
1154
1154
1155 def savehist(self):
1155 def savehist(self):
1156 """Save input history to a file (via readline library)."""
1156 """Save input history to a file (via readline library)."""
1157 try:
1157 try:
1158 self.readline.write_history_file(self.histfile)
1158 self.readline.write_history_file(self.histfile)
1159 except:
1159 except:
1160 print 'Unable to save IPython command history to file: ' + \
1160 print 'Unable to save IPython command history to file: ' + \
1161 `self.histfile`
1161 `self.histfile`
1162
1162
1163 def pre_readline(self):
1163 def pre_readline(self):
1164 """readline hook to be used at the start of each line.
1164 """readline hook to be used at the start of each line.
1165
1165
1166 Currently it handles auto-indent only."""
1166 Currently it handles auto-indent only."""
1167
1167
1168 #debugx('self.indent_current_nsp','pre_readline:')
1168 #debugx('self.indent_current_nsp','pre_readline:')
1169 self.readline.insert_text(self.indent_current_str())
1169 self.readline.insert_text(self.indent_current_str())
1170
1170
1171 def init_readline(self):
1171 def init_readline(self):
1172 """Command history completion/saving/reloading."""
1172 """Command history completion/saving/reloading."""
1173
1173
1174 using_pyreadline = False
1174 import IPython.rlineimpl as readline
1175 if sys.platform == 'win32':
1175 if not readline.have_readline:
1176 try:
1177 import pyreadline as readline
1178 using_pyrl = True
1179 print "Using the new pyreadline (thanks for participating in the testing!)"
1180 except ImportError:
1181 print "The IPython team recommends the new pyreadline for Windows use, it wasn't found."
1182 print "Try installing it with 'easy_install pyreadline (ctypes is required) or"
1183 print "svn co http://ipython.scipy.org/svn/ipython/pyreadline/trunk pyreadline"
1184 print "Trying 'old' windows readline."
1185
1186
1187 try:
1188 if not using_pyreadline:
1189 import readline
1190 except ImportError:
1191 self.has_readline = 0
1176 self.has_readline = 0
1192 self.readline = None
1177 self.readline = None
1193 # no point in bugging windows users with this every time:
1178 # no point in bugging windows users with this every time:
1194 warn('Readline services not available on this platform.')
1179 warn('Readline services not available on this platform.')
1195 else:
1180 else:
1181 sys.modules['readline'] = readline
1196 import atexit
1182 import atexit
1197 from IPython.completer import IPCompleter
1183 from IPython.completer import IPCompleter
1198 self.Completer = IPCompleter(self,
1184 self.Completer = IPCompleter(self,
1199 self.user_ns,
1185 self.user_ns,
1200 self.user_global_ns,
1186 self.user_global_ns,
1201 self.rc.readline_omit__names,
1187 self.rc.readline_omit__names,
1202 self.alias_table)
1188 self.alias_table)
1203
1189
1204 # Platform-specific configuration
1190 # Platform-specific configuration
1205 if os.name == 'nt':
1191 if os.name == 'nt':
1206 self.readline_startup_hook = readline.set_pre_input_hook
1192 self.readline_startup_hook = readline.set_pre_input_hook
1207 else:
1193 else:
1208 self.readline_startup_hook = readline.set_startup_hook
1194 self.readline_startup_hook = readline.set_startup_hook
1209
1195
1210 # Load user's initrc file (readline config)
1196 # Load user's initrc file (readline config)
1211 inputrc_name = os.environ.get('INPUTRC')
1197 inputrc_name = os.environ.get('INPUTRC')
1212 if inputrc_name is None:
1198 if inputrc_name is None:
1213 home_dir = get_home_dir()
1199 home_dir = get_home_dir()
1214 if home_dir is not None:
1200 if home_dir is not None:
1215 inputrc_name = os.path.join(home_dir,'.inputrc')
1201 inputrc_name = os.path.join(home_dir,'.inputrc')
1216 if os.path.isfile(inputrc_name):
1202 if os.path.isfile(inputrc_name):
1217 try:
1203 try:
1218 readline.read_init_file(inputrc_name)
1204 readline.read_init_file(inputrc_name)
1219 except:
1205 except:
1220 warn('Problems reading readline initialization file <%s>'
1206 warn('Problems reading readline initialization file <%s>'
1221 % inputrc_name)
1207 % inputrc_name)
1222
1208
1223 self.has_readline = 1
1209 self.has_readline = 1
1224 self.readline = readline
1210 self.readline = readline
1225 # save this in sys so embedded copies can restore it properly
1211 # save this in sys so embedded copies can restore it properly
1226 sys.ipcompleter = self.Completer.complete
1212 sys.ipcompleter = self.Completer.complete
1227 readline.set_completer(self.Completer.complete)
1213 readline.set_completer(self.Completer.complete)
1228
1214
1229 # Configure readline according to user's prefs
1215 # Configure readline according to user's prefs
1230 for rlcommand in self.rc.readline_parse_and_bind:
1216 for rlcommand in self.rc.readline_parse_and_bind:
1231 readline.parse_and_bind(rlcommand)
1217 readline.parse_and_bind(rlcommand)
1232
1218
1233 # remove some chars from the delimiters list
1219 # remove some chars from the delimiters list
1234 delims = readline.get_completer_delims()
1220 delims = readline.get_completer_delims()
1235 delims = delims.translate(string._idmap,
1221 delims = delims.translate(string._idmap,
1236 self.rc.readline_remove_delims)
1222 self.rc.readline_remove_delims)
1237 readline.set_completer_delims(delims)
1223 readline.set_completer_delims(delims)
1238 # otherwise we end up with a monster history after a while:
1224 # otherwise we end up with a monster history after a while:
1239 readline.set_history_length(1000)
1225 readline.set_history_length(1000)
1240 try:
1226 try:
1241 #print '*** Reading readline history' # dbg
1227 #print '*** Reading readline history' # dbg
1242 readline.read_history_file(self.histfile)
1228 readline.read_history_file(self.histfile)
1243 except IOError:
1229 except IOError:
1244 pass # It doesn't exist yet.
1230 pass # It doesn't exist yet.
1245
1231
1246 atexit.register(self.atexit_operations)
1232 atexit.register(self.atexit_operations)
1247 del atexit
1233 del atexit
1248
1234
1249 # Configure auto-indent for all platforms
1235 # Configure auto-indent for all platforms
1250 self.set_autoindent(self.rc.autoindent)
1236 self.set_autoindent(self.rc.autoindent)
1251
1237
1252 def _should_recompile(self,e):
1238 def _should_recompile(self,e):
1253 """Utility routine for edit_syntax_error"""
1239 """Utility routine for edit_syntax_error"""
1254
1240
1255 if e.filename in ('<ipython console>','<input>','<string>',
1241 if e.filename in ('<ipython console>','<input>','<string>',
1256 '<console>',None):
1242 '<console>',None):
1257
1243
1258 return False
1244 return False
1259 try:
1245 try:
1260 if (self.rc.autoedit_syntax != 2 and
1246 if (self.rc.autoedit_syntax != 2 and
1261 not ask_yes_no('Return to editor to correct syntax error? '
1247 not ask_yes_no('Return to editor to correct syntax error? '
1262 '[Y/n] ','y')):
1248 '[Y/n] ','y')):
1263 return False
1249 return False
1264 except EOFError:
1250 except EOFError:
1265 return False
1251 return False
1266
1252
1267 def int0(x):
1253 def int0(x):
1268 try:
1254 try:
1269 return int(x)
1255 return int(x)
1270 except TypeError:
1256 except TypeError:
1271 return 0
1257 return 0
1272 # always pass integer line and offset values to editor hook
1258 # always pass integer line and offset values to editor hook
1273 self.hooks.fix_error_editor(e.filename,
1259 self.hooks.fix_error_editor(e.filename,
1274 int0(e.lineno),int0(e.offset),e.msg)
1260 int0(e.lineno),int0(e.offset),e.msg)
1275 return True
1261 return True
1276
1262
1277 def edit_syntax_error(self):
1263 def edit_syntax_error(self):
1278 """The bottom half of the syntax error handler called in the main loop.
1264 """The bottom half of the syntax error handler called in the main loop.
1279
1265
1280 Loop until syntax error is fixed or user cancels.
1266 Loop until syntax error is fixed or user cancels.
1281 """
1267 """
1282
1268
1283 while self.SyntaxTB.last_syntax_error:
1269 while self.SyntaxTB.last_syntax_error:
1284 # copy and clear last_syntax_error
1270 # copy and clear last_syntax_error
1285 err = self.SyntaxTB.clear_err_state()
1271 err = self.SyntaxTB.clear_err_state()
1286 if not self._should_recompile(err):
1272 if not self._should_recompile(err):
1287 return
1273 return
1288 try:
1274 try:
1289 # may set last_syntax_error again if a SyntaxError is raised
1275 # may set last_syntax_error again if a SyntaxError is raised
1290 self.safe_execfile(err.filename,self.shell.user_ns)
1276 self.safe_execfile(err.filename,self.shell.user_ns)
1291 except:
1277 except:
1292 self.showtraceback()
1278 self.showtraceback()
1293 else:
1279 else:
1294 f = file(err.filename)
1280 f = file(err.filename)
1295 try:
1281 try:
1296 sys.displayhook(f.read())
1282 sys.displayhook(f.read())
1297 finally:
1283 finally:
1298 f.close()
1284 f.close()
1299
1285
1300 def showsyntaxerror(self, filename=None):
1286 def showsyntaxerror(self, filename=None):
1301 """Display the syntax error that just occurred.
1287 """Display the syntax error that just occurred.
1302
1288
1303 This doesn't display a stack trace because there isn't one.
1289 This doesn't display a stack trace because there isn't one.
1304
1290
1305 If a filename is given, it is stuffed in the exception instead
1291 If a filename is given, it is stuffed in the exception instead
1306 of what was there before (because Python's parser always uses
1292 of what was there before (because Python's parser always uses
1307 "<string>" when reading from a string).
1293 "<string>" when reading from a string).
1308 """
1294 """
1309 etype, value, last_traceback = sys.exc_info()
1295 etype, value, last_traceback = sys.exc_info()
1310 if filename and etype is SyntaxError:
1296 if filename and etype is SyntaxError:
1311 # Work hard to stuff the correct filename in the exception
1297 # Work hard to stuff the correct filename in the exception
1312 try:
1298 try:
1313 msg, (dummy_filename, lineno, offset, line) = value
1299 msg, (dummy_filename, lineno, offset, line) = value
1314 except:
1300 except:
1315 # Not the format we expect; leave it alone
1301 # Not the format we expect; leave it alone
1316 pass
1302 pass
1317 else:
1303 else:
1318 # Stuff in the right filename
1304 # Stuff in the right filename
1319 try:
1305 try:
1320 # Assume SyntaxError is a class exception
1306 # Assume SyntaxError is a class exception
1321 value = SyntaxError(msg, (filename, lineno, offset, line))
1307 value = SyntaxError(msg, (filename, lineno, offset, line))
1322 except:
1308 except:
1323 # If that failed, assume SyntaxError is a string
1309 # If that failed, assume SyntaxError is a string
1324 value = msg, (filename, lineno, offset, line)
1310 value = msg, (filename, lineno, offset, line)
1325 self.SyntaxTB(etype,value,[])
1311 self.SyntaxTB(etype,value,[])
1326
1312
1327 def debugger(self):
1313 def debugger(self):
1328 """Call the pdb debugger."""
1314 """Call the pdb debugger."""
1329
1315
1330 if not self.rc.pdb:
1316 if not self.rc.pdb:
1331 return
1317 return
1332 pdb.pm()
1318 pdb.pm()
1333
1319
1334 def showtraceback(self,exc_tuple = None,filename=None):
1320 def showtraceback(self,exc_tuple = None,filename=None):
1335 """Display the exception that just occurred."""
1321 """Display the exception that just occurred."""
1336
1322
1337 # Though this won't be called by syntax errors in the input line,
1323 # Though this won't be called by syntax errors in the input line,
1338 # there may be SyntaxError cases whith imported code.
1324 # there may be SyntaxError cases whith imported code.
1339 if exc_tuple is None:
1325 if exc_tuple is None:
1340 type, value, tb = sys.exc_info()
1326 type, value, tb = sys.exc_info()
1341 else:
1327 else:
1342 type, value, tb = exc_tuple
1328 type, value, tb = exc_tuple
1343 if type is SyntaxError:
1329 if type is SyntaxError:
1344 self.showsyntaxerror(filename)
1330 self.showsyntaxerror(filename)
1345 else:
1331 else:
1346 self.InteractiveTB()
1332 self.InteractiveTB()
1347 if self.InteractiveTB.call_pdb and self.has_readline:
1333 if self.InteractiveTB.call_pdb and self.has_readline:
1348 # pdb mucks up readline, fix it back
1334 # pdb mucks up readline, fix it back
1349 self.readline.set_completer(self.Completer.complete)
1335 self.readline.set_completer(self.Completer.complete)
1350
1336
1351 def mainloop(self,banner=None):
1337 def mainloop(self,banner=None):
1352 """Creates the local namespace and starts the mainloop.
1338 """Creates the local namespace and starts the mainloop.
1353
1339
1354 If an optional banner argument is given, it will override the
1340 If an optional banner argument is given, it will override the
1355 internally created default banner."""
1341 internally created default banner."""
1356
1342
1357 if self.rc.c: # Emulate Python's -c option
1343 if self.rc.c: # Emulate Python's -c option
1358 self.exec_init_cmd()
1344 self.exec_init_cmd()
1359 if banner is None:
1345 if banner is None:
1360 if self.rc.banner:
1346 if self.rc.banner:
1361 banner = self.BANNER+self.banner2
1347 banner = self.BANNER+self.banner2
1362 else:
1348 else:
1363 banner = ''
1349 banner = ''
1364 self.interact(banner)
1350 self.interact(banner)
1365
1351
1366 def exec_init_cmd(self):
1352 def exec_init_cmd(self):
1367 """Execute a command given at the command line.
1353 """Execute a command given at the command line.
1368
1354
1369 This emulates Python's -c option."""
1355 This emulates Python's -c option."""
1370
1356
1371 #sys.argv = ['-c']
1357 #sys.argv = ['-c']
1372 self.push(self.rc.c)
1358 self.push(self.rc.c)
1373
1359
1374 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1360 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1375 """Embeds IPython into a running python program.
1361 """Embeds IPython into a running python program.
1376
1362
1377 Input:
1363 Input:
1378
1364
1379 - header: An optional header message can be specified.
1365 - header: An optional header message can be specified.
1380
1366
1381 - local_ns, global_ns: working namespaces. If given as None, the
1367 - local_ns, global_ns: working namespaces. If given as None, the
1382 IPython-initialized one is updated with __main__.__dict__, so that
1368 IPython-initialized one is updated with __main__.__dict__, so that
1383 program variables become visible but user-specific configuration
1369 program variables become visible but user-specific configuration
1384 remains possible.
1370 remains possible.
1385
1371
1386 - stack_depth: specifies how many levels in the stack to go to
1372 - stack_depth: specifies how many levels in the stack to go to
1387 looking for namespaces (when local_ns and global_ns are None). This
1373 looking for namespaces (when local_ns and global_ns are None). This
1388 allows an intermediate caller to make sure that this function gets
1374 allows an intermediate caller to make sure that this function gets
1389 the namespace from the intended level in the stack. By default (0)
1375 the namespace from the intended level in the stack. By default (0)
1390 it will get its locals and globals from the immediate caller.
1376 it will get its locals and globals from the immediate caller.
1391
1377
1392 Warning: it's possible to use this in a program which is being run by
1378 Warning: it's possible to use this in a program which is being run by
1393 IPython itself (via %run), but some funny things will happen (a few
1379 IPython itself (via %run), but some funny things will happen (a few
1394 globals get overwritten). In the future this will be cleaned up, as
1380 globals get overwritten). In the future this will be cleaned up, as
1395 there is no fundamental reason why it can't work perfectly."""
1381 there is no fundamental reason why it can't work perfectly."""
1396
1382
1397 # Get locals and globals from caller
1383 # Get locals and globals from caller
1398 if local_ns is None or global_ns is None:
1384 if local_ns is None or global_ns is None:
1399 call_frame = sys._getframe(stack_depth).f_back
1385 call_frame = sys._getframe(stack_depth).f_back
1400
1386
1401 if local_ns is None:
1387 if local_ns is None:
1402 local_ns = call_frame.f_locals
1388 local_ns = call_frame.f_locals
1403 if global_ns is None:
1389 if global_ns is None:
1404 global_ns = call_frame.f_globals
1390 global_ns = call_frame.f_globals
1405
1391
1406 # Update namespaces and fire up interpreter
1392 # Update namespaces and fire up interpreter
1407
1393
1408 # The global one is easy, we can just throw it in
1394 # The global one is easy, we can just throw it in
1409 self.user_global_ns = global_ns
1395 self.user_global_ns = global_ns
1410
1396
1411 # but the user/local one is tricky: ipython needs it to store internal
1397 # but the user/local one is tricky: ipython needs it to store internal
1412 # data, but we also need the locals. We'll copy locals in the user
1398 # data, but we also need the locals. We'll copy locals in the user
1413 # one, but will track what got copied so we can delete them at exit.
1399 # one, but will track what got copied so we can delete them at exit.
1414 # This is so that a later embedded call doesn't see locals from a
1400 # This is so that a later embedded call doesn't see locals from a
1415 # previous call (which most likely existed in a separate scope).
1401 # previous call (which most likely existed in a separate scope).
1416 local_varnames = local_ns.keys()
1402 local_varnames = local_ns.keys()
1417 self.user_ns.update(local_ns)
1403 self.user_ns.update(local_ns)
1418
1404
1419 # Patch for global embedding to make sure that things don't overwrite
1405 # Patch for global embedding to make sure that things don't overwrite
1420 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1406 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1421 # FIXME. Test this a bit more carefully (the if.. is new)
1407 # FIXME. Test this a bit more carefully (the if.. is new)
1422 if local_ns is None and global_ns is None:
1408 if local_ns is None and global_ns is None:
1423 self.user_global_ns.update(__main__.__dict__)
1409 self.user_global_ns.update(__main__.__dict__)
1424
1410
1425 # make sure the tab-completer has the correct frame information, so it
1411 # make sure the tab-completer has the correct frame information, so it
1426 # actually completes using the frame's locals/globals
1412 # actually completes using the frame's locals/globals
1427 self.set_completer_frame()
1413 self.set_completer_frame()
1428
1414
1429 # before activating the interactive mode, we need to make sure that
1415 # before activating the interactive mode, we need to make sure that
1430 # all names in the builtin namespace needed by ipython point to
1416 # all names in the builtin namespace needed by ipython point to
1431 # ourselves, and not to other instances.
1417 # ourselves, and not to other instances.
1432 self.add_builtins()
1418 self.add_builtins()
1433
1419
1434 self.interact(header)
1420 self.interact(header)
1435
1421
1436 # now, purge out the user namespace from anything we might have added
1422 # now, purge out the user namespace from anything we might have added
1437 # from the caller's local namespace
1423 # from the caller's local namespace
1438 delvar = self.user_ns.pop
1424 delvar = self.user_ns.pop
1439 for var in local_varnames:
1425 for var in local_varnames:
1440 delvar(var,None)
1426 delvar(var,None)
1441 # and clean builtins we may have overridden
1427 # and clean builtins we may have overridden
1442 self.clean_builtins()
1428 self.clean_builtins()
1443
1429
1444 def interact(self, banner=None):
1430 def interact(self, banner=None):
1445 """Closely emulate the interactive Python console.
1431 """Closely emulate the interactive Python console.
1446
1432
1447 The optional banner argument specify the banner to print
1433 The optional banner argument specify the banner to print
1448 before the first interaction; by default it prints a banner
1434 before the first interaction; by default it prints a banner
1449 similar to the one printed by the real Python interpreter,
1435 similar to the one printed by the real Python interpreter,
1450 followed by the current class name in parentheses (so as not
1436 followed by the current class name in parentheses (so as not
1451 to confuse this with the real interpreter -- since it's so
1437 to confuse this with the real interpreter -- since it's so
1452 close!).
1438 close!).
1453
1439
1454 """
1440 """
1455 cprt = 'Type "copyright", "credits" or "license" for more information.'
1441 cprt = 'Type "copyright", "credits" or "license" for more information.'
1456 if banner is None:
1442 if banner is None:
1457 self.write("Python %s on %s\n%s\n(%s)\n" %
1443 self.write("Python %s on %s\n%s\n(%s)\n" %
1458 (sys.version, sys.platform, cprt,
1444 (sys.version, sys.platform, cprt,
1459 self.__class__.__name__))
1445 self.__class__.__name__))
1460 else:
1446 else:
1461 self.write(banner)
1447 self.write(banner)
1462
1448
1463 more = 0
1449 more = 0
1464
1450
1465 # Mark activity in the builtins
1451 # Mark activity in the builtins
1466 __builtin__.__dict__['__IPYTHON__active'] += 1
1452 __builtin__.__dict__['__IPYTHON__active'] += 1
1467
1453
1468 # exit_now is set by a call to %Exit or %Quit
1454 # exit_now is set by a call to %Exit or %Quit
1469 self.exit_now = False
1455 self.exit_now = False
1470 while not self.exit_now:
1456 while not self.exit_now:
1471
1457
1472 try:
1458 try:
1473 if more:
1459 if more:
1474 prompt = self.outputcache.prompt2
1460 prompt = self.outputcache.prompt2
1475 if self.autoindent:
1461 if self.autoindent:
1476 self.readline_startup_hook(self.pre_readline)
1462 self.readline_startup_hook(self.pre_readline)
1477 else:
1463 else:
1478 prompt = self.outputcache.prompt1
1464 prompt = self.outputcache.prompt1
1479 try:
1465 try:
1480 line = self.raw_input(prompt,more)
1466 line = self.raw_input(prompt,more)
1481 if self.autoindent:
1467 if self.autoindent:
1482 self.readline_startup_hook(None)
1468 self.readline_startup_hook(None)
1483 except EOFError:
1469 except EOFError:
1484 if self.autoindent:
1470 if self.autoindent:
1485 self.readline_startup_hook(None)
1471 self.readline_startup_hook(None)
1486 self.write("\n")
1472 self.write("\n")
1487 self.exit()
1473 self.exit()
1488 except:
1474 except:
1489 # exceptions here are VERY RARE, but they can be triggered
1475 # exceptions here are VERY RARE, but they can be triggered
1490 # asynchronously by signal handlers, for example.
1476 # asynchronously by signal handlers, for example.
1491 self.showtraceback()
1477 self.showtraceback()
1492 else:
1478 else:
1493 more = self.push(line)
1479 more = self.push(line)
1494
1480
1495 if (self.SyntaxTB.last_syntax_error and
1481 if (self.SyntaxTB.last_syntax_error and
1496 self.rc.autoedit_syntax):
1482 self.rc.autoedit_syntax):
1497 self.edit_syntax_error()
1483 self.edit_syntax_error()
1498
1484
1499 except KeyboardInterrupt:
1485 except KeyboardInterrupt:
1500 self.write("\nKeyboardInterrupt\n")
1486 self.write("\nKeyboardInterrupt\n")
1501 self.resetbuffer()
1487 self.resetbuffer()
1502 more = 0
1488 more = 0
1503 # keep cache in sync with the prompt counter:
1489 # keep cache in sync with the prompt counter:
1504 self.outputcache.prompt_count -= 1
1490 self.outputcache.prompt_count -= 1
1505
1491
1506 if self.autoindent:
1492 if self.autoindent:
1507 self.indent_current_nsp = 0
1493 self.indent_current_nsp = 0
1508
1494
1509 except bdb.BdbQuit:
1495 except bdb.BdbQuit:
1510 warn("The Python debugger has exited with a BdbQuit exception.\n"
1496 warn("The Python debugger has exited with a BdbQuit exception.\n"
1511 "Because of how pdb handles the stack, it is impossible\n"
1497 "Because of how pdb handles the stack, it is impossible\n"
1512 "for IPython to properly format this particular exception.\n"
1498 "for IPython to properly format this particular exception.\n"
1513 "IPython will resume normal operation.")
1499 "IPython will resume normal operation.")
1514
1500
1515 # We are off again...
1501 # We are off again...
1516 __builtin__.__dict__['__IPYTHON__active'] -= 1
1502 __builtin__.__dict__['__IPYTHON__active'] -= 1
1517
1503
1518 def excepthook(self, type, value, tb):
1504 def excepthook(self, type, value, tb):
1519 """One more defense for GUI apps that call sys.excepthook.
1505 """One more defense for GUI apps that call sys.excepthook.
1520
1506
1521 GUI frameworks like wxPython trap exceptions and call
1507 GUI frameworks like wxPython trap exceptions and call
1522 sys.excepthook themselves. I guess this is a feature that
1508 sys.excepthook themselves. I guess this is a feature that
1523 enables them to keep running after exceptions that would
1509 enables them to keep running after exceptions that would
1524 otherwise kill their mainloop. This is a bother for IPython
1510 otherwise kill their mainloop. This is a bother for IPython
1525 which excepts to catch all of the program exceptions with a try:
1511 which excepts to catch all of the program exceptions with a try:
1526 except: statement.
1512 except: statement.
1527
1513
1528 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1514 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1529 any app directly invokes sys.excepthook, it will look to the user like
1515 any app directly invokes sys.excepthook, it will look to the user like
1530 IPython crashed. In order to work around this, we can disable the
1516 IPython crashed. In order to work around this, we can disable the
1531 CrashHandler and replace it with this excepthook instead, which prints a
1517 CrashHandler and replace it with this excepthook instead, which prints a
1532 regular traceback using our InteractiveTB. In this fashion, apps which
1518 regular traceback using our InteractiveTB. In this fashion, apps which
1533 call sys.excepthook will generate a regular-looking exception from
1519 call sys.excepthook will generate a regular-looking exception from
1534 IPython, and the CrashHandler will only be triggered by real IPython
1520 IPython, and the CrashHandler will only be triggered by real IPython
1535 crashes.
1521 crashes.
1536
1522
1537 This hook should be used sparingly, only in places which are not likely
1523 This hook should be used sparingly, only in places which are not likely
1538 to be true IPython errors.
1524 to be true IPython errors.
1539 """
1525 """
1540
1526
1541 self.InteractiveTB(type, value, tb, tb_offset=0)
1527 self.InteractiveTB(type, value, tb, tb_offset=0)
1542 if self.InteractiveTB.call_pdb and self.has_readline:
1528 if self.InteractiveTB.call_pdb and self.has_readline:
1543 self.readline.set_completer(self.Completer.complete)
1529 self.readline.set_completer(self.Completer.complete)
1544
1530
1545 def call_alias(self,alias,rest=''):
1531 def call_alias(self,alias,rest=''):
1546 """Call an alias given its name and the rest of the line.
1532 """Call an alias given its name and the rest of the line.
1547
1533
1548 This function MUST be given a proper alias, because it doesn't make
1534 This function MUST be given a proper alias, because it doesn't make
1549 any checks when looking up into the alias table. The caller is
1535 any checks when looking up into the alias table. The caller is
1550 responsible for invoking it only with a valid alias."""
1536 responsible for invoking it only with a valid alias."""
1551
1537
1552 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1538 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1553 nargs,cmd = self.alias_table[alias]
1539 nargs,cmd = self.alias_table[alias]
1554 # Expand the %l special to be the user's input line
1540 # Expand the %l special to be the user's input line
1555 if cmd.find('%l') >= 0:
1541 if cmd.find('%l') >= 0:
1556 cmd = cmd.replace('%l',rest)
1542 cmd = cmd.replace('%l',rest)
1557 rest = ''
1543 rest = ''
1558 if nargs==0:
1544 if nargs==0:
1559 # Simple, argument-less aliases
1545 # Simple, argument-less aliases
1560 cmd = '%s %s' % (cmd,rest)
1546 cmd = '%s %s' % (cmd,rest)
1561 else:
1547 else:
1562 # Handle aliases with positional arguments
1548 # Handle aliases with positional arguments
1563 args = rest.split(None,nargs)
1549 args = rest.split(None,nargs)
1564 if len(args)< nargs:
1550 if len(args)< nargs:
1565 error('Alias <%s> requires %s arguments, %s given.' %
1551 error('Alias <%s> requires %s arguments, %s given.' %
1566 (alias,nargs,len(args)))
1552 (alias,nargs,len(args)))
1567 return
1553 return
1568 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1554 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1569 # Now call the macro, evaluating in the user's namespace
1555 # Now call the macro, evaluating in the user's namespace
1570 try:
1556 try:
1571 self.system(cmd)
1557 self.system(cmd)
1572 except:
1558 except:
1573 self.showtraceback()
1559 self.showtraceback()
1574
1560
1575 def indent_current_str(self):
1561 def indent_current_str(self):
1576 """return the current level of indentation as a string"""
1562 """return the current level of indentation as a string"""
1577 return self.indent_current_nsp * ' '
1563 return self.indent_current_nsp * ' '
1578
1564
1579 def autoindent_update(self,line):
1565 def autoindent_update(self,line):
1580 """Keep track of the indent level."""
1566 """Keep track of the indent level."""
1581
1567
1582 #debugx('line')
1568 #debugx('line')
1583 #debugx('self.indent_current_nsp')
1569 #debugx('self.indent_current_nsp')
1584 if self.autoindent:
1570 if self.autoindent:
1585 if line:
1571 if line:
1586 inisp = num_ini_spaces(line)
1572 inisp = num_ini_spaces(line)
1587 if inisp < self.indent_current_nsp:
1573 if inisp < self.indent_current_nsp:
1588 self.indent_current_nsp = inisp
1574 self.indent_current_nsp = inisp
1589
1575
1590 if line[-1] == ':':
1576 if line[-1] == ':':
1591 self.indent_current_nsp += 4
1577 self.indent_current_nsp += 4
1592 elif dedent_re.match(line):
1578 elif dedent_re.match(line):
1593 self.indent_current_nsp -= 4
1579 self.indent_current_nsp -= 4
1594 else:
1580 else:
1595 self.indent_current_nsp = 0
1581 self.indent_current_nsp = 0
1596
1582
1597 def runlines(self,lines):
1583 def runlines(self,lines):
1598 """Run a string of one or more lines of source.
1584 """Run a string of one or more lines of source.
1599
1585
1600 This method is capable of running a string containing multiple source
1586 This method is capable of running a string containing multiple source
1601 lines, as if they had been entered at the IPython prompt. Since it
1587 lines, as if they had been entered at the IPython prompt. Since it
1602 exposes IPython's processing machinery, the given strings can contain
1588 exposes IPython's processing machinery, the given strings can contain
1603 magic calls (%magic), special shell access (!cmd), etc."""
1589 magic calls (%magic), special shell access (!cmd), etc."""
1604
1590
1605 # We must start with a clean buffer, in case this is run from an
1591 # We must start with a clean buffer, in case this is run from an
1606 # interactive IPython session (via a magic, for example).
1592 # interactive IPython session (via a magic, for example).
1607 self.resetbuffer()
1593 self.resetbuffer()
1608 lines = lines.split('\n')
1594 lines = lines.split('\n')
1609 more = 0
1595 more = 0
1610 for line in lines:
1596 for line in lines:
1611 # skip blank lines so we don't mess up the prompt counter, but do
1597 # skip blank lines so we don't mess up the prompt counter, but do
1612 # NOT skip even a blank line if we are in a code block (more is
1598 # NOT skip even a blank line if we are in a code block (more is
1613 # true)
1599 # true)
1614 if line or more:
1600 if line or more:
1615 more = self.push(self.prefilter(line,more))
1601 more = self.push(self.prefilter(line,more))
1616 # IPython's runsource returns None if there was an error
1602 # IPython's runsource returns None if there was an error
1617 # compiling the code. This allows us to stop processing right
1603 # compiling the code. This allows us to stop processing right
1618 # away, so the user gets the error message at the right place.
1604 # away, so the user gets the error message at the right place.
1619 if more is None:
1605 if more is None:
1620 break
1606 break
1621 # final newline in case the input didn't have it, so that the code
1607 # final newline in case the input didn't have it, so that the code
1622 # actually does get executed
1608 # actually does get executed
1623 if more:
1609 if more:
1624 self.push('\n')
1610 self.push('\n')
1625
1611
1626 def runsource(self, source, filename='<input>', symbol='single'):
1612 def runsource(self, source, filename='<input>', symbol='single'):
1627 """Compile and run some source in the interpreter.
1613 """Compile and run some source in the interpreter.
1628
1614
1629 Arguments are as for compile_command().
1615 Arguments are as for compile_command().
1630
1616
1631 One several things can happen:
1617 One several things can happen:
1632
1618
1633 1) The input is incorrect; compile_command() raised an
1619 1) The input is incorrect; compile_command() raised an
1634 exception (SyntaxError or OverflowError). A syntax traceback
1620 exception (SyntaxError or OverflowError). A syntax traceback
1635 will be printed by calling the showsyntaxerror() method.
1621 will be printed by calling the showsyntaxerror() method.
1636
1622
1637 2) The input is incomplete, and more input is required;
1623 2) The input is incomplete, and more input is required;
1638 compile_command() returned None. Nothing happens.
1624 compile_command() returned None. Nothing happens.
1639
1625
1640 3) The input is complete; compile_command() returned a code
1626 3) The input is complete; compile_command() returned a code
1641 object. The code is executed by calling self.runcode() (which
1627 object. The code is executed by calling self.runcode() (which
1642 also handles run-time exceptions, except for SystemExit).
1628 also handles run-time exceptions, except for SystemExit).
1643
1629
1644 The return value is:
1630 The return value is:
1645
1631
1646 - True in case 2
1632 - True in case 2
1647
1633
1648 - False in the other cases, unless an exception is raised, where
1634 - False in the other cases, unless an exception is raised, where
1649 None is returned instead. This can be used by external callers to
1635 None is returned instead. This can be used by external callers to
1650 know whether to continue feeding input or not.
1636 know whether to continue feeding input or not.
1651
1637
1652 The return value can be used to decide whether to use sys.ps1 or
1638 The return value can be used to decide whether to use sys.ps1 or
1653 sys.ps2 to prompt the next line."""
1639 sys.ps2 to prompt the next line."""
1654
1640
1655 try:
1641 try:
1656 code = self.compile(source,filename,symbol)
1642 code = self.compile(source,filename,symbol)
1657 except (OverflowError, SyntaxError, ValueError):
1643 except (OverflowError, SyntaxError, ValueError):
1658 # Case 1
1644 # Case 1
1659 self.showsyntaxerror(filename)
1645 self.showsyntaxerror(filename)
1660 return None
1646 return None
1661
1647
1662 if code is None:
1648 if code is None:
1663 # Case 2
1649 # Case 2
1664 return True
1650 return True
1665
1651
1666 # Case 3
1652 # Case 3
1667 # We store the code object so that threaded shells and
1653 # We store the code object so that threaded shells and
1668 # custom exception handlers can access all this info if needed.
1654 # custom exception handlers can access all this info if needed.
1669 # The source corresponding to this can be obtained from the
1655 # The source corresponding to this can be obtained from the
1670 # buffer attribute as '\n'.join(self.buffer).
1656 # buffer attribute as '\n'.join(self.buffer).
1671 self.code_to_run = code
1657 self.code_to_run = code
1672 # now actually execute the code object
1658 # now actually execute the code object
1673 if self.runcode(code) == 0:
1659 if self.runcode(code) == 0:
1674 return False
1660 return False
1675 else:
1661 else:
1676 return None
1662 return None
1677
1663
1678 def runcode(self,code_obj):
1664 def runcode(self,code_obj):
1679 """Execute a code object.
1665 """Execute a code object.
1680
1666
1681 When an exception occurs, self.showtraceback() is called to display a
1667 When an exception occurs, self.showtraceback() is called to display a
1682 traceback.
1668 traceback.
1683
1669
1684 Return value: a flag indicating whether the code to be run completed
1670 Return value: a flag indicating whether the code to be run completed
1685 successfully:
1671 successfully:
1686
1672
1687 - 0: successful execution.
1673 - 0: successful execution.
1688 - 1: an error occurred.
1674 - 1: an error occurred.
1689 """
1675 """
1690
1676
1691 # Set our own excepthook in case the user code tries to call it
1677 # Set our own excepthook in case the user code tries to call it
1692 # directly, so that the IPython crash handler doesn't get triggered
1678 # directly, so that the IPython crash handler doesn't get triggered
1693 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1679 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1694
1680
1695 # we save the original sys.excepthook in the instance, in case config
1681 # we save the original sys.excepthook in the instance, in case config
1696 # code (such as magics) needs access to it.
1682 # code (such as magics) needs access to it.
1697 self.sys_excepthook = old_excepthook
1683 self.sys_excepthook = old_excepthook
1698 outflag = 1 # happens in more places, so it's easier as default
1684 outflag = 1 # happens in more places, so it's easier as default
1699 try:
1685 try:
1700 try:
1686 try:
1701 # Embedded instances require separate global/local namespaces
1687 # Embedded instances require separate global/local namespaces
1702 # so they can see both the surrounding (local) namespace and
1688 # so they can see both the surrounding (local) namespace and
1703 # the module-level globals when called inside another function.
1689 # the module-level globals when called inside another function.
1704 if self.embedded:
1690 if self.embedded:
1705 exec code_obj in self.user_global_ns, self.user_ns
1691 exec code_obj in self.user_global_ns, self.user_ns
1706 # Normal (non-embedded) instances should only have a single
1692 # Normal (non-embedded) instances should only have a single
1707 # namespace for user code execution, otherwise functions won't
1693 # namespace for user code execution, otherwise functions won't
1708 # see interactive top-level globals.
1694 # see interactive top-level globals.
1709 else:
1695 else:
1710 exec code_obj in self.user_ns
1696 exec code_obj in self.user_ns
1711 finally:
1697 finally:
1712 # Reset our crash handler in place
1698 # Reset our crash handler in place
1713 sys.excepthook = old_excepthook
1699 sys.excepthook = old_excepthook
1714 except SystemExit:
1700 except SystemExit:
1715 self.resetbuffer()
1701 self.resetbuffer()
1716 self.showtraceback()
1702 self.showtraceback()
1717 warn("Type exit or quit to exit IPython "
1703 warn("Type exit or quit to exit IPython "
1718 "(%Exit or %Quit do so unconditionally).",level=1)
1704 "(%Exit or %Quit do so unconditionally).",level=1)
1719 except self.custom_exceptions:
1705 except self.custom_exceptions:
1720 etype,value,tb = sys.exc_info()
1706 etype,value,tb = sys.exc_info()
1721 self.CustomTB(etype,value,tb)
1707 self.CustomTB(etype,value,tb)
1722 except:
1708 except:
1723 self.showtraceback()
1709 self.showtraceback()
1724 else:
1710 else:
1725 outflag = 0
1711 outflag = 0
1726 if softspace(sys.stdout, 0):
1712 if softspace(sys.stdout, 0):
1727 print
1713 print
1728 # Flush out code object which has been run (and source)
1714 # Flush out code object which has been run (and source)
1729 self.code_to_run = None
1715 self.code_to_run = None
1730 return outflag
1716 return outflag
1731
1717
1732 def push(self, line):
1718 def push(self, line):
1733 """Push a line to the interpreter.
1719 """Push a line to the interpreter.
1734
1720
1735 The line should not have a trailing newline; it may have
1721 The line should not have a trailing newline; it may have
1736 internal newlines. The line is appended to a buffer and the
1722 internal newlines. The line is appended to a buffer and the
1737 interpreter's runsource() method is called with the
1723 interpreter's runsource() method is called with the
1738 concatenated contents of the buffer as source. If this
1724 concatenated contents of the buffer as source. If this
1739 indicates that the command was executed or invalid, the buffer
1725 indicates that the command was executed or invalid, the buffer
1740 is reset; otherwise, the command is incomplete, and the buffer
1726 is reset; otherwise, the command is incomplete, and the buffer
1741 is left as it was after the line was appended. The return
1727 is left as it was after the line was appended. The return
1742 value is 1 if more input is required, 0 if the line was dealt
1728 value is 1 if more input is required, 0 if the line was dealt
1743 with in some way (this is the same as runsource()).
1729 with in some way (this is the same as runsource()).
1744 """
1730 """
1745
1731
1746 # autoindent management should be done here, and not in the
1732 # autoindent management should be done here, and not in the
1747 # interactive loop, since that one is only seen by keyboard input. We
1733 # interactive loop, since that one is only seen by keyboard input. We
1748 # need this done correctly even for code run via runlines (which uses
1734 # need this done correctly even for code run via runlines (which uses
1749 # push).
1735 # push).
1750
1736
1751 #print 'push line: <%s>' % line # dbg
1737 #print 'push line: <%s>' % line # dbg
1752 self.autoindent_update(line)
1738 self.autoindent_update(line)
1753
1739
1754 self.buffer.append(line)
1740 self.buffer.append(line)
1755 more = self.runsource('\n'.join(self.buffer), self.filename)
1741 more = self.runsource('\n'.join(self.buffer), self.filename)
1756 if not more:
1742 if not more:
1757 self.resetbuffer()
1743 self.resetbuffer()
1758 return more
1744 return more
1759
1745
1760 def resetbuffer(self):
1746 def resetbuffer(self):
1761 """Reset the input buffer."""
1747 """Reset the input buffer."""
1762 self.buffer[:] = []
1748 self.buffer[:] = []
1763
1749
1764 def raw_input(self,prompt='',continue_prompt=False):
1750 def raw_input(self,prompt='',continue_prompt=False):
1765 """Write a prompt and read a line.
1751 """Write a prompt and read a line.
1766
1752
1767 The returned line does not include the trailing newline.
1753 The returned line does not include the trailing newline.
1768 When the user enters the EOF key sequence, EOFError is raised.
1754 When the user enters the EOF key sequence, EOFError is raised.
1769
1755
1770 Optional inputs:
1756 Optional inputs:
1771
1757
1772 - prompt(''): a string to be printed to prompt the user.
1758 - prompt(''): a string to be printed to prompt the user.
1773
1759
1774 - continue_prompt(False): whether this line is the first one or a
1760 - continue_prompt(False): whether this line is the first one or a
1775 continuation in a sequence of inputs.
1761 continuation in a sequence of inputs.
1776 """
1762 """
1777
1763
1778 line = raw_input_original(prompt)
1764 line = raw_input_original(prompt)
1779 # Try to be reasonably smart about not re-indenting pasted input more
1765 # Try to be reasonably smart about not re-indenting pasted input more
1780 # than necessary. We do this by trimming out the auto-indent initial
1766 # than necessary. We do this by trimming out the auto-indent initial
1781 # spaces, if the user's actual input started itself with whitespace.
1767 # spaces, if the user's actual input started itself with whitespace.
1782 #debugx('self.buffer[-1]')
1768 #debugx('self.buffer[-1]')
1783
1769
1784 if self.autoindent:
1770 if self.autoindent:
1785 if num_ini_spaces(line) > self.indent_current_nsp:
1771 if num_ini_spaces(line) > self.indent_current_nsp:
1786 line = line[self.indent_current_nsp:]
1772 line = line[self.indent_current_nsp:]
1787 self.indent_current_nsp = 0
1773 self.indent_current_nsp = 0
1788
1774
1789 # store the unfiltered input before the user has any chance to modify
1775 # store the unfiltered input before the user has any chance to modify
1790 # it.
1776 # it.
1791 if line.strip():
1777 if line.strip():
1792 if continue_prompt:
1778 if continue_prompt:
1793 self.input_hist_raw[-1] += '%s\n' % line
1779 self.input_hist_raw[-1] += '%s\n' % line
1794 else:
1780 else:
1795 self.input_hist_raw.append('%s\n' % line)
1781 self.input_hist_raw.append('%s\n' % line)
1796
1782
1797 lineout = self.prefilter(line,continue_prompt)
1783 lineout = self.prefilter(line,continue_prompt)
1798 return lineout
1784 return lineout
1799
1785
1800 def split_user_input(self,line):
1786 def split_user_input(self,line):
1801 """Split user input into pre-char, function part and rest."""
1787 """Split user input into pre-char, function part and rest."""
1802
1788
1803 lsplit = self.line_split.match(line)
1789 lsplit = self.line_split.match(line)
1804 if lsplit is None: # no regexp match returns None
1790 if lsplit is None: # no regexp match returns None
1805 try:
1791 try:
1806 iFun,theRest = line.split(None,1)
1792 iFun,theRest = line.split(None,1)
1807 except ValueError:
1793 except ValueError:
1808 iFun,theRest = line,''
1794 iFun,theRest = line,''
1809 pre = re.match('^(\s*)(.*)',line).groups()[0]
1795 pre = re.match('^(\s*)(.*)',line).groups()[0]
1810 else:
1796 else:
1811 pre,iFun,theRest = lsplit.groups()
1797 pre,iFun,theRest = lsplit.groups()
1812
1798
1813 #print 'line:<%s>' % line # dbg
1799 #print 'line:<%s>' % line # dbg
1814 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1800 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1815 return pre,iFun.strip(),theRest
1801 return pre,iFun.strip(),theRest
1816
1802
1817 def _prefilter(self, line, continue_prompt):
1803 def _prefilter(self, line, continue_prompt):
1818 """Calls different preprocessors, depending on the form of line."""
1804 """Calls different preprocessors, depending on the form of line."""
1819
1805
1820 # All handlers *must* return a value, even if it's blank ('').
1806 # All handlers *must* return a value, even if it's blank ('').
1821
1807
1822 # Lines are NOT logged here. Handlers should process the line as
1808 # Lines are NOT logged here. Handlers should process the line as
1823 # needed, update the cache AND log it (so that the input cache array
1809 # needed, update the cache AND log it (so that the input cache array
1824 # stays synced).
1810 # stays synced).
1825
1811
1826 # This function is _very_ delicate, and since it's also the one which
1812 # This function is _very_ delicate, and since it's also the one which
1827 # determines IPython's response to user input, it must be as efficient
1813 # determines IPython's response to user input, it must be as efficient
1828 # as possible. For this reason it has _many_ returns in it, trying
1814 # as possible. For this reason it has _many_ returns in it, trying
1829 # always to exit as quickly as it can figure out what it needs to do.
1815 # always to exit as quickly as it can figure out what it needs to do.
1830
1816
1831 # This function is the main responsible for maintaining IPython's
1817 # This function is the main responsible for maintaining IPython's
1832 # behavior respectful of Python's semantics. So be _very_ careful if
1818 # behavior respectful of Python's semantics. So be _very_ careful if
1833 # making changes to anything here.
1819 # making changes to anything here.
1834
1820
1835 #.....................................................................
1821 #.....................................................................
1836 # Code begins
1822 # Code begins
1837
1823
1838 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1824 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1839
1825
1840 # save the line away in case we crash, so the post-mortem handler can
1826 # save the line away in case we crash, so the post-mortem handler can
1841 # record it
1827 # record it
1842 self._last_input_line = line
1828 self._last_input_line = line
1843
1829
1844 #print '***line: <%s>' % line # dbg
1830 #print '***line: <%s>' % line # dbg
1845
1831
1846 # the input history needs to track even empty lines
1832 # the input history needs to track even empty lines
1847 stripped = line.strip()
1833 stripped = line.strip()
1848
1834
1849 if not stripped:
1835 if not stripped:
1850 if not continue_prompt:
1836 if not continue_prompt:
1851 self.outputcache.prompt_count -= 1
1837 self.outputcache.prompt_count -= 1
1852 return self.handle_normal(line,continue_prompt)
1838 return self.handle_normal(line,continue_prompt)
1853 #return self.handle_normal('',continue_prompt)
1839 #return self.handle_normal('',continue_prompt)
1854
1840
1855 # print '***cont',continue_prompt # dbg
1841 # print '***cont',continue_prompt # dbg
1856 # special handlers are only allowed for single line statements
1842 # special handlers are only allowed for single line statements
1857 if continue_prompt and not self.rc.multi_line_specials:
1843 if continue_prompt and not self.rc.multi_line_specials:
1858 return self.handle_normal(line,continue_prompt)
1844 return self.handle_normal(line,continue_prompt)
1859
1845
1860
1846
1861 # For the rest, we need the structure of the input
1847 # For the rest, we need the structure of the input
1862 pre,iFun,theRest = self.split_user_input(line)
1848 pre,iFun,theRest = self.split_user_input(line)
1863
1849
1864 # See whether any pre-existing handler can take care of it
1850 # See whether any pre-existing handler can take care of it
1865
1851
1866 rewritten = self.hooks.input_prefilter(stripped)
1852 rewritten = self.hooks.input_prefilter(stripped)
1867 if rewritten != stripped: # ok, some prefilter did something
1853 if rewritten != stripped: # ok, some prefilter did something
1868 rewritten = pre + rewritten # add indentation
1854 rewritten = pre + rewritten # add indentation
1869 return self.handle_normal(rewritten)
1855 return self.handle_normal(rewritten)
1870
1856
1871
1857
1872
1858
1873
1859
1874 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1860 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1875
1861
1876 # First check for explicit escapes in the last/first character
1862 # First check for explicit escapes in the last/first character
1877 handler = None
1863 handler = None
1878 if line[-1] == self.ESC_HELP:
1864 if line[-1] == self.ESC_HELP:
1879 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1865 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1880 if handler is None:
1866 if handler is None:
1881 # look at the first character of iFun, NOT of line, so we skip
1867 # look at the first character of iFun, NOT of line, so we skip
1882 # leading whitespace in multiline input
1868 # leading whitespace in multiline input
1883 handler = self.esc_handlers.get(iFun[0:1])
1869 handler = self.esc_handlers.get(iFun[0:1])
1884 if handler is not None:
1870 if handler is not None:
1885 return handler(line,continue_prompt,pre,iFun,theRest)
1871 return handler(line,continue_prompt,pre,iFun,theRest)
1886 # Emacs ipython-mode tags certain input lines
1872 # Emacs ipython-mode tags certain input lines
1887 if line.endswith('# PYTHON-MODE'):
1873 if line.endswith('# PYTHON-MODE'):
1888 return self.handle_emacs(line,continue_prompt)
1874 return self.handle_emacs(line,continue_prompt)
1889
1875
1890 # Next, check if we can automatically execute this thing
1876 # Next, check if we can automatically execute this thing
1891
1877
1892 # Allow ! in multi-line statements if multi_line_specials is on:
1878 # Allow ! in multi-line statements if multi_line_specials is on:
1893 if continue_prompt and self.rc.multi_line_specials and \
1879 if continue_prompt and self.rc.multi_line_specials and \
1894 iFun.startswith(self.ESC_SHELL):
1880 iFun.startswith(self.ESC_SHELL):
1895 return self.handle_shell_escape(line,continue_prompt,
1881 return self.handle_shell_escape(line,continue_prompt,
1896 pre=pre,iFun=iFun,
1882 pre=pre,iFun=iFun,
1897 theRest=theRest)
1883 theRest=theRest)
1898
1884
1899 # Let's try to find if the input line is a magic fn
1885 # Let's try to find if the input line is a magic fn
1900 oinfo = None
1886 oinfo = None
1901 if hasattr(self,'magic_'+iFun):
1887 if hasattr(self,'magic_'+iFun):
1902 # WARNING: _ofind uses getattr(), so it can consume generators and
1888 # WARNING: _ofind uses getattr(), so it can consume generators and
1903 # cause other side effects.
1889 # cause other side effects.
1904 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1890 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1905 if oinfo['ismagic']:
1891 if oinfo['ismagic']:
1906 # Be careful not to call magics when a variable assignment is
1892 # Be careful not to call magics when a variable assignment is
1907 # being made (ls='hi', for example)
1893 # being made (ls='hi', for example)
1908 if self.rc.automagic and \
1894 if self.rc.automagic and \
1909 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1895 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1910 (self.rc.multi_line_specials or not continue_prompt):
1896 (self.rc.multi_line_specials or not continue_prompt):
1911 return self.handle_magic(line,continue_prompt,
1897 return self.handle_magic(line,continue_prompt,
1912 pre,iFun,theRest)
1898 pre,iFun,theRest)
1913 else:
1899 else:
1914 return self.handle_normal(line,continue_prompt)
1900 return self.handle_normal(line,continue_prompt)
1915
1901
1916 # If the rest of the line begins with an (in)equality, assginment or
1902 # If the rest of the line begins with an (in)equality, assginment or
1917 # function call, we should not call _ofind but simply execute it.
1903 # function call, we should not call _ofind but simply execute it.
1918 # This avoids spurious geattr() accesses on objects upon assignment.
1904 # This avoids spurious geattr() accesses on objects upon assignment.
1919 #
1905 #
1920 # It also allows users to assign to either alias or magic names true
1906 # It also allows users to assign to either alias or magic names true
1921 # python variables (the magic/alias systems always take second seat to
1907 # python variables (the magic/alias systems always take second seat to
1922 # true python code).
1908 # true python code).
1923 if theRest and theRest[0] in '!=()':
1909 if theRest and theRest[0] in '!=()':
1924 return self.handle_normal(line,continue_prompt)
1910 return self.handle_normal(line,continue_prompt)
1925
1911
1926 if oinfo is None:
1912 if oinfo is None:
1927 # let's try to ensure that _oinfo is ONLY called when autocall is
1913 # let's try to ensure that _oinfo is ONLY called when autocall is
1928 # on. Since it has inevitable potential side effects, at least
1914 # on. Since it has inevitable potential side effects, at least
1929 # having autocall off should be a guarantee to the user that no
1915 # having autocall off should be a guarantee to the user that no
1930 # weird things will happen.
1916 # weird things will happen.
1931
1917
1932 if self.rc.autocall:
1918 if self.rc.autocall:
1933 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1919 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1934 else:
1920 else:
1935 # in this case, all that's left is either an alias or
1921 # in this case, all that's left is either an alias or
1936 # processing the line normally.
1922 # processing the line normally.
1937 if iFun in self.alias_table:
1923 if iFun in self.alias_table:
1938 return self.handle_alias(line,continue_prompt,
1924 return self.handle_alias(line,continue_prompt,
1939 pre,iFun,theRest)
1925 pre,iFun,theRest)
1940
1926
1941 else:
1927 else:
1942 return self.handle_normal(line,continue_prompt)
1928 return self.handle_normal(line,continue_prompt)
1943
1929
1944 if not oinfo['found']:
1930 if not oinfo['found']:
1945 return self.handle_normal(line,continue_prompt)
1931 return self.handle_normal(line,continue_prompt)
1946 else:
1932 else:
1947 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1933 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1948 if oinfo['isalias']:
1934 if oinfo['isalias']:
1949 return self.handle_alias(line,continue_prompt,
1935 return self.handle_alias(line,continue_prompt,
1950 pre,iFun,theRest)
1936 pre,iFun,theRest)
1951
1937
1952 if (self.rc.autocall
1938 if (self.rc.autocall
1953 and
1939 and
1954 (
1940 (
1955 #only consider exclusion re if not "," or ";" autoquoting
1941 #only consider exclusion re if not "," or ";" autoquoting
1956 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
1942 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
1957 or pre == self.ESC_PAREN) or
1943 or pre == self.ESC_PAREN) or
1958 (not self.re_exclude_auto.match(theRest)))
1944 (not self.re_exclude_auto.match(theRest)))
1959 and
1945 and
1960 self.re_fun_name.match(iFun) and
1946 self.re_fun_name.match(iFun) and
1961 callable(oinfo['obj'])) :
1947 callable(oinfo['obj'])) :
1962 #print 'going auto' # dbg
1948 #print 'going auto' # dbg
1963 return self.handle_auto(line,continue_prompt,
1949 return self.handle_auto(line,continue_prompt,
1964 pre,iFun,theRest,oinfo['obj'])
1950 pre,iFun,theRest,oinfo['obj'])
1965 else:
1951 else:
1966 #print 'was callable?', callable(oinfo['obj']) # dbg
1952 #print 'was callable?', callable(oinfo['obj']) # dbg
1967 return self.handle_normal(line,continue_prompt)
1953 return self.handle_normal(line,continue_prompt)
1968
1954
1969 # If we get here, we have a normal Python line. Log and return.
1955 # If we get here, we have a normal Python line. Log and return.
1970 return self.handle_normal(line,continue_prompt)
1956 return self.handle_normal(line,continue_prompt)
1971
1957
1972 def _prefilter_dumb(self, line, continue_prompt):
1958 def _prefilter_dumb(self, line, continue_prompt):
1973 """simple prefilter function, for debugging"""
1959 """simple prefilter function, for debugging"""
1974 return self.handle_normal(line,continue_prompt)
1960 return self.handle_normal(line,continue_prompt)
1975
1961
1976 # Set the default prefilter() function (this can be user-overridden)
1962 # Set the default prefilter() function (this can be user-overridden)
1977 prefilter = _prefilter
1963 prefilter = _prefilter
1978
1964
1979 def handle_normal(self,line,continue_prompt=None,
1965 def handle_normal(self,line,continue_prompt=None,
1980 pre=None,iFun=None,theRest=None):
1966 pre=None,iFun=None,theRest=None):
1981 """Handle normal input lines. Use as a template for handlers."""
1967 """Handle normal input lines. Use as a template for handlers."""
1982
1968
1983 # With autoindent on, we need some way to exit the input loop, and I
1969 # With autoindent on, we need some way to exit the input loop, and I
1984 # don't want to force the user to have to backspace all the way to
1970 # don't want to force the user to have to backspace all the way to
1985 # clear the line. The rule will be in this case, that either two
1971 # clear the line. The rule will be in this case, that either two
1986 # lines of pure whitespace in a row, or a line of pure whitespace but
1972 # lines of pure whitespace in a row, or a line of pure whitespace but
1987 # of a size different to the indent level, will exit the input loop.
1973 # of a size different to the indent level, will exit the input loop.
1988
1974
1989 if (continue_prompt and self.autoindent and line.isspace() and
1975 if (continue_prompt and self.autoindent and line.isspace() and
1990 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
1976 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
1991 (self.buffer[-1]).isspace() )):
1977 (self.buffer[-1]).isspace() )):
1992 line = ''
1978 line = ''
1993
1979
1994 self.log(line,continue_prompt)
1980 self.log(line,continue_prompt)
1995 return line
1981 return line
1996
1982
1997 def handle_alias(self,line,continue_prompt=None,
1983 def handle_alias(self,line,continue_prompt=None,
1998 pre=None,iFun=None,theRest=None):
1984 pre=None,iFun=None,theRest=None):
1999 """Handle alias input lines. """
1985 """Handle alias input lines. """
2000
1986
2001 # pre is needed, because it carries the leading whitespace. Otherwise
1987 # pre is needed, because it carries the leading whitespace. Otherwise
2002 # aliases won't work in indented sections.
1988 # aliases won't work in indented sections.
2003 line_out = '%sipalias(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1989 line_out = '%sipalias(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2004 self.log(line_out,continue_prompt)
1990 self.log(line_out,continue_prompt)
2005 return line_out
1991 return line_out
2006
1992
2007 def handle_shell_escape(self, line, continue_prompt=None,
1993 def handle_shell_escape(self, line, continue_prompt=None,
2008 pre=None,iFun=None,theRest=None):
1994 pre=None,iFun=None,theRest=None):
2009 """Execute the line in a shell, empty return value"""
1995 """Execute the line in a shell, empty return value"""
2010
1996
2011 #print 'line in :', `line` # dbg
1997 #print 'line in :', `line` # dbg
2012 # Example of a special handler. Others follow a similar pattern.
1998 # Example of a special handler. Others follow a similar pattern.
2013 if line.lstrip().startswith('!!'):
1999 if line.lstrip().startswith('!!'):
2014 # rewrite iFun/theRest to properly hold the call to %sx and
2000 # rewrite iFun/theRest to properly hold the call to %sx and
2015 # the actual command to be executed, so handle_magic can work
2001 # the actual command to be executed, so handle_magic can work
2016 # correctly
2002 # correctly
2017 theRest = '%s %s' % (iFun[2:],theRest)
2003 theRest = '%s %s' % (iFun[2:],theRest)
2018 iFun = 'sx'
2004 iFun = 'sx'
2019 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2005 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2020 line.lstrip()[2:]),
2006 line.lstrip()[2:]),
2021 continue_prompt,pre,iFun,theRest)
2007 continue_prompt,pre,iFun,theRest)
2022 else:
2008 else:
2023 cmd=line.lstrip().lstrip('!')
2009 cmd=line.lstrip().lstrip('!')
2024 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2010 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2025 # update cache/log and return
2011 # update cache/log and return
2026 self.log(line_out,continue_prompt)
2012 self.log(line_out,continue_prompt)
2027 return line_out
2013 return line_out
2028
2014
2029 def handle_magic(self, line, continue_prompt=None,
2015 def handle_magic(self, line, continue_prompt=None,
2030 pre=None,iFun=None,theRest=None):
2016 pre=None,iFun=None,theRest=None):
2031 """Execute magic functions."""
2017 """Execute magic functions."""
2032
2018
2033
2019
2034 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2020 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2035 self.log(cmd,continue_prompt)
2021 self.log(cmd,continue_prompt)
2036 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2022 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2037 return cmd
2023 return cmd
2038
2024
2039 def handle_auto(self, line, continue_prompt=None,
2025 def handle_auto(self, line, continue_prompt=None,
2040 pre=None,iFun=None,theRest=None,obj=None):
2026 pre=None,iFun=None,theRest=None,obj=None):
2041 """Hande lines which can be auto-executed, quoting if requested."""
2027 """Hande lines which can be auto-executed, quoting if requested."""
2042
2028
2043 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2029 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2044
2030
2045 # This should only be active for single-line input!
2031 # This should only be active for single-line input!
2046 if continue_prompt:
2032 if continue_prompt:
2047 self.log(line,continue_prompt)
2033 self.log(line,continue_prompt)
2048 return line
2034 return line
2049
2035
2050 auto_rewrite = True
2036 auto_rewrite = True
2051
2037
2052 if pre == self.ESC_QUOTE:
2038 if pre == self.ESC_QUOTE:
2053 # Auto-quote splitting on whitespace
2039 # Auto-quote splitting on whitespace
2054 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2040 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2055 elif pre == self.ESC_QUOTE2:
2041 elif pre == self.ESC_QUOTE2:
2056 # Auto-quote whole string
2042 # Auto-quote whole string
2057 newcmd = '%s("%s")' % (iFun,theRest)
2043 newcmd = '%s("%s")' % (iFun,theRest)
2058 elif pre == self.ESC_PAREN:
2044 elif pre == self.ESC_PAREN:
2059 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2045 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2060 else:
2046 else:
2061 # Auto-paren.
2047 # Auto-paren.
2062 # We only apply it to argument-less calls if the autocall
2048 # We only apply it to argument-less calls if the autocall
2063 # parameter is set to 2. We only need to check that autocall is <
2049 # parameter is set to 2. We only need to check that autocall is <
2064 # 2, since this function isn't called unless it's at least 1.
2050 # 2, since this function isn't called unless it's at least 1.
2065 if not theRest and (self.rc.autocall < 2):
2051 if not theRest and (self.rc.autocall < 2):
2066 newcmd = '%s %s' % (iFun,theRest)
2052 newcmd = '%s %s' % (iFun,theRest)
2067 auto_rewrite = False
2053 auto_rewrite = False
2068 else:
2054 else:
2069 if theRest.startswith('['):
2055 if theRest.startswith('['):
2070 if hasattr(obj,'__getitem__'):
2056 if hasattr(obj,'__getitem__'):
2071 # Don't autocall in this case: item access for an object
2057 # Don't autocall in this case: item access for an object
2072 # which is BOTH callable and implements __getitem__.
2058 # which is BOTH callable and implements __getitem__.
2073 newcmd = '%s %s' % (iFun,theRest)
2059 newcmd = '%s %s' % (iFun,theRest)
2074 auto_rewrite = False
2060 auto_rewrite = False
2075 else:
2061 else:
2076 # if the object doesn't support [] access, go ahead and
2062 # if the object doesn't support [] access, go ahead and
2077 # autocall
2063 # autocall
2078 newcmd = '%s(%s)' % (iFun.rstrip(),",".join(theRest.split()))
2064 newcmd = '%s(%s)' % (iFun.rstrip(),",".join(theRest.split()))
2079 elif theRest.endswith(';'):
2065 elif theRest.endswith(';'):
2080 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2066 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2081 else:
2067 else:
2082 newcmd = '%s(%s)' % (iFun.rstrip(),",".join(theRest.split()))
2068 newcmd = '%s(%s)' % (iFun.rstrip(),",".join(theRest.split()))
2083
2069
2084 if auto_rewrite:
2070 if auto_rewrite:
2085 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2071 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2086 # log what is now valid Python, not the actual user input (without the
2072 # log what is now valid Python, not the actual user input (without the
2087 # final newline)
2073 # final newline)
2088 self.log(newcmd,continue_prompt)
2074 self.log(newcmd,continue_prompt)
2089 return newcmd
2075 return newcmd
2090
2076
2091 def handle_help(self, line, continue_prompt=None,
2077 def handle_help(self, line, continue_prompt=None,
2092 pre=None,iFun=None,theRest=None):
2078 pre=None,iFun=None,theRest=None):
2093 """Try to get some help for the object.
2079 """Try to get some help for the object.
2094
2080
2095 obj? or ?obj -> basic information.
2081 obj? or ?obj -> basic information.
2096 obj?? or ??obj -> more details.
2082 obj?? or ??obj -> more details.
2097 """
2083 """
2098
2084
2099 # We need to make sure that we don't process lines which would be
2085 # We need to make sure that we don't process lines which would be
2100 # otherwise valid python, such as "x=1 # what?"
2086 # otherwise valid python, such as "x=1 # what?"
2101 try:
2087 try:
2102 codeop.compile_command(line)
2088 codeop.compile_command(line)
2103 except SyntaxError:
2089 except SyntaxError:
2104 # We should only handle as help stuff which is NOT valid syntax
2090 # We should only handle as help stuff which is NOT valid syntax
2105 if line[0]==self.ESC_HELP:
2091 if line[0]==self.ESC_HELP:
2106 line = line[1:]
2092 line = line[1:]
2107 elif line[-1]==self.ESC_HELP:
2093 elif line[-1]==self.ESC_HELP:
2108 line = line[:-1]
2094 line = line[:-1]
2109 self.log('#?'+line)
2095 self.log('#?'+line)
2110 if line:
2096 if line:
2111 self.magic_pinfo(line)
2097 self.magic_pinfo(line)
2112 else:
2098 else:
2113 page(self.usage,screen_lines=self.rc.screen_length)
2099 page(self.usage,screen_lines=self.rc.screen_length)
2114 return '' # Empty string is needed here!
2100 return '' # Empty string is needed here!
2115 except:
2101 except:
2116 # Pass any other exceptions through to the normal handler
2102 # Pass any other exceptions through to the normal handler
2117 return self.handle_normal(line,continue_prompt)
2103 return self.handle_normal(line,continue_prompt)
2118 else:
2104 else:
2119 # If the code compiles ok, we should handle it normally
2105 # If the code compiles ok, we should handle it normally
2120 return self.handle_normal(line,continue_prompt)
2106 return self.handle_normal(line,continue_prompt)
2121
2107
2122 def getapi(self):
2108 def getapi(self):
2123 """ Get an IPApi object for this shell instance
2109 """ Get an IPApi object for this shell instance
2124
2110
2125 Getting an IPApi object is always preferable to accessing the shell
2111 Getting an IPApi object is always preferable to accessing the shell
2126 directly, but this holds true especially for extensions.
2112 directly, but this holds true especially for extensions.
2127
2113
2128 It should always be possible to implement an extension with IPApi
2114 It should always be possible to implement an extension with IPApi
2129 alone. If not, contact maintainer to request an addition.
2115 alone. If not, contact maintainer to request an addition.
2130
2116
2131 """
2117 """
2132 return self.api
2118 return self.api
2133
2119
2134 def handle_emacs(self,line,continue_prompt=None,
2120 def handle_emacs(self,line,continue_prompt=None,
2135 pre=None,iFun=None,theRest=None):
2121 pre=None,iFun=None,theRest=None):
2136 """Handle input lines marked by python-mode."""
2122 """Handle input lines marked by python-mode."""
2137
2123
2138 # Currently, nothing is done. Later more functionality can be added
2124 # Currently, nothing is done. Later more functionality can be added
2139 # here if needed.
2125 # here if needed.
2140
2126
2141 # The input cache shouldn't be updated
2127 # The input cache shouldn't be updated
2142
2128
2143 return line
2129 return line
2144
2130
2145 def mktempfile(self,data=None):
2131 def mktempfile(self,data=None):
2146 """Make a new tempfile and return its filename.
2132 """Make a new tempfile and return its filename.
2147
2133
2148 This makes a call to tempfile.mktemp, but it registers the created
2134 This makes a call to tempfile.mktemp, but it registers the created
2149 filename internally so ipython cleans it up at exit time.
2135 filename internally so ipython cleans it up at exit time.
2150
2136
2151 Optional inputs:
2137 Optional inputs:
2152
2138
2153 - data(None): if data is given, it gets written out to the temp file
2139 - data(None): if data is given, it gets written out to the temp file
2154 immediately, and the file is closed again."""
2140 immediately, and the file is closed again."""
2155
2141
2156 filename = tempfile.mktemp('.py','ipython_edit_')
2142 filename = tempfile.mktemp('.py','ipython_edit_')
2157 self.tempfiles.append(filename)
2143 self.tempfiles.append(filename)
2158
2144
2159 if data:
2145 if data:
2160 tmp_file = open(filename,'w')
2146 tmp_file = open(filename,'w')
2161 tmp_file.write(data)
2147 tmp_file.write(data)
2162 tmp_file.close()
2148 tmp_file.close()
2163 return filename
2149 return filename
2164
2150
2165 def write(self,data):
2151 def write(self,data):
2166 """Write a string to the default output"""
2152 """Write a string to the default output"""
2167 Term.cout.write(data)
2153 Term.cout.write(data)
2168
2154
2169 def write_err(self,data):
2155 def write_err(self,data):
2170 """Write a string to the default error output"""
2156 """Write a string to the default error output"""
2171 Term.cerr.write(data)
2157 Term.cerr.write(data)
2172
2158
2173 def exit(self):
2159 def exit(self):
2174 """Handle interactive exit.
2160 """Handle interactive exit.
2175
2161
2176 This method sets the exit_now attribute."""
2162 This method sets the exit_now attribute."""
2177
2163
2178 if self.rc.confirm_exit:
2164 if self.rc.confirm_exit:
2179 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2165 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2180 self.exit_now = True
2166 self.exit_now = True
2181 else:
2167 else:
2182 self.exit_now = True
2168 self.exit_now = True
2183 return self.exit_now
2169 return self.exit_now
2184
2170
2185 def safe_execfile(self,fname,*where,**kw):
2171 def safe_execfile(self,fname,*where,**kw):
2186 fname = os.path.expanduser(fname)
2172 fname = os.path.expanduser(fname)
2187
2173
2188 # find things also in current directory
2174 # find things also in current directory
2189 dname = os.path.dirname(fname)
2175 dname = os.path.dirname(fname)
2190 if not sys.path.count(dname):
2176 if not sys.path.count(dname):
2191 sys.path.append(dname)
2177 sys.path.append(dname)
2192
2178
2193 try:
2179 try:
2194 xfile = open(fname)
2180 xfile = open(fname)
2195 except:
2181 except:
2196 print >> Term.cerr, \
2182 print >> Term.cerr, \
2197 'Could not open file <%s> for safe execution.' % fname
2183 'Could not open file <%s> for safe execution.' % fname
2198 return None
2184 return None
2199
2185
2200 kw.setdefault('islog',0)
2186 kw.setdefault('islog',0)
2201 kw.setdefault('quiet',1)
2187 kw.setdefault('quiet',1)
2202 kw.setdefault('exit_ignore',0)
2188 kw.setdefault('exit_ignore',0)
2203 first = xfile.readline()
2189 first = xfile.readline()
2204 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2190 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2205 xfile.close()
2191 xfile.close()
2206 # line by line execution
2192 # line by line execution
2207 if first.startswith(loghead) or kw['islog']:
2193 if first.startswith(loghead) or kw['islog']:
2208 print 'Loading log file <%s> one line at a time...' % fname
2194 print 'Loading log file <%s> one line at a time...' % fname
2209 if kw['quiet']:
2195 if kw['quiet']:
2210 stdout_save = sys.stdout
2196 stdout_save = sys.stdout
2211 sys.stdout = StringIO.StringIO()
2197 sys.stdout = StringIO.StringIO()
2212 try:
2198 try:
2213 globs,locs = where[0:2]
2199 globs,locs = where[0:2]
2214 except:
2200 except:
2215 try:
2201 try:
2216 globs = locs = where[0]
2202 globs = locs = where[0]
2217 except:
2203 except:
2218 globs = locs = globals()
2204 globs = locs = globals()
2219 badblocks = []
2205 badblocks = []
2220
2206
2221 # we also need to identify indented blocks of code when replaying
2207 # we also need to identify indented blocks of code when replaying
2222 # logs and put them together before passing them to an exec
2208 # logs and put them together before passing them to an exec
2223 # statement. This takes a bit of regexp and look-ahead work in the
2209 # statement. This takes a bit of regexp and look-ahead work in the
2224 # file. It's easiest if we swallow the whole thing in memory
2210 # file. It's easiest if we swallow the whole thing in memory
2225 # first, and manually walk through the lines list moving the
2211 # first, and manually walk through the lines list moving the
2226 # counter ourselves.
2212 # counter ourselves.
2227 indent_re = re.compile('\s+\S')
2213 indent_re = re.compile('\s+\S')
2228 xfile = open(fname)
2214 xfile = open(fname)
2229 filelines = xfile.readlines()
2215 filelines = xfile.readlines()
2230 xfile.close()
2216 xfile.close()
2231 nlines = len(filelines)
2217 nlines = len(filelines)
2232 lnum = 0
2218 lnum = 0
2233 while lnum < nlines:
2219 while lnum < nlines:
2234 line = filelines[lnum]
2220 line = filelines[lnum]
2235 lnum += 1
2221 lnum += 1
2236 # don't re-insert logger status info into cache
2222 # don't re-insert logger status info into cache
2237 if line.startswith('#log#'):
2223 if line.startswith('#log#'):
2238 continue
2224 continue
2239 else:
2225 else:
2240 # build a block of code (maybe a single line) for execution
2226 # build a block of code (maybe a single line) for execution
2241 block = line
2227 block = line
2242 try:
2228 try:
2243 next = filelines[lnum] # lnum has already incremented
2229 next = filelines[lnum] # lnum has already incremented
2244 except:
2230 except:
2245 next = None
2231 next = None
2246 while next and indent_re.match(next):
2232 while next and indent_re.match(next):
2247 block += next
2233 block += next
2248 lnum += 1
2234 lnum += 1
2249 try:
2235 try:
2250 next = filelines[lnum]
2236 next = filelines[lnum]
2251 except:
2237 except:
2252 next = None
2238 next = None
2253 # now execute the block of one or more lines
2239 # now execute the block of one or more lines
2254 try:
2240 try:
2255 exec block in globs,locs
2241 exec block in globs,locs
2256 except SystemExit:
2242 except SystemExit:
2257 pass
2243 pass
2258 except:
2244 except:
2259 badblocks.append(block.rstrip())
2245 badblocks.append(block.rstrip())
2260 if kw['quiet']: # restore stdout
2246 if kw['quiet']: # restore stdout
2261 sys.stdout.close()
2247 sys.stdout.close()
2262 sys.stdout = stdout_save
2248 sys.stdout = stdout_save
2263 print 'Finished replaying log file <%s>' % fname
2249 print 'Finished replaying log file <%s>' % fname
2264 if badblocks:
2250 if badblocks:
2265 print >> sys.stderr, ('\nThe following lines/blocks in file '
2251 print >> sys.stderr, ('\nThe following lines/blocks in file '
2266 '<%s> reported errors:' % fname)
2252 '<%s> reported errors:' % fname)
2267
2253
2268 for badline in badblocks:
2254 for badline in badblocks:
2269 print >> sys.stderr, badline
2255 print >> sys.stderr, badline
2270 else: # regular file execution
2256 else: # regular file execution
2271 try:
2257 try:
2272 execfile(fname,*where)
2258 execfile(fname,*where)
2273 except SyntaxError:
2259 except SyntaxError:
2274 etype,evalue = sys.exc_info()[:2]
2260 etype,evalue = sys.exc_info()[:2]
2275 self.SyntaxTB(etype,evalue,[])
2261 self.SyntaxTB(etype,evalue,[])
2276 warn('Failure executing file: <%s>' % fname)
2262 warn('Failure executing file: <%s>' % fname)
2277 except SystemExit,status:
2263 except SystemExit,status:
2278 if not kw['exit_ignore']:
2264 if not kw['exit_ignore']:
2279 self.InteractiveTB()
2265 self.InteractiveTB()
2280 warn('Failure executing file: <%s>' % fname)
2266 warn('Failure executing file: <%s>' % fname)
2281 except:
2267 except:
2282 self.InteractiveTB()
2268 self.InteractiveTB()
2283 warn('Failure executing file: <%s>' % fname)
2269 warn('Failure executing file: <%s>' % fname)
2284
2270
2285 #************************* end of file <iplib.py> *****************************
2271 #************************* end of file <iplib.py> *****************************
General Comments 0
You need to be logged in to leave comments. Login now