##// END OF EJS Templates
- Work around pexcept buglet which causes wraparound problems with long...
fptest -
Show More

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

@@ -1,526 +1,548 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tools for inspecting Python objects.
2 """Tools for inspecting Python objects.
3
3
4 Uses syntax highlighting for presenting the various information elements.
4 Uses syntax highlighting for presenting the various information elements.
5
5
6 Similar in spirit to the inspect module, but all calls take a name argument to
6 Similar in spirit to the inspect module, but all calls take a name argument to
7 reference the name under which an object is being read.
7 reference the name under which an object is being read.
8
8
9 $Id: OInspect.py 1625 2006-08-12 10:34:44Z vivainio $
9 $Id: OInspect.py 1850 2006-10-28 19:48:13Z fptest $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
13 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #*****************************************************************************
17 #*****************************************************************************
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 __all__ = ['Inspector','InspectColors']
23 __all__ = ['Inspector','InspectColors']
24
24
25 # stdlib modules
25 # stdlib modules
26 import __builtin__
26 import __builtin__
27 import inspect
27 import inspect
28 import linecache
28 import linecache
29 import string
29 import string
30 import StringIO
30 import StringIO
31 import types
31 import types
32 import os
32 import os
33 import sys
33 import sys
34 # IPython's own
34 # IPython's own
35 from IPython import PyColorize
35 from IPython import PyColorize
36 from IPython.genutils import page,indent,Term,mkdict
36 from IPython.genutils import page,indent,Term,mkdict
37 from IPython.Itpl import itpl
37 from IPython.Itpl import itpl
38 from IPython.wildcard import list_namespace
38 from IPython.wildcard import list_namespace
39 from IPython.ColorANSI import *
39 from IPython.ColorANSI import *
40
40
41 #****************************************************************************
41 #****************************************************************************
42 # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We
42 # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We
43 # simply monkeypatch inspect with code copied from python 2.4.
43 # simply monkeypatch inspect with code copied from python 2.4.
44 if sys.version_info[:2] == (2,3):
44 if sys.version_info[:2] == (2,3):
45 from inspect import ismodule, getabsfile, modulesbyfile
45 from inspect import ismodule, getabsfile, modulesbyfile
46 def getmodule(object):
46 def getmodule(object):
47 """Return the module an object was defined in, or None if not found."""
47 """Return the module an object was defined in, or None if not found."""
48 if ismodule(object):
48 if ismodule(object):
49 return object
49 return object
50 if hasattr(object, '__module__'):
50 if hasattr(object, '__module__'):
51 return sys.modules.get(object.__module__)
51 return sys.modules.get(object.__module__)
52 try:
52 try:
53 file = getabsfile(object)
53 file = getabsfile(object)
54 except TypeError:
54 except TypeError:
55 return None
55 return None
56 if file in modulesbyfile:
56 if file in modulesbyfile:
57 return sys.modules.get(modulesbyfile[file])
57 return sys.modules.get(modulesbyfile[file])
58 for module in sys.modules.values():
58 for module in sys.modules.values():
59 if hasattr(module, '__file__'):
59 if hasattr(module, '__file__'):
60 modulesbyfile[
60 modulesbyfile[
61 os.path.realpath(
61 os.path.realpath(
62 getabsfile(module))] = module.__name__
62 getabsfile(module))] = module.__name__
63 if file in modulesbyfile:
63 if file in modulesbyfile:
64 return sys.modules.get(modulesbyfile[file])
64 return sys.modules.get(modulesbyfile[file])
65 main = sys.modules['__main__']
65 main = sys.modules['__main__']
66 if not hasattr(object, '__name__'):
66 if not hasattr(object, '__name__'):
67 return None
67 return None
68 if hasattr(main, object.__name__):
68 if hasattr(main, object.__name__):
69 mainobject = getattr(main, object.__name__)
69 mainobject = getattr(main, object.__name__)
70 if mainobject is object:
70 if mainobject is object:
71 return main
71 return main
72 builtin = sys.modules['__builtin__']
72 builtin = sys.modules['__builtin__']
73 if hasattr(builtin, object.__name__):
73 if hasattr(builtin, object.__name__):
74 builtinobject = getattr(builtin, object.__name__)
74 builtinobject = getattr(builtin, object.__name__)
75 if builtinobject is object:
75 if builtinobject is object:
76 return builtin
76 return builtin
77
77
78 inspect.getmodule = getmodule
78 inspect.getmodule = getmodule
79
79
80 #****************************************************************************
80 #****************************************************************************
81 # Builtin color schemes
81 # Builtin color schemes
82
82
83 Colors = TermColors # just a shorthand
83 Colors = TermColors # just a shorthand
84
84
85 # Build a few color schemes
85 # Build a few color schemes
86 NoColor = ColorScheme(
86 NoColor = ColorScheme(
87 'NoColor',{
87 'NoColor',{
88 'header' : Colors.NoColor,
88 'header' : Colors.NoColor,
89 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
89 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
90 } )
90 } )
91
91
92 LinuxColors = ColorScheme(
92 LinuxColors = ColorScheme(
93 'Linux',{
93 'Linux',{
94 'header' : Colors.LightRed,
94 'header' : Colors.LightRed,
95 'normal' : Colors.Normal # color off (usu. Colors.Normal)
95 'normal' : Colors.Normal # color off (usu. Colors.Normal)
96 } )
96 } )
97
97
98 LightBGColors = ColorScheme(
98 LightBGColors = ColorScheme(
99 'LightBG',{
99 'LightBG',{
100 'header' : Colors.Red,
100 'header' : Colors.Red,
101 'normal' : Colors.Normal # color off (usu. Colors.Normal)
101 'normal' : Colors.Normal # color off (usu. Colors.Normal)
102 } )
102 } )
103
103
104 # Build table of color schemes (needed by the parser)
104 # Build table of color schemes (needed by the parser)
105 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
105 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
106 'Linux')
106 'Linux')
107
107
108 #****************************************************************************
108 #****************************************************************************
109 # Auxiliary functions
109 # Auxiliary functions
110 def getdoc(obj):
110 def getdoc(obj):
111 """Stable wrapper around inspect.getdoc.
111 """Stable wrapper around inspect.getdoc.
112
112
113 This can't crash because of attribute problems.
113 This can't crash because of attribute problems.
114
114
115 It also attempts to call a getdoc() method on the given object. This
115 It also attempts to call a getdoc() method on the given object. This
116 allows objects which provide their docstrings via non-standard mechanisms
116 allows objects which provide their docstrings via non-standard mechanisms
117 (like Pyro proxies) to still be inspected by ipython's ? system."""
117 (like Pyro proxies) to still be inspected by ipython's ? system."""
118
118
119 ds = None # default return value
119 ds = None # default return value
120 try:
120 try:
121 ds = inspect.getdoc(obj)
121 ds = inspect.getdoc(obj)
122 except:
122 except:
123 # Harden against an inspect failure, which can occur with
123 # Harden against an inspect failure, which can occur with
124 # SWIG-wrapped extensions.
124 # SWIG-wrapped extensions.
125 pass
125 pass
126 # Allow objects to offer customized documentation via a getdoc method:
126 # Allow objects to offer customized documentation via a getdoc method:
127 try:
127 try:
128 ds2 = obj.getdoc()
128 ds2 = obj.getdoc()
129 except:
129 except:
130 pass
130 pass
131 else:
131 else:
132 # if we get extra info, we add it to the normal docstring.
132 # if we get extra info, we add it to the normal docstring.
133 if ds is None:
133 if ds is None:
134 ds = ds2
134 ds = ds2
135 else:
135 else:
136 ds = '%s\n%s' % (ds,ds2)
136 ds = '%s\n%s' % (ds,ds2)
137 return ds
137 return ds
138
138
139 def getsource(obj,is_binary=False):
140 """Wrapper around inspect.getsource.
141
142 This can be modified by other projects to provide customized source
143 extraction.
144
145 Inputs:
146
147 - obj: an object whose source code we will attempt to extract.
148
149 Optional inputs:
150
151 - is_binary: whether the object is known to come from a binary source.
152 This implementation will skip returning any output for binary objects, but
153 custom extractors may know how to meaninfully process them."""
154
155 if is_binary:
156 return None
157 else:
158 return inspect.getsource(obj)
159
139 #****************************************************************************
160 #****************************************************************************
140 # Class definitions
161 # Class definitions
141
162
142 class myStringIO(StringIO.StringIO):
163 class myStringIO(StringIO.StringIO):
143 """Adds a writeln method to normal StringIO."""
164 """Adds a writeln method to normal StringIO."""
144 def writeln(self,*arg,**kw):
165 def writeln(self,*arg,**kw):
145 """Does a write() and then a write('\n')"""
166 """Does a write() and then a write('\n')"""
146 self.write(*arg,**kw)
167 self.write(*arg,**kw)
147 self.write('\n')
168 self.write('\n')
148
169
149 class Inspector:
170 class Inspector:
150 def __init__(self,color_table,code_color_table,scheme,
171 def __init__(self,color_table,code_color_table,scheme,
151 str_detail_level=0):
172 str_detail_level=0):
152 self.color_table = color_table
173 self.color_table = color_table
153 self.parser = PyColorize.Parser(code_color_table,out='str')
174 self.parser = PyColorize.Parser(code_color_table,out='str')
154 self.format = self.parser.format
175 self.format = self.parser.format
155 self.str_detail_level = str_detail_level
176 self.str_detail_level = str_detail_level
156 self.set_active_scheme(scheme)
177 self.set_active_scheme(scheme)
157
178
158 def __getargspec(self,obj):
179 def __getargspec(self,obj):
159 """Get the names and default values of a function's arguments.
180 """Get the names and default values of a function's arguments.
160
181
161 A tuple of four things is returned: (args, varargs, varkw, defaults).
182 A tuple of four things is returned: (args, varargs, varkw, defaults).
162 'args' is a list of the argument names (it may contain nested lists).
183 'args' is a list of the argument names (it may contain nested lists).
163 'varargs' and 'varkw' are the names of the * and ** arguments or None.
184 'varargs' and 'varkw' are the names of the * and ** arguments or None.
164 'defaults' is an n-tuple of the default values of the last n arguments.
185 'defaults' is an n-tuple of the default values of the last n arguments.
165
186
166 Modified version of inspect.getargspec from the Python Standard
187 Modified version of inspect.getargspec from the Python Standard
167 Library."""
188 Library."""
168
189
169 if inspect.isfunction(obj):
190 if inspect.isfunction(obj):
170 func_obj = obj
191 func_obj = obj
171 elif inspect.ismethod(obj):
192 elif inspect.ismethod(obj):
172 func_obj = obj.im_func
193 func_obj = obj.im_func
173 else:
194 else:
174 raise TypeError, 'arg is not a Python function'
195 raise TypeError, 'arg is not a Python function'
175 args, varargs, varkw = inspect.getargs(func_obj.func_code)
196 args, varargs, varkw = inspect.getargs(func_obj.func_code)
176 return args, varargs, varkw, func_obj.func_defaults
197 return args, varargs, varkw, func_obj.func_defaults
177
198
178 def __getdef(self,obj,oname=''):
199 def __getdef(self,obj,oname=''):
179 """Return the definition header for any callable object.
200 """Return the definition header for any callable object.
180
201
181 If any exception is generated, None is returned instead and the
202 If any exception is generated, None is returned instead and the
182 exception is suppressed."""
203 exception is suppressed."""
183
204
184 try:
205 try:
185 return oname + inspect.formatargspec(*self.__getargspec(obj))
206 return oname + inspect.formatargspec(*self.__getargspec(obj))
186 except:
207 except:
187 return None
208 return None
188
209
189 def __head(self,h):
210 def __head(self,h):
190 """Return a header string with proper colors."""
211 """Return a header string with proper colors."""
191 return '%s%s%s' % (self.color_table.active_colors.header,h,
212 return '%s%s%s' % (self.color_table.active_colors.header,h,
192 self.color_table.active_colors.normal)
213 self.color_table.active_colors.normal)
193
214
194 def set_active_scheme(self,scheme):
215 def set_active_scheme(self,scheme):
195 self.color_table.set_active_scheme(scheme)
216 self.color_table.set_active_scheme(scheme)
196 self.parser.color_table.set_active_scheme(scheme)
217 self.parser.color_table.set_active_scheme(scheme)
197
218
198 def noinfo(self,msg,oname):
219 def noinfo(self,msg,oname):
199 """Generic message when no information is found."""
220 """Generic message when no information is found."""
200 print 'No %s found' % msg,
221 print 'No %s found' % msg,
201 if oname:
222 if oname:
202 print 'for %s' % oname
223 print 'for %s' % oname
203 else:
224 else:
204 print
225 print
205
226
206 def pdef(self,obj,oname=''):
227 def pdef(self,obj,oname=''):
207 """Print the definition header for any callable object.
228 """Print the definition header for any callable object.
208
229
209 If the object is a class, print the constructor information."""
230 If the object is a class, print the constructor information."""
210
231
211 if not callable(obj):
232 if not callable(obj):
212 print 'Object is not callable.'
233 print 'Object is not callable.'
213 return
234 return
214
235
215 header = ''
236 header = ''
216 if type(obj) is types.ClassType:
237 if type(obj) is types.ClassType:
217 header = self.__head('Class constructor information:\n')
238 header = self.__head('Class constructor information:\n')
218 obj = obj.__init__
239 obj = obj.__init__
219 elif type(obj) is types.InstanceType:
240 elif type(obj) is types.InstanceType:
220 obj = obj.__call__
241 obj = obj.__call__
221
242
222 output = self.__getdef(obj,oname)
243 output = self.__getdef(obj,oname)
223 if output is None:
244 if output is None:
224 self.noinfo('definition header',oname)
245 self.noinfo('definition header',oname)
225 else:
246 else:
226 print >>Term.cout, header,self.format(output),
247 print >>Term.cout, header,self.format(output),
227
248
228 def pdoc(self,obj,oname='',formatter = None):
249 def pdoc(self,obj,oname='',formatter = None):
229 """Print the docstring for any object.
250 """Print the docstring for any object.
230
251
231 Optional:
252 Optional:
232 -formatter: a function to run the docstring through for specially
253 -formatter: a function to run the docstring through for specially
233 formatted docstrings."""
254 formatted docstrings."""
234
255
235 head = self.__head # so that itpl can find it even if private
256 head = self.__head # so that itpl can find it even if private
236 ds = getdoc(obj)
257 ds = getdoc(obj)
237 if formatter:
258 if formatter:
238 ds = formatter(ds)
259 ds = formatter(ds)
239 if type(obj) is types.ClassType:
260 if type(obj) is types.ClassType:
240 init_ds = getdoc(obj.__init__)
261 init_ds = getdoc(obj.__init__)
241 output = itpl('$head("Class Docstring:")\n'
262 output = itpl('$head("Class Docstring:")\n'
242 '$indent(ds)\n'
263 '$indent(ds)\n'
243 '$head("Constructor Docstring"):\n'
264 '$head("Constructor Docstring"):\n'
244 '$indent(init_ds)')
265 '$indent(init_ds)')
245 elif type(obj) is types.InstanceType and hasattr(obj,'__call__'):
266 elif type(obj) is types.InstanceType and hasattr(obj,'__call__'):
246 call_ds = getdoc(obj.__call__)
267 call_ds = getdoc(obj.__call__)
247 if call_ds:
268 if call_ds:
248 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
269 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
249 '$head("Calling Docstring:")\n$indent(call_ds)')
270 '$head("Calling Docstring:")\n$indent(call_ds)')
250 else:
271 else:
251 output = ds
272 output = ds
252 else:
273 else:
253 output = ds
274 output = ds
254 if output is None:
275 if output is None:
255 self.noinfo('documentation',oname)
276 self.noinfo('documentation',oname)
256 return
277 return
257 page(output)
278 page(output)
258
279
259 def psource(self,obj,oname=''):
280 def psource(self,obj,oname=''):
260 """Print the source code for an object."""
281 """Print the source code for an object."""
261
282
262 # Flush the source cache because inspect can return out-of-date source
283 # Flush the source cache because inspect can return out-of-date source
263 linecache.checkcache()
284 linecache.checkcache()
264 try:
285 try:
265 src = inspect.getsource(obj)
286 src = getsource(obj)
266 except:
287 except:
267 self.noinfo('source',oname)
288 self.noinfo('source',oname)
268 else:
289 else:
269 page(self.format(src))
290 page(self.format(src))
270
291
271 def pfile(self,obj,oname=''):
292 def pfile(self,obj,oname=''):
272 """Show the whole file where an object was defined."""
293 """Show the whole file where an object was defined."""
273 try:
294 try:
274 sourcelines,lineno = inspect.getsourcelines(obj)
295 sourcelines,lineno = inspect.getsourcelines(obj)
275 except:
296 except:
276 self.noinfo('file',oname)
297 self.noinfo('file',oname)
277 else:
298 else:
278 # run contents of file through pager starting at line
299 # run contents of file through pager starting at line
279 # where the object is defined
300 # where the object is defined
280 ofile = inspect.getabsfile(obj)
301 ofile = inspect.getabsfile(obj)
281
302
282 if (ofile.endswith('.so') or ofile.endswith('.dll')):
303 if (ofile.endswith('.so') or ofile.endswith('.dll')):
283 print 'File %r is binary, not printing.' % ofile
304 print 'File %r is binary, not printing.' % ofile
284 elif not os.path.isfile(ofile):
305 elif not os.path.isfile(ofile):
285 print 'File %r does not exist, not printing.' % ofile
306 print 'File %r does not exist, not printing.' % ofile
286 else:
307 else:
287 # Print only text files, not extension binaries.
308 # Print only text files, not extension binaries.
288 page(self.format(open(ofile).read()),lineno)
309 page(self.format(open(ofile).read()),lineno)
289 #page(self.format(open(inspect.getabsfile(obj)).read()),lineno)
310 #page(self.format(open(inspect.getabsfile(obj)).read()),lineno)
290
311
291 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
312 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
292 """Show detailed information about an object.
313 """Show detailed information about an object.
293
314
294 Optional arguments:
315 Optional arguments:
295
316
296 - oname: name of the variable pointing to the object.
317 - oname: name of the variable pointing to the object.
297
318
298 - formatter: special formatter for docstrings (see pdoc)
319 - formatter: special formatter for docstrings (see pdoc)
299
320
300 - info: a structure with some information fields which may have been
321 - info: a structure with some information fields which may have been
301 precomputed already.
322 precomputed already.
302
323
303 - detail_level: if set to 1, more information is given.
324 - detail_level: if set to 1, more information is given.
304 """
325 """
305
326
306 obj_type = type(obj)
327 obj_type = type(obj)
307
328
308 header = self.__head
329 header = self.__head
309 if info is None:
330 if info is None:
310 ismagic = 0
331 ismagic = 0
311 isalias = 0
332 isalias = 0
312 ospace = ''
333 ospace = ''
313 else:
334 else:
314 ismagic = info.ismagic
335 ismagic = info.ismagic
315 isalias = info.isalias
336 isalias = info.isalias
316 ospace = info.namespace
337 ospace = info.namespace
317 # Get docstring, special-casing aliases:
338 # Get docstring, special-casing aliases:
318 if isalias:
339 if isalias:
319 ds = "Alias to the system command:\n %s" % obj[1]
340 ds = "Alias to the system command:\n %s" % obj[1]
320 else:
341 else:
321 ds = getdoc(obj)
342 ds = getdoc(obj)
322 if ds is None:
343 if ds is None:
323 ds = '<no docstring>'
344 ds = '<no docstring>'
324 if formatter is not None:
345 if formatter is not None:
325 ds = formatter(ds)
346 ds = formatter(ds)
326
347
327 # store output in a list which gets joined with \n at the end.
348 # store output in a list which gets joined with \n at the end.
328 out = myStringIO()
349 out = myStringIO()
329
350
330 string_max = 200 # max size of strings to show (snipped if longer)
351 string_max = 200 # max size of strings to show (snipped if longer)
331 shalf = int((string_max -5)/2)
352 shalf = int((string_max -5)/2)
332
353
333 if ismagic:
354 if ismagic:
334 obj_type_name = 'Magic function'
355 obj_type_name = 'Magic function'
335 elif isalias:
356 elif isalias:
336 obj_type_name = 'System alias'
357 obj_type_name = 'System alias'
337 else:
358 else:
338 obj_type_name = obj_type.__name__
359 obj_type_name = obj_type.__name__
339 out.writeln(header('Type:\t\t')+obj_type_name)
360 out.writeln(header('Type:\t\t')+obj_type_name)
340
361
341 try:
362 try:
342 bclass = obj.__class__
363 bclass = obj.__class__
343 out.writeln(header('Base Class:\t')+str(bclass))
364 out.writeln(header('Base Class:\t')+str(bclass))
344 except: pass
365 except: pass
345
366
346 # String form, but snip if too long in ? form (full in ??)
367 # String form, but snip if too long in ? form (full in ??)
347 if detail_level >= self.str_detail_level:
368 if detail_level >= self.str_detail_level:
348 try:
369 try:
349 ostr = str(obj)
370 ostr = str(obj)
350 str_head = 'String Form:'
371 str_head = 'String Form:'
351 if not detail_level and len(ostr)>string_max:
372 if not detail_level and len(ostr)>string_max:
352 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
373 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
353 ostr = ("\n" + " " * len(str_head.expandtabs())).\
374 ostr = ("\n" + " " * len(str_head.expandtabs())).\
354 join(map(string.strip,ostr.split("\n")))
375 join(map(string.strip,ostr.split("\n")))
355 if ostr.find('\n') > -1:
376 if ostr.find('\n') > -1:
356 # Print multi-line strings starting at the next line.
377 # Print multi-line strings starting at the next line.
357 str_sep = '\n'
378 str_sep = '\n'
358 else:
379 else:
359 str_sep = '\t'
380 str_sep = '\t'
360 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
381 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
361 except:
382 except:
362 pass
383 pass
363
384
364 if ospace:
385 if ospace:
365 out.writeln(header('Namespace:\t')+ospace)
386 out.writeln(header('Namespace:\t')+ospace)
366
387
367 # Length (for strings and lists)
388 # Length (for strings and lists)
368 try:
389 try:
369 length = str(len(obj))
390 length = str(len(obj))
370 out.writeln(header('Length:\t\t')+length)
391 out.writeln(header('Length:\t\t')+length)
371 except: pass
392 except: pass
372
393
373 # Filename where object was defined
394 # Filename where object was defined
374 binary_file = False
395 binary_file = False
375 try:
396 try:
376 fname = inspect.getabsfile(obj)
397 fname = inspect.getabsfile(obj)
377 if fname.endswith('<string>'):
398 if fname.endswith('<string>'):
378 fname = 'Dynamically generated function. No source code available.'
399 fname = 'Dynamically generated function. No source code available.'
379 if (fname.endswith('.so') or fname.endswith('.dll') or
400 if (fname.endswith('.so') or fname.endswith('.dll') or
380 not os.path.isfile(fname)):
401 not os.path.isfile(fname)):
381 binary_file = True
402 binary_file = True
382 out.writeln(header('File:\t\t')+fname)
403 out.writeln(header('File:\t\t')+fname)
383 except:
404 except:
384 # if anything goes wrong, we don't want to show source, so it's as
405 # if anything goes wrong, we don't want to show source, so it's as
385 # if the file was binary
406 # if the file was binary
386 binary_file = True
407 binary_file = True
387
408
388 # reconstruct the function definition and print it:
409 # reconstruct the function definition and print it:
389 defln = self.__getdef(obj,oname)
410 defln = self.__getdef(obj,oname)
390 if defln:
411 if defln:
391 out.write(header('Definition:\t')+self.format(defln))
412 out.write(header('Definition:\t')+self.format(defln))
392
413
393 # Docstrings only in detail 0 mode, since source contains them (we
414 # Docstrings only in detail 0 mode, since source contains them (we
394 # avoid repetitions). If source fails, we add them back, see below.
415 # avoid repetitions). If source fails, we add them back, see below.
395 if ds and detail_level == 0:
416 if ds and detail_level == 0:
396 out.writeln(header('Docstring:\n') + indent(ds))
417 out.writeln(header('Docstring:\n') + indent(ds))
397
418
398
419
399 # Original source code for any callable
420 # Original source code for any callable
400 if detail_level:
421 if detail_level:
401 # Flush the source cache because inspect can return out-of-date source
422 # Flush the source cache because inspect can return out-of-date source
402 linecache.checkcache()
423 linecache.checkcache()
403 source_success = False
424 source_success = False
404 try:
425 try:
405 if not binary_file:
426 source = self.format(getsource(obj,binary_file))
406 source = self.format(inspect.getsource(obj))
427 if source:
407 out.write(header('Source:\n')+source.rstrip())
428 out.write(header('Source:\n')+source.rstrip())
408 source_success = True
429 source_success = True
409 except:
430 except Exception, msg:
410 pass
431 pass
411
432
412 if ds and not source_success:
433 if ds and not source_success:
413 out.writeln(header('Docstring [source file open failed]:\n') + indent(ds))
434 out.writeln(header('Docstring [source file open failed]:\n')
435 + indent(ds))
414
436
415 # Constructor docstring for classes
437 # Constructor docstring for classes
416 if obj_type is types.ClassType:
438 if obj_type is types.ClassType:
417 # reconstruct the function definition and print it:
439 # reconstruct the function definition and print it:
418 try:
440 try:
419 obj_init = obj.__init__
441 obj_init = obj.__init__
420 except AttributeError:
442 except AttributeError:
421 init_def = init_ds = None
443 init_def = init_ds = None
422 else:
444 else:
423 init_def = self.__getdef(obj_init,oname)
445 init_def = self.__getdef(obj_init,oname)
424 init_ds = getdoc(obj_init)
446 init_ds = getdoc(obj_init)
425
447
426 if init_def or init_ds:
448 if init_def or init_ds:
427 out.writeln(header('\nConstructor information:'))
449 out.writeln(header('\nConstructor information:'))
428 if init_def:
450 if init_def:
429 out.write(header('Definition:\t')+ self.format(init_def))
451 out.write(header('Definition:\t')+ self.format(init_def))
430 if init_ds:
452 if init_ds:
431 out.writeln(header('Docstring:\n') + indent(init_ds))
453 out.writeln(header('Docstring:\n') + indent(init_ds))
432 # and class docstring for instances:
454 # and class docstring for instances:
433 elif obj_type is types.InstanceType:
455 elif obj_type is types.InstanceType:
434
456
435 # First, check whether the instance docstring is identical to the
457 # First, check whether the instance docstring is identical to the
436 # class one, and print it separately if they don't coincide. In
458 # class one, and print it separately if they don't coincide. In
437 # most cases they will, but it's nice to print all the info for
459 # most cases they will, but it's nice to print all the info for
438 # objects which use instance-customized docstrings.
460 # objects which use instance-customized docstrings.
439 if ds:
461 if ds:
440 class_ds = getdoc(obj.__class__)
462 class_ds = getdoc(obj.__class__)
441 if class_ds and ds != class_ds:
463 if class_ds and ds != class_ds:
442 out.writeln(header('Class Docstring:\n') +
464 out.writeln(header('Class Docstring:\n') +
443 indent(class_ds))
465 indent(class_ds))
444
466
445 # Next, try to show constructor docstrings
467 # Next, try to show constructor docstrings
446 try:
468 try:
447 init_ds = getdoc(obj.__init__)
469 init_ds = getdoc(obj.__init__)
448 except AttributeError:
470 except AttributeError:
449 init_ds = None
471 init_ds = None
450 if init_ds:
472 if init_ds:
451 out.writeln(header('Constructor Docstring:\n') +
473 out.writeln(header('Constructor Docstring:\n') +
452 indent(init_ds))
474 indent(init_ds))
453
475
454 # Call form docstring for callable instances
476 # Call form docstring for callable instances
455 if hasattr(obj,'__call__'):
477 if hasattr(obj,'__call__'):
456 out.writeln(header('Callable:\t')+'Yes')
478 out.writeln(header('Callable:\t')+'Yes')
457 call_def = self.__getdef(obj.__call__,oname)
479 call_def = self.__getdef(obj.__call__,oname)
458 if call_def is None:
480 if call_def is None:
459 out.write(header('Call def:\t')+
481 out.write(header('Call def:\t')+
460 'Calling definition not available.')
482 'Calling definition not available.')
461 else:
483 else:
462 out.write(header('Call def:\t')+self.format(call_def))
484 out.write(header('Call def:\t')+self.format(call_def))
463 call_ds = getdoc(obj.__call__)
485 call_ds = getdoc(obj.__call__)
464 if call_ds:
486 if call_ds:
465 out.writeln(header('Call docstring:\n') + indent(call_ds))
487 out.writeln(header('Call docstring:\n') + indent(call_ds))
466
488
467 # Finally send to printer/pager
489 # Finally send to printer/pager
468 output = out.getvalue()
490 output = out.getvalue()
469 if output:
491 if output:
470 page(output)
492 page(output)
471 # end pinfo
493 # end pinfo
472
494
473 def psearch(self,pattern,ns_table,ns_search=[],
495 def psearch(self,pattern,ns_table,ns_search=[],
474 ignore_case=False,show_all=False):
496 ignore_case=False,show_all=False):
475 """Search namespaces with wildcards for objects.
497 """Search namespaces with wildcards for objects.
476
498
477 Arguments:
499 Arguments:
478
500
479 - pattern: string containing shell-like wildcards to use in namespace
501 - pattern: string containing shell-like wildcards to use in namespace
480 searches and optionally a type specification to narrow the search to
502 searches and optionally a type specification to narrow the search to
481 objects of that type.
503 objects of that type.
482
504
483 - ns_table: dict of name->namespaces for search.
505 - ns_table: dict of name->namespaces for search.
484
506
485 Optional arguments:
507 Optional arguments:
486
508
487 - ns_search: list of namespace names to include in search.
509 - ns_search: list of namespace names to include in search.
488
510
489 - ignore_case(False): make the search case-insensitive.
511 - ignore_case(False): make the search case-insensitive.
490
512
491 - show_all(False): show all names, including those starting with
513 - show_all(False): show all names, including those starting with
492 underscores.
514 underscores.
493 """
515 """
494 # defaults
516 # defaults
495 type_pattern = 'all'
517 type_pattern = 'all'
496 filter = ''
518 filter = ''
497
519
498 cmds = pattern.split()
520 cmds = pattern.split()
499 len_cmds = len(cmds)
521 len_cmds = len(cmds)
500 if len_cmds == 1:
522 if len_cmds == 1:
501 # Only filter pattern given
523 # Only filter pattern given
502 filter = cmds[0]
524 filter = cmds[0]
503 elif len_cmds == 2:
525 elif len_cmds == 2:
504 # Both filter and type specified
526 # Both filter and type specified
505 filter,type_pattern = cmds
527 filter,type_pattern = cmds
506 else:
528 else:
507 raise ValueError('invalid argument string for psearch: <%s>' %
529 raise ValueError('invalid argument string for psearch: <%s>' %
508 pattern)
530 pattern)
509
531
510 # filter search namespaces
532 # filter search namespaces
511 for name in ns_search:
533 for name in ns_search:
512 if name not in ns_table:
534 if name not in ns_table:
513 raise ValueError('invalid namespace <%s>. Valid names: %s' %
535 raise ValueError('invalid namespace <%s>. Valid names: %s' %
514 (name,ns_table.keys()))
536 (name,ns_table.keys()))
515
537
516 #print 'type_pattern:',type_pattern # dbg
538 #print 'type_pattern:',type_pattern # dbg
517 search_result = []
539 search_result = []
518 for ns_name in ns_search:
540 for ns_name in ns_search:
519 ns = ns_table[ns_name]
541 ns = ns_table[ns_name]
520 tmp_res = list(list_namespace(ns,type_pattern,filter,
542 tmp_res = list(list_namespace(ns,type_pattern,filter,
521 ignore_case=ignore_case,
543 ignore_case=ignore_case,
522 show_all=show_all))
544 show_all=show_all))
523 search_result.extend(tmp_res)
545 search_result.extend(tmp_res)
524 search_result.sort()
546 search_result.sort()
525
547
526 page('\n'.join(search_result))
548 page('\n'.join(search_result))
@@ -1,588 +1,588 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Classes for handling input/output prompts.
3 Classes for handling input/output prompts.
4
4
5 $Id: Prompts.py 1366 2006-06-15 19:45:50Z vivainio $"""
5 $Id: Prompts.py 1850 2006-10-28 19:48:13Z fptest $"""
6
6
7 #*****************************************************************************
7 #*****************************************************************************
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 from IPython import Release
14 from IPython import Release
15 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __author__ = '%s <%s>' % Release.authors['Fernando']
16 __license__ = Release.license
16 __license__ = Release.license
17 __version__ = Release.version
17 __version__ = Release.version
18
18
19 #****************************************************************************
19 #****************************************************************************
20 # Required modules
20 # Required modules
21 import __builtin__
21 import __builtin__
22 import os
22 import os
23 import socket
23 import socket
24 import sys
24 import sys
25 import time
25 import time
26
26
27 # IPython's own
27 # IPython's own
28 from IPython import ColorANSI
28 from IPython import ColorANSI
29 from IPython.Itpl import ItplNS
29 from IPython.Itpl import ItplNS
30 from IPython.ipstruct import Struct
30 from IPython.ipstruct import Struct
31 from IPython.macro import Macro
31 from IPython.macro import Macro
32 from IPython.genutils import *
32 from IPython.genutils import *
33
33
34 #****************************************************************************
34 #****************************************************************************
35 #Color schemes for Prompts.
35 #Color schemes for Prompts.
36
36
37 PromptColors = ColorANSI.ColorSchemeTable()
37 PromptColors = ColorANSI.ColorSchemeTable()
38 InputColors = ColorANSI.InputTermColors # just a shorthand
38 InputColors = ColorANSI.InputTermColors # just a shorthand
39 Colors = ColorANSI.TermColors # just a shorthand
39 Colors = ColorANSI.TermColors # just a shorthand
40
40
41 PromptColors.add_scheme(ColorANSI.ColorScheme(
41 PromptColors.add_scheme(ColorANSI.ColorScheme(
42 'NoColor',
42 'NoColor',
43 in_prompt = InputColors.NoColor, # Input prompt
43 in_prompt = InputColors.NoColor, # Input prompt
44 in_number = InputColors.NoColor, # Input prompt number
44 in_number = InputColors.NoColor, # Input prompt number
45 in_prompt2 = InputColors.NoColor, # Continuation prompt
45 in_prompt2 = InputColors.NoColor, # Continuation prompt
46 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
46 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
47
47
48 out_prompt = Colors.NoColor, # Output prompt
48 out_prompt = Colors.NoColor, # Output prompt
49 out_number = Colors.NoColor, # Output prompt number
49 out_number = Colors.NoColor, # Output prompt number
50
50
51 normal = Colors.NoColor # color off (usu. Colors.Normal)
51 normal = Colors.NoColor # color off (usu. Colors.Normal)
52 ))
52 ))
53
53
54 # make some schemes as instances so we can copy them for modification easily:
54 # make some schemes as instances so we can copy them for modification easily:
55 __PColLinux = ColorANSI.ColorScheme(
55 __PColLinux = ColorANSI.ColorScheme(
56 'Linux',
56 'Linux',
57 in_prompt = InputColors.Green,
57 in_prompt = InputColors.Green,
58 in_number = InputColors.LightGreen,
58 in_number = InputColors.LightGreen,
59 in_prompt2 = InputColors.Green,
59 in_prompt2 = InputColors.Green,
60 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
60 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
61
61
62 out_prompt = Colors.Red,
62 out_prompt = Colors.Red,
63 out_number = Colors.LightRed,
63 out_number = Colors.LightRed,
64
64
65 normal = Colors.Normal
65 normal = Colors.Normal
66 )
66 )
67 # Don't forget to enter it into the table!
67 # Don't forget to enter it into the table!
68 PromptColors.add_scheme(__PColLinux)
68 PromptColors.add_scheme(__PColLinux)
69
69
70 # Slightly modified Linux for light backgrounds
70 # Slightly modified Linux for light backgrounds
71 __PColLightBG = __PColLinux.copy('LightBG')
71 __PColLightBG = __PColLinux.copy('LightBG')
72
72
73 __PColLightBG.colors.update(
73 __PColLightBG.colors.update(
74 in_prompt = InputColors.Blue,
74 in_prompt = InputColors.Blue,
75 in_number = InputColors.LightBlue,
75 in_number = InputColors.LightBlue,
76 in_prompt2 = InputColors.Blue
76 in_prompt2 = InputColors.Blue
77 )
77 )
78 PromptColors.add_scheme(__PColLightBG)
78 PromptColors.add_scheme(__PColLightBG)
79
79
80 del Colors,InputColors
80 del Colors,InputColors
81
81
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83 def multiple_replace(dict, text):
83 def multiple_replace(dict, text):
84 """ Replace in 'text' all occurences of any key in the given
84 """ Replace in 'text' all occurences of any key in the given
85 dictionary by its corresponding value. Returns the new string."""
85 dictionary by its corresponding value. Returns the new string."""
86
86
87 # Function by Xavier Defrang, originally found at:
87 # Function by Xavier Defrang, originally found at:
88 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
88 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
89
89
90 # Create a regular expression from the dictionary keys
90 # Create a regular expression from the dictionary keys
91 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
91 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
92 # For each match, look-up corresponding value in dictionary
92 # For each match, look-up corresponding value in dictionary
93 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
93 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
94
94
95 #-----------------------------------------------------------------------------
95 #-----------------------------------------------------------------------------
96 # Special characters that can be used in prompt templates, mainly bash-like
96 # Special characters that can be used in prompt templates, mainly bash-like
97
97
98 # If $HOME isn't defined (Windows), make it an absurd string so that it can
98 # If $HOME isn't defined (Windows), make it an absurd string so that it can
99 # never be expanded out into '~'. Basically anything which can never be a
99 # never be expanded out into '~'. Basically anything which can never be a
100 # reasonable directory name will do, we just want the $HOME -> '~' operation
100 # reasonable directory name will do, we just want the $HOME -> '~' operation
101 # to become a no-op. We pre-compute $HOME here so it's not done on every
101 # to become a no-op. We pre-compute $HOME here so it's not done on every
102 # prompt call.
102 # prompt call.
103
103
104 # FIXME:
104 # FIXME:
105
105
106 # - This should be turned into a class which does proper namespace management,
106 # - This should be turned into a class which does proper namespace management,
107 # since the prompt specials need to be evaluated in a certain namespace.
107 # since the prompt specials need to be evaluated in a certain namespace.
108 # Currently it's just globals, which need to be managed manually by code
108 # Currently it's just globals, which need to be managed manually by code
109 # below.
109 # below.
110
110
111 # - I also need to split up the color schemes from the prompt specials
111 # - I also need to split up the color schemes from the prompt specials
112 # somehow. I don't have a clean design for that quite yet.
112 # somehow. I don't have a clean design for that quite yet.
113
113
114 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
114 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
115
115
116 # We precompute a few more strings here for the prompt_specials, which are
116 # We precompute a few more strings here for the prompt_specials, which are
117 # fixed once ipython starts. This reduces the runtime overhead of computing
117 # fixed once ipython starts. This reduces the runtime overhead of computing
118 # prompt strings.
118 # prompt strings.
119 USER = os.environ.get("USER")
119 USER = os.environ.get("USER")
120 HOSTNAME = socket.gethostname()
120 HOSTNAME = socket.gethostname()
121 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
121 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
122 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
122 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
123
123
124 prompt_specials_color = {
124 prompt_specials_color = {
125 # Prompt/history count
125 # Prompt/history count
126 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
126 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
127 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
127 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
128 # Prompt/history count, with the actual digits replaced by dots. Used
128 # Prompt/history count, with the actual digits replaced by dots. Used
129 # mainly in continuation prompts (prompt_in2)
129 # mainly in continuation prompts (prompt_in2)
130 '\\D': '${"."*len(str(self.cache.prompt_count))}',
130 '\\D': '${"."*len(str(self.cache.prompt_count))}',
131 # Current working directory
131 # Current working directory
132 '\\w': '${os.getcwd()}',
132 '\\w': '${os.getcwd()}',
133 # Current time
133 # Current time
134 '\\t' : '${time.strftime("%H:%M:%S")}',
134 '\\t' : '${time.strftime("%H:%M:%S")}',
135 # Basename of current working directory.
135 # Basename of current working directory.
136 # (use os.sep to make this portable across OSes)
136 # (use os.sep to make this portable across OSes)
137 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
137 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
138 # These X<N> are an extension to the normal bash prompts. They return
138 # These X<N> are an extension to the normal bash prompts. They return
139 # N terms of the path, after replacing $HOME with '~'
139 # N terms of the path, after replacing $HOME with '~'
140 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
140 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
141 '\\X1': '${self.cwd_filt(1)}',
141 '\\X1': '${self.cwd_filt(1)}',
142 '\\X2': '${self.cwd_filt(2)}',
142 '\\X2': '${self.cwd_filt(2)}',
143 '\\X3': '${self.cwd_filt(3)}',
143 '\\X3': '${self.cwd_filt(3)}',
144 '\\X4': '${self.cwd_filt(4)}',
144 '\\X4': '${self.cwd_filt(4)}',
145 '\\X5': '${self.cwd_filt(5)}',
145 '\\X5': '${self.cwd_filt(5)}',
146 # Y<N> are similar to X<N>, but they show '~' if it's the directory
146 # Y<N> are similar to X<N>, but they show '~' if it's the directory
147 # N+1 in the list. Somewhat like %cN in tcsh.
147 # N+1 in the list. Somewhat like %cN in tcsh.
148 '\\Y0': '${self.cwd_filt2(0)}',
148 '\\Y0': '${self.cwd_filt2(0)}',
149 '\\Y1': '${self.cwd_filt2(1)}',
149 '\\Y1': '${self.cwd_filt2(1)}',
150 '\\Y2': '${self.cwd_filt2(2)}',
150 '\\Y2': '${self.cwd_filt2(2)}',
151 '\\Y3': '${self.cwd_filt2(3)}',
151 '\\Y3': '${self.cwd_filt2(3)}',
152 '\\Y4': '${self.cwd_filt2(4)}',
152 '\\Y4': '${self.cwd_filt2(4)}',
153 '\\Y5': '${self.cwd_filt2(5)}',
153 '\\Y5': '${self.cwd_filt2(5)}',
154 # Hostname up to first .
154 # Hostname up to first .
155 '\\h': HOSTNAME_SHORT,
155 '\\h': HOSTNAME_SHORT,
156 # Full hostname
156 # Full hostname
157 '\\H': HOSTNAME,
157 '\\H': HOSTNAME,
158 # Username of current user
158 # Username of current user
159 '\\u': USER,
159 '\\u': USER,
160 # Escaped '\'
160 # Escaped '\'
161 '\\\\': '\\',
161 '\\\\': '\\',
162 # Newline
162 # Newline
163 '\\n': '\n',
163 '\\n': '\n',
164 # Carriage return
164 # Carriage return
165 '\\r': '\r',
165 '\\r': '\r',
166 # Release version
166 # Release version
167 '\\v': __version__,
167 '\\v': __version__,
168 # Root symbol ($ or #)
168 # Root symbol ($ or #)
169 '\\$': ROOT_SYMBOL,
169 '\\$': ROOT_SYMBOL,
170 }
170 }
171
171
172 # A copy of the prompt_specials dictionary but with all color escapes removed,
172 # A copy of the prompt_specials dictionary but with all color escapes removed,
173 # so we can correctly compute the prompt length for the auto_rewrite method.
173 # so we can correctly compute the prompt length for the auto_rewrite method.
174 prompt_specials_nocolor = prompt_specials_color.copy()
174 prompt_specials_nocolor = prompt_specials_color.copy()
175 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
175 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
176 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
176 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
177
177
178 # Add in all the InputTermColors color escapes as valid prompt characters.
178 # Add in all the InputTermColors color escapes as valid prompt characters.
179 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
179 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
180 # with a color name which may begin with a letter used by any other of the
180 # with a color name which may begin with a letter used by any other of the
181 # allowed specials. This of course means that \\C will never be allowed for
181 # allowed specials. This of course means that \\C will never be allowed for
182 # anything else.
182 # anything else.
183 input_colors = ColorANSI.InputTermColors
183 input_colors = ColorANSI.InputTermColors
184 for _color in dir(input_colors):
184 for _color in dir(input_colors):
185 if _color[0] != '_':
185 if _color[0] != '_':
186 c_name = '\\C_'+_color
186 c_name = '\\C_'+_color
187 prompt_specials_color[c_name] = getattr(input_colors,_color)
187 prompt_specials_color[c_name] = getattr(input_colors,_color)
188 prompt_specials_nocolor[c_name] = ''
188 prompt_specials_nocolor[c_name] = ''
189
189
190 # we default to no color for safety. Note that prompt_specials is a global
190 # we default to no color for safety. Note that prompt_specials is a global
191 # variable used by all prompt objects.
191 # variable used by all prompt objects.
192 prompt_specials = prompt_specials_nocolor
192 prompt_specials = prompt_specials_nocolor
193
193
194 #-----------------------------------------------------------------------------
194 #-----------------------------------------------------------------------------
195 def str_safe(arg):
195 def str_safe(arg):
196 """Convert to a string, without ever raising an exception.
196 """Convert to a string, without ever raising an exception.
197
197
198 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
198 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
199 error message."""
199 error message."""
200
200
201 try:
201 try:
202 out = str(arg)
202 out = str(arg)
203 except UnicodeError:
203 except UnicodeError:
204 try:
204 try:
205 out = arg.encode('utf_8','replace')
205 out = arg.encode('utf_8','replace')
206 except Exception,msg:
206 except Exception,msg:
207 # let's keep this little duplication here, so that the most common
207 # let's keep this little duplication here, so that the most common
208 # case doesn't suffer from a double try wrapping.
208 # case doesn't suffer from a double try wrapping.
209 out = '<ERROR: %s>' % msg
209 out = '<ERROR: %s>' % msg
210 except Exception,msg:
210 except Exception,msg:
211 out = '<ERROR: %s>' % msg
211 out = '<ERROR: %s>' % msg
212 return out
212 return out
213
213
214 class BasePrompt:
214 class BasePrompt:
215 """Interactive prompt similar to Mathematica's."""
215 """Interactive prompt similar to Mathematica's."""
216 def __init__(self,cache,sep,prompt,pad_left=False):
216 def __init__(self,cache,sep,prompt,pad_left=False):
217
217
218 # Hack: we access information about the primary prompt through the
218 # Hack: we access information about the primary prompt through the
219 # cache argument. We need this, because we want the secondary prompt
219 # cache argument. We need this, because we want the secondary prompt
220 # to be aligned with the primary one. Color table info is also shared
220 # to be aligned with the primary one. Color table info is also shared
221 # by all prompt classes through the cache. Nice OO spaghetti code!
221 # by all prompt classes through the cache. Nice OO spaghetti code!
222 self.cache = cache
222 self.cache = cache
223 self.sep = sep
223 self.sep = sep
224
224
225 # regexp to count the number of spaces at the end of a prompt
225 # regexp to count the number of spaces at the end of a prompt
226 # expression, useful for prompt auto-rewriting
226 # expression, useful for prompt auto-rewriting
227 self.rspace = re.compile(r'(\s*)$')
227 self.rspace = re.compile(r'(\s*)$')
228 # Flag to left-pad prompt strings to match the length of the primary
228 # Flag to left-pad prompt strings to match the length of the primary
229 # prompt
229 # prompt
230 self.pad_left = pad_left
230 self.pad_left = pad_left
231 # Set template to create each actual prompt (where numbers change)
231 # Set template to create each actual prompt (where numbers change)
232 self.p_template = prompt
232 self.p_template = prompt
233 self.set_p_str()
233 self.set_p_str()
234
234
235 def set_p_str(self):
235 def set_p_str(self):
236 """ Set the interpolating prompt strings.
236 """ Set the interpolating prompt strings.
237
237
238 This must be called every time the color settings change, because the
238 This must be called every time the color settings change, because the
239 prompt_specials global may have changed."""
239 prompt_specials global may have changed."""
240
240
241 import os,time # needed in locals for prompt string handling
241 import os,time # needed in locals for prompt string handling
242 loc = locals()
242 loc = locals()
243 self.p_str = ItplNS('%s%s%s' %
243 self.p_str = ItplNS('%s%s%s' %
244 ('${self.sep}${self.col_p}',
244 ('${self.sep}${self.col_p}',
245 multiple_replace(prompt_specials, self.p_template),
245 multiple_replace(prompt_specials, self.p_template),
246 '${self.col_norm}'),self.cache.user_ns,loc)
246 '${self.col_norm}'),self.cache.user_ns,loc)
247
247
248 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
248 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
249 self.p_template),
249 self.p_template),
250 self.cache.user_ns,loc)
250 self.cache.user_ns,loc)
251
251
252 def write(self,msg): # dbg
252 def write(self,msg): # dbg
253 sys.stdout.write(msg)
253 sys.stdout.write(msg)
254 return ''
254 return ''
255
255
256 def __str__(self):
256 def __str__(self):
257 """Return a string form of the prompt.
257 """Return a string form of the prompt.
258
258
259 This for is useful for continuation and output prompts, since it is
259 This for is useful for continuation and output prompts, since it is
260 left-padded to match lengths with the primary one (if the
260 left-padded to match lengths with the primary one (if the
261 self.pad_left attribute is set)."""
261 self.pad_left attribute is set)."""
262
262
263 out_str = str_safe(self.p_str)
263 out_str = str_safe(self.p_str)
264 if self.pad_left:
264 if self.pad_left:
265 # We must find the amount of padding required to match lengths,
265 # We must find the amount of padding required to match lengths,
266 # taking the color escapes (which are invisible on-screen) into
266 # taking the color escapes (which are invisible on-screen) into
267 # account.
267 # account.
268 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
268 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
269 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
269 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
270 return format % out_str
270 return format % out_str
271 else:
271 else:
272 return out_str
272 return out_str
273
273
274 # these path filters are put in as methods so that we can control the
274 # these path filters are put in as methods so that we can control the
275 # namespace where the prompt strings get evaluated
275 # namespace where the prompt strings get evaluated
276 def cwd_filt(self,depth):
276 def cwd_filt(self,depth):
277 """Return the last depth elements of the current working directory.
277 """Return the last depth elements of the current working directory.
278
278
279 $HOME is always replaced with '~'.
279 $HOME is always replaced with '~'.
280 If depth==0, the full path is returned."""
280 If depth==0, the full path is returned."""
281
281
282 cwd = os.getcwd().replace(HOME,"~")
282 cwd = os.getcwd().replace(HOME,"~")
283 out = os.sep.join(cwd.split(os.sep)[-depth:])
283 out = os.sep.join(cwd.split(os.sep)[-depth:])
284 if out:
284 if out:
285 return out
285 return out
286 else:
286 else:
287 return os.sep
287 return os.sep
288
288
289 def cwd_filt2(self,depth):
289 def cwd_filt2(self,depth):
290 """Return the last depth elements of the current working directory.
290 """Return the last depth elements of the current working directory.
291
291
292 $HOME is always replaced with '~'.
292 $HOME is always replaced with '~'.
293 If depth==0, the full path is returned."""
293 If depth==0, the full path is returned."""
294
294
295 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
295 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
296 if '~' in cwd and len(cwd) == depth+1:
296 if '~' in cwd and len(cwd) == depth+1:
297 depth += 1
297 depth += 1
298 out = os.sep.join(cwd[-depth:])
298 out = os.sep.join(cwd[-depth:])
299 if out:
299 if out:
300 return out
300 return out
301 else:
301 else:
302 return os.sep
302 return os.sep
303
303
304 class Prompt1(BasePrompt):
304 class Prompt1(BasePrompt):
305 """Input interactive prompt similar to Mathematica's."""
305 """Input interactive prompt similar to Mathematica's."""
306
306
307 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
307 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
308 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
308 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
309
309
310 def set_colors(self):
310 def set_colors(self):
311 self.set_p_str()
311 self.set_p_str()
312 Colors = self.cache.color_table.active_colors # shorthand
312 Colors = self.cache.color_table.active_colors # shorthand
313 self.col_p = Colors.in_prompt
313 self.col_p = Colors.in_prompt
314 self.col_num = Colors.in_number
314 self.col_num = Colors.in_number
315 self.col_norm = Colors.in_normal
315 self.col_norm = Colors.in_normal
316 # We need a non-input version of these escapes for the '--->'
316 # We need a non-input version of these escapes for the '--->'
317 # auto-call prompts used in the auto_rewrite() method.
317 # auto-call prompts used in the auto_rewrite() method.
318 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
318 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
319 self.col_norm_ni = Colors.normal
319 self.col_norm_ni = Colors.normal
320
320
321 def __str__(self):
321 def __str__(self):
322 self.cache.prompt_count += 1
322 self.cache.prompt_count += 1
323 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
323 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
324 return str_safe(self.p_str)
324 return str_safe(self.p_str)
325
325
326 def auto_rewrite(self):
326 def auto_rewrite(self):
327 """Print a string of the form '--->' which lines up with the previous
327 """Print a string of the form '--->' which lines up with the previous
328 input string. Useful for systems which re-write the user input when
328 input string. Useful for systems which re-write the user input when
329 handling automatically special syntaxes."""
329 handling automatically special syntaxes."""
330
330
331 curr = str(self.cache.last_prompt)
331 curr = str(self.cache.last_prompt)
332 nrspaces = len(self.rspace.search(curr).group())
332 nrspaces = len(self.rspace.search(curr).group())
333 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
333 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
334 ' '*nrspaces,self.col_norm_ni)
334 ' '*nrspaces,self.col_norm_ni)
335
335
336 class PromptOut(BasePrompt):
336 class PromptOut(BasePrompt):
337 """Output interactive prompt similar to Mathematica's."""
337 """Output interactive prompt similar to Mathematica's."""
338
338
339 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
339 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
340 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
340 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
341 if not self.p_template:
341 if not self.p_template:
342 self.__str__ = lambda: ''
342 self.__str__ = lambda: ''
343
343
344 def set_colors(self):
344 def set_colors(self):
345 self.set_p_str()
345 self.set_p_str()
346 Colors = self.cache.color_table.active_colors # shorthand
346 Colors = self.cache.color_table.active_colors # shorthand
347 self.col_p = Colors.out_prompt
347 self.col_p = Colors.out_prompt
348 self.col_num = Colors.out_number
348 self.col_num = Colors.out_number
349 self.col_norm = Colors.normal
349 self.col_norm = Colors.normal
350
350
351 class Prompt2(BasePrompt):
351 class Prompt2(BasePrompt):
352 """Interactive continuation prompt."""
352 """Interactive continuation prompt."""
353
353
354 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
354 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
355 self.cache = cache
355 self.cache = cache
356 self.p_template = prompt
356 self.p_template = prompt
357 self.pad_left = pad_left
357 self.pad_left = pad_left
358 self.set_p_str()
358 self.set_p_str()
359
359
360 def set_p_str(self):
360 def set_p_str(self):
361 import os,time # needed in locals for prompt string handling
361 import os,time # needed in locals for prompt string handling
362 loc = locals()
362 loc = locals()
363 self.p_str = ItplNS('%s%s%s' %
363 self.p_str = ItplNS('%s%s%s' %
364 ('${self.col_p2}',
364 ('${self.col_p2}',
365 multiple_replace(prompt_specials, self.p_template),
365 multiple_replace(prompt_specials, self.p_template),
366 '$self.col_norm'),
366 '$self.col_norm'),
367 self.cache.user_ns,loc)
367 self.cache.user_ns,loc)
368 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
368 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
369 self.p_template),
369 self.p_template),
370 self.cache.user_ns,loc)
370 self.cache.user_ns,loc)
371
371
372 def set_colors(self):
372 def set_colors(self):
373 self.set_p_str()
373 self.set_p_str()
374 Colors = self.cache.color_table.active_colors
374 Colors = self.cache.color_table.active_colors
375 self.col_p2 = Colors.in_prompt2
375 self.col_p2 = Colors.in_prompt2
376 self.col_norm = Colors.in_normal
376 self.col_norm = Colors.in_normal
377 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
377 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
378 # updated their prompt_in2 definitions. Remove eventually.
378 # updated their prompt_in2 definitions. Remove eventually.
379 self.col_p = Colors.out_prompt
379 self.col_p = Colors.out_prompt
380 self.col_num = Colors.out_number
380 self.col_num = Colors.out_number
381
381
382
382
383 #-----------------------------------------------------------------------------
383 #-----------------------------------------------------------------------------
384 class CachedOutput:
384 class CachedOutput:
385 """Class for printing output from calculations while keeping a cache of
385 """Class for printing output from calculations while keeping a cache of
386 reults. It dynamically creates global variables prefixed with _ which
386 reults. It dynamically creates global variables prefixed with _ which
387 contain these results.
387 contain these results.
388
388
389 Meant to be used as a sys.displayhook replacement, providing numbered
389 Meant to be used as a sys.displayhook replacement, providing numbered
390 prompts and cache services.
390 prompts and cache services.
391
391
392 Initialize with initial and final values for cache counter (this defines
392 Initialize with initial and final values for cache counter (this defines
393 the maximum size of the cache."""
393 the maximum size of the cache."""
394
394
395 def __init__(self,shell,cache_size,Pprint,
395 def __init__(self,shell,cache_size,Pprint,
396 colors='NoColor',input_sep='\n',
396 colors='NoColor',input_sep='\n',
397 output_sep='\n',output_sep2='',
397 output_sep='\n',output_sep2='',
398 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
398 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
399
399
400 cache_size_min = 3
400 cache_size_min = 3
401 if cache_size <= 0:
401 if cache_size <= 0:
402 self.do_full_cache = 0
402 self.do_full_cache = 0
403 cache_size = 0
403 cache_size = 0
404 elif cache_size < cache_size_min:
404 elif cache_size < cache_size_min:
405 self.do_full_cache = 0
405 self.do_full_cache = 0
406 cache_size = 0
406 cache_size = 0
407 warn('caching was disabled (min value for cache size is %s).' %
407 warn('caching was disabled (min value for cache size is %s).' %
408 cache_size_min,level=3)
408 cache_size_min,level=3)
409 else:
409 else:
410 self.do_full_cache = 1
410 self.do_full_cache = 1
411
411
412 self.cache_size = cache_size
412 self.cache_size = cache_size
413 self.input_sep = input_sep
413 self.input_sep = input_sep
414
414
415 # we need a reference to the user-level namespace
415 # we need a reference to the user-level namespace
416 self.shell = shell
416 self.shell = shell
417 self.user_ns = shell.user_ns
417 self.user_ns = shell.user_ns
418 # and to the user's input
418 # and to the user's input
419 self.input_hist = shell.input_hist
419 self.input_hist = shell.input_hist
420 # and to the user's logger, for logging output
420 # and to the user's logger, for logging output
421 self.logger = shell.logger
421 self.logger = shell.logger
422
422
423 # Set input prompt strings and colors
423 # Set input prompt strings and colors
424 if cache_size == 0:
424 if cache_size == 0:
425 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
425 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
426 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
426 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
427 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
427 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
428 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
428 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
429 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
429 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
430
430
431 self.color_table = PromptColors
431 self.color_table = PromptColors
432 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
432 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
433 pad_left=pad_left)
433 pad_left=pad_left)
434 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
434 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
435 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
435 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
436 pad_left=pad_left)
436 pad_left=pad_left)
437 self.set_colors(colors)
437 self.set_colors(colors)
438
438
439 # other more normal stuff
439 # other more normal stuff
440 # b/c each call to the In[] prompt raises it by 1, even the first.
440 # b/c each call to the In[] prompt raises it by 1, even the first.
441 self.prompt_count = 0
441 self.prompt_count = 0
442 # Store the last prompt string each time, we need it for aligning
442 # Store the last prompt string each time, we need it for aligning
443 # continuation and auto-rewrite prompts
443 # continuation and auto-rewrite prompts
444 self.last_prompt = ''
444 self.last_prompt = ''
445 self.Pprint = Pprint
445 self.Pprint = Pprint
446 self.output_sep = output_sep
446 self.output_sep = output_sep
447 self.output_sep2 = output_sep2
447 self.output_sep2 = output_sep2
448 self._,self.__,self.___ = '','',''
448 self._,self.__,self.___ = '','',''
449 self.pprint_types = map(type,[(),[],{}])
449 self.pprint_types = map(type,[(),[],{}])
450
450
451 # these are deliberately global:
451 # these are deliberately global:
452 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
452 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
453 self.user_ns.update(to_user_ns)
453 self.user_ns.update(to_user_ns)
454
454
455 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
455 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
456 if p_str is None:
456 if p_str is None:
457 if self.do_full_cache:
457 if self.do_full_cache:
458 return cache_def
458 return cache_def
459 else:
459 else:
460 return no_cache_def
460 return no_cache_def
461 else:
461 else:
462 return p_str
462 return p_str
463
463
464 def set_colors(self,colors):
464 def set_colors(self,colors):
465 """Set the active color scheme and configure colors for the three
465 """Set the active color scheme and configure colors for the three
466 prompt subsystems."""
466 prompt subsystems."""
467
467
468 # FIXME: the prompt_specials global should be gobbled inside this
468 # FIXME: the prompt_specials global should be gobbled inside this
469 # class instead. Do it when cleaning up the whole 3-prompt system.
469 # class instead. Do it when cleaning up the whole 3-prompt system.
470 global prompt_specials
470 global prompt_specials
471 if colors.lower()=='nocolor':
471 if colors.lower()=='nocolor':
472 prompt_specials = prompt_specials_nocolor
472 prompt_specials = prompt_specials_nocolor
473 else:
473 else:
474 prompt_specials = prompt_specials_color
474 prompt_specials = prompt_specials_color
475
475
476 self.color_table.set_active_scheme(colors)
476 self.color_table.set_active_scheme(colors)
477 self.prompt1.set_colors()
477 self.prompt1.set_colors()
478 self.prompt2.set_colors()
478 self.prompt2.set_colors()
479 self.prompt_out.set_colors()
479 self.prompt_out.set_colors()
480
480
481 def __call__(self,arg=None):
481 def __call__(self,arg=None):
482 """Printing with history cache management.
482 """Printing with history cache management.
483
483
484 This is invoked everytime the interpreter needs to print, and is
484 This is invoked everytime the interpreter needs to print, and is
485 activated by setting the variable sys.displayhook to it."""
485 activated by setting the variable sys.displayhook to it."""
486
486
487 # If something injected a '_' variable in __builtin__, delete
487 # If something injected a '_' variable in __builtin__, delete
488 # ipython's automatic one so we don't clobber that. gettext() in
488 # ipython's automatic one so we don't clobber that. gettext() in
489 # particular uses _, so we need to stay away from it.
489 # particular uses _, so we need to stay away from it.
490 if '_' in __builtin__.__dict__:
490 if '_' in __builtin__.__dict__:
491 try:
491 try:
492 del self.user_ns['_']
492 del self.user_ns['_']
493 except KeyError:
493 except KeyError:
494 pass
494 pass
495 if arg is not None:
495 if arg is not None:
496 cout_write = Term.cout.write # fast lookup
496 cout_write = Term.cout.write # fast lookup
497 # first handle the cache and counters
497 # first handle the cache and counters
498
498
499 # do not print output if input ends in ';'
499 # do not print output if input ends in ';'
500 if self.input_hist[self.prompt_count].endswith(';\n'):
500 if self.input_hist[self.prompt_count].endswith(';\n'):
501 return
501 return
502 # don't use print, puts an extra space
502 # don't use print, puts an extra space
503 cout_write(self.output_sep)
503 cout_write(self.output_sep)
504 outprompt = self.shell.hooks.generate_output_prompt()
504 outprompt = self.shell.hooks.generate_output_prompt()
505 if self.do_full_cache:
505 if self.do_full_cache:
506 cout_write(outprompt)
506 cout_write(outprompt)
507
507
508 if isinstance(arg,Macro):
508 if isinstance(arg,Macro):
509 print 'Executing Macro...'
509 print 'Executing Macro...'
510 # in case the macro takes a long time to execute
510 # in case the macro takes a long time to execute
511 Term.cout.flush()
511 Term.cout.flush()
512 self.shell.runlines(arg.value)
512 self.shell.runlines(arg.value)
513 return None
513 return None
514
514
515 # and now call a possibly user-defined print mechanism
515 # and now call a possibly user-defined print mechanism
516 manipulated_val = self.display(arg)
516 manipulated_val = self.display(arg)
517
517
518 # user display hooks can change the variable to be stored in
518 # user display hooks can change the variable to be stored in
519 # output history
519 # output history
520
520
521 if manipulated_val is not None:
521 if manipulated_val is not None:
522 arg = manipulated_val
522 arg = manipulated_val
523
523
524 # avoid recursive reference when displaying _oh/Out
524 # avoid recursive reference when displaying _oh/Out
525 if arg is not self.user_ns['_oh']:
525 if arg is not self.user_ns['_oh']:
526 self.update(arg)
526 self.update(arg)
527
527
528 if self.logger.log_output:
528 if self.logger.log_output:
529 self.logger.log_write(repr(arg),'output')
529 self.logger.log_write(repr(arg),'output')
530 cout_write(self.output_sep2)
530 cout_write(self.output_sep2)
531 Term.cout.flush()
531 Term.cout.flush()
532
532
533 def _display(self,arg):
533 def _display(self,arg):
534 """Default printer method, uses pprint.
534 """Default printer method, uses pprint.
535
535
536 Do ip.set_hook("result_display", my_displayhook) for custom result
536 Do ip.set_hook("result_display", my_displayhook) for custom result
537 display, e.g. when your own objects need special formatting.
537 display, e.g. when your own objects need special formatting.
538 """
538 """
539
539
540 return self.shell.hooks.result_display(arg)
540 return self.shell.hooks.result_display(arg)
541
541
542 # Assign the default display method:
542 # Assign the default display method:
543 display = _display
543 display = _display
544
544
545 def update(self,arg):
545 def update(self,arg):
546 #print '***cache_count', self.cache_count # dbg
546 #print '***cache_count', self.cache_count # dbg
547 if len(self.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
547 if len(self.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
548 warn('Output cache limit (currently '+
548 warn('Output cache limit (currently '+
549 `self.cache_size`+' entries) hit.\n'
549 `self.cache_size`+' entries) hit.\n'
550 'Flushing cache and resetting history counter...\n'
550 'Flushing cache and resetting history counter...\n'
551 'The only history variables available will be _,__,___ and _1\n'
551 'The only history variables available will be _,__,___ and _1\n'
552 'with the current result.')
552 'with the current result.')
553
553
554 self.flush()
554 self.flush()
555 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
555 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
556 # we cause buggy behavior for things like gettext).
556 # we cause buggy behavior for things like gettext).
557 if '_' not in __builtin__.__dict__:
557 if '_' not in __builtin__.__dict__:
558 self.___ = self.__
558 self.___ = self.__
559 self.__ = self._
559 self.__ = self._
560 self._ = arg
560 self._ = arg
561 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
561 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
562
562
563 # hackish access to top-level namespace to create _1,_2... dynamically
563 # hackish access to top-level namespace to create _1,_2... dynamically
564 to_main = {}
564 to_main = {}
565 if self.do_full_cache:
565 if self.do_full_cache:
566 new_result = '_'+`self.prompt_count`
566 new_result = '_'+`self.prompt_count`
567 to_main[new_result] = arg
567 to_main[new_result] = arg
568 self.user_ns.update(to_main)
568 self.user_ns.update(to_main)
569 self.user_ns['_oh'][self.prompt_count] = arg
569 self.user_ns['_oh'][self.prompt_count] = arg
570
570
571 def flush(self):
571 def flush(self):
572 if not self.do_full_cache:
572 if not self.do_full_cache:
573 raise ValueError,"You shouldn't have reached the cache flush "\
573 raise ValueError,"You shouldn't have reached the cache flush "\
574 "if full caching is not enabled!"
574 "if full caching is not enabled!"
575 # delete auto-generated vars from global namespace
575 # delete auto-generated vars from global namespace
576
576
577 for n in range(1,self.prompt_count + 1):
577 for n in range(1,self.prompt_count + 1):
578 key = '_'+`n`
578 key = '_'+`n`
579 try:
579 try:
580 del self.user_ns[key]
580 del self.user_ns[key]
581 except: pass
581 except: pass
582 self.user_ns['_oh'].clear()
582 self.user_ns['_oh'].clear()
583
583
584 if '_' not in __builtin__.__dict__:
584 if '_' not in __builtin__.__dict__:
585 self.user_ns.update({'_':None,'__':None, '___':None})
585 self.user_ns.update({'_':None,'__':None, '___':None})
586 import gc
586 import gc
587 gc.collect() # xxx needed?
587 gc.collect() # xxx needed?
588
588
@@ -1,2432 +1,2434 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 1828 2006-10-16 02:04:33Z fptest $
9 $Id: iplib.py 1850 2006-10-28 19:48:13Z fptest $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from IPython import Release
31 from IPython import Release
32 __author__ = '%s <%s>\n%s <%s>' % \
32 __author__ = '%s <%s>\n%s <%s>' % \
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 __license__ = Release.license
34 __license__ = Release.license
35 __version__ = Release.version
35 __version__ = Release.version
36
36
37 # Python standard modules
37 # Python standard modules
38 import __main__
38 import __main__
39 import __builtin__
39 import __builtin__
40 import StringIO
40 import StringIO
41 import bdb
41 import bdb
42 import cPickle as pickle
42 import cPickle as pickle
43 import codeop
43 import codeop
44 import exceptions
44 import exceptions
45 import glob
45 import glob
46 import inspect
46 import inspect
47 import keyword
47 import keyword
48 import new
48 import new
49 import os
49 import os
50 import pdb
50 import pdb
51 import pydoc
51 import pydoc
52 import re
52 import re
53 import shutil
53 import shutil
54 import string
54 import string
55 import sys
55 import sys
56 import tempfile
56 import tempfile
57 import traceback
57 import traceback
58 import types
58 import types
59 import pickleshare
59 import pickleshare
60 from sets import Set
60 from sets import Set
61 from pprint import pprint, pformat
61 from pprint import pprint, pformat
62
62
63 # IPython's own modules
63 # IPython's own modules
64 import IPython
64 import IPython
65 from IPython import OInspect,PyColorize,ultraTB
65 from IPython import OInspect,PyColorize,ultraTB
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.FakeModule import FakeModule
67 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
69 from IPython.Logger import Logger
70 from IPython.Magic import Magic
70 from IPython.Magic import Magic
71 from IPython.Prompts import CachedOutput
71 from IPython.Prompts import CachedOutput
72 from IPython.ipstruct import Struct
72 from IPython.ipstruct import Struct
73 from IPython.background_jobs import BackgroundJobManager
73 from IPython.background_jobs import BackgroundJobManager
74 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.genutils import *
75 from IPython.genutils import *
76 import IPython.ipapi
76 import IPython.ipapi
77
77
78 # Globals
78 # Globals
79
79
80 # store the builtin raw_input globally, and use this always, in case user code
80 # store the builtin raw_input globally, and use this always, in case user code
81 # overwrites it (like wx.py.PyShell does)
81 # overwrites it (like wx.py.PyShell does)
82 raw_input_original = raw_input
82 raw_input_original = raw_input
83
83
84 # compiled regexps for autoindent management
84 # compiled regexps for autoindent management
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86
86
87
87
88 #****************************************************************************
88 #****************************************************************************
89 # Some utility function definitions
89 # Some utility function definitions
90
90
91 ini_spaces_re = re.compile(r'^(\s+)')
91 ini_spaces_re = re.compile(r'^(\s+)')
92
92
93 def num_ini_spaces(strng):
93 def num_ini_spaces(strng):
94 """Return the number of initial spaces in a string"""
94 """Return the number of initial spaces in a string"""
95
95
96 ini_spaces = ini_spaces_re.match(strng)
96 ini_spaces = ini_spaces_re.match(strng)
97 if ini_spaces:
97 if ini_spaces:
98 return ini_spaces.end()
98 return ini_spaces.end()
99 else:
99 else:
100 return 0
100 return 0
101
101
102 def softspace(file, newvalue):
102 def softspace(file, newvalue):
103 """Copied from code.py, to remove the dependency"""
103 """Copied from code.py, to remove the dependency"""
104
104
105 oldvalue = 0
105 oldvalue = 0
106 try:
106 try:
107 oldvalue = file.softspace
107 oldvalue = file.softspace
108 except AttributeError:
108 except AttributeError:
109 pass
109 pass
110 try:
110 try:
111 file.softspace = newvalue
111 file.softspace = newvalue
112 except (AttributeError, TypeError):
112 except (AttributeError, TypeError):
113 # "attribute-less object" or "read-only attributes"
113 # "attribute-less object" or "read-only attributes"
114 pass
114 pass
115 return oldvalue
115 return oldvalue
116
116
117
117
118 #****************************************************************************
118 #****************************************************************************
119 # Local use exceptions
119 # Local use exceptions
120 class SpaceInInput(exceptions.Exception): pass
120 class SpaceInInput(exceptions.Exception): pass
121
121
122
122
123 #****************************************************************************
123 #****************************************************************************
124 # Local use classes
124 # Local use classes
125 class Bunch: pass
125 class Bunch: pass
126
126
127 class Undefined: pass
127 class Undefined: pass
128
128
129 class Quitter(object):
129 class Quitter(object):
130 """Simple class to handle exit, similar to Python 2.5's.
130 """Simple class to handle exit, similar to Python 2.5's.
131
131
132 It handles exiting in an ipython-safe manner, which the one in Python 2.5
132 It handles exiting in an ipython-safe manner, which the one in Python 2.5
133 doesn't do (obviously, since it doesn't know about ipython)."""
133 doesn't do (obviously, since it doesn't know about ipython)."""
134
134
135 def __init__(self,shell,name):
135 def __init__(self,shell,name):
136 self.shell = shell
136 self.shell = shell
137 self.name = name
137 self.name = name
138
138
139 def __repr__(self):
139 def __repr__(self):
140 return 'Type %s() to exit.' % self.name
140 return 'Type %s() to exit.' % self.name
141 __str__ = __repr__
141 __str__ = __repr__
142
142
143 def __call__(self):
143 def __call__(self):
144 self.shell.exit()
144 self.shell.exit()
145
145
146 class InputList(list):
146 class InputList(list):
147 """Class to store user input.
147 """Class to store user input.
148
148
149 It's basically a list, but slices return a string instead of a list, thus
149 It's basically a list, but slices return a string instead of a list, thus
150 allowing things like (assuming 'In' is an instance):
150 allowing things like (assuming 'In' is an instance):
151
151
152 exec In[4:7]
152 exec In[4:7]
153
153
154 or
154 or
155
155
156 exec In[5:9] + In[14] + In[21:25]"""
156 exec In[5:9] + In[14] + In[21:25]"""
157
157
158 def __getslice__(self,i,j):
158 def __getslice__(self,i,j):
159 return ''.join(list.__getslice__(self,i,j))
159 return ''.join(list.__getslice__(self,i,j))
160
160
161 class SyntaxTB(ultraTB.ListTB):
161 class SyntaxTB(ultraTB.ListTB):
162 """Extension which holds some state: the last exception value"""
162 """Extension which holds some state: the last exception value"""
163
163
164 def __init__(self,color_scheme = 'NoColor'):
164 def __init__(self,color_scheme = 'NoColor'):
165 ultraTB.ListTB.__init__(self,color_scheme)
165 ultraTB.ListTB.__init__(self,color_scheme)
166 self.last_syntax_error = None
166 self.last_syntax_error = None
167
167
168 def __call__(self, etype, value, elist):
168 def __call__(self, etype, value, elist):
169 self.last_syntax_error = value
169 self.last_syntax_error = value
170 ultraTB.ListTB.__call__(self,etype,value,elist)
170 ultraTB.ListTB.__call__(self,etype,value,elist)
171
171
172 def clear_err_state(self):
172 def clear_err_state(self):
173 """Return the current error state and clear it"""
173 """Return the current error state and clear it"""
174 e = self.last_syntax_error
174 e = self.last_syntax_error
175 self.last_syntax_error = None
175 self.last_syntax_error = None
176 return e
176 return e
177
177
178 #****************************************************************************
178 #****************************************************************************
179 # Main IPython class
179 # Main IPython class
180
180
181 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
181 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
182 # until a full rewrite is made. I've cleaned all cross-class uses of
182 # until a full rewrite is made. I've cleaned all cross-class uses of
183 # attributes and methods, but too much user code out there relies on the
183 # attributes and methods, but too much user code out there relies on the
184 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
184 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
185 #
185 #
186 # But at least now, all the pieces have been separated and we could, in
186 # But at least now, all the pieces have been separated and we could, in
187 # principle, stop using the mixin. This will ease the transition to the
187 # principle, stop using the mixin. This will ease the transition to the
188 # chainsaw branch.
188 # chainsaw branch.
189
189
190 # For reference, the following is the list of 'self.foo' uses in the Magic
190 # For reference, the following is the list of 'self.foo' uses in the Magic
191 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
191 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
192 # class, to prevent clashes.
192 # class, to prevent clashes.
193
193
194 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
194 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
195 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
195 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
196 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
196 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
197 # 'self.value']
197 # 'self.value']
198
198
199 class InteractiveShell(object,Magic):
199 class InteractiveShell(object,Magic):
200 """An enhanced console for Python."""
200 """An enhanced console for Python."""
201
201
202 # class attribute to indicate whether the class supports threads or not.
202 # class attribute to indicate whether the class supports threads or not.
203 # Subclasses with thread support should override this as needed.
203 # Subclasses with thread support should override this as needed.
204 isthreaded = False
204 isthreaded = False
205
205
206 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
206 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
207 user_ns = None,user_global_ns=None,banner2='',
207 user_ns = None,user_global_ns=None,banner2='',
208 custom_exceptions=((),None),embedded=False):
208 custom_exceptions=((),None),embedded=False):
209
209
210 # log system
210 # log system
211 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
211 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
212
212
213 # some minimal strict typechecks. For some core data structures, I
213 # some minimal strict typechecks. For some core data structures, I
214 # want actual basic python types, not just anything that looks like
214 # want actual basic python types, not just anything that looks like
215 # one. This is especially true for namespaces.
215 # one. This is especially true for namespaces.
216 for ns in (user_ns,user_global_ns):
216 for ns in (user_ns,user_global_ns):
217 if ns is not None and type(ns) != types.DictType:
217 if ns is not None and type(ns) != types.DictType:
218 raise TypeError,'namespace must be a dictionary'
218 raise TypeError,'namespace must be a dictionary'
219
219
220 # Job manager (for jobs run as background threads)
220 # Job manager (for jobs run as background threads)
221 self.jobs = BackgroundJobManager()
221 self.jobs = BackgroundJobManager()
222
222
223 # Store the actual shell's name
223 # Store the actual shell's name
224 self.name = name
224 self.name = name
225
225
226 # We need to know whether the instance is meant for embedding, since
226 # We need to know whether the instance is meant for embedding, since
227 # global/local namespaces need to be handled differently in that case
227 # global/local namespaces need to be handled differently in that case
228 self.embedded = embedded
228 self.embedded = embedded
229
229
230 # command compiler
230 # command compiler
231 self.compile = codeop.CommandCompiler()
231 self.compile = codeop.CommandCompiler()
232
232
233 # User input buffer
233 # User input buffer
234 self.buffer = []
234 self.buffer = []
235
235
236 # Default name given in compilation of code
236 # Default name given in compilation of code
237 self.filename = '<ipython console>'
237 self.filename = '<ipython console>'
238
238
239 # Install our own quitter instead of the builtins. For python2.3-2.4,
239 # Install our own quitter instead of the builtins. For python2.3-2.4,
240 # this brings in behavior like 2.5, and for 2.5 it's identical.
240 # this brings in behavior like 2.5, and for 2.5 it's identical.
241 __builtin__.exit = Quitter(self,'exit')
241 __builtin__.exit = Quitter(self,'exit')
242 __builtin__.quit = Quitter(self,'quit')
242 __builtin__.quit = Quitter(self,'quit')
243
243
244 # Make an empty namespace, which extension writers can rely on both
244 # Make an empty namespace, which extension writers can rely on both
245 # existing and NEVER being used by ipython itself. This gives them a
245 # existing and NEVER being used by ipython itself. This gives them a
246 # convenient location for storing additional information and state
246 # convenient location for storing additional information and state
247 # their extensions may require, without fear of collisions with other
247 # their extensions may require, without fear of collisions with other
248 # ipython names that may develop later.
248 # ipython names that may develop later.
249 self.meta = Struct()
249 self.meta = Struct()
250
250
251 # Create the namespace where the user will operate. user_ns is
251 # Create the namespace where the user will operate. user_ns is
252 # normally the only one used, and it is passed to the exec calls as
252 # normally the only one used, and it is passed to the exec calls as
253 # the locals argument. But we do carry a user_global_ns namespace
253 # the locals argument. But we do carry a user_global_ns namespace
254 # given as the exec 'globals' argument, This is useful in embedding
254 # given as the exec 'globals' argument, This is useful in embedding
255 # situations where the ipython shell opens in a context where the
255 # situations where the ipython shell opens in a context where the
256 # distinction between locals and globals is meaningful.
256 # distinction between locals and globals is meaningful.
257
257
258 # FIXME. For some strange reason, __builtins__ is showing up at user
258 # FIXME. For some strange reason, __builtins__ is showing up at user
259 # level as a dict instead of a module. This is a manual fix, but I
259 # level as a dict instead of a module. This is a manual fix, but I
260 # should really track down where the problem is coming from. Alex
260 # should really track down where the problem is coming from. Alex
261 # Schmolck reported this problem first.
261 # Schmolck reported this problem first.
262
262
263 # A useful post by Alex Martelli on this topic:
263 # A useful post by Alex Martelli on this topic:
264 # Re: inconsistent value from __builtins__
264 # Re: inconsistent value from __builtins__
265 # Von: Alex Martelli <aleaxit@yahoo.com>
265 # Von: Alex Martelli <aleaxit@yahoo.com>
266 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
266 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
267 # Gruppen: comp.lang.python
267 # Gruppen: comp.lang.python
268
268
269 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
269 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
270 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
270 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
271 # > <type 'dict'>
271 # > <type 'dict'>
272 # > >>> print type(__builtins__)
272 # > >>> print type(__builtins__)
273 # > <type 'module'>
273 # > <type 'module'>
274 # > Is this difference in return value intentional?
274 # > Is this difference in return value intentional?
275
275
276 # Well, it's documented that '__builtins__' can be either a dictionary
276 # Well, it's documented that '__builtins__' can be either a dictionary
277 # or a module, and it's been that way for a long time. Whether it's
277 # or a module, and it's been that way for a long time. Whether it's
278 # intentional (or sensible), I don't know. In any case, the idea is
278 # intentional (or sensible), I don't know. In any case, the idea is
279 # that if you need to access the built-in namespace directly, you
279 # that if you need to access the built-in namespace directly, you
280 # should start with "import __builtin__" (note, no 's') which will
280 # should start with "import __builtin__" (note, no 's') which will
281 # definitely give you a module. Yeah, it's somewhat confusing:-(.
281 # definitely give you a module. Yeah, it's somewhat confusing:-(.
282
282
283 # These routines return properly built dicts as needed by the rest of
283 # These routines return properly built dicts as needed by the rest of
284 # the code, and can also be used by extension writers to generate
284 # the code, and can also be used by extension writers to generate
285 # properly initialized namespaces.
285 # properly initialized namespaces.
286 user_ns = IPython.ipapi.make_user_ns(user_ns)
286 user_ns = IPython.ipapi.make_user_ns(user_ns)
287 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
287 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
288
288
289 # Assign namespaces
289 # Assign namespaces
290 # This is the namespace where all normal user variables live
290 # This is the namespace where all normal user variables live
291 self.user_ns = user_ns
291 self.user_ns = user_ns
292 # Embedded instances require a separate namespace for globals.
292 # Embedded instances require a separate namespace for globals.
293 # Normally this one is unused by non-embedded instances.
293 # Normally this one is unused by non-embedded instances.
294 self.user_global_ns = user_global_ns
294 self.user_global_ns = user_global_ns
295 # A namespace to keep track of internal data structures to prevent
295 # A namespace to keep track of internal data structures to prevent
296 # them from cluttering user-visible stuff. Will be updated later
296 # them from cluttering user-visible stuff. Will be updated later
297 self.internal_ns = {}
297 self.internal_ns = {}
298
298
299 # Namespace of system aliases. Each entry in the alias
299 # Namespace of system aliases. Each entry in the alias
300 # table must be a 2-tuple of the form (N,name), where N is the number
300 # table must be a 2-tuple of the form (N,name), where N is the number
301 # of positional arguments of the alias.
301 # of positional arguments of the alias.
302 self.alias_table = {}
302 self.alias_table = {}
303
303
304 # A table holding all the namespaces IPython deals with, so that
304 # A table holding all the namespaces IPython deals with, so that
305 # introspection facilities can search easily.
305 # introspection facilities can search easily.
306 self.ns_table = {'user':user_ns,
306 self.ns_table = {'user':user_ns,
307 'user_global':user_global_ns,
307 'user_global':user_global_ns,
308 'alias':self.alias_table,
308 'alias':self.alias_table,
309 'internal':self.internal_ns,
309 'internal':self.internal_ns,
310 'builtin':__builtin__.__dict__
310 'builtin':__builtin__.__dict__
311 }
311 }
312
312
313 # The user namespace MUST have a pointer to the shell itself.
313 # The user namespace MUST have a pointer to the shell itself.
314 self.user_ns[name] = self
314 self.user_ns[name] = self
315
315
316 # We need to insert into sys.modules something that looks like a
316 # We need to insert into sys.modules something that looks like a
317 # module but which accesses the IPython namespace, for shelve and
317 # module but which accesses the IPython namespace, for shelve and
318 # pickle to work interactively. Normally they rely on getting
318 # pickle to work interactively. Normally they rely on getting
319 # everything out of __main__, but for embedding purposes each IPython
319 # everything out of __main__, but for embedding purposes each IPython
320 # instance has its own private namespace, so we can't go shoving
320 # instance has its own private namespace, so we can't go shoving
321 # everything into __main__.
321 # everything into __main__.
322
322
323 # note, however, that we should only do this for non-embedded
323 # note, however, that we should only do this for non-embedded
324 # ipythons, which really mimic the __main__.__dict__ with their own
324 # ipythons, which really mimic the __main__.__dict__ with their own
325 # namespace. Embedded instances, on the other hand, should not do
325 # namespace. Embedded instances, on the other hand, should not do
326 # this because they need to manage the user local/global namespaces
326 # this because they need to manage the user local/global namespaces
327 # only, but they live within a 'normal' __main__ (meaning, they
327 # only, but they live within a 'normal' __main__ (meaning, they
328 # shouldn't overtake the execution environment of the script they're
328 # shouldn't overtake the execution environment of the script they're
329 # embedded in).
329 # embedded in).
330
330
331 if not embedded:
331 if not embedded:
332 try:
332 try:
333 main_name = self.user_ns['__name__']
333 main_name = self.user_ns['__name__']
334 except KeyError:
334 except KeyError:
335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
336 else:
336 else:
337 #print "pickle hack in place" # dbg
337 #print "pickle hack in place" # dbg
338 #print 'main_name:',main_name # dbg
338 #print 'main_name:',main_name # dbg
339 sys.modules[main_name] = FakeModule(self.user_ns)
339 sys.modules[main_name] = FakeModule(self.user_ns)
340
340
341 # List of input with multi-line handling.
341 # List of input with multi-line handling.
342 # Fill its zero entry, user counter starts at 1
342 # Fill its zero entry, user counter starts at 1
343 self.input_hist = InputList(['\n'])
343 self.input_hist = InputList(['\n'])
344 # This one will hold the 'raw' input history, without any
344 # This one will hold the 'raw' input history, without any
345 # pre-processing. This will allow users to retrieve the input just as
345 # pre-processing. This will allow users to retrieve the input just as
346 # it was exactly typed in by the user, with %hist -r.
346 # it was exactly typed in by the user, with %hist -r.
347 self.input_hist_raw = InputList(['\n'])
347 self.input_hist_raw = InputList(['\n'])
348
348
349 # list of visited directories
349 # list of visited directories
350 try:
350 try:
351 self.dir_hist = [os.getcwd()]
351 self.dir_hist = [os.getcwd()]
352 except IOError, e:
352 except IOError, e:
353 self.dir_hist = []
353 self.dir_hist = []
354
354
355 # dict of output history
355 # dict of output history
356 self.output_hist = {}
356 self.output_hist = {}
357
357
358 # dict of things NOT to alias (keywords, builtins and some magics)
358 # dict of things NOT to alias (keywords, builtins and some magics)
359 no_alias = {}
359 no_alias = {}
360 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
360 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
361 for key in keyword.kwlist + no_alias_magics:
361 for key in keyword.kwlist + no_alias_magics:
362 no_alias[key] = 1
362 no_alias[key] = 1
363 no_alias.update(__builtin__.__dict__)
363 no_alias.update(__builtin__.__dict__)
364 self.no_alias = no_alias
364 self.no_alias = no_alias
365
365
366 # make global variables for user access to these
366 # make global variables for user access to these
367 self.user_ns['_ih'] = self.input_hist
367 self.user_ns['_ih'] = self.input_hist
368 self.user_ns['_oh'] = self.output_hist
368 self.user_ns['_oh'] = self.output_hist
369 self.user_ns['_dh'] = self.dir_hist
369 self.user_ns['_dh'] = self.dir_hist
370
370
371 # user aliases to input and output histories
371 # user aliases to input and output histories
372 self.user_ns['In'] = self.input_hist
372 self.user_ns['In'] = self.input_hist
373 self.user_ns['Out'] = self.output_hist
373 self.user_ns['Out'] = self.output_hist
374
374
375 # Object variable to store code object waiting execution. This is
375 # Object variable to store code object waiting execution. This is
376 # used mainly by the multithreaded shells, but it can come in handy in
376 # used mainly by the multithreaded shells, but it can come in handy in
377 # other situations. No need to use a Queue here, since it's a single
377 # other situations. No need to use a Queue here, since it's a single
378 # item which gets cleared once run.
378 # item which gets cleared once run.
379 self.code_to_run = None
379 self.code_to_run = None
380
380
381 # escapes for automatic behavior on the command line
381 # escapes for automatic behavior on the command line
382 self.ESC_SHELL = '!'
382 self.ESC_SHELL = '!'
383 self.ESC_HELP = '?'
383 self.ESC_HELP = '?'
384 self.ESC_MAGIC = '%'
384 self.ESC_MAGIC = '%'
385 self.ESC_QUOTE = ','
385 self.ESC_QUOTE = ','
386 self.ESC_QUOTE2 = ';'
386 self.ESC_QUOTE2 = ';'
387 self.ESC_PAREN = '/'
387 self.ESC_PAREN = '/'
388
388
389 # And their associated handlers
389 # And their associated handlers
390 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
390 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
391 self.ESC_QUOTE : self.handle_auto,
391 self.ESC_QUOTE : self.handle_auto,
392 self.ESC_QUOTE2 : self.handle_auto,
392 self.ESC_QUOTE2 : self.handle_auto,
393 self.ESC_MAGIC : self.handle_magic,
393 self.ESC_MAGIC : self.handle_magic,
394 self.ESC_HELP : self.handle_help,
394 self.ESC_HELP : self.handle_help,
395 self.ESC_SHELL : self.handle_shell_escape,
395 self.ESC_SHELL : self.handle_shell_escape,
396 }
396 }
397
397
398 # class initializations
398 # class initializations
399 Magic.__init__(self,self)
399 Magic.__init__(self,self)
400
400
401 # Python source parser/formatter for syntax highlighting
401 # Python source parser/formatter for syntax highlighting
402 pyformat = PyColorize.Parser().format
402 pyformat = PyColorize.Parser().format
403 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
403 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
404
404
405 # hooks holds pointers used for user-side customizations
405 # hooks holds pointers used for user-side customizations
406 self.hooks = Struct()
406 self.hooks = Struct()
407
407
408 # 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(self.var_expand(cmd),
475 getoutputerror(self.var_expand(cmd),
476 header='IPython system call: ',
476 header='IPython system call: ',
477 verbose=self.rc.system_verbose)
477 verbose=self.rc.system_verbose)
478
478
479 # RegExp for splitting line contents into pre-char//first
479 # RegExp for splitting line contents into pre-char//first
480 # word-method//rest. For clarity, each group in on one line.
480 # word-method//rest. For clarity, each group in on one line.
481
481
482 # WARNING: update the regexp if the above escapes are changed, as they
482 # WARNING: update the regexp if the above escapes are changed, as they
483 # are hardwired in.
483 # are hardwired in.
484
484
485 # Don't get carried away with trying to make the autocalling catch too
485 # Don't get carried away with trying to make the autocalling catch too
486 # much: it's better to be conservative rather than to trigger hidden
486 # much: it's better to be conservative rather than to trigger hidden
487 # evals() somewhere and end up causing side effects.
487 # evals() somewhere and end up causing side effects.
488
488
489 self.line_split = re.compile(r'^([\s*,;/])'
489 self.line_split = re.compile(r'^([\s*,;/])'
490 r'([\?\w\.]+\w*\s*)'
490 r'([\?\w\.]+\w*\s*)'
491 r'(\(?.*$)')
491 r'(\(?.*$)')
492
492
493 # Original re, keep around for a while in case changes break something
493 # Original re, keep around for a while in case changes break something
494 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
494 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
495 # r'(\s*[\?\w\.]+\w*\s*)'
495 # r'(\s*[\?\w\.]+\w*\s*)'
496 # r'(\(?.*$)')
496 # r'(\(?.*$)')
497
497
498 # RegExp to identify potential function names
498 # RegExp to identify potential function names
499 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
499 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
500
500
501 # RegExp to exclude strings with this start from autocalling. In
501 # RegExp to exclude strings with this start from autocalling. In
502 # particular, all binary operators should be excluded, so that if foo
502 # particular, all binary operators should be excluded, so that if foo
503 # is callable, foo OP bar doesn't become foo(OP bar), which is
503 # is callable, foo OP bar doesn't become foo(OP bar), which is
504 # invalid. The characters '!=()' don't need to be checked for, as the
504 # invalid. The characters '!=()' don't need to be checked for, as the
505 # _prefilter routine explicitely does so, to catch direct calls and
505 # _prefilter routine explicitely does so, to catch direct calls and
506 # rebindings of existing names.
506 # rebindings of existing names.
507
507
508 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
508 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
509 # it affects the rest of the group in square brackets.
509 # it affects the rest of the group in square brackets.
510 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
510 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
511 '|^is |^not |^in |^and |^or ')
511 '|^is |^not |^in |^and |^or ')
512
512
513 # try to catch also methods for stuff in lists/tuples/dicts: off
513 # try to catch also methods for stuff in lists/tuples/dicts: off
514 # (experimental). For this to work, the line_split regexp would need
514 # (experimental). For this to work, the line_split regexp would need
515 # to be modified so it wouldn't break things at '['. That line is
515 # to be modified so it wouldn't break things at '['. That line is
516 # nasty enough that I shouldn't change it until I can test it _well_.
516 # nasty enough that I shouldn't change it until I can test it _well_.
517 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
517 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
518
518
519 # keep track of where we started running (mainly for crash post-mortem)
519 # keep track of where we started running (mainly for crash post-mortem)
520 self.starting_dir = os.getcwd()
520 self.starting_dir = os.getcwd()
521
521
522 # Various switches which can be set
522 # Various switches which can be set
523 self.CACHELENGTH = 5000 # this is cheap, it's just text
523 self.CACHELENGTH = 5000 # this is cheap, it's just text
524 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
524 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
525 self.banner2 = banner2
525 self.banner2 = banner2
526
526
527 # TraceBack handlers:
527 # TraceBack handlers:
528
528
529 # Syntax error handler.
529 # Syntax error handler.
530 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
530 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
531
531
532 # The interactive one is initialized with an offset, meaning we always
532 # The interactive one is initialized with an offset, meaning we always
533 # want to remove the topmost item in the traceback, which is our own
533 # want to remove the topmost item in the traceback, which is our own
534 # internal code. Valid modes: ['Plain','Context','Verbose']
534 # internal code. Valid modes: ['Plain','Context','Verbose']
535 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
535 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
536 color_scheme='NoColor',
536 color_scheme='NoColor',
537 tb_offset = 1)
537 tb_offset = 1)
538
538
539 # IPython itself shouldn't crash. This will produce a detailed
539 # IPython itself shouldn't crash. This will produce a detailed
540 # post-mortem if it does. But we only install the crash handler for
540 # post-mortem if it does. But we only install the crash handler for
541 # non-threaded shells, the threaded ones use a normal verbose reporter
541 # non-threaded shells, the threaded ones use a normal verbose reporter
542 # and lose the crash handler. This is because exceptions in the main
542 # and lose the crash handler. This is because exceptions in the main
543 # thread (such as in GUI code) propagate directly to sys.excepthook,
543 # thread (such as in GUI code) propagate directly to sys.excepthook,
544 # and there's no point in printing crash dumps for every user exception.
544 # and there's no point in printing crash dumps for every user exception.
545 if self.isthreaded:
545 if self.isthreaded:
546 ipCrashHandler = ultraTB.FormattedTB()
546 ipCrashHandler = ultraTB.FormattedTB()
547 else:
547 else:
548 from IPython import CrashHandler
548 from IPython import CrashHandler
549 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
549 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
550 self.set_crash_handler(ipCrashHandler)
550 self.set_crash_handler(ipCrashHandler)
551
551
552 # and add any custom exception handlers the user may have specified
552 # and add any custom exception handlers the user may have specified
553 self.set_custom_exc(*custom_exceptions)
553 self.set_custom_exc(*custom_exceptions)
554
554
555 # indentation management
555 # indentation management
556 self.autoindent = False
556 self.autoindent = False
557 self.indent_current_nsp = 0
557 self.indent_current_nsp = 0
558
558
559 # Make some aliases automatically
559 # Make some aliases automatically
560 # Prepare list of shell aliases to auto-define
560 # Prepare list of shell aliases to auto-define
561 if os.name == 'posix':
561 if os.name == 'posix':
562 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
562 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
563 'mv mv -i','rm rm -i','cp cp -i',
563 'mv mv -i','rm rm -i','cp cp -i',
564 'cat cat','less less','clear clear',
564 'cat cat','less less','clear clear',
565 # a better ls
565 # a better ls
566 'ls ls -F',
566 'ls ls -F',
567 # long ls
567 # long ls
568 'll ls -lF')
568 'll ls -lF')
569 # Extra ls aliases with color, which need special treatment on BSD
569 # Extra ls aliases with color, which need special treatment on BSD
570 # variants
570 # variants
571 ls_extra = ( # color ls
571 ls_extra = ( # color ls
572 'lc ls -F -o --color',
572 'lc ls -F -o --color',
573 # ls normal files only
573 # ls normal files only
574 'lf ls -F -o --color %l | grep ^-',
574 'lf ls -F -o --color %l | grep ^-',
575 # ls symbolic links
575 # ls symbolic links
576 'lk ls -F -o --color %l | grep ^l',
576 'lk ls -F -o --color %l | grep ^l',
577 # directories or links to directories,
577 # directories or links to directories,
578 'ldir ls -F -o --color %l | grep /$',
578 'ldir ls -F -o --color %l | grep /$',
579 # things which are executable
579 # things which are executable
580 'lx ls -F -o --color %l | grep ^-..x',
580 'lx ls -F -o --color %l | grep ^-..x',
581 )
581 )
582 # The BSDs don't ship GNU ls, so they don't understand the
582 # The BSDs don't ship GNU ls, so they don't understand the
583 # --color switch out of the box
583 # --color switch out of the box
584 if 'bsd' in sys.platform:
584 if 'bsd' in sys.platform:
585 ls_extra = ( # ls normal files only
585 ls_extra = ( # ls normal files only
586 'lf ls -lF | grep ^-',
586 'lf ls -lF | grep ^-',
587 # ls symbolic links
587 # ls symbolic links
588 'lk ls -lF | grep ^l',
588 'lk ls -lF | grep ^l',
589 # directories or links to directories,
589 # directories or links to directories,
590 'ldir ls -lF | grep /$',
590 'ldir ls -lF | grep /$',
591 # things which are executable
591 # things which are executable
592 'lx ls -lF | grep ^-..x',
592 'lx ls -lF | grep ^-..x',
593 )
593 )
594 auto_alias = auto_alias + ls_extra
594 auto_alias = auto_alias + ls_extra
595 elif os.name in ['nt','dos']:
595 elif os.name in ['nt','dos']:
596 auto_alias = ('dir dir /on', 'ls dir /on',
596 auto_alias = ('dir dir /on', 'ls dir /on',
597 'ddir dir /ad /on', 'ldir dir /ad /on',
597 'ddir dir /ad /on', 'ldir dir /ad /on',
598 'mkdir mkdir','rmdir rmdir','echo echo',
598 'mkdir mkdir','rmdir rmdir','echo echo',
599 'ren ren','cls cls','copy copy')
599 'ren ren','cls cls','copy copy')
600 else:
600 else:
601 auto_alias = ()
601 auto_alias = ()
602 self.auto_alias = [s.split(None,1) for s in auto_alias]
602 self.auto_alias = [s.split(None,1) for s in auto_alias]
603 # Call the actual (public) initializer
603 # Call the actual (public) initializer
604 self.init_auto_alias()
604 self.init_auto_alias()
605
605
606 # Produce a public API instance
606 # Produce a public API instance
607 self.api = IPython.ipapi.IPApi(self)
607 self.api = IPython.ipapi.IPApi(self)
608
608
609 # track which builtins we add, so we can clean up later
609 # track which builtins we add, so we can clean up later
610 self.builtins_added = {}
610 self.builtins_added = {}
611 # This method will add the necessary builtins for operation, but
611 # This method will add the necessary builtins for operation, but
612 # tracking what it did via the builtins_added dict.
612 # tracking what it did via the builtins_added dict.
613 self.add_builtins()
613 self.add_builtins()
614
614
615 # end __init__
615 # end __init__
616
616
617 def pre_config_initialization(self):
617 def pre_config_initialization(self):
618 """Pre-configuration init method
618 """Pre-configuration init method
619
619
620 This is called before the configuration files are processed to
620 This is called before the configuration files are processed to
621 prepare the services the config files might need.
621 prepare the services the config files might need.
622
622
623 self.rc already has reasonable default values at this point.
623 self.rc already has reasonable default values at this point.
624 """
624 """
625 rc = self.rc
625 rc = self.rc
626
626
627 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
627 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
628
628
629 def post_config_initialization(self):
629 def post_config_initialization(self):
630 """Post configuration init method
630 """Post configuration init method
631
631
632 This is called after the configuration files have been processed to
632 This is called after the configuration files have been processed to
633 'finalize' the initialization."""
633 'finalize' the initialization."""
634
634
635 rc = self.rc
635 rc = self.rc
636
636
637 # Object inspector
637 # Object inspector
638 self.inspector = OInspect.Inspector(OInspect.InspectColors,
638 self.inspector = OInspect.Inspector(OInspect.InspectColors,
639 PyColorize.ANSICodeColors,
639 PyColorize.ANSICodeColors,
640 'NoColor',
640 'NoColor',
641 rc.object_info_string_level)
641 rc.object_info_string_level)
642
642
643 # Load readline proper
643 # Load readline proper
644 if rc.readline:
644 if rc.readline:
645 self.init_readline()
645 self.init_readline()
646
646
647 # local shortcut, this is used a LOT
647 # local shortcut, this is used a LOT
648 self.log = self.logger.log
648 self.log = self.logger.log
649
649
650 # Initialize cache, set in/out prompts and printing system
650 # Initialize cache, set in/out prompts and printing system
651 self.outputcache = CachedOutput(self,
651 self.outputcache = CachedOutput(self,
652 rc.cache_size,
652 rc.cache_size,
653 rc.pprint,
653 rc.pprint,
654 input_sep = rc.separate_in,
654 input_sep = rc.separate_in,
655 output_sep = rc.separate_out,
655 output_sep = rc.separate_out,
656 output_sep2 = rc.separate_out2,
656 output_sep2 = rc.separate_out2,
657 ps1 = rc.prompt_in1,
657 ps1 = rc.prompt_in1,
658 ps2 = rc.prompt_in2,
658 ps2 = rc.prompt_in2,
659 ps_out = rc.prompt_out,
659 ps_out = rc.prompt_out,
660 pad_left = rc.prompts_pad_left)
660 pad_left = rc.prompts_pad_left)
661
661
662 # user may have over-ridden the default print hook:
662 # user may have over-ridden the default print hook:
663 try:
663 try:
664 self.outputcache.__class__.display = self.hooks.display
664 self.outputcache.__class__.display = self.hooks.display
665 except AttributeError:
665 except AttributeError:
666 pass
666 pass
667
667
668 # I don't like assigning globally to sys, because it means when embedding
668 # I don't like assigning globally to sys, because it means when
669 # instances, each embedded instance overrides the previous choice. But
669 # embedding instances, each embedded instance overrides the previous
670 # sys.displayhook seems to be called internally by exec, so I don't see a
670 # choice. But sys.displayhook seems to be called internally by exec,
671 # way around it.
671 # so I don't see a way around it. We first save the original and then
672 # overwrite it.
673 self.sys_displayhook = sys.displayhook
672 sys.displayhook = self.outputcache
674 sys.displayhook = self.outputcache
673
675
674 # Set user colors (don't do it in the constructor above so that it
676 # Set user colors (don't do it in the constructor above so that it
675 # doesn't crash if colors option is invalid)
677 # doesn't crash if colors option is invalid)
676 self.magic_colors(rc.colors)
678 self.magic_colors(rc.colors)
677
679
678 # Set calling of pdb on exceptions
680 # Set calling of pdb on exceptions
679 self.call_pdb = rc.pdb
681 self.call_pdb = rc.pdb
680
682
681 # Load user aliases
683 # Load user aliases
682 for alias in rc.alias:
684 for alias in rc.alias:
683 self.magic_alias(alias)
685 self.magic_alias(alias)
684 self.hooks.late_startup_hook()
686 self.hooks.late_startup_hook()
685
687
686 batchrun = False
688 batchrun = False
687 for batchfile in [path(arg) for arg in self.rc.args
689 for batchfile in [path(arg) for arg in self.rc.args
688 if arg.lower().endswith('.ipy')]:
690 if arg.lower().endswith('.ipy')]:
689 if not batchfile.isfile():
691 if not batchfile.isfile():
690 print "No such batch file:", batchfile
692 print "No such batch file:", batchfile
691 continue
693 continue
692 self.api.runlines(batchfile.text())
694 self.api.runlines(batchfile.text())
693 batchrun = True
695 batchrun = True
694 if batchrun:
696 if batchrun:
695 self.exit_now = True
697 self.exit_now = True
696
698
697 def add_builtins(self):
699 def add_builtins(self):
698 """Store ipython references into the builtin namespace.
700 """Store ipython references into the builtin namespace.
699
701
700 Some parts of ipython operate via builtins injected here, which hold a
702 Some parts of ipython operate via builtins injected here, which hold a
701 reference to IPython itself."""
703 reference to IPython itself."""
702
704
703 # TODO: deprecate all except _ip; 'jobs' should be installed
705 # TODO: deprecate all except _ip; 'jobs' should be installed
704 # by an extension and the rest are under _ip, ipalias is redundant
706 # by an extension and the rest are under _ip, ipalias is redundant
705 builtins_new = dict(__IPYTHON__ = self,
707 builtins_new = dict(__IPYTHON__ = self,
706 ip_set_hook = self.set_hook,
708 ip_set_hook = self.set_hook,
707 jobs = self.jobs,
709 jobs = self.jobs,
708 ipmagic = self.ipmagic,
710 ipmagic = self.ipmagic,
709 ipalias = self.ipalias,
711 ipalias = self.ipalias,
710 ipsystem = self.ipsystem,
712 ipsystem = self.ipsystem,
711 _ip = self.api
713 _ip = self.api
712 )
714 )
713 for biname,bival in builtins_new.items():
715 for biname,bival in builtins_new.items():
714 try:
716 try:
715 # store the orignal value so we can restore it
717 # store the orignal value so we can restore it
716 self.builtins_added[biname] = __builtin__.__dict__[biname]
718 self.builtins_added[biname] = __builtin__.__dict__[biname]
717 except KeyError:
719 except KeyError:
718 # or mark that it wasn't defined, and we'll just delete it at
720 # or mark that it wasn't defined, and we'll just delete it at
719 # cleanup
721 # cleanup
720 self.builtins_added[biname] = Undefined
722 self.builtins_added[biname] = Undefined
721 __builtin__.__dict__[biname] = bival
723 __builtin__.__dict__[biname] = bival
722
724
723 # Keep in the builtins a flag for when IPython is active. We set it
725 # Keep in the builtins a flag for when IPython is active. We set it
724 # with setdefault so that multiple nested IPythons don't clobber one
726 # with setdefault so that multiple nested IPythons don't clobber one
725 # another. Each will increase its value by one upon being activated,
727 # another. Each will increase its value by one upon being activated,
726 # which also gives us a way to determine the nesting level.
728 # which also gives us a way to determine the nesting level.
727 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
729 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
728
730
729 def clean_builtins(self):
731 def clean_builtins(self):
730 """Remove any builtins which might have been added by add_builtins, or
732 """Remove any builtins which might have been added by add_builtins, or
731 restore overwritten ones to their previous values."""
733 restore overwritten ones to their previous values."""
732 for biname,bival in self.builtins_added.items():
734 for biname,bival in self.builtins_added.items():
733 if bival is Undefined:
735 if bival is Undefined:
734 del __builtin__.__dict__[biname]
736 del __builtin__.__dict__[biname]
735 else:
737 else:
736 __builtin__.__dict__[biname] = bival
738 __builtin__.__dict__[biname] = bival
737 self.builtins_added.clear()
739 self.builtins_added.clear()
738
740
739 def set_hook(self,name,hook, priority = 50):
741 def set_hook(self,name,hook, priority = 50):
740 """set_hook(name,hook) -> sets an internal IPython hook.
742 """set_hook(name,hook) -> sets an internal IPython hook.
741
743
742 IPython exposes some of its internal API as user-modifiable hooks. By
744 IPython exposes some of its internal API as user-modifiable hooks. By
743 adding your function to one of these hooks, you can modify IPython's
745 adding your function to one of these hooks, you can modify IPython's
744 behavior to call at runtime your own routines."""
746 behavior to call at runtime your own routines."""
745
747
746 # At some point in the future, this should validate the hook before it
748 # At some point in the future, this should validate the hook before it
747 # accepts it. Probably at least check that the hook takes the number
749 # accepts it. Probably at least check that the hook takes the number
748 # of args it's supposed to.
750 # of args it's supposed to.
749 dp = getattr(self.hooks, name, None)
751 dp = getattr(self.hooks, name, None)
750 if name not in IPython.hooks.__all__:
752 if name not in IPython.hooks.__all__:
751 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
753 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
752 if not dp:
754 if not dp:
753 dp = IPython.hooks.CommandChainDispatcher()
755 dp = IPython.hooks.CommandChainDispatcher()
754
756
755 f = new.instancemethod(hook,self,self.__class__)
757 f = new.instancemethod(hook,self,self.__class__)
756 try:
758 try:
757 dp.add(f,priority)
759 dp.add(f,priority)
758 except AttributeError:
760 except AttributeError:
759 # it was not commandchain, plain old func - replace
761 # it was not commandchain, plain old func - replace
760 dp = f
762 dp = f
761
763
762 setattr(self.hooks,name, dp)
764 setattr(self.hooks,name, dp)
763
765
764
766
765 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
767 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
766
768
767 def set_crash_handler(self,crashHandler):
769 def set_crash_handler(self,crashHandler):
768 """Set the IPython crash handler.
770 """Set the IPython crash handler.
769
771
770 This must be a callable with a signature suitable for use as
772 This must be a callable with a signature suitable for use as
771 sys.excepthook."""
773 sys.excepthook."""
772
774
773 # Install the given crash handler as the Python exception hook
775 # Install the given crash handler as the Python exception hook
774 sys.excepthook = crashHandler
776 sys.excepthook = crashHandler
775
777
776 # The instance will store a pointer to this, so that runtime code
778 # The instance will store a pointer to this, so that runtime code
777 # (such as magics) can access it. This is because during the
779 # (such as magics) can access it. This is because during the
778 # read-eval loop, it gets temporarily overwritten (to deal with GUI
780 # read-eval loop, it gets temporarily overwritten (to deal with GUI
779 # frameworks).
781 # frameworks).
780 self.sys_excepthook = sys.excepthook
782 self.sys_excepthook = sys.excepthook
781
783
782
784
783 def set_custom_exc(self,exc_tuple,handler):
785 def set_custom_exc(self,exc_tuple,handler):
784 """set_custom_exc(exc_tuple,handler)
786 """set_custom_exc(exc_tuple,handler)
785
787
786 Set a custom exception handler, which will be called if any of the
788 Set a custom exception handler, which will be called if any of the
787 exceptions in exc_tuple occur in the mainloop (specifically, in the
789 exceptions in exc_tuple occur in the mainloop (specifically, in the
788 runcode() method.
790 runcode() method.
789
791
790 Inputs:
792 Inputs:
791
793
792 - exc_tuple: a *tuple* of valid exceptions to call the defined
794 - exc_tuple: a *tuple* of valid exceptions to call the defined
793 handler for. It is very important that you use a tuple, and NOT A
795 handler for. It is very important that you use a tuple, and NOT A
794 LIST here, because of the way Python's except statement works. If
796 LIST here, because of the way Python's except statement works. If
795 you only want to trap a single exception, use a singleton tuple:
797 you only want to trap a single exception, use a singleton tuple:
796
798
797 exc_tuple == (MyCustomException,)
799 exc_tuple == (MyCustomException,)
798
800
799 - handler: this must be defined as a function with the following
801 - handler: this must be defined as a function with the following
800 basic interface: def my_handler(self,etype,value,tb).
802 basic interface: def my_handler(self,etype,value,tb).
801
803
802 This will be made into an instance method (via new.instancemethod)
804 This will be made into an instance method (via new.instancemethod)
803 of IPython itself, and it will be called if any of the exceptions
805 of IPython itself, and it will be called if any of the exceptions
804 listed in the exc_tuple are caught. If the handler is None, an
806 listed in the exc_tuple are caught. If the handler is None, an
805 internal basic one is used, which just prints basic info.
807 internal basic one is used, which just prints basic info.
806
808
807 WARNING: by putting in your own exception handler into IPython's main
809 WARNING: by putting in your own exception handler into IPython's main
808 execution loop, you run a very good chance of nasty crashes. This
810 execution loop, you run a very good chance of nasty crashes. This
809 facility should only be used if you really know what you are doing."""
811 facility should only be used if you really know what you are doing."""
810
812
811 assert type(exc_tuple)==type(()) , \
813 assert type(exc_tuple)==type(()) , \
812 "The custom exceptions must be given AS A TUPLE."
814 "The custom exceptions must be given AS A TUPLE."
813
815
814 def dummy_handler(self,etype,value,tb):
816 def dummy_handler(self,etype,value,tb):
815 print '*** Simple custom exception handler ***'
817 print '*** Simple custom exception handler ***'
816 print 'Exception type :',etype
818 print 'Exception type :',etype
817 print 'Exception value:',value
819 print 'Exception value:',value
818 print 'Traceback :',tb
820 print 'Traceback :',tb
819 print 'Source code :','\n'.join(self.buffer)
821 print 'Source code :','\n'.join(self.buffer)
820
822
821 if handler is None: handler = dummy_handler
823 if handler is None: handler = dummy_handler
822
824
823 self.CustomTB = new.instancemethod(handler,self,self.__class__)
825 self.CustomTB = new.instancemethod(handler,self,self.__class__)
824 self.custom_exceptions = exc_tuple
826 self.custom_exceptions = exc_tuple
825
827
826 def set_custom_completer(self,completer,pos=0):
828 def set_custom_completer(self,completer,pos=0):
827 """set_custom_completer(completer,pos=0)
829 """set_custom_completer(completer,pos=0)
828
830
829 Adds a new custom completer function.
831 Adds a new custom completer function.
830
832
831 The position argument (defaults to 0) is the index in the completers
833 The position argument (defaults to 0) is the index in the completers
832 list where you want the completer to be inserted."""
834 list where you want the completer to be inserted."""
833
835
834 newcomp = new.instancemethod(completer,self.Completer,
836 newcomp = new.instancemethod(completer,self.Completer,
835 self.Completer.__class__)
837 self.Completer.__class__)
836 self.Completer.matchers.insert(pos,newcomp)
838 self.Completer.matchers.insert(pos,newcomp)
837
839
838 def _get_call_pdb(self):
840 def _get_call_pdb(self):
839 return self._call_pdb
841 return self._call_pdb
840
842
841 def _set_call_pdb(self,val):
843 def _set_call_pdb(self,val):
842
844
843 if val not in (0,1,False,True):
845 if val not in (0,1,False,True):
844 raise ValueError,'new call_pdb value must be boolean'
846 raise ValueError,'new call_pdb value must be boolean'
845
847
846 # store value in instance
848 # store value in instance
847 self._call_pdb = val
849 self._call_pdb = val
848
850
849 # notify the actual exception handlers
851 # notify the actual exception handlers
850 self.InteractiveTB.call_pdb = val
852 self.InteractiveTB.call_pdb = val
851 if self.isthreaded:
853 if self.isthreaded:
852 try:
854 try:
853 self.sys_excepthook.call_pdb = val
855 self.sys_excepthook.call_pdb = val
854 except:
856 except:
855 warn('Failed to activate pdb for threaded exception handler')
857 warn('Failed to activate pdb for threaded exception handler')
856
858
857 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
859 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
858 'Control auto-activation of pdb at exceptions')
860 'Control auto-activation of pdb at exceptions')
859
861
860
862
861 # These special functions get installed in the builtin namespace, to
863 # These special functions get installed in the builtin namespace, to
862 # provide programmatic (pure python) access to magics, aliases and system
864 # provide programmatic (pure python) access to magics, aliases and system
863 # calls. This is important for logging, user scripting, and more.
865 # calls. This is important for logging, user scripting, and more.
864
866
865 # We are basically exposing, via normal python functions, the three
867 # We are basically exposing, via normal python functions, the three
866 # mechanisms in which ipython offers special call modes (magics for
868 # mechanisms in which ipython offers special call modes (magics for
867 # internal control, aliases for direct system access via pre-selected
869 # internal control, aliases for direct system access via pre-selected
868 # names, and !cmd for calling arbitrary system commands).
870 # names, and !cmd for calling arbitrary system commands).
869
871
870 def ipmagic(self,arg_s):
872 def ipmagic(self,arg_s):
871 """Call a magic function by name.
873 """Call a magic function by name.
872
874
873 Input: a string containing the name of the magic function to call and any
875 Input: a string containing the name of the magic function to call and any
874 additional arguments to be passed to the magic.
876 additional arguments to be passed to the magic.
875
877
876 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
878 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
877 prompt:
879 prompt:
878
880
879 In[1]: %name -opt foo bar
881 In[1]: %name -opt foo bar
880
882
881 To call a magic without arguments, simply use ipmagic('name').
883 To call a magic without arguments, simply use ipmagic('name').
882
884
883 This provides a proper Python function to call IPython's magics in any
885 This provides a proper Python function to call IPython's magics in any
884 valid Python code you can type at the interpreter, including loops and
886 valid Python code you can type at the interpreter, including loops and
885 compound statements. It is added by IPython to the Python builtin
887 compound statements. It is added by IPython to the Python builtin
886 namespace upon initialization."""
888 namespace upon initialization."""
887
889
888 args = arg_s.split(' ',1)
890 args = arg_s.split(' ',1)
889 magic_name = args[0]
891 magic_name = args[0]
890 magic_name = magic_name.lstrip(self.ESC_MAGIC)
892 magic_name = magic_name.lstrip(self.ESC_MAGIC)
891
893
892 try:
894 try:
893 magic_args = args[1]
895 magic_args = args[1]
894 except IndexError:
896 except IndexError:
895 magic_args = ''
897 magic_args = ''
896 fn = getattr(self,'magic_'+magic_name,None)
898 fn = getattr(self,'magic_'+magic_name,None)
897 if fn is None:
899 if fn is None:
898 error("Magic function `%s` not found." % magic_name)
900 error("Magic function `%s` not found." % magic_name)
899 else:
901 else:
900 magic_args = self.var_expand(magic_args)
902 magic_args = self.var_expand(magic_args)
901 return fn(magic_args)
903 return fn(magic_args)
902
904
903 def ipalias(self,arg_s):
905 def ipalias(self,arg_s):
904 """Call an alias by name.
906 """Call an alias by name.
905
907
906 Input: a string containing the name of the alias to call and any
908 Input: a string containing the name of the alias to call and any
907 additional arguments to be passed to the magic.
909 additional arguments to be passed to the magic.
908
910
909 ipalias('name -opt foo bar') is equivalent to typing at the ipython
911 ipalias('name -opt foo bar') is equivalent to typing at the ipython
910 prompt:
912 prompt:
911
913
912 In[1]: name -opt foo bar
914 In[1]: name -opt foo bar
913
915
914 To call an alias without arguments, simply use ipalias('name').
916 To call an alias without arguments, simply use ipalias('name').
915
917
916 This provides a proper Python function to call IPython's aliases in any
918 This provides a proper Python function to call IPython's aliases in any
917 valid Python code you can type at the interpreter, including loops and
919 valid Python code you can type at the interpreter, including loops and
918 compound statements. It is added by IPython to the Python builtin
920 compound statements. It is added by IPython to the Python builtin
919 namespace upon initialization."""
921 namespace upon initialization."""
920
922
921 args = arg_s.split(' ',1)
923 args = arg_s.split(' ',1)
922 alias_name = args[0]
924 alias_name = args[0]
923 try:
925 try:
924 alias_args = args[1]
926 alias_args = args[1]
925 except IndexError:
927 except IndexError:
926 alias_args = ''
928 alias_args = ''
927 if alias_name in self.alias_table:
929 if alias_name in self.alias_table:
928 self.call_alias(alias_name,alias_args)
930 self.call_alias(alias_name,alias_args)
929 else:
931 else:
930 error("Alias `%s` not found." % alias_name)
932 error("Alias `%s` not found." % alias_name)
931
933
932 def ipsystem(self,arg_s):
934 def ipsystem(self,arg_s):
933 """Make a system call, using IPython."""
935 """Make a system call, using IPython."""
934
936
935 self.system(arg_s)
937 self.system(arg_s)
936
938
937 def complete(self,text):
939 def complete(self,text):
938 """Return a sorted list of all possible completions on text.
940 """Return a sorted list of all possible completions on text.
939
941
940 Inputs:
942 Inputs:
941
943
942 - text: a string of text to be completed on.
944 - text: a string of text to be completed on.
943
945
944 This is a wrapper around the completion mechanism, similar to what
946 This is a wrapper around the completion mechanism, similar to what
945 readline does at the command line when the TAB key is hit. By
947 readline does at the command line when the TAB key is hit. By
946 exposing it as a method, it can be used by other non-readline
948 exposing it as a method, it can be used by other non-readline
947 environments (such as GUIs) for text completion.
949 environments (such as GUIs) for text completion.
948
950
949 Simple usage example:
951 Simple usage example:
950
952
951 In [1]: x = 'hello'
953 In [1]: x = 'hello'
952
954
953 In [2]: __IP.complete('x.l')
955 In [2]: __IP.complete('x.l')
954 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
956 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
955
957
956 complete = self.Completer.complete
958 complete = self.Completer.complete
957 state = 0
959 state = 0
958 # use a dict so we get unique keys, since ipyhton's multiple
960 # use a dict so we get unique keys, since ipyhton's multiple
959 # completers can return duplicates.
961 # completers can return duplicates.
960 comps = {}
962 comps = {}
961 while True:
963 while True:
962 newcomp = complete(text,state)
964 newcomp = complete(text,state)
963 if newcomp is None:
965 if newcomp is None:
964 break
966 break
965 comps[newcomp] = 1
967 comps[newcomp] = 1
966 state += 1
968 state += 1
967 outcomps = comps.keys()
969 outcomps = comps.keys()
968 outcomps.sort()
970 outcomps.sort()
969 return outcomps
971 return outcomps
970
972
971 def set_completer_frame(self, frame=None):
973 def set_completer_frame(self, frame=None):
972 if frame:
974 if frame:
973 self.Completer.namespace = frame.f_locals
975 self.Completer.namespace = frame.f_locals
974 self.Completer.global_namespace = frame.f_globals
976 self.Completer.global_namespace = frame.f_globals
975 else:
977 else:
976 self.Completer.namespace = self.user_ns
978 self.Completer.namespace = self.user_ns
977 self.Completer.global_namespace = self.user_global_ns
979 self.Completer.global_namespace = self.user_global_ns
978
980
979 def init_auto_alias(self):
981 def init_auto_alias(self):
980 """Define some aliases automatically.
982 """Define some aliases automatically.
981
983
982 These are ALL parameter-less aliases"""
984 These are ALL parameter-less aliases"""
983
985
984 for alias,cmd in self.auto_alias:
986 for alias,cmd in self.auto_alias:
985 self.alias_table[alias] = (0,cmd)
987 self.alias_table[alias] = (0,cmd)
986
988
987 def alias_table_validate(self,verbose=0):
989 def alias_table_validate(self,verbose=0):
988 """Update information about the alias table.
990 """Update information about the alias table.
989
991
990 In particular, make sure no Python keywords/builtins are in it."""
992 In particular, make sure no Python keywords/builtins are in it."""
991
993
992 no_alias = self.no_alias
994 no_alias = self.no_alias
993 for k in self.alias_table.keys():
995 for k in self.alias_table.keys():
994 if k in no_alias:
996 if k in no_alias:
995 del self.alias_table[k]
997 del self.alias_table[k]
996 if verbose:
998 if verbose:
997 print ("Deleting alias <%s>, it's a Python "
999 print ("Deleting alias <%s>, it's a Python "
998 "keyword or builtin." % k)
1000 "keyword or builtin." % k)
999
1001
1000 def set_autoindent(self,value=None):
1002 def set_autoindent(self,value=None):
1001 """Set the autoindent flag, checking for readline support.
1003 """Set the autoindent flag, checking for readline support.
1002
1004
1003 If called with no arguments, it acts as a toggle."""
1005 If called with no arguments, it acts as a toggle."""
1004
1006
1005 if not self.has_readline:
1007 if not self.has_readline:
1006 if os.name == 'posix':
1008 if os.name == 'posix':
1007 warn("The auto-indent feature requires the readline library")
1009 warn("The auto-indent feature requires the readline library")
1008 self.autoindent = 0
1010 self.autoindent = 0
1009 return
1011 return
1010 if value is None:
1012 if value is None:
1011 self.autoindent = not self.autoindent
1013 self.autoindent = not self.autoindent
1012 else:
1014 else:
1013 self.autoindent = value
1015 self.autoindent = value
1014
1016
1015 def rc_set_toggle(self,rc_field,value=None):
1017 def rc_set_toggle(self,rc_field,value=None):
1016 """Set or toggle a field in IPython's rc config. structure.
1018 """Set or toggle a field in IPython's rc config. structure.
1017
1019
1018 If called with no arguments, it acts as a toggle.
1020 If called with no arguments, it acts as a toggle.
1019
1021
1020 If called with a non-existent field, the resulting AttributeError
1022 If called with a non-existent field, the resulting AttributeError
1021 exception will propagate out."""
1023 exception will propagate out."""
1022
1024
1023 rc_val = getattr(self.rc,rc_field)
1025 rc_val = getattr(self.rc,rc_field)
1024 if value is None:
1026 if value is None:
1025 value = not rc_val
1027 value = not rc_val
1026 setattr(self.rc,rc_field,value)
1028 setattr(self.rc,rc_field,value)
1027
1029
1028 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1030 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1029 """Install the user configuration directory.
1031 """Install the user configuration directory.
1030
1032
1031 Can be called when running for the first time or to upgrade the user's
1033 Can be called when running for the first time or to upgrade the user's
1032 .ipython/ directory with the mode parameter. Valid modes are 'install'
1034 .ipython/ directory with the mode parameter. Valid modes are 'install'
1033 and 'upgrade'."""
1035 and 'upgrade'."""
1034
1036
1035 def wait():
1037 def wait():
1036 try:
1038 try:
1037 raw_input("Please press <RETURN> to start IPython.")
1039 raw_input("Please press <RETURN> to start IPython.")
1038 except EOFError:
1040 except EOFError:
1039 print >> Term.cout
1041 print >> Term.cout
1040 print '*'*70
1042 print '*'*70
1041
1043
1042 cwd = os.getcwd() # remember where we started
1044 cwd = os.getcwd() # remember where we started
1043 glb = glob.glob
1045 glb = glob.glob
1044 print '*'*70
1046 print '*'*70
1045 if mode == 'install':
1047 if mode == 'install':
1046 print \
1048 print \
1047 """Welcome to IPython. I will try to create a personal configuration directory
1049 """Welcome to IPython. I will try to create a personal configuration directory
1048 where you can customize many aspects of IPython's functionality in:\n"""
1050 where you can customize many aspects of IPython's functionality in:\n"""
1049 else:
1051 else:
1050 print 'I am going to upgrade your configuration in:'
1052 print 'I am going to upgrade your configuration in:'
1051
1053
1052 print ipythondir
1054 print ipythondir
1053
1055
1054 rcdirend = os.path.join('IPython','UserConfig')
1056 rcdirend = os.path.join('IPython','UserConfig')
1055 cfg = lambda d: os.path.join(d,rcdirend)
1057 cfg = lambda d: os.path.join(d,rcdirend)
1056 try:
1058 try:
1057 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1059 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1058 except IOError:
1060 except IOError:
1059 warning = """
1061 warning = """
1060 Installation error. IPython's directory was not found.
1062 Installation error. IPython's directory was not found.
1061
1063
1062 Check the following:
1064 Check the following:
1063
1065
1064 The ipython/IPython directory should be in a directory belonging to your
1066 The ipython/IPython directory should be in a directory belonging to your
1065 PYTHONPATH environment variable (that is, it should be in a directory
1067 PYTHONPATH environment variable (that is, it should be in a directory
1066 belonging to sys.path). You can copy it explicitly there or just link to it.
1068 belonging to sys.path). You can copy it explicitly there or just link to it.
1067
1069
1068 IPython will proceed with builtin defaults.
1070 IPython will proceed with builtin defaults.
1069 """
1071 """
1070 warn(warning)
1072 warn(warning)
1071 wait()
1073 wait()
1072 return
1074 return
1073
1075
1074 if mode == 'install':
1076 if mode == 'install':
1075 try:
1077 try:
1076 shutil.copytree(rcdir,ipythondir)
1078 shutil.copytree(rcdir,ipythondir)
1077 os.chdir(ipythondir)
1079 os.chdir(ipythondir)
1078 rc_files = glb("ipythonrc*")
1080 rc_files = glb("ipythonrc*")
1079 for rc_file in rc_files:
1081 for rc_file in rc_files:
1080 os.rename(rc_file,rc_file+rc_suffix)
1082 os.rename(rc_file,rc_file+rc_suffix)
1081 except:
1083 except:
1082 warning = """
1084 warning = """
1083
1085
1084 There was a problem with the installation:
1086 There was a problem with the installation:
1085 %s
1087 %s
1086 Try to correct it or contact the developers if you think it's a bug.
1088 Try to correct it or contact the developers if you think it's a bug.
1087 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1089 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1088 warn(warning)
1090 warn(warning)
1089 wait()
1091 wait()
1090 return
1092 return
1091
1093
1092 elif mode == 'upgrade':
1094 elif mode == 'upgrade':
1093 try:
1095 try:
1094 os.chdir(ipythondir)
1096 os.chdir(ipythondir)
1095 except:
1097 except:
1096 print """
1098 print """
1097 Can not upgrade: changing to directory %s failed. Details:
1099 Can not upgrade: changing to directory %s failed. Details:
1098 %s
1100 %s
1099 """ % (ipythondir,sys.exc_info()[1])
1101 """ % (ipythondir,sys.exc_info()[1])
1100 wait()
1102 wait()
1101 return
1103 return
1102 else:
1104 else:
1103 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1105 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1104 for new_full_path in sources:
1106 for new_full_path in sources:
1105 new_filename = os.path.basename(new_full_path)
1107 new_filename = os.path.basename(new_full_path)
1106 if new_filename.startswith('ipythonrc'):
1108 if new_filename.startswith('ipythonrc'):
1107 new_filename = new_filename + rc_suffix
1109 new_filename = new_filename + rc_suffix
1108 # The config directory should only contain files, skip any
1110 # The config directory should only contain files, skip any
1109 # directories which may be there (like CVS)
1111 # directories which may be there (like CVS)
1110 if os.path.isdir(new_full_path):
1112 if os.path.isdir(new_full_path):
1111 continue
1113 continue
1112 if os.path.exists(new_filename):
1114 if os.path.exists(new_filename):
1113 old_file = new_filename+'.old'
1115 old_file = new_filename+'.old'
1114 if os.path.exists(old_file):
1116 if os.path.exists(old_file):
1115 os.remove(old_file)
1117 os.remove(old_file)
1116 os.rename(new_filename,old_file)
1118 os.rename(new_filename,old_file)
1117 shutil.copy(new_full_path,new_filename)
1119 shutil.copy(new_full_path,new_filename)
1118 else:
1120 else:
1119 raise ValueError,'unrecognized mode for install:',`mode`
1121 raise ValueError,'unrecognized mode for install:',`mode`
1120
1122
1121 # Fix line-endings to those native to each platform in the config
1123 # Fix line-endings to those native to each platform in the config
1122 # directory.
1124 # directory.
1123 try:
1125 try:
1124 os.chdir(ipythondir)
1126 os.chdir(ipythondir)
1125 except:
1127 except:
1126 print """
1128 print """
1127 Problem: changing to directory %s failed.
1129 Problem: changing to directory %s failed.
1128 Details:
1130 Details:
1129 %s
1131 %s
1130
1132
1131 Some configuration files may have incorrect line endings. This should not
1133 Some configuration files may have incorrect line endings. This should not
1132 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1134 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1133 wait()
1135 wait()
1134 else:
1136 else:
1135 for fname in glb('ipythonrc*'):
1137 for fname in glb('ipythonrc*'):
1136 try:
1138 try:
1137 native_line_ends(fname,backup=0)
1139 native_line_ends(fname,backup=0)
1138 except IOError:
1140 except IOError:
1139 pass
1141 pass
1140
1142
1141 if mode == 'install':
1143 if mode == 'install':
1142 print """
1144 print """
1143 Successful installation!
1145 Successful installation!
1144
1146
1145 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1147 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1146 IPython manual (there are both HTML and PDF versions supplied with the
1148 IPython manual (there are both HTML and PDF versions supplied with the
1147 distribution) to make sure that your system environment is properly configured
1149 distribution) to make sure that your system environment is properly configured
1148 to take advantage of IPython's features.
1150 to take advantage of IPython's features.
1149
1151
1150 Important note: the configuration system has changed! The old system is
1152 Important note: the configuration system has changed! The old system is
1151 still in place, but its setting may be partly overridden by the settings in
1153 still in place, but its setting may be partly overridden by the settings in
1152 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1154 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1153 if some of the new settings bother you.
1155 if some of the new settings bother you.
1154
1156
1155 """
1157 """
1156 else:
1158 else:
1157 print """
1159 print """
1158 Successful upgrade!
1160 Successful upgrade!
1159
1161
1160 All files in your directory:
1162 All files in your directory:
1161 %(ipythondir)s
1163 %(ipythondir)s
1162 which would have been overwritten by the upgrade were backed up with a .old
1164 which would have been overwritten by the upgrade were backed up with a .old
1163 extension. If you had made particular customizations in those files you may
1165 extension. If you had made particular customizations in those files you may
1164 want to merge them back into the new files.""" % locals()
1166 want to merge them back into the new files.""" % locals()
1165 wait()
1167 wait()
1166 os.chdir(cwd)
1168 os.chdir(cwd)
1167 # end user_setup()
1169 # end user_setup()
1168
1170
1169 def atexit_operations(self):
1171 def atexit_operations(self):
1170 """This will be executed at the time of exit.
1172 """This will be executed at the time of exit.
1171
1173
1172 Saving of persistent data should be performed here. """
1174 Saving of persistent data should be performed here. """
1173
1175
1174 #print '*** IPython exit cleanup ***' # dbg
1176 #print '*** IPython exit cleanup ***' # dbg
1175 # input history
1177 # input history
1176 self.savehist()
1178 self.savehist()
1177
1179
1178 # Cleanup all tempfiles left around
1180 # Cleanup all tempfiles left around
1179 for tfile in self.tempfiles:
1181 for tfile in self.tempfiles:
1180 try:
1182 try:
1181 os.unlink(tfile)
1183 os.unlink(tfile)
1182 except OSError:
1184 except OSError:
1183 pass
1185 pass
1184
1186
1185 # save the "persistent data" catch-all dictionary
1187 # save the "persistent data" catch-all dictionary
1186 self.hooks.shutdown_hook()
1188 self.hooks.shutdown_hook()
1187
1189
1188 def savehist(self):
1190 def savehist(self):
1189 """Save input history to a file (via readline library)."""
1191 """Save input history to a file (via readline library)."""
1190 try:
1192 try:
1191 self.readline.write_history_file(self.histfile)
1193 self.readline.write_history_file(self.histfile)
1192 except:
1194 except:
1193 print 'Unable to save IPython command history to file: ' + \
1195 print 'Unable to save IPython command history to file: ' + \
1194 `self.histfile`
1196 `self.histfile`
1195
1197
1196 def pre_readline(self):
1198 def pre_readline(self):
1197 """readline hook to be used at the start of each line.
1199 """readline hook to be used at the start of each line.
1198
1200
1199 Currently it handles auto-indent only."""
1201 Currently it handles auto-indent only."""
1200
1202
1201 #debugx('self.indent_current_nsp','pre_readline:')
1203 #debugx('self.indent_current_nsp','pre_readline:')
1202 self.readline.insert_text(self.indent_current_str())
1204 self.readline.insert_text(self.indent_current_str())
1203
1205
1204 def init_readline(self):
1206 def init_readline(self):
1205 """Command history completion/saving/reloading."""
1207 """Command history completion/saving/reloading."""
1206
1208
1207 import IPython.rlineimpl as readline
1209 import IPython.rlineimpl as readline
1208 if not readline.have_readline:
1210 if not readline.have_readline:
1209 self.has_readline = 0
1211 self.has_readline = 0
1210 self.readline = None
1212 self.readline = None
1211 # no point in bugging windows users with this every time:
1213 # no point in bugging windows users with this every time:
1212 warn('Readline services not available on this platform.')
1214 warn('Readline services not available on this platform.')
1213 else:
1215 else:
1214 sys.modules['readline'] = readline
1216 sys.modules['readline'] = readline
1215 import atexit
1217 import atexit
1216 from IPython.completer import IPCompleter
1218 from IPython.completer import IPCompleter
1217 self.Completer = IPCompleter(self,
1219 self.Completer = IPCompleter(self,
1218 self.user_ns,
1220 self.user_ns,
1219 self.user_global_ns,
1221 self.user_global_ns,
1220 self.rc.readline_omit__names,
1222 self.rc.readline_omit__names,
1221 self.alias_table)
1223 self.alias_table)
1222
1224
1223 # Platform-specific configuration
1225 # Platform-specific configuration
1224 if os.name == 'nt':
1226 if os.name == 'nt':
1225 self.readline_startup_hook = readline.set_pre_input_hook
1227 self.readline_startup_hook = readline.set_pre_input_hook
1226 else:
1228 else:
1227 self.readline_startup_hook = readline.set_startup_hook
1229 self.readline_startup_hook = readline.set_startup_hook
1228
1230
1229 # Load user's initrc file (readline config)
1231 # Load user's initrc file (readline config)
1230 inputrc_name = os.environ.get('INPUTRC')
1232 inputrc_name = os.environ.get('INPUTRC')
1231 if inputrc_name is None:
1233 if inputrc_name is None:
1232 home_dir = get_home_dir()
1234 home_dir = get_home_dir()
1233 if home_dir is not None:
1235 if home_dir is not None:
1234 inputrc_name = os.path.join(home_dir,'.inputrc')
1236 inputrc_name = os.path.join(home_dir,'.inputrc')
1235 if os.path.isfile(inputrc_name):
1237 if os.path.isfile(inputrc_name):
1236 try:
1238 try:
1237 readline.read_init_file(inputrc_name)
1239 readline.read_init_file(inputrc_name)
1238 except:
1240 except:
1239 warn('Problems reading readline initialization file <%s>'
1241 warn('Problems reading readline initialization file <%s>'
1240 % inputrc_name)
1242 % inputrc_name)
1241
1243
1242 self.has_readline = 1
1244 self.has_readline = 1
1243 self.readline = readline
1245 self.readline = readline
1244 # save this in sys so embedded copies can restore it properly
1246 # save this in sys so embedded copies can restore it properly
1245 sys.ipcompleter = self.Completer.complete
1247 sys.ipcompleter = self.Completer.complete
1246 readline.set_completer(self.Completer.complete)
1248 readline.set_completer(self.Completer.complete)
1247
1249
1248 # Configure readline according to user's prefs
1250 # Configure readline according to user's prefs
1249 for rlcommand in self.rc.readline_parse_and_bind:
1251 for rlcommand in self.rc.readline_parse_and_bind:
1250 readline.parse_and_bind(rlcommand)
1252 readline.parse_and_bind(rlcommand)
1251
1253
1252 # remove some chars from the delimiters list
1254 # remove some chars from the delimiters list
1253 delims = readline.get_completer_delims()
1255 delims = readline.get_completer_delims()
1254 delims = delims.translate(string._idmap,
1256 delims = delims.translate(string._idmap,
1255 self.rc.readline_remove_delims)
1257 self.rc.readline_remove_delims)
1256 readline.set_completer_delims(delims)
1258 readline.set_completer_delims(delims)
1257 # otherwise we end up with a monster history after a while:
1259 # otherwise we end up with a monster history after a while:
1258 readline.set_history_length(1000)
1260 readline.set_history_length(1000)
1259 try:
1261 try:
1260 #print '*** Reading readline history' # dbg
1262 #print '*** Reading readline history' # dbg
1261 readline.read_history_file(self.histfile)
1263 readline.read_history_file(self.histfile)
1262 except IOError:
1264 except IOError:
1263 pass # It doesn't exist yet.
1265 pass # It doesn't exist yet.
1264
1266
1265 atexit.register(self.atexit_operations)
1267 atexit.register(self.atexit_operations)
1266 del atexit
1268 del atexit
1267
1269
1268 # Configure auto-indent for all platforms
1270 # Configure auto-indent for all platforms
1269 self.set_autoindent(self.rc.autoindent)
1271 self.set_autoindent(self.rc.autoindent)
1270
1272
1271 def ask_yes_no(self,prompt,default=True):
1273 def ask_yes_no(self,prompt,default=True):
1272 if self.rc.quiet:
1274 if self.rc.quiet:
1273 return True
1275 return True
1274 return ask_yes_no(prompt,default)
1276 return ask_yes_no(prompt,default)
1275
1277
1276 def _should_recompile(self,e):
1278 def _should_recompile(self,e):
1277 """Utility routine for edit_syntax_error"""
1279 """Utility routine for edit_syntax_error"""
1278
1280
1279 if e.filename in ('<ipython console>','<input>','<string>',
1281 if e.filename in ('<ipython console>','<input>','<string>',
1280 '<console>','<BackgroundJob compilation>',
1282 '<console>','<BackgroundJob compilation>',
1281 None):
1283 None):
1282
1284
1283 return False
1285 return False
1284 try:
1286 try:
1285 if (self.rc.autoedit_syntax and
1287 if (self.rc.autoedit_syntax and
1286 not self.ask_yes_no('Return to editor to correct syntax error? '
1288 not self.ask_yes_no('Return to editor to correct syntax error? '
1287 '[Y/n] ','y')):
1289 '[Y/n] ','y')):
1288 return False
1290 return False
1289 except EOFError:
1291 except EOFError:
1290 return False
1292 return False
1291
1293
1292 def int0(x):
1294 def int0(x):
1293 try:
1295 try:
1294 return int(x)
1296 return int(x)
1295 except TypeError:
1297 except TypeError:
1296 return 0
1298 return 0
1297 # always pass integer line and offset values to editor hook
1299 # always pass integer line and offset values to editor hook
1298 self.hooks.fix_error_editor(e.filename,
1300 self.hooks.fix_error_editor(e.filename,
1299 int0(e.lineno),int0(e.offset),e.msg)
1301 int0(e.lineno),int0(e.offset),e.msg)
1300 return True
1302 return True
1301
1303
1302 def edit_syntax_error(self):
1304 def edit_syntax_error(self):
1303 """The bottom half of the syntax error handler called in the main loop.
1305 """The bottom half of the syntax error handler called in the main loop.
1304
1306
1305 Loop until syntax error is fixed or user cancels.
1307 Loop until syntax error is fixed or user cancels.
1306 """
1308 """
1307
1309
1308 while self.SyntaxTB.last_syntax_error:
1310 while self.SyntaxTB.last_syntax_error:
1309 # copy and clear last_syntax_error
1311 # copy and clear last_syntax_error
1310 err = self.SyntaxTB.clear_err_state()
1312 err = self.SyntaxTB.clear_err_state()
1311 if not self._should_recompile(err):
1313 if not self._should_recompile(err):
1312 return
1314 return
1313 try:
1315 try:
1314 # may set last_syntax_error again if a SyntaxError is raised
1316 # may set last_syntax_error again if a SyntaxError is raised
1315 self.safe_execfile(err.filename,self.user_ns)
1317 self.safe_execfile(err.filename,self.user_ns)
1316 except:
1318 except:
1317 self.showtraceback()
1319 self.showtraceback()
1318 else:
1320 else:
1319 try:
1321 try:
1320 f = file(err.filename)
1322 f = file(err.filename)
1321 try:
1323 try:
1322 sys.displayhook(f.read())
1324 sys.displayhook(f.read())
1323 finally:
1325 finally:
1324 f.close()
1326 f.close()
1325 except:
1327 except:
1326 self.showtraceback()
1328 self.showtraceback()
1327
1329
1328 def showsyntaxerror(self, filename=None):
1330 def showsyntaxerror(self, filename=None):
1329 """Display the syntax error that just occurred.
1331 """Display the syntax error that just occurred.
1330
1332
1331 This doesn't display a stack trace because there isn't one.
1333 This doesn't display a stack trace because there isn't one.
1332
1334
1333 If a filename is given, it is stuffed in the exception instead
1335 If a filename is given, it is stuffed in the exception instead
1334 of what was there before (because Python's parser always uses
1336 of what was there before (because Python's parser always uses
1335 "<string>" when reading from a string).
1337 "<string>" when reading from a string).
1336 """
1338 """
1337 etype, value, last_traceback = sys.exc_info()
1339 etype, value, last_traceback = sys.exc_info()
1338
1340
1339 # See note about these variables in showtraceback() below
1341 # See note about these variables in showtraceback() below
1340 sys.last_type = etype
1342 sys.last_type = etype
1341 sys.last_value = value
1343 sys.last_value = value
1342 sys.last_traceback = last_traceback
1344 sys.last_traceback = last_traceback
1343
1345
1344 if filename and etype is SyntaxError:
1346 if filename and etype is SyntaxError:
1345 # Work hard to stuff the correct filename in the exception
1347 # Work hard to stuff the correct filename in the exception
1346 try:
1348 try:
1347 msg, (dummy_filename, lineno, offset, line) = value
1349 msg, (dummy_filename, lineno, offset, line) = value
1348 except:
1350 except:
1349 # Not the format we expect; leave it alone
1351 # Not the format we expect; leave it alone
1350 pass
1352 pass
1351 else:
1353 else:
1352 # Stuff in the right filename
1354 # Stuff in the right filename
1353 try:
1355 try:
1354 # Assume SyntaxError is a class exception
1356 # Assume SyntaxError is a class exception
1355 value = SyntaxError(msg, (filename, lineno, offset, line))
1357 value = SyntaxError(msg, (filename, lineno, offset, line))
1356 except:
1358 except:
1357 # If that failed, assume SyntaxError is a string
1359 # If that failed, assume SyntaxError is a string
1358 value = msg, (filename, lineno, offset, line)
1360 value = msg, (filename, lineno, offset, line)
1359 self.SyntaxTB(etype,value,[])
1361 self.SyntaxTB(etype,value,[])
1360
1362
1361 def debugger(self):
1363 def debugger(self):
1362 """Call the pdb debugger."""
1364 """Call the pdb debugger."""
1363
1365
1364 if not self.rc.pdb:
1366 if not self.rc.pdb:
1365 return
1367 return
1366 pdb.pm()
1368 pdb.pm()
1367
1369
1368 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1370 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1369 """Display the exception that just occurred.
1371 """Display the exception that just occurred.
1370
1372
1371 If nothing is known about the exception, this is the method which
1373 If nothing is known about the exception, this is the method which
1372 should be used throughout the code for presenting user tracebacks,
1374 should be used throughout the code for presenting user tracebacks,
1373 rather than directly invoking the InteractiveTB object.
1375 rather than directly invoking the InteractiveTB object.
1374
1376
1375 A specific showsyntaxerror() also exists, but this method can take
1377 A specific showsyntaxerror() also exists, but this method can take
1376 care of calling it if needed, so unless you are explicitly catching a
1378 care of calling it if needed, so unless you are explicitly catching a
1377 SyntaxError exception, don't try to analyze the stack manually and
1379 SyntaxError exception, don't try to analyze the stack manually and
1378 simply call this method."""
1380 simply call this method."""
1379
1381
1380 # Though this won't be called by syntax errors in the input line,
1382 # Though this won't be called by syntax errors in the input line,
1381 # there may be SyntaxError cases whith imported code.
1383 # there may be SyntaxError cases whith imported code.
1382 if exc_tuple is None:
1384 if exc_tuple is None:
1383 etype, value, tb = sys.exc_info()
1385 etype, value, tb = sys.exc_info()
1384 else:
1386 else:
1385 etype, value, tb = exc_tuple
1387 etype, value, tb = exc_tuple
1386 if etype is SyntaxError:
1388 if etype is SyntaxError:
1387 self.showsyntaxerror(filename)
1389 self.showsyntaxerror(filename)
1388 else:
1390 else:
1389 # WARNING: these variables are somewhat deprecated and not
1391 # WARNING: these variables are somewhat deprecated and not
1390 # necessarily safe to use in a threaded environment, but tools
1392 # necessarily safe to use in a threaded environment, but tools
1391 # like pdb depend on their existence, so let's set them. If we
1393 # like pdb depend on their existence, so let's set them. If we
1392 # find problems in the field, we'll need to revisit their use.
1394 # find problems in the field, we'll need to revisit their use.
1393 sys.last_type = etype
1395 sys.last_type = etype
1394 sys.last_value = value
1396 sys.last_value = value
1395 sys.last_traceback = tb
1397 sys.last_traceback = tb
1396
1398
1397 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1399 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1398 if self.InteractiveTB.call_pdb and self.has_readline:
1400 if self.InteractiveTB.call_pdb and self.has_readline:
1399 # pdb mucks up readline, fix it back
1401 # pdb mucks up readline, fix it back
1400 self.readline.set_completer(self.Completer.complete)
1402 self.readline.set_completer(self.Completer.complete)
1401
1403
1402 def mainloop(self,banner=None):
1404 def mainloop(self,banner=None):
1403 """Creates the local namespace and starts the mainloop.
1405 """Creates the local namespace and starts the mainloop.
1404
1406
1405 If an optional banner argument is given, it will override the
1407 If an optional banner argument is given, it will override the
1406 internally created default banner."""
1408 internally created default banner."""
1407
1409
1408 if self.rc.c: # Emulate Python's -c option
1410 if self.rc.c: # Emulate Python's -c option
1409 self.exec_init_cmd()
1411 self.exec_init_cmd()
1410 if banner is None:
1412 if banner is None:
1411 if not self.rc.banner:
1413 if not self.rc.banner:
1412 banner = ''
1414 banner = ''
1413 # banner is string? Use it directly!
1415 # banner is string? Use it directly!
1414 elif isinstance(self.rc.banner,basestring):
1416 elif isinstance(self.rc.banner,basestring):
1415 banner = self.rc.banner
1417 banner = self.rc.banner
1416 else:
1418 else:
1417 banner = self.BANNER+self.banner2
1419 banner = self.BANNER+self.banner2
1418
1420
1419 self.interact(banner)
1421 self.interact(banner)
1420
1422
1421 def exec_init_cmd(self):
1423 def exec_init_cmd(self):
1422 """Execute a command given at the command line.
1424 """Execute a command given at the command line.
1423
1425
1424 This emulates Python's -c option."""
1426 This emulates Python's -c option."""
1425
1427
1426 #sys.argv = ['-c']
1428 #sys.argv = ['-c']
1427 self.push(self.rc.c)
1429 self.push(self.rc.c)
1428
1430
1429 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1431 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1430 """Embeds IPython into a running python program.
1432 """Embeds IPython into a running python program.
1431
1433
1432 Input:
1434 Input:
1433
1435
1434 - header: An optional header message can be specified.
1436 - header: An optional header message can be specified.
1435
1437
1436 - local_ns, global_ns: working namespaces. If given as None, the
1438 - local_ns, global_ns: working namespaces. If given as None, the
1437 IPython-initialized one is updated with __main__.__dict__, so that
1439 IPython-initialized one is updated with __main__.__dict__, so that
1438 program variables become visible but user-specific configuration
1440 program variables become visible but user-specific configuration
1439 remains possible.
1441 remains possible.
1440
1442
1441 - stack_depth: specifies how many levels in the stack to go to
1443 - stack_depth: specifies how many levels in the stack to go to
1442 looking for namespaces (when local_ns and global_ns are None). This
1444 looking for namespaces (when local_ns and global_ns are None). This
1443 allows an intermediate caller to make sure that this function gets
1445 allows an intermediate caller to make sure that this function gets
1444 the namespace from the intended level in the stack. By default (0)
1446 the namespace from the intended level in the stack. By default (0)
1445 it will get its locals and globals from the immediate caller.
1447 it will get its locals and globals from the immediate caller.
1446
1448
1447 Warning: it's possible to use this in a program which is being run by
1449 Warning: it's possible to use this in a program which is being run by
1448 IPython itself (via %run), but some funny things will happen (a few
1450 IPython itself (via %run), but some funny things will happen (a few
1449 globals get overwritten). In the future this will be cleaned up, as
1451 globals get overwritten). In the future this will be cleaned up, as
1450 there is no fundamental reason why it can't work perfectly."""
1452 there is no fundamental reason why it can't work perfectly."""
1451
1453
1452 # Get locals and globals from caller
1454 # Get locals and globals from caller
1453 if local_ns is None or global_ns is None:
1455 if local_ns is None or global_ns is None:
1454 call_frame = sys._getframe(stack_depth).f_back
1456 call_frame = sys._getframe(stack_depth).f_back
1455
1457
1456 if local_ns is None:
1458 if local_ns is None:
1457 local_ns = call_frame.f_locals
1459 local_ns = call_frame.f_locals
1458 if global_ns is None:
1460 if global_ns is None:
1459 global_ns = call_frame.f_globals
1461 global_ns = call_frame.f_globals
1460
1462
1461 # Update namespaces and fire up interpreter
1463 # Update namespaces and fire up interpreter
1462
1464
1463 # The global one is easy, we can just throw it in
1465 # The global one is easy, we can just throw it in
1464 self.user_global_ns = global_ns
1466 self.user_global_ns = global_ns
1465
1467
1466 # but the user/local one is tricky: ipython needs it to store internal
1468 # but the user/local one is tricky: ipython needs it to store internal
1467 # data, but we also need the locals. We'll copy locals in the user
1469 # data, but we also need the locals. We'll copy locals in the user
1468 # one, but will track what got copied so we can delete them at exit.
1470 # one, but will track what got copied so we can delete them at exit.
1469 # This is so that a later embedded call doesn't see locals from a
1471 # This is so that a later embedded call doesn't see locals from a
1470 # previous call (which most likely existed in a separate scope).
1472 # previous call (which most likely existed in a separate scope).
1471 local_varnames = local_ns.keys()
1473 local_varnames = local_ns.keys()
1472 self.user_ns.update(local_ns)
1474 self.user_ns.update(local_ns)
1473
1475
1474 # Patch for global embedding to make sure that things don't overwrite
1476 # Patch for global embedding to make sure that things don't overwrite
1475 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1477 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1476 # FIXME. Test this a bit more carefully (the if.. is new)
1478 # FIXME. Test this a bit more carefully (the if.. is new)
1477 if local_ns is None and global_ns is None:
1479 if local_ns is None and global_ns is None:
1478 self.user_global_ns.update(__main__.__dict__)
1480 self.user_global_ns.update(__main__.__dict__)
1479
1481
1480 # make sure the tab-completer has the correct frame information, so it
1482 # make sure the tab-completer has the correct frame information, so it
1481 # actually completes using the frame's locals/globals
1483 # actually completes using the frame's locals/globals
1482 self.set_completer_frame()
1484 self.set_completer_frame()
1483
1485
1484 # before activating the interactive mode, we need to make sure that
1486 # before activating the interactive mode, we need to make sure that
1485 # all names in the builtin namespace needed by ipython point to
1487 # all names in the builtin namespace needed by ipython point to
1486 # ourselves, and not to other instances.
1488 # ourselves, and not to other instances.
1487 self.add_builtins()
1489 self.add_builtins()
1488
1490
1489 self.interact(header)
1491 self.interact(header)
1490
1492
1491 # now, purge out the user namespace from anything we might have added
1493 # now, purge out the user namespace from anything we might have added
1492 # from the caller's local namespace
1494 # from the caller's local namespace
1493 delvar = self.user_ns.pop
1495 delvar = self.user_ns.pop
1494 for var in local_varnames:
1496 for var in local_varnames:
1495 delvar(var,None)
1497 delvar(var,None)
1496 # and clean builtins we may have overridden
1498 # and clean builtins we may have overridden
1497 self.clean_builtins()
1499 self.clean_builtins()
1498
1500
1499 def interact(self, banner=None):
1501 def interact(self, banner=None):
1500 """Closely emulate the interactive Python console.
1502 """Closely emulate the interactive Python console.
1501
1503
1502 The optional banner argument specify the banner to print
1504 The optional banner argument specify the banner to print
1503 before the first interaction; by default it prints a banner
1505 before the first interaction; by default it prints a banner
1504 similar to the one printed by the real Python interpreter,
1506 similar to the one printed by the real Python interpreter,
1505 followed by the current class name in parentheses (so as not
1507 followed by the current class name in parentheses (so as not
1506 to confuse this with the real interpreter -- since it's so
1508 to confuse this with the real interpreter -- since it's so
1507 close!).
1509 close!).
1508
1510
1509 """
1511 """
1510
1512
1511 if self.exit_now:
1513 if self.exit_now:
1512 # batch run -> do not interact
1514 # batch run -> do not interact
1513 return
1515 return
1514 cprt = 'Type "copyright", "credits" or "license" for more information.'
1516 cprt = 'Type "copyright", "credits" or "license" for more information.'
1515 if banner is None:
1517 if banner is None:
1516 self.write("Python %s on %s\n%s\n(%s)\n" %
1518 self.write("Python %s on %s\n%s\n(%s)\n" %
1517 (sys.version, sys.platform, cprt,
1519 (sys.version, sys.platform, cprt,
1518 self.__class__.__name__))
1520 self.__class__.__name__))
1519 else:
1521 else:
1520 self.write(banner)
1522 self.write(banner)
1521
1523
1522 more = 0
1524 more = 0
1523
1525
1524 # Mark activity in the builtins
1526 # Mark activity in the builtins
1525 __builtin__.__dict__['__IPYTHON__active'] += 1
1527 __builtin__.__dict__['__IPYTHON__active'] += 1
1526
1528
1527 # exit_now is set by a call to %Exit or %Quit
1529 # exit_now is set by a call to %Exit or %Quit
1528 while not self.exit_now:
1530 while not self.exit_now:
1529 if more:
1531 if more:
1530 prompt = self.hooks.generate_prompt(True)
1532 prompt = self.hooks.generate_prompt(True)
1531 if self.autoindent:
1533 if self.autoindent:
1532 self.readline_startup_hook(self.pre_readline)
1534 self.readline_startup_hook(self.pre_readline)
1533 else:
1535 else:
1534 prompt = self.hooks.generate_prompt(False)
1536 prompt = self.hooks.generate_prompt(False)
1535 try:
1537 try:
1536 line = self.raw_input(prompt,more)
1538 line = self.raw_input(prompt,more)
1537 if self.exit_now:
1539 if self.exit_now:
1538 # quick exit on sys.std[in|out] close
1540 # quick exit on sys.std[in|out] close
1539 break
1541 break
1540 if self.autoindent:
1542 if self.autoindent:
1541 self.readline_startup_hook(None)
1543 self.readline_startup_hook(None)
1542 except KeyboardInterrupt:
1544 except KeyboardInterrupt:
1543 self.write('\nKeyboardInterrupt\n')
1545 self.write('\nKeyboardInterrupt\n')
1544 self.resetbuffer()
1546 self.resetbuffer()
1545 # keep cache in sync with the prompt counter:
1547 # keep cache in sync with the prompt counter:
1546 self.outputcache.prompt_count -= 1
1548 self.outputcache.prompt_count -= 1
1547
1549
1548 if self.autoindent:
1550 if self.autoindent:
1549 self.indent_current_nsp = 0
1551 self.indent_current_nsp = 0
1550 more = 0
1552 more = 0
1551 except EOFError:
1553 except EOFError:
1552 if self.autoindent:
1554 if self.autoindent:
1553 self.readline_startup_hook(None)
1555 self.readline_startup_hook(None)
1554 self.write('\n')
1556 self.write('\n')
1555 self.exit()
1557 self.exit()
1556 except bdb.BdbQuit:
1558 except bdb.BdbQuit:
1557 warn('The Python debugger has exited with a BdbQuit exception.\n'
1559 warn('The Python debugger has exited with a BdbQuit exception.\n'
1558 'Because of how pdb handles the stack, it is impossible\n'
1560 'Because of how pdb handles the stack, it is impossible\n'
1559 'for IPython to properly format this particular exception.\n'
1561 'for IPython to properly format this particular exception.\n'
1560 'IPython will resume normal operation.')
1562 'IPython will resume normal operation.')
1561 except:
1563 except:
1562 # exceptions here are VERY RARE, but they can be triggered
1564 # exceptions here are VERY RARE, but they can be triggered
1563 # asynchronously by signal handlers, for example.
1565 # asynchronously by signal handlers, for example.
1564 self.showtraceback()
1566 self.showtraceback()
1565 else:
1567 else:
1566 more = self.push(line)
1568 more = self.push(line)
1567 if (self.SyntaxTB.last_syntax_error and
1569 if (self.SyntaxTB.last_syntax_error and
1568 self.rc.autoedit_syntax):
1570 self.rc.autoedit_syntax):
1569 self.edit_syntax_error()
1571 self.edit_syntax_error()
1570
1572
1571 # We are off again...
1573 # We are off again...
1572 __builtin__.__dict__['__IPYTHON__active'] -= 1
1574 __builtin__.__dict__['__IPYTHON__active'] -= 1
1573
1575
1574 def excepthook(self, etype, value, tb):
1576 def excepthook(self, etype, value, tb):
1575 """One more defense for GUI apps that call sys.excepthook.
1577 """One more defense for GUI apps that call sys.excepthook.
1576
1578
1577 GUI frameworks like wxPython trap exceptions and call
1579 GUI frameworks like wxPython trap exceptions and call
1578 sys.excepthook themselves. I guess this is a feature that
1580 sys.excepthook themselves. I guess this is a feature that
1579 enables them to keep running after exceptions that would
1581 enables them to keep running after exceptions that would
1580 otherwise kill their mainloop. This is a bother for IPython
1582 otherwise kill their mainloop. This is a bother for IPython
1581 which excepts to catch all of the program exceptions with a try:
1583 which excepts to catch all of the program exceptions with a try:
1582 except: statement.
1584 except: statement.
1583
1585
1584 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1586 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1585 any app directly invokes sys.excepthook, it will look to the user like
1587 any app directly invokes sys.excepthook, it will look to the user like
1586 IPython crashed. In order to work around this, we can disable the
1588 IPython crashed. In order to work around this, we can disable the
1587 CrashHandler and replace it with this excepthook instead, which prints a
1589 CrashHandler and replace it with this excepthook instead, which prints a
1588 regular traceback using our InteractiveTB. In this fashion, apps which
1590 regular traceback using our InteractiveTB. In this fashion, apps which
1589 call sys.excepthook will generate a regular-looking exception from
1591 call sys.excepthook will generate a regular-looking exception from
1590 IPython, and the CrashHandler will only be triggered by real IPython
1592 IPython, and the CrashHandler will only be triggered by real IPython
1591 crashes.
1593 crashes.
1592
1594
1593 This hook should be used sparingly, only in places which are not likely
1595 This hook should be used sparingly, only in places which are not likely
1594 to be true IPython errors.
1596 to be true IPython errors.
1595 """
1597 """
1596 self.showtraceback((etype,value,tb),tb_offset=0)
1598 self.showtraceback((etype,value,tb),tb_offset=0)
1597
1599
1598 def expand_aliases(self,fn,rest):
1600 def expand_aliases(self,fn,rest):
1599 """ Expand multiple levels of aliases:
1601 """ Expand multiple levels of aliases:
1600
1602
1601 if:
1603 if:
1602
1604
1603 alias foo bar /tmp
1605 alias foo bar /tmp
1604 alias baz foo
1606 alias baz foo
1605
1607
1606 then:
1608 then:
1607
1609
1608 baz huhhahhei -> bar /tmp huhhahhei
1610 baz huhhahhei -> bar /tmp huhhahhei
1609
1611
1610 """
1612 """
1611 line = fn + " " + rest
1613 line = fn + " " + rest
1612
1614
1613 done = Set()
1615 done = Set()
1614 while 1:
1616 while 1:
1615 pre,fn,rest = self.split_user_input(line)
1617 pre,fn,rest = self.split_user_input(line)
1616 if fn in self.alias_table:
1618 if fn in self.alias_table:
1617 if fn in done:
1619 if fn in done:
1618 warn("Cyclic alias definition, repeated '%s'" % fn)
1620 warn("Cyclic alias definition, repeated '%s'" % fn)
1619 return ""
1621 return ""
1620 done.add(fn)
1622 done.add(fn)
1621
1623
1622 l2 = self.transform_alias(fn,rest)
1624 l2 = self.transform_alias(fn,rest)
1623 # dir -> dir
1625 # dir -> dir
1624 if l2 == line:
1626 if l2 == line:
1625 break
1627 break
1626 # ls -> ls -F should not recurse forever
1628 # ls -> ls -F should not recurse forever
1627 if l2.split(None,1)[0] == line.split(None,1)[0]:
1629 if l2.split(None,1)[0] == line.split(None,1)[0]:
1628 line = l2
1630 line = l2
1629 break
1631 break
1630
1632
1631 line=l2
1633 line=l2
1632
1634
1633
1635
1634 # print "al expand to",line #dbg
1636 # print "al expand to",line #dbg
1635 else:
1637 else:
1636 break
1638 break
1637
1639
1638 return line
1640 return line
1639
1641
1640 def transform_alias(self, alias,rest=''):
1642 def transform_alias(self, alias,rest=''):
1641 """ Transform alias to system command string.
1643 """ Transform alias to system command string.
1642 """
1644 """
1643 nargs,cmd = self.alias_table[alias]
1645 nargs,cmd = self.alias_table[alias]
1644 if ' ' in cmd and os.path.isfile(cmd):
1646 if ' ' in cmd and os.path.isfile(cmd):
1645 cmd = '"%s"' % cmd
1647 cmd = '"%s"' % cmd
1646
1648
1647 # Expand the %l special to be the user's input line
1649 # Expand the %l special to be the user's input line
1648 if cmd.find('%l') >= 0:
1650 if cmd.find('%l') >= 0:
1649 cmd = cmd.replace('%l',rest)
1651 cmd = cmd.replace('%l',rest)
1650 rest = ''
1652 rest = ''
1651 if nargs==0:
1653 if nargs==0:
1652 # Simple, argument-less aliases
1654 # Simple, argument-less aliases
1653 cmd = '%s %s' % (cmd,rest)
1655 cmd = '%s %s' % (cmd,rest)
1654 else:
1656 else:
1655 # Handle aliases with positional arguments
1657 # Handle aliases with positional arguments
1656 args = rest.split(None,nargs)
1658 args = rest.split(None,nargs)
1657 if len(args)< nargs:
1659 if len(args)< nargs:
1658 error('Alias <%s> requires %s arguments, %s given.' %
1660 error('Alias <%s> requires %s arguments, %s given.' %
1659 (alias,nargs,len(args)))
1661 (alias,nargs,len(args)))
1660 return None
1662 return None
1661 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1663 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1662 # Now call the macro, evaluating in the user's namespace
1664 # Now call the macro, evaluating in the user's namespace
1663 #print 'new command: <%r>' % cmd # dbg
1665 #print 'new command: <%r>' % cmd # dbg
1664 return cmd
1666 return cmd
1665
1667
1666 def call_alias(self,alias,rest=''):
1668 def call_alias(self,alias,rest=''):
1667 """Call an alias given its name and the rest of the line.
1669 """Call an alias given its name and the rest of the line.
1668
1670
1669 This is only used to provide backwards compatibility for users of
1671 This is only used to provide backwards compatibility for users of
1670 ipalias(), use of which is not recommended for anymore."""
1672 ipalias(), use of which is not recommended for anymore."""
1671
1673
1672 # Now call the macro, evaluating in the user's namespace
1674 # Now call the macro, evaluating in the user's namespace
1673 cmd = self.transform_alias(alias, rest)
1675 cmd = self.transform_alias(alias, rest)
1674 try:
1676 try:
1675 self.system(cmd)
1677 self.system(cmd)
1676 except:
1678 except:
1677 self.showtraceback()
1679 self.showtraceback()
1678
1680
1679 def indent_current_str(self):
1681 def indent_current_str(self):
1680 """return the current level of indentation as a string"""
1682 """return the current level of indentation as a string"""
1681 return self.indent_current_nsp * ' '
1683 return self.indent_current_nsp * ' '
1682
1684
1683 def autoindent_update(self,line):
1685 def autoindent_update(self,line):
1684 """Keep track of the indent level."""
1686 """Keep track of the indent level."""
1685
1687
1686 #debugx('line')
1688 #debugx('line')
1687 #debugx('self.indent_current_nsp')
1689 #debugx('self.indent_current_nsp')
1688 if self.autoindent:
1690 if self.autoindent:
1689 if line:
1691 if line:
1690 inisp = num_ini_spaces(line)
1692 inisp = num_ini_spaces(line)
1691 if inisp < self.indent_current_nsp:
1693 if inisp < self.indent_current_nsp:
1692 self.indent_current_nsp = inisp
1694 self.indent_current_nsp = inisp
1693
1695
1694 if line[-1] == ':':
1696 if line[-1] == ':':
1695 self.indent_current_nsp += 4
1697 self.indent_current_nsp += 4
1696 elif dedent_re.match(line):
1698 elif dedent_re.match(line):
1697 self.indent_current_nsp -= 4
1699 self.indent_current_nsp -= 4
1698 else:
1700 else:
1699 self.indent_current_nsp = 0
1701 self.indent_current_nsp = 0
1700
1702
1701 def runlines(self,lines):
1703 def runlines(self,lines):
1702 """Run a string of one or more lines of source.
1704 """Run a string of one or more lines of source.
1703
1705
1704 This method is capable of running a string containing multiple source
1706 This method is capable of running a string containing multiple source
1705 lines, as if they had been entered at the IPython prompt. Since it
1707 lines, as if they had been entered at the IPython prompt. Since it
1706 exposes IPython's processing machinery, the given strings can contain
1708 exposes IPython's processing machinery, the given strings can contain
1707 magic calls (%magic), special shell access (!cmd), etc."""
1709 magic calls (%magic), special shell access (!cmd), etc."""
1708
1710
1709 # We must start with a clean buffer, in case this is run from an
1711 # We must start with a clean buffer, in case this is run from an
1710 # interactive IPython session (via a magic, for example).
1712 # interactive IPython session (via a magic, for example).
1711 self.resetbuffer()
1713 self.resetbuffer()
1712 lines = lines.split('\n')
1714 lines = lines.split('\n')
1713 more = 0
1715 more = 0
1714 for line in lines:
1716 for line in lines:
1715 # skip blank lines so we don't mess up the prompt counter, but do
1717 # skip blank lines so we don't mess up the prompt counter, but do
1716 # NOT skip even a blank line if we are in a code block (more is
1718 # NOT skip even a blank line if we are in a code block (more is
1717 # true)
1719 # true)
1718 if line or more:
1720 if line or more:
1719 more = self.push(self.prefilter(line,more))
1721 more = self.push(self.prefilter(line,more))
1720 # IPython's runsource returns None if there was an error
1722 # IPython's runsource returns None if there was an error
1721 # compiling the code. This allows us to stop processing right
1723 # compiling the code. This allows us to stop processing right
1722 # away, so the user gets the error message at the right place.
1724 # away, so the user gets the error message at the right place.
1723 if more is None:
1725 if more is None:
1724 break
1726 break
1725 # final newline in case the input didn't have it, so that the code
1727 # final newline in case the input didn't have it, so that the code
1726 # actually does get executed
1728 # actually does get executed
1727 if more:
1729 if more:
1728 self.push('\n')
1730 self.push('\n')
1729
1731
1730 def runsource(self, source, filename='<input>', symbol='single'):
1732 def runsource(self, source, filename='<input>', symbol='single'):
1731 """Compile and run some source in the interpreter.
1733 """Compile and run some source in the interpreter.
1732
1734
1733 Arguments are as for compile_command().
1735 Arguments are as for compile_command().
1734
1736
1735 One several things can happen:
1737 One several things can happen:
1736
1738
1737 1) The input is incorrect; compile_command() raised an
1739 1) The input is incorrect; compile_command() raised an
1738 exception (SyntaxError or OverflowError). A syntax traceback
1740 exception (SyntaxError or OverflowError). A syntax traceback
1739 will be printed by calling the showsyntaxerror() method.
1741 will be printed by calling the showsyntaxerror() method.
1740
1742
1741 2) The input is incomplete, and more input is required;
1743 2) The input is incomplete, and more input is required;
1742 compile_command() returned None. Nothing happens.
1744 compile_command() returned None. Nothing happens.
1743
1745
1744 3) The input is complete; compile_command() returned a code
1746 3) The input is complete; compile_command() returned a code
1745 object. The code is executed by calling self.runcode() (which
1747 object. The code is executed by calling self.runcode() (which
1746 also handles run-time exceptions, except for SystemExit).
1748 also handles run-time exceptions, except for SystemExit).
1747
1749
1748 The return value is:
1750 The return value is:
1749
1751
1750 - True in case 2
1752 - True in case 2
1751
1753
1752 - False in the other cases, unless an exception is raised, where
1754 - False in the other cases, unless an exception is raised, where
1753 None is returned instead. This can be used by external callers to
1755 None is returned instead. This can be used by external callers to
1754 know whether to continue feeding input or not.
1756 know whether to continue feeding input or not.
1755
1757
1756 The return value can be used to decide whether to use sys.ps1 or
1758 The return value can be used to decide whether to use sys.ps1 or
1757 sys.ps2 to prompt the next line."""
1759 sys.ps2 to prompt the next line."""
1758
1760
1759 try:
1761 try:
1760 code = self.compile(source,filename,symbol)
1762 code = self.compile(source,filename,symbol)
1761 except (OverflowError, SyntaxError, ValueError):
1763 except (OverflowError, SyntaxError, ValueError):
1762 # Case 1
1764 # Case 1
1763 self.showsyntaxerror(filename)
1765 self.showsyntaxerror(filename)
1764 return None
1766 return None
1765
1767
1766 if code is None:
1768 if code is None:
1767 # Case 2
1769 # Case 2
1768 return True
1770 return True
1769
1771
1770 # Case 3
1772 # Case 3
1771 # We store the code object so that threaded shells and
1773 # We store the code object so that threaded shells and
1772 # custom exception handlers can access all this info if needed.
1774 # custom exception handlers can access all this info if needed.
1773 # The source corresponding to this can be obtained from the
1775 # The source corresponding to this can be obtained from the
1774 # buffer attribute as '\n'.join(self.buffer).
1776 # buffer attribute as '\n'.join(self.buffer).
1775 self.code_to_run = code
1777 self.code_to_run = code
1776 # now actually execute the code object
1778 # now actually execute the code object
1777 if self.runcode(code) == 0:
1779 if self.runcode(code) == 0:
1778 return False
1780 return False
1779 else:
1781 else:
1780 return None
1782 return None
1781
1783
1782 def runcode(self,code_obj):
1784 def runcode(self,code_obj):
1783 """Execute a code object.
1785 """Execute a code object.
1784
1786
1785 When an exception occurs, self.showtraceback() is called to display a
1787 When an exception occurs, self.showtraceback() is called to display a
1786 traceback.
1788 traceback.
1787
1789
1788 Return value: a flag indicating whether the code to be run completed
1790 Return value: a flag indicating whether the code to be run completed
1789 successfully:
1791 successfully:
1790
1792
1791 - 0: successful execution.
1793 - 0: successful execution.
1792 - 1: an error occurred.
1794 - 1: an error occurred.
1793 """
1795 """
1794
1796
1795 # Set our own excepthook in case the user code tries to call it
1797 # Set our own excepthook in case the user code tries to call it
1796 # directly, so that the IPython crash handler doesn't get triggered
1798 # directly, so that the IPython crash handler doesn't get triggered
1797 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1799 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1798
1800
1799 # we save the original sys.excepthook in the instance, in case config
1801 # we save the original sys.excepthook in the instance, in case config
1800 # code (such as magics) needs access to it.
1802 # code (such as magics) needs access to it.
1801 self.sys_excepthook = old_excepthook
1803 self.sys_excepthook = old_excepthook
1802 outflag = 1 # happens in more places, so it's easier as default
1804 outflag = 1 # happens in more places, so it's easier as default
1803 try:
1805 try:
1804 try:
1806 try:
1805 # Embedded instances require separate global/local namespaces
1807 # Embedded instances require separate global/local namespaces
1806 # so they can see both the surrounding (local) namespace and
1808 # so they can see both the surrounding (local) namespace and
1807 # the module-level globals when called inside another function.
1809 # the module-level globals when called inside another function.
1808 if self.embedded:
1810 if self.embedded:
1809 exec code_obj in self.user_global_ns, self.user_ns
1811 exec code_obj in self.user_global_ns, self.user_ns
1810 # Normal (non-embedded) instances should only have a single
1812 # Normal (non-embedded) instances should only have a single
1811 # namespace for user code execution, otherwise functions won't
1813 # namespace for user code execution, otherwise functions won't
1812 # see interactive top-level globals.
1814 # see interactive top-level globals.
1813 else:
1815 else:
1814 exec code_obj in self.user_ns
1816 exec code_obj in self.user_ns
1815 finally:
1817 finally:
1816 # Reset our crash handler in place
1818 # Reset our crash handler in place
1817 sys.excepthook = old_excepthook
1819 sys.excepthook = old_excepthook
1818 except SystemExit:
1820 except SystemExit:
1819 self.resetbuffer()
1821 self.resetbuffer()
1820 self.showtraceback()
1822 self.showtraceback()
1821 warn("Type %exit or %quit to exit IPython "
1823 warn("Type %exit or %quit to exit IPython "
1822 "(%Exit or %Quit do so unconditionally).",level=1)
1824 "(%Exit or %Quit do so unconditionally).",level=1)
1823 except self.custom_exceptions:
1825 except self.custom_exceptions:
1824 etype,value,tb = sys.exc_info()
1826 etype,value,tb = sys.exc_info()
1825 self.CustomTB(etype,value,tb)
1827 self.CustomTB(etype,value,tb)
1826 except:
1828 except:
1827 self.showtraceback()
1829 self.showtraceback()
1828 else:
1830 else:
1829 outflag = 0
1831 outflag = 0
1830 if softspace(sys.stdout, 0):
1832 if softspace(sys.stdout, 0):
1831 print
1833 print
1832 # Flush out code object which has been run (and source)
1834 # Flush out code object which has been run (and source)
1833 self.code_to_run = None
1835 self.code_to_run = None
1834 return outflag
1836 return outflag
1835
1837
1836 def push(self, line):
1838 def push(self, line):
1837 """Push a line to the interpreter.
1839 """Push a line to the interpreter.
1838
1840
1839 The line should not have a trailing newline; it may have
1841 The line should not have a trailing newline; it may have
1840 internal newlines. The line is appended to a buffer and the
1842 internal newlines. The line is appended to a buffer and the
1841 interpreter's runsource() method is called with the
1843 interpreter's runsource() method is called with the
1842 concatenated contents of the buffer as source. If this
1844 concatenated contents of the buffer as source. If this
1843 indicates that the command was executed or invalid, the buffer
1845 indicates that the command was executed or invalid, the buffer
1844 is reset; otherwise, the command is incomplete, and the buffer
1846 is reset; otherwise, the command is incomplete, and the buffer
1845 is left as it was after the line was appended. The return
1847 is left as it was after the line was appended. The return
1846 value is 1 if more input is required, 0 if the line was dealt
1848 value is 1 if more input is required, 0 if the line was dealt
1847 with in some way (this is the same as runsource()).
1849 with in some way (this is the same as runsource()).
1848 """
1850 """
1849
1851
1850 # autoindent management should be done here, and not in the
1852 # autoindent management should be done here, and not in the
1851 # interactive loop, since that one is only seen by keyboard input. We
1853 # interactive loop, since that one is only seen by keyboard input. We
1852 # need this done correctly even for code run via runlines (which uses
1854 # need this done correctly even for code run via runlines (which uses
1853 # push).
1855 # push).
1854
1856
1855 #print 'push line: <%s>' % line # dbg
1857 #print 'push line: <%s>' % line # dbg
1856 for subline in line.splitlines():
1858 for subline in line.splitlines():
1857 self.autoindent_update(subline)
1859 self.autoindent_update(subline)
1858 self.buffer.append(line)
1860 self.buffer.append(line)
1859 more = self.runsource('\n'.join(self.buffer), self.filename)
1861 more = self.runsource('\n'.join(self.buffer), self.filename)
1860 if not more:
1862 if not more:
1861 self.resetbuffer()
1863 self.resetbuffer()
1862 return more
1864 return more
1863
1865
1864 def resetbuffer(self):
1866 def resetbuffer(self):
1865 """Reset the input buffer."""
1867 """Reset the input buffer."""
1866 self.buffer[:] = []
1868 self.buffer[:] = []
1867
1869
1868 def raw_input(self,prompt='',continue_prompt=False):
1870 def raw_input(self,prompt='',continue_prompt=False):
1869 """Write a prompt and read a line.
1871 """Write a prompt and read a line.
1870
1872
1871 The returned line does not include the trailing newline.
1873 The returned line does not include the trailing newline.
1872 When the user enters the EOF key sequence, EOFError is raised.
1874 When the user enters the EOF key sequence, EOFError is raised.
1873
1875
1874 Optional inputs:
1876 Optional inputs:
1875
1877
1876 - prompt(''): a string to be printed to prompt the user.
1878 - prompt(''): a string to be printed to prompt the user.
1877
1879
1878 - continue_prompt(False): whether this line is the first one or a
1880 - continue_prompt(False): whether this line is the first one or a
1879 continuation in a sequence of inputs.
1881 continuation in a sequence of inputs.
1880 """
1882 """
1881
1883
1882 try:
1884 try:
1883 line = raw_input_original(prompt)
1885 line = raw_input_original(prompt)
1884 except ValueError:
1886 except ValueError:
1885 warn("\n********\nYou or a %run:ed script called sys.stdin.close() or sys.stdout.close()!\nExiting IPython!")
1887 warn("\n********\nYou or a %run:ed script called sys.stdin.close() or sys.stdout.close()!\nExiting IPython!")
1886 self.exit_now = True
1888 self.exit_now = True
1887 return ""
1889 return ""
1888
1890
1889
1891
1890 # Try to be reasonably smart about not re-indenting pasted input more
1892 # Try to be reasonably smart about not re-indenting pasted input more
1891 # than necessary. We do this by trimming out the auto-indent initial
1893 # than necessary. We do this by trimming out the auto-indent initial
1892 # spaces, if the user's actual input started itself with whitespace.
1894 # spaces, if the user's actual input started itself with whitespace.
1893 #debugx('self.buffer[-1]')
1895 #debugx('self.buffer[-1]')
1894
1896
1895 if self.autoindent:
1897 if self.autoindent:
1896 if num_ini_spaces(line) > self.indent_current_nsp:
1898 if num_ini_spaces(line) > self.indent_current_nsp:
1897 line = line[self.indent_current_nsp:]
1899 line = line[self.indent_current_nsp:]
1898 self.indent_current_nsp = 0
1900 self.indent_current_nsp = 0
1899
1901
1900 # store the unfiltered input before the user has any chance to modify
1902 # store the unfiltered input before the user has any chance to modify
1901 # it.
1903 # it.
1902 if line.strip():
1904 if line.strip():
1903 if continue_prompt:
1905 if continue_prompt:
1904 self.input_hist_raw[-1] += '%s\n' % line
1906 self.input_hist_raw[-1] += '%s\n' % line
1905 if self.has_readline: # and some config option is set?
1907 if self.has_readline: # and some config option is set?
1906 try:
1908 try:
1907 histlen = self.readline.get_current_history_length()
1909 histlen = self.readline.get_current_history_length()
1908 newhist = self.input_hist_raw[-1].rstrip()
1910 newhist = self.input_hist_raw[-1].rstrip()
1909 self.readline.remove_history_item(histlen-1)
1911 self.readline.remove_history_item(histlen-1)
1910 self.readline.replace_history_item(histlen-2,newhist)
1912 self.readline.replace_history_item(histlen-2,newhist)
1911 except AttributeError:
1913 except AttributeError:
1912 pass # re{move,place}_history_item are new in 2.4.
1914 pass # re{move,place}_history_item are new in 2.4.
1913 else:
1915 else:
1914 self.input_hist_raw.append('%s\n' % line)
1916 self.input_hist_raw.append('%s\n' % line)
1915
1917
1916 try:
1918 try:
1917 lineout = self.prefilter(line,continue_prompt)
1919 lineout = self.prefilter(line,continue_prompt)
1918 except:
1920 except:
1919 # blanket except, in case a user-defined prefilter crashes, so it
1921 # blanket except, in case a user-defined prefilter crashes, so it
1920 # can't take all of ipython with it.
1922 # can't take all of ipython with it.
1921 self.showtraceback()
1923 self.showtraceback()
1922 return ''
1924 return ''
1923 else:
1925 else:
1924 return lineout
1926 return lineout
1925
1927
1926 def split_user_input(self,line):
1928 def split_user_input(self,line):
1927 """Split user input into pre-char, function part and rest."""
1929 """Split user input into pre-char, function part and rest."""
1928
1930
1929 lsplit = self.line_split.match(line)
1931 lsplit = self.line_split.match(line)
1930 if lsplit is None: # no regexp match returns None
1932 if lsplit is None: # no regexp match returns None
1931 try:
1933 try:
1932 iFun,theRest = line.split(None,1)
1934 iFun,theRest = line.split(None,1)
1933 except ValueError:
1935 except ValueError:
1934 iFun,theRest = line,''
1936 iFun,theRest = line,''
1935 pre = re.match('^(\s*)(.*)',line).groups()[0]
1937 pre = re.match('^(\s*)(.*)',line).groups()[0]
1936 else:
1938 else:
1937 pre,iFun,theRest = lsplit.groups()
1939 pre,iFun,theRest = lsplit.groups()
1938
1940
1939 #print 'line:<%s>' % line # dbg
1941 #print 'line:<%s>' % line # dbg
1940 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1942 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1941 return pre,iFun.strip(),theRest
1943 return pre,iFun.strip(),theRest
1942
1944
1943 def _prefilter(self, line, continue_prompt):
1945 def _prefilter(self, line, continue_prompt):
1944 """Calls different preprocessors, depending on the form of line."""
1946 """Calls different preprocessors, depending on the form of line."""
1945
1947
1946 # All handlers *must* return a value, even if it's blank ('').
1948 # All handlers *must* return a value, even if it's blank ('').
1947
1949
1948 # Lines are NOT logged here. Handlers should process the line as
1950 # Lines are NOT logged here. Handlers should process the line as
1949 # needed, update the cache AND log it (so that the input cache array
1951 # needed, update the cache AND log it (so that the input cache array
1950 # stays synced).
1952 # stays synced).
1951
1953
1952 # This function is _very_ delicate, and since it's also the one which
1954 # This function is _very_ delicate, and since it's also the one which
1953 # determines IPython's response to user input, it must be as efficient
1955 # determines IPython's response to user input, it must be as efficient
1954 # as possible. For this reason it has _many_ returns in it, trying
1956 # as possible. For this reason it has _many_ returns in it, trying
1955 # always to exit as quickly as it can figure out what it needs to do.
1957 # always to exit as quickly as it can figure out what it needs to do.
1956
1958
1957 # This function is the main responsible for maintaining IPython's
1959 # This function is the main responsible for maintaining IPython's
1958 # behavior respectful of Python's semantics. So be _very_ careful if
1960 # behavior respectful of Python's semantics. So be _very_ careful if
1959 # making changes to anything here.
1961 # making changes to anything here.
1960
1962
1961 #.....................................................................
1963 #.....................................................................
1962 # Code begins
1964 # Code begins
1963
1965
1964 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1966 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1965
1967
1966 # save the line away in case we crash, so the post-mortem handler can
1968 # save the line away in case we crash, so the post-mortem handler can
1967 # record it
1969 # record it
1968 self._last_input_line = line
1970 self._last_input_line = line
1969
1971
1970 #print '***line: <%s>' % line # dbg
1972 #print '***line: <%s>' % line # dbg
1971
1973
1972 # the input history needs to track even empty lines
1974 # the input history needs to track even empty lines
1973 stripped = line.strip()
1975 stripped = line.strip()
1974
1976
1975 if not stripped:
1977 if not stripped:
1976 if not continue_prompt:
1978 if not continue_prompt:
1977 self.outputcache.prompt_count -= 1
1979 self.outputcache.prompt_count -= 1
1978 return self.handle_normal(line,continue_prompt)
1980 return self.handle_normal(line,continue_prompt)
1979 #return self.handle_normal('',continue_prompt)
1981 #return self.handle_normal('',continue_prompt)
1980
1982
1981 # print '***cont',continue_prompt # dbg
1983 # print '***cont',continue_prompt # dbg
1982 # special handlers are only allowed for single line statements
1984 # special handlers are only allowed for single line statements
1983 if continue_prompt and not self.rc.multi_line_specials:
1985 if continue_prompt and not self.rc.multi_line_specials:
1984 return self.handle_normal(line,continue_prompt)
1986 return self.handle_normal(line,continue_prompt)
1985
1987
1986
1988
1987 # For the rest, we need the structure of the input
1989 # For the rest, we need the structure of the input
1988 pre,iFun,theRest = self.split_user_input(line)
1990 pre,iFun,theRest = self.split_user_input(line)
1989
1991
1990 # See whether any pre-existing handler can take care of it
1992 # See whether any pre-existing handler can take care of it
1991
1993
1992 rewritten = self.hooks.input_prefilter(stripped)
1994 rewritten = self.hooks.input_prefilter(stripped)
1993 if rewritten != stripped: # ok, some prefilter did something
1995 if rewritten != stripped: # ok, some prefilter did something
1994 rewritten = pre + rewritten # add indentation
1996 rewritten = pre + rewritten # add indentation
1995 return self.handle_normal(rewritten)
1997 return self.handle_normal(rewritten)
1996
1998
1997 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1999 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1998
2000
1999 # First check for explicit escapes in the last/first character
2001 # First check for explicit escapes in the last/first character
2000 handler = None
2002 handler = None
2001 if line[-1] == self.ESC_HELP:
2003 if line[-1] == self.ESC_HELP:
2002 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
2004 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
2003 if handler is None:
2005 if handler is None:
2004 # look at the first character of iFun, NOT of line, so we skip
2006 # look at the first character of iFun, NOT of line, so we skip
2005 # leading whitespace in multiline input
2007 # leading whitespace in multiline input
2006 handler = self.esc_handlers.get(iFun[0:1])
2008 handler = self.esc_handlers.get(iFun[0:1])
2007 if handler is not None:
2009 if handler is not None:
2008 return handler(line,continue_prompt,pre,iFun,theRest)
2010 return handler(line,continue_prompt,pre,iFun,theRest)
2009 # Emacs ipython-mode tags certain input lines
2011 # Emacs ipython-mode tags certain input lines
2010 if line.endswith('# PYTHON-MODE'):
2012 if line.endswith('# PYTHON-MODE'):
2011 return self.handle_emacs(line,continue_prompt)
2013 return self.handle_emacs(line,continue_prompt)
2012
2014
2013 # Next, check if we can automatically execute this thing
2015 # Next, check if we can automatically execute this thing
2014
2016
2015 # Allow ! in multi-line statements if multi_line_specials is on:
2017 # Allow ! in multi-line statements if multi_line_specials is on:
2016 if continue_prompt and self.rc.multi_line_specials and \
2018 if continue_prompt and self.rc.multi_line_specials and \
2017 iFun.startswith(self.ESC_SHELL):
2019 iFun.startswith(self.ESC_SHELL):
2018 return self.handle_shell_escape(line,continue_prompt,
2020 return self.handle_shell_escape(line,continue_prompt,
2019 pre=pre,iFun=iFun,
2021 pre=pre,iFun=iFun,
2020 theRest=theRest)
2022 theRest=theRest)
2021
2023
2022 # Let's try to find if the input line is a magic fn
2024 # Let's try to find if the input line is a magic fn
2023 oinfo = None
2025 oinfo = None
2024 if hasattr(self,'magic_'+iFun):
2026 if hasattr(self,'magic_'+iFun):
2025 # WARNING: _ofind uses getattr(), so it can consume generators and
2027 # WARNING: _ofind uses getattr(), so it can consume generators and
2026 # cause other side effects.
2028 # cause other side effects.
2027 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2029 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2028 if oinfo['ismagic']:
2030 if oinfo['ismagic']:
2029 # Be careful not to call magics when a variable assignment is
2031 # Be careful not to call magics when a variable assignment is
2030 # being made (ls='hi', for example)
2032 # being made (ls='hi', for example)
2031 if self.rc.automagic and \
2033 if self.rc.automagic and \
2032 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
2034 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
2033 (self.rc.multi_line_specials or not continue_prompt):
2035 (self.rc.multi_line_specials or not continue_prompt):
2034 return self.handle_magic(line,continue_prompt,
2036 return self.handle_magic(line,continue_prompt,
2035 pre,iFun,theRest)
2037 pre,iFun,theRest)
2036 else:
2038 else:
2037 return self.handle_normal(line,continue_prompt)
2039 return self.handle_normal(line,continue_prompt)
2038
2040
2039 # If the rest of the line begins with an (in)equality, assginment or
2041 # If the rest of the line begins with an (in)equality, assginment or
2040 # function call, we should not call _ofind but simply execute it.
2042 # function call, we should not call _ofind but simply execute it.
2041 # This avoids spurious geattr() accesses on objects upon assignment.
2043 # This avoids spurious geattr() accesses on objects upon assignment.
2042 #
2044 #
2043 # It also allows users to assign to either alias or magic names true
2045 # It also allows users to assign to either alias or magic names true
2044 # python variables (the magic/alias systems always take second seat to
2046 # python variables (the magic/alias systems always take second seat to
2045 # true python code).
2047 # true python code).
2046 if theRest and theRest[0] in '!=()':
2048 if theRest and theRest[0] in '!=()':
2047 return self.handle_normal(line,continue_prompt)
2049 return self.handle_normal(line,continue_prompt)
2048
2050
2049 if oinfo is None:
2051 if oinfo is None:
2050 # let's try to ensure that _oinfo is ONLY called when autocall is
2052 # let's try to ensure that _oinfo is ONLY called when autocall is
2051 # on. Since it has inevitable potential side effects, at least
2053 # on. Since it has inevitable potential side effects, at least
2052 # having autocall off should be a guarantee to the user that no
2054 # having autocall off should be a guarantee to the user that no
2053 # weird things will happen.
2055 # weird things will happen.
2054
2056
2055 if self.rc.autocall:
2057 if self.rc.autocall:
2056 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2058 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
2057 else:
2059 else:
2058 # in this case, all that's left is either an alias or
2060 # in this case, all that's left is either an alias or
2059 # processing the line normally.
2061 # processing the line normally.
2060 if iFun in self.alias_table:
2062 if iFun in self.alias_table:
2061 # if autocall is off, by not running _ofind we won't know
2063 # if autocall is off, by not running _ofind we won't know
2062 # whether the given name may also exist in one of the
2064 # whether the given name may also exist in one of the
2063 # user's namespace. At this point, it's best to do a
2065 # user's namespace. At this point, it's best to do a
2064 # quick check just to be sure that we don't let aliases
2066 # quick check just to be sure that we don't let aliases
2065 # shadow variables.
2067 # shadow variables.
2066 head = iFun.split('.',1)[0]
2068 head = iFun.split('.',1)[0]
2067 if head in self.user_ns or head in self.internal_ns \
2069 if head in self.user_ns or head in self.internal_ns \
2068 or head in __builtin__.__dict__:
2070 or head in __builtin__.__dict__:
2069 return self.handle_normal(line,continue_prompt)
2071 return self.handle_normal(line,continue_prompt)
2070 else:
2072 else:
2071 return self.handle_alias(line,continue_prompt,
2073 return self.handle_alias(line,continue_prompt,
2072 pre,iFun,theRest)
2074 pre,iFun,theRest)
2073
2075
2074 else:
2076 else:
2075 return self.handle_normal(line,continue_prompt)
2077 return self.handle_normal(line,continue_prompt)
2076
2078
2077 if not oinfo['found']:
2079 if not oinfo['found']:
2078 return self.handle_normal(line,continue_prompt)
2080 return self.handle_normal(line,continue_prompt)
2079 else:
2081 else:
2080 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2082 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2081 if oinfo['isalias']:
2083 if oinfo['isalias']:
2082 return self.handle_alias(line,continue_prompt,
2084 return self.handle_alias(line,continue_prompt,
2083 pre,iFun,theRest)
2085 pre,iFun,theRest)
2084
2086
2085 if (self.rc.autocall
2087 if (self.rc.autocall
2086 and
2088 and
2087 (
2089 (
2088 #only consider exclusion re if not "," or ";" autoquoting
2090 #only consider exclusion re if not "," or ";" autoquoting
2089 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
2091 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
2090 or pre == self.ESC_PAREN) or
2092 or pre == self.ESC_PAREN) or
2091 (not self.re_exclude_auto.match(theRest)))
2093 (not self.re_exclude_auto.match(theRest)))
2092 and
2094 and
2093 self.re_fun_name.match(iFun) and
2095 self.re_fun_name.match(iFun) and
2094 callable(oinfo['obj'])) :
2096 callable(oinfo['obj'])) :
2095 #print 'going auto' # dbg
2097 #print 'going auto' # dbg
2096 return self.handle_auto(line,continue_prompt,
2098 return self.handle_auto(line,continue_prompt,
2097 pre,iFun,theRest,oinfo['obj'])
2099 pre,iFun,theRest,oinfo['obj'])
2098 else:
2100 else:
2099 #print 'was callable?', callable(oinfo['obj']) # dbg
2101 #print 'was callable?', callable(oinfo['obj']) # dbg
2100 return self.handle_normal(line,continue_prompt)
2102 return self.handle_normal(line,continue_prompt)
2101
2103
2102 # If we get here, we have a normal Python line. Log and return.
2104 # If we get here, we have a normal Python line. Log and return.
2103 return self.handle_normal(line,continue_prompt)
2105 return self.handle_normal(line,continue_prompt)
2104
2106
2105 def _prefilter_dumb(self, line, continue_prompt):
2107 def _prefilter_dumb(self, line, continue_prompt):
2106 """simple prefilter function, for debugging"""
2108 """simple prefilter function, for debugging"""
2107 return self.handle_normal(line,continue_prompt)
2109 return self.handle_normal(line,continue_prompt)
2108
2110
2109
2111
2110 def multiline_prefilter(self, line, continue_prompt):
2112 def multiline_prefilter(self, line, continue_prompt):
2111 """ Run _prefilter for each line of input
2113 """ Run _prefilter for each line of input
2112
2114
2113 Covers cases where there are multiple lines in the user entry,
2115 Covers cases where there are multiple lines in the user entry,
2114 which is the case when the user goes back to a multiline history
2116 which is the case when the user goes back to a multiline history
2115 entry and presses enter.
2117 entry and presses enter.
2116
2118
2117 """
2119 """
2118 out = []
2120 out = []
2119 for l in line.rstrip('\n').split('\n'):
2121 for l in line.rstrip('\n').split('\n'):
2120 out.append(self._prefilter(l, continue_prompt))
2122 out.append(self._prefilter(l, continue_prompt))
2121 return '\n'.join(out)
2123 return '\n'.join(out)
2122
2124
2123 # Set the default prefilter() function (this can be user-overridden)
2125 # Set the default prefilter() function (this can be user-overridden)
2124 prefilter = multiline_prefilter
2126 prefilter = multiline_prefilter
2125
2127
2126 def handle_normal(self,line,continue_prompt=None,
2128 def handle_normal(self,line,continue_prompt=None,
2127 pre=None,iFun=None,theRest=None):
2129 pre=None,iFun=None,theRest=None):
2128 """Handle normal input lines. Use as a template for handlers."""
2130 """Handle normal input lines. Use as a template for handlers."""
2129
2131
2130 # With autoindent on, we need some way to exit the input loop, and I
2132 # With autoindent on, we need some way to exit the input loop, and I
2131 # don't want to force the user to have to backspace all the way to
2133 # don't want to force the user to have to backspace all the way to
2132 # clear the line. The rule will be in this case, that either two
2134 # clear the line. The rule will be in this case, that either two
2133 # lines of pure whitespace in a row, or a line of pure whitespace but
2135 # lines of pure whitespace in a row, or a line of pure whitespace but
2134 # of a size different to the indent level, will exit the input loop.
2136 # of a size different to the indent level, will exit the input loop.
2135
2137
2136 if (continue_prompt and self.autoindent and line.isspace() and
2138 if (continue_prompt and self.autoindent and line.isspace() and
2137 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2139 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2138 (self.buffer[-1]).isspace() )):
2140 (self.buffer[-1]).isspace() )):
2139 line = ''
2141 line = ''
2140
2142
2141 self.log(line,line,continue_prompt)
2143 self.log(line,line,continue_prompt)
2142 return line
2144 return line
2143
2145
2144 def handle_alias(self,line,continue_prompt=None,
2146 def handle_alias(self,line,continue_prompt=None,
2145 pre=None,iFun=None,theRest=None):
2147 pre=None,iFun=None,theRest=None):
2146 """Handle alias input lines. """
2148 """Handle alias input lines. """
2147
2149
2148 # pre is needed, because it carries the leading whitespace. Otherwise
2150 # pre is needed, because it carries the leading whitespace. Otherwise
2149 # aliases won't work in indented sections.
2151 # aliases won't work in indented sections.
2150 transformed = self.expand_aliases(iFun, theRest)
2152 transformed = self.expand_aliases(iFun, theRest)
2151 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2153 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2152 self.log(line,line_out,continue_prompt)
2154 self.log(line,line_out,continue_prompt)
2153 #print 'line out:',line_out # dbg
2155 #print 'line out:',line_out # dbg
2154 return line_out
2156 return line_out
2155
2157
2156 def handle_shell_escape(self, line, continue_prompt=None,
2158 def handle_shell_escape(self, line, continue_prompt=None,
2157 pre=None,iFun=None,theRest=None):
2159 pre=None,iFun=None,theRest=None):
2158 """Execute the line in a shell, empty return value"""
2160 """Execute the line in a shell, empty return value"""
2159
2161
2160 #print 'line in :', `line` # dbg
2162 #print 'line in :', `line` # dbg
2161 # Example of a special handler. Others follow a similar pattern.
2163 # Example of a special handler. Others follow a similar pattern.
2162 if line.lstrip().startswith('!!'):
2164 if line.lstrip().startswith('!!'):
2163 # rewrite iFun/theRest to properly hold the call to %sx and
2165 # rewrite iFun/theRest to properly hold the call to %sx and
2164 # the actual command to be executed, so handle_magic can work
2166 # the actual command to be executed, so handle_magic can work
2165 # correctly
2167 # correctly
2166 theRest = '%s %s' % (iFun[2:],theRest)
2168 theRest = '%s %s' % (iFun[2:],theRest)
2167 iFun = 'sx'
2169 iFun = 'sx'
2168 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2170 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2169 line.lstrip()[2:]),
2171 line.lstrip()[2:]),
2170 continue_prompt,pre,iFun,theRest)
2172 continue_prompt,pre,iFun,theRest)
2171 else:
2173 else:
2172 cmd=line.lstrip().lstrip('!')
2174 cmd=line.lstrip().lstrip('!')
2173 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2175 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2174 # update cache/log and return
2176 # update cache/log and return
2175 self.log(line,line_out,continue_prompt)
2177 self.log(line,line_out,continue_prompt)
2176 return line_out
2178 return line_out
2177
2179
2178 def handle_magic(self, line, continue_prompt=None,
2180 def handle_magic(self, line, continue_prompt=None,
2179 pre=None,iFun=None,theRest=None):
2181 pre=None,iFun=None,theRest=None):
2180 """Execute magic functions."""
2182 """Execute magic functions."""
2181
2183
2182
2184
2183 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2185 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2184 self.log(line,cmd,continue_prompt)
2186 self.log(line,cmd,continue_prompt)
2185 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2187 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2186 return cmd
2188 return cmd
2187
2189
2188 def handle_auto(self, line, continue_prompt=None,
2190 def handle_auto(self, line, continue_prompt=None,
2189 pre=None,iFun=None,theRest=None,obj=None):
2191 pre=None,iFun=None,theRest=None,obj=None):
2190 """Hande lines which can be auto-executed, quoting if requested."""
2192 """Hande lines which can be auto-executed, quoting if requested."""
2191
2193
2192 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2194 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2193
2195
2194 # This should only be active for single-line input!
2196 # This should only be active for single-line input!
2195 if continue_prompt:
2197 if continue_prompt:
2196 self.log(line,line,continue_prompt)
2198 self.log(line,line,continue_prompt)
2197 return line
2199 return line
2198
2200
2199 auto_rewrite = True
2201 auto_rewrite = True
2200
2202
2201 if pre == self.ESC_QUOTE:
2203 if pre == self.ESC_QUOTE:
2202 # Auto-quote splitting on whitespace
2204 # Auto-quote splitting on whitespace
2203 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2205 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2204 elif pre == self.ESC_QUOTE2:
2206 elif pre == self.ESC_QUOTE2:
2205 # Auto-quote whole string
2207 # Auto-quote whole string
2206 newcmd = '%s("%s")' % (iFun,theRest)
2208 newcmd = '%s("%s")' % (iFun,theRest)
2207 elif pre == self.ESC_PAREN:
2209 elif pre == self.ESC_PAREN:
2208 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2210 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2209 else:
2211 else:
2210 # Auto-paren.
2212 # Auto-paren.
2211 # We only apply it to argument-less calls if the autocall
2213 # We only apply it to argument-less calls if the autocall
2212 # parameter is set to 2. We only need to check that autocall is <
2214 # parameter is set to 2. We only need to check that autocall is <
2213 # 2, since this function isn't called unless it's at least 1.
2215 # 2, since this function isn't called unless it's at least 1.
2214 if not theRest and (self.rc.autocall < 2):
2216 if not theRest and (self.rc.autocall < 2):
2215 newcmd = '%s %s' % (iFun,theRest)
2217 newcmd = '%s %s' % (iFun,theRest)
2216 auto_rewrite = False
2218 auto_rewrite = False
2217 else:
2219 else:
2218 if theRest.startswith('['):
2220 if theRest.startswith('['):
2219 if hasattr(obj,'__getitem__'):
2221 if hasattr(obj,'__getitem__'):
2220 # Don't autocall in this case: item access for an object
2222 # Don't autocall in this case: item access for an object
2221 # which is BOTH callable and implements __getitem__.
2223 # which is BOTH callable and implements __getitem__.
2222 newcmd = '%s %s' % (iFun,theRest)
2224 newcmd = '%s %s' % (iFun,theRest)
2223 auto_rewrite = False
2225 auto_rewrite = False
2224 else:
2226 else:
2225 # if the object doesn't support [] access, go ahead and
2227 # if the object doesn't support [] access, go ahead and
2226 # autocall
2228 # autocall
2227 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2229 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2228 elif theRest.endswith(';'):
2230 elif theRest.endswith(';'):
2229 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2231 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2230 else:
2232 else:
2231 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2233 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2232
2234
2233 if auto_rewrite:
2235 if auto_rewrite:
2234 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2236 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2235 # log what is now valid Python, not the actual user input (without the
2237 # log what is now valid Python, not the actual user input (without the
2236 # final newline)
2238 # final newline)
2237 self.log(line,newcmd,continue_prompt)
2239 self.log(line,newcmd,continue_prompt)
2238 return newcmd
2240 return newcmd
2239
2241
2240 def handle_help(self, line, continue_prompt=None,
2242 def handle_help(self, line, continue_prompt=None,
2241 pre=None,iFun=None,theRest=None):
2243 pre=None,iFun=None,theRest=None):
2242 """Try to get some help for the object.
2244 """Try to get some help for the object.
2243
2245
2244 obj? or ?obj -> basic information.
2246 obj? or ?obj -> basic information.
2245 obj?? or ??obj -> more details.
2247 obj?? or ??obj -> more details.
2246 """
2248 """
2247
2249
2248 # We need to make sure that we don't process lines which would be
2250 # We need to make sure that we don't process lines which would be
2249 # otherwise valid python, such as "x=1 # what?"
2251 # otherwise valid python, such as "x=1 # what?"
2250 try:
2252 try:
2251 codeop.compile_command(line)
2253 codeop.compile_command(line)
2252 except SyntaxError:
2254 except SyntaxError:
2253 # We should only handle as help stuff which is NOT valid syntax
2255 # We should only handle as help stuff which is NOT valid syntax
2254 if line[0]==self.ESC_HELP:
2256 if line[0]==self.ESC_HELP:
2255 line = line[1:]
2257 line = line[1:]
2256 elif line[-1]==self.ESC_HELP:
2258 elif line[-1]==self.ESC_HELP:
2257 line = line[:-1]
2259 line = line[:-1]
2258 self.log(line,'#?'+line,continue_prompt)
2260 self.log(line,'#?'+line,continue_prompt)
2259 if line:
2261 if line:
2260 self.magic_pinfo(line)
2262 self.magic_pinfo(line)
2261 else:
2263 else:
2262 page(self.usage,screen_lines=self.rc.screen_length)
2264 page(self.usage,screen_lines=self.rc.screen_length)
2263 return '' # Empty string is needed here!
2265 return '' # Empty string is needed here!
2264 except:
2266 except:
2265 # Pass any other exceptions through to the normal handler
2267 # Pass any other exceptions through to the normal handler
2266 return self.handle_normal(line,continue_prompt)
2268 return self.handle_normal(line,continue_prompt)
2267 else:
2269 else:
2268 # If the code compiles ok, we should handle it normally
2270 # If the code compiles ok, we should handle it normally
2269 return self.handle_normal(line,continue_prompt)
2271 return self.handle_normal(line,continue_prompt)
2270
2272
2271 def getapi(self):
2273 def getapi(self):
2272 """ Get an IPApi object for this shell instance
2274 """ Get an IPApi object for this shell instance
2273
2275
2274 Getting an IPApi object is always preferable to accessing the shell
2276 Getting an IPApi object is always preferable to accessing the shell
2275 directly, but this holds true especially for extensions.
2277 directly, but this holds true especially for extensions.
2276
2278
2277 It should always be possible to implement an extension with IPApi
2279 It should always be possible to implement an extension with IPApi
2278 alone. If not, contact maintainer to request an addition.
2280 alone. If not, contact maintainer to request an addition.
2279
2281
2280 """
2282 """
2281 return self.api
2283 return self.api
2282
2284
2283 def handle_emacs(self,line,continue_prompt=None,
2285 def handle_emacs(self,line,continue_prompt=None,
2284 pre=None,iFun=None,theRest=None):
2286 pre=None,iFun=None,theRest=None):
2285 """Handle input lines marked by python-mode."""
2287 """Handle input lines marked by python-mode."""
2286
2288
2287 # Currently, nothing is done. Later more functionality can be added
2289 # Currently, nothing is done. Later more functionality can be added
2288 # here if needed.
2290 # here if needed.
2289
2291
2290 # The input cache shouldn't be updated
2292 # The input cache shouldn't be updated
2291
2293
2292 return line
2294 return line
2293
2295
2294 def mktempfile(self,data=None):
2296 def mktempfile(self,data=None):
2295 """Make a new tempfile and return its filename.
2297 """Make a new tempfile and return its filename.
2296
2298
2297 This makes a call to tempfile.mktemp, but it registers the created
2299 This makes a call to tempfile.mktemp, but it registers the created
2298 filename internally so ipython cleans it up at exit time.
2300 filename internally so ipython cleans it up at exit time.
2299
2301
2300 Optional inputs:
2302 Optional inputs:
2301
2303
2302 - data(None): if data is given, it gets written out to the temp file
2304 - data(None): if data is given, it gets written out to the temp file
2303 immediately, and the file is closed again."""
2305 immediately, and the file is closed again."""
2304
2306
2305 filename = tempfile.mktemp('.py','ipython_edit_')
2307 filename = tempfile.mktemp('.py','ipython_edit_')
2306 self.tempfiles.append(filename)
2308 self.tempfiles.append(filename)
2307
2309
2308 if data:
2310 if data:
2309 tmp_file = open(filename,'w')
2311 tmp_file = open(filename,'w')
2310 tmp_file.write(data)
2312 tmp_file.write(data)
2311 tmp_file.close()
2313 tmp_file.close()
2312 return filename
2314 return filename
2313
2315
2314 def write(self,data):
2316 def write(self,data):
2315 """Write a string to the default output"""
2317 """Write a string to the default output"""
2316 Term.cout.write(data)
2318 Term.cout.write(data)
2317
2319
2318 def write_err(self,data):
2320 def write_err(self,data):
2319 """Write a string to the default error output"""
2321 """Write a string to the default error output"""
2320 Term.cerr.write(data)
2322 Term.cerr.write(data)
2321
2323
2322 def exit(self):
2324 def exit(self):
2323 """Handle interactive exit.
2325 """Handle interactive exit.
2324
2326
2325 This method sets the exit_now attribute."""
2327 This method sets the exit_now attribute."""
2326
2328
2327 if self.rc.confirm_exit:
2329 if self.rc.confirm_exit:
2328 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2330 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2329 self.exit_now = True
2331 self.exit_now = True
2330 else:
2332 else:
2331 self.exit_now = True
2333 self.exit_now = True
2332
2334
2333 def safe_execfile(self,fname,*where,**kw):
2335 def safe_execfile(self,fname,*where,**kw):
2334 fname = os.path.expanduser(fname)
2336 fname = os.path.expanduser(fname)
2335
2337
2336 # find things also in current directory
2338 # find things also in current directory
2337 dname = os.path.dirname(fname)
2339 dname = os.path.dirname(fname)
2338 if not sys.path.count(dname):
2340 if not sys.path.count(dname):
2339 sys.path.append(dname)
2341 sys.path.append(dname)
2340
2342
2341 try:
2343 try:
2342 xfile = open(fname)
2344 xfile = open(fname)
2343 except:
2345 except:
2344 print >> Term.cerr, \
2346 print >> Term.cerr, \
2345 'Could not open file <%s> for safe execution.' % fname
2347 'Could not open file <%s> for safe execution.' % fname
2346 return None
2348 return None
2347
2349
2348 kw.setdefault('islog',0)
2350 kw.setdefault('islog',0)
2349 kw.setdefault('quiet',1)
2351 kw.setdefault('quiet',1)
2350 kw.setdefault('exit_ignore',0)
2352 kw.setdefault('exit_ignore',0)
2351 first = xfile.readline()
2353 first = xfile.readline()
2352 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2354 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2353 xfile.close()
2355 xfile.close()
2354 # line by line execution
2356 # line by line execution
2355 if first.startswith(loghead) or kw['islog']:
2357 if first.startswith(loghead) or kw['islog']:
2356 print 'Loading log file <%s> one line at a time...' % fname
2358 print 'Loading log file <%s> one line at a time...' % fname
2357 if kw['quiet']:
2359 if kw['quiet']:
2358 stdout_save = sys.stdout
2360 stdout_save = sys.stdout
2359 sys.stdout = StringIO.StringIO()
2361 sys.stdout = StringIO.StringIO()
2360 try:
2362 try:
2361 globs,locs = where[0:2]
2363 globs,locs = where[0:2]
2362 except:
2364 except:
2363 try:
2365 try:
2364 globs = locs = where[0]
2366 globs = locs = where[0]
2365 except:
2367 except:
2366 globs = locs = globals()
2368 globs = locs = globals()
2367 badblocks = []
2369 badblocks = []
2368
2370
2369 # we also need to identify indented blocks of code when replaying
2371 # we also need to identify indented blocks of code when replaying
2370 # logs and put them together before passing them to an exec
2372 # logs and put them together before passing them to an exec
2371 # statement. This takes a bit of regexp and look-ahead work in the
2373 # statement. This takes a bit of regexp and look-ahead work in the
2372 # file. It's easiest if we swallow the whole thing in memory
2374 # file. It's easiest if we swallow the whole thing in memory
2373 # first, and manually walk through the lines list moving the
2375 # first, and manually walk through the lines list moving the
2374 # counter ourselves.
2376 # counter ourselves.
2375 indent_re = re.compile('\s+\S')
2377 indent_re = re.compile('\s+\S')
2376 xfile = open(fname)
2378 xfile = open(fname)
2377 filelines = xfile.readlines()
2379 filelines = xfile.readlines()
2378 xfile.close()
2380 xfile.close()
2379 nlines = len(filelines)
2381 nlines = len(filelines)
2380 lnum = 0
2382 lnum = 0
2381 while lnum < nlines:
2383 while lnum < nlines:
2382 line = filelines[lnum]
2384 line = filelines[lnum]
2383 lnum += 1
2385 lnum += 1
2384 # don't re-insert logger status info into cache
2386 # don't re-insert logger status info into cache
2385 if line.startswith('#log#'):
2387 if line.startswith('#log#'):
2386 continue
2388 continue
2387 else:
2389 else:
2388 # build a block of code (maybe a single line) for execution
2390 # build a block of code (maybe a single line) for execution
2389 block = line
2391 block = line
2390 try:
2392 try:
2391 next = filelines[lnum] # lnum has already incremented
2393 next = filelines[lnum] # lnum has already incremented
2392 except:
2394 except:
2393 next = None
2395 next = None
2394 while next and indent_re.match(next):
2396 while next and indent_re.match(next):
2395 block += next
2397 block += next
2396 lnum += 1
2398 lnum += 1
2397 try:
2399 try:
2398 next = filelines[lnum]
2400 next = filelines[lnum]
2399 except:
2401 except:
2400 next = None
2402 next = None
2401 # now execute the block of one or more lines
2403 # now execute the block of one or more lines
2402 try:
2404 try:
2403 exec block in globs,locs
2405 exec block in globs,locs
2404 except SystemExit:
2406 except SystemExit:
2405 pass
2407 pass
2406 except:
2408 except:
2407 badblocks.append(block.rstrip())
2409 badblocks.append(block.rstrip())
2408 if kw['quiet']: # restore stdout
2410 if kw['quiet']: # restore stdout
2409 sys.stdout.close()
2411 sys.stdout.close()
2410 sys.stdout = stdout_save
2412 sys.stdout = stdout_save
2411 print 'Finished replaying log file <%s>' % fname
2413 print 'Finished replaying log file <%s>' % fname
2412 if badblocks:
2414 if badblocks:
2413 print >> sys.stderr, ('\nThe following lines/blocks in file '
2415 print >> sys.stderr, ('\nThe following lines/blocks in file '
2414 '<%s> reported errors:' % fname)
2416 '<%s> reported errors:' % fname)
2415
2417
2416 for badline in badblocks:
2418 for badline in badblocks:
2417 print >> sys.stderr, badline
2419 print >> sys.stderr, badline
2418 else: # regular file execution
2420 else: # regular file execution
2419 try:
2421 try:
2420 execfile(fname,*where)
2422 execfile(fname,*where)
2421 except SyntaxError:
2423 except SyntaxError:
2422 self.showsyntaxerror()
2424 self.showsyntaxerror()
2423 warn('Failure executing file: <%s>' % fname)
2425 warn('Failure executing file: <%s>' % fname)
2424 except SystemExit,status:
2426 except SystemExit,status:
2425 if not kw['exit_ignore']:
2427 if not kw['exit_ignore']:
2426 self.showtraceback()
2428 self.showtraceback()
2427 warn('Failure executing file: <%s>' % fname)
2429 warn('Failure executing file: <%s>' % fname)
2428 except:
2430 except:
2429 self.showtraceback()
2431 self.showtraceback()
2430 warn('Failure executing file: <%s>' % fname)
2432 warn('Failure executing file: <%s>' % fname)
2431
2433
2432 #************************* end of file <iplib.py> *****************************
2434 #************************* end of file <iplib.py> *****************************
@@ -1,297 +1,305 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Module for interactively running scripts.
2 """Module for interactively running scripts.
3
3
4 This module implements classes for interactively running scripts written for
4 This module implements classes for interactively running scripts written for
5 any system with a prompt which can be matched by a regexp suitable for
5 any system with a prompt which can be matched by a regexp suitable for
6 pexpect. It can be used to run as if they had been typed up interactively, an
6 pexpect. It can be used to run as if they had been typed up interactively, an
7 arbitrary series of commands for the target system.
7 arbitrary series of commands for the target system.
8
8
9 The module includes classes ready for IPython (with the default prompts),
9 The module includes classes ready for IPython (with the default prompts),
10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
11 simply run the module as a script:
11 simply run the module as a script:
12
12
13 ./irunner.py --help
13 ./irunner.py --help
14
14
15
15
16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
17 contributed on the ipython-user list:
17 contributed on the ipython-user list:
18
18
19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
20
20
21
21
22 NOTES:
22 NOTES:
23
23
24 - This module requires pexpect, available in most linux distros, or which can
24 - This module requires pexpect, available in most linux distros, or which can
25 be downloaded from
25 be downloaded from
26
26
27 http://pexpect.sourceforge.net
27 http://pexpect.sourceforge.net
28
28
29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
30 limitations. This means that it will NOT work under native windows Python.
30 limitations. This means that it will NOT work under native windows Python.
31 """
31 """
32
32
33 # Stdlib imports
33 # Stdlib imports
34 import optparse
34 import optparse
35 import os
35 import os
36 import sys
36 import sys
37
37
38 # Third-party modules.
38 # Third-party modules.
39 import pexpect
39 import pexpect
40
40
41 # Global usage strings, to avoid indentation issues when typing it below.
41 # Global usage strings, to avoid indentation issues when typing it below.
42 USAGE = """
42 USAGE = """
43 Interactive script runner, type: %s
43 Interactive script runner, type: %s
44
44
45 runner [opts] script_name
45 runner [opts] script_name
46 """
46 """
47
47
48 # The generic runner class
48 # The generic runner class
49 class InteractiveRunner(object):
49 class InteractiveRunner(object):
50 """Class to run a sequence of commands through an interactive program."""
50 """Class to run a sequence of commands through an interactive program."""
51
51
52 def __init__(self,program,prompts,args=None):
52 def __init__(self,program,prompts,args=None):
53 """Construct a runner.
53 """Construct a runner.
54
54
55 Inputs:
55 Inputs:
56
56
57 - program: command to execute the given program.
57 - program: command to execute the given program.
58
58
59 - prompts: a list of patterns to match as valid prompts, in the
59 - prompts: a list of patterns to match as valid prompts, in the
60 format used by pexpect. This basically means that it can be either
60 format used by pexpect. This basically means that it can be either
61 a string (to be compiled as a regular expression) or a list of such
61 a string (to be compiled as a regular expression) or a list of such
62 (it must be a true list, as pexpect does type checks).
62 (it must be a true list, as pexpect does type checks).
63
63
64 If more than one prompt is given, the first is treated as the main
64 If more than one prompt is given, the first is treated as the main
65 program prompt and the others as 'continuation' prompts, like
65 program prompt and the others as 'continuation' prompts, like
66 python's. This means that blank lines in the input source are
66 python's. This means that blank lines in the input source are
67 ommitted when the first prompt is matched, but are NOT ommitted when
67 ommitted when the first prompt is matched, but are NOT ommitted when
68 the continuation one matches, since this is how python signals the
68 the continuation one matches, since this is how python signals the
69 end of multiline input interactively.
69 end of multiline input interactively.
70
70
71 Optional inputs:
71 Optional inputs:
72
72
73 - args(None): optional list of strings to pass as arguments to the
73 - args(None): optional list of strings to pass as arguments to the
74 child program.
74 child program.
75
75
76 Public members not parameterized in the constructor:
76 Public members not parameterized in the constructor:
77
77
78 - delaybeforesend(0): Newer versions of pexpect have a delay before
78 - delaybeforesend(0): Newer versions of pexpect have a delay before
79 sending each new input. For our purposes here, it's typically best
79 sending each new input. For our purposes here, it's typically best
80 to just set this to zero, but if you encounter reliability problems
80 to just set this to zero, but if you encounter reliability problems
81 or want an interactive run to pause briefly at each prompt, just
81 or want an interactive run to pause briefly at each prompt, just
82 increase this value (it is measured in seconds). Note that this
82 increase this value (it is measured in seconds). Note that this
83 variable is not honored at all by older versions of pexpect.
83 variable is not honored at all by older versions of pexpect.
84 """
84 """
85
85
86 self.program = program
86 self.program = program
87 self.prompts = prompts
87 self.prompts = prompts
88 if args is None: args = []
88 if args is None: args = []
89 self.args = args
89 self.args = args
90 # Other public members which we don't make as parameters, but which
90 # Other public members which we don't make as parameters, but which
91 # users may occasionally want to tweak
91 # users may occasionally want to tweak
92 self.delaybeforesend = 0
92 self.delaybeforesend = 0
93
93
94 def run_file(self,fname,interact=False):
94 def run_file(self,fname,interact=False):
95 """Run the given file interactively.
95 """Run the given file interactively.
96
96
97 Inputs:
97 Inputs:
98
98
99 -fname: name of the file to execute.
99 -fname: name of the file to execute.
100
100
101 See the run_source docstring for the meaning of the optional
101 See the run_source docstring for the meaning of the optional
102 arguments."""
102 arguments."""
103
103
104 fobj = open(fname,'r')
104 fobj = open(fname,'r')
105 try:
105 try:
106 self.run_source(fobj,interact)
106 self.run_source(fobj,interact)
107 finally:
107 finally:
108 fobj.close()
108 fobj.close()
109
109
110 def run_source(self,source,interact=False):
110 def run_source(self,source,interact=False):
111 """Run the given source code interactively.
111 """Run the given source code interactively.
112
112
113 Inputs:
113 Inputs:
114
114
115 - source: a string of code to be executed, or an open file object we
115 - source: a string of code to be executed, or an open file object we
116 can iterate over.
116 can iterate over.
117
117
118 Optional inputs:
118 Optional inputs:
119
119
120 - interact(False): if true, start to interact with the running
120 - interact(False): if true, start to interact with the running
121 program at the end of the script. Otherwise, just exit.
121 program at the end of the script. Otherwise, just exit.
122 """
122 """
123
123
124 # if the source is a string, chop it up in lines so we can iterate
124 # if the source is a string, chop it up in lines so we can iterate
125 # over it just as if it were an open file.
125 # over it just as if it were an open file.
126 if not isinstance(source,file):
126 if not isinstance(source,file):
127 source = source.splitlines(True)
127 source = source.splitlines(True)
128
128
129 # grab the true write method of stdout, in case anything later
129 # grab the true write method of stdout, in case anything later
130 # reassigns sys.stdout, so that we really are writing to the true
130 # reassigns sys.stdout, so that we really are writing to the true
131 # stdout and not to something else. We also normalize all strings we
131 # stdout and not to something else. We also normalize all strings we
132 # write to use the native OS line separators.
132 # write to use the native OS line separators.
133 linesep = os.linesep
133 linesep = os.linesep
134 stdwrite = sys.stdout.write
134 stdwrite = sys.stdout.write
135 write = lambda s: stdwrite(s.replace('\r\n',linesep))
135 write = lambda s: stdwrite(s.replace('\r\n',linesep))
136
136
137 c = pexpect.spawn(self.program,self.args,timeout=None)
137 c = pexpect.spawn(self.program,self.args,timeout=None)
138 c.delaybeforesend = self.delaybeforesend
138 c.delaybeforesend = self.delaybeforesend
139
139
140 # pexpect hard-codes the terminal size as (24,80) (rows,columns).
141 # This causes problems because any line longer than 80 characters gets
142 # completely overwrapped on the printed outptut (even though
143 # internally the code runs fine). We reset this to 99 rows X 200
144 # columns (arbitrarily chosen), which should avoid problems in all
145 # reasonable cases.
146 c.setwinsize(99,200)
147
140 prompts = c.compile_pattern_list(self.prompts)
148 prompts = c.compile_pattern_list(self.prompts)
141
149
142 prompt_idx = c.expect_list(prompts)
150 prompt_idx = c.expect_list(prompts)
143 # Flag whether the script ends normally or not, to know whether we can
151 # Flag whether the script ends normally or not, to know whether we can
144 # do anything further with the underlying process.
152 # do anything further with the underlying process.
145 end_normal = True
153 end_normal = True
146 for cmd in source:
154 for cmd in source:
147 # skip blank lines for all matches to the 'main' prompt, while the
155 # skip blank lines for all matches to the 'main' prompt, while the
148 # secondary prompts do not
156 # secondary prompts do not
149 if prompt_idx==0 and \
157 if prompt_idx==0 and \
150 (cmd.isspace() or cmd.lstrip().startswith('#')):
158 (cmd.isspace() or cmd.lstrip().startswith('#')):
151 print cmd,
159 print cmd,
152 continue
160 continue
153
161
154 write(c.after)
162 write(c.after)
155 c.send(cmd)
163 c.send(cmd)
156 try:
164 try:
157 prompt_idx = c.expect_list(prompts)
165 prompt_idx = c.expect_list(prompts)
158 except pexpect.EOF:
166 except pexpect.EOF:
159 # this will happen if the child dies unexpectedly
167 # this will happen if the child dies unexpectedly
160 write(c.before)
168 write(c.before)
161 end_normal = False
169 end_normal = False
162 break
170 break
163 write(c.before)
171 write(c.before)
164
172
165 if end_normal:
173 if end_normal:
166 if interact:
174 if interact:
167 c.send('\n')
175 c.send('\n')
168 print '<< Starting interactive mode >>',
176 print '<< Starting interactive mode >>',
169 try:
177 try:
170 c.interact()
178 c.interact()
171 except OSError:
179 except OSError:
172 # This is what fires when the child stops. Simply print a
180 # This is what fires when the child stops. Simply print a
173 # newline so the system prompt is aligned. The extra
181 # newline so the system prompt is aligned. The extra
174 # space is there to make sure it gets printed, otherwise
182 # space is there to make sure it gets printed, otherwise
175 # OS buffering sometimes just suppresses it.
183 # OS buffering sometimes just suppresses it.
176 write(' \n')
184 write(' \n')
177 sys.stdout.flush()
185 sys.stdout.flush()
178 else:
186 else:
179 c.close()
187 c.close()
180 else:
188 else:
181 if interact:
189 if interact:
182 e="Further interaction is not possible: child process is dead."
190 e="Further interaction is not possible: child process is dead."
183 print >> sys.stderr, e
191 print >> sys.stderr, e
184
192
185 def main(self,argv=None):
193 def main(self,argv=None):
186 """Run as a command-line script."""
194 """Run as a command-line script."""
187
195
188 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
196 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
189 newopt = parser.add_option
197 newopt = parser.add_option
190 newopt('-i','--interact',action='store_true',default=False,
198 newopt('-i','--interact',action='store_true',default=False,
191 help='Interact with the program after the script is run.')
199 help='Interact with the program after the script is run.')
192
200
193 opts,args = parser.parse_args(argv)
201 opts,args = parser.parse_args(argv)
194
202
195 if len(args) != 1:
203 if len(args) != 1:
196 print >> sys.stderr,"You must supply exactly one file to run."
204 print >> sys.stderr,"You must supply exactly one file to run."
197 sys.exit(1)
205 sys.exit(1)
198
206
199 self.run_file(args[0],opts.interact)
207 self.run_file(args[0],opts.interact)
200
208
201
209
202 # Specific runners for particular programs
210 # Specific runners for particular programs
203 class IPythonRunner(InteractiveRunner):
211 class IPythonRunner(InteractiveRunner):
204 """Interactive IPython runner.
212 """Interactive IPython runner.
205
213
206 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
214 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
207 avoid having to write a regexp that matches ANSI sequences, though pexpect
215 avoid having to write a regexp that matches ANSI sequences, though pexpect
208 does support them. If anyone contributes patches for ANSI color support,
216 does support them. If anyone contributes patches for ANSI color support,
209 they will be welcome.
217 they will be welcome.
210
218
211 It also sets the prompts manually, since the prompt regexps for
219 It also sets the prompts manually, since the prompt regexps for
212 pexpect need to be matched to the actual prompts, so user-customized
220 pexpect need to be matched to the actual prompts, so user-customized
213 prompts would break this.
221 prompts would break this.
214 """
222 """
215
223
216 def __init__(self,program = 'ipython',args=None):
224 def __init__(self,program = 'ipython',args=None):
217 """New runner, optionally passing the ipython command to use."""
225 """New runner, optionally passing the ipython command to use."""
218
226
219 args0 = ['-colors','NoColor',
227 args0 = ['-colors','NoColor',
220 '-pi1','In [\\#]: ',
228 '-pi1','In [\\#]: ',
221 '-pi2',' .\\D.: ']
229 '-pi2',' .\\D.: ']
222 if args is None: args = args0
230 if args is None: args = args0
223 else: args = args0 + args
231 else: args = args0 + args
224 prompts = [r'In \[\d+\]: ',r' \.*: ']
232 prompts = [r'In \[\d+\]: ',r' \.*: ']
225 InteractiveRunner.__init__(self,program,prompts,args)
233 InteractiveRunner.__init__(self,program,prompts,args)
226
234
227
235
228 class PythonRunner(InteractiveRunner):
236 class PythonRunner(InteractiveRunner):
229 """Interactive Python runner."""
237 """Interactive Python runner."""
230
238
231 def __init__(self,program='python',args=None):
239 def __init__(self,program='python',args=None):
232 """New runner, optionally passing the python command to use."""
240 """New runner, optionally passing the python command to use."""
233
241
234 prompts = [r'>>> ',r'\.\.\. ']
242 prompts = [r'>>> ',r'\.\.\. ']
235 InteractiveRunner.__init__(self,program,prompts,args)
243 InteractiveRunner.__init__(self,program,prompts,args)
236
244
237
245
238 class SAGERunner(InteractiveRunner):
246 class SAGERunner(InteractiveRunner):
239 """Interactive SAGE runner.
247 """Interactive SAGE runner.
240
248
241 WARNING: this runner only works if you manually configure your SAGE copy
249 WARNING: this runner only works if you manually configure your SAGE copy
242 to use 'colors NoColor' in the ipythonrc config file, since currently the
250 to use 'colors NoColor' in the ipythonrc config file, since currently the
243 prompt matching regexp does not identify color sequences."""
251 prompt matching regexp does not identify color sequences."""
244
252
245 def __init__(self,program='sage',args=None):
253 def __init__(self,program='sage',args=None):
246 """New runner, optionally passing the sage command to use."""
254 """New runner, optionally passing the sage command to use."""
247
255
248 prompts = ['sage: ',r'\s*\.\.\. ']
256 prompts = ['sage: ',r'\s*\.\.\. ']
249 InteractiveRunner.__init__(self,program,prompts,args)
257 InteractiveRunner.__init__(self,program,prompts,args)
250
258
251 # Global usage string, to avoid indentation issues if typed in a function def.
259 # Global usage string, to avoid indentation issues if typed in a function def.
252 MAIN_USAGE = """
260 MAIN_USAGE = """
253 %prog [options] file_to_run
261 %prog [options] file_to_run
254
262
255 This is an interface to the various interactive runners available in this
263 This is an interface to the various interactive runners available in this
256 module. If you want to pass specific options to one of the runners, you need
264 module. If you want to pass specific options to one of the runners, you need
257 to first terminate the main options with a '--', and then provide the runner's
265 to first terminate the main options with a '--', and then provide the runner's
258 options. For example:
266 options. For example:
259
267
260 irunner.py --python -- --help
268 irunner.py --python -- --help
261
269
262 will pass --help to the python runner. Similarly,
270 will pass --help to the python runner. Similarly,
263
271
264 irunner.py --ipython -- --interact script.ipy
272 irunner.py --ipython -- --interact script.ipy
265
273
266 will run the script.ipy file under the IPython runner, and then will start to
274 will run the script.ipy file under the IPython runner, and then will start to
267 interact with IPython at the end of the script (instead of exiting).
275 interact with IPython at the end of the script (instead of exiting).
268
276
269 The already implemented runners are listed below; adding one for a new program
277 The already implemented runners are listed below; adding one for a new program
270 is a trivial task, see the source for examples.
278 is a trivial task, see the source for examples.
271
279
272 WARNING: the SAGE runner only works if you manually configure your SAGE copy
280 WARNING: the SAGE runner only works if you manually configure your SAGE copy
273 to use 'colors NoColor' in the ipythonrc config file, since currently the
281 to use 'colors NoColor' in the ipythonrc config file, since currently the
274 prompt matching regexp does not identify color sequences.
282 prompt matching regexp does not identify color sequences.
275 """
283 """
276
284
277 def main():
285 def main():
278 """Run as a command-line script."""
286 """Run as a command-line script."""
279
287
280 parser = optparse.OptionParser(usage=MAIN_USAGE)
288 parser = optparse.OptionParser(usage=MAIN_USAGE)
281 newopt = parser.add_option
289 newopt = parser.add_option
282 parser.set_defaults(mode='ipython')
290 parser.set_defaults(mode='ipython')
283 newopt('--ipython',action='store_const',dest='mode',const='ipython',
291 newopt('--ipython',action='store_const',dest='mode',const='ipython',
284 help='IPython interactive runner (default).')
292 help='IPython interactive runner (default).')
285 newopt('--python',action='store_const',dest='mode',const='python',
293 newopt('--python',action='store_const',dest='mode',const='python',
286 help='Python interactive runner.')
294 help='Python interactive runner.')
287 newopt('--sage',action='store_const',dest='mode',const='sage',
295 newopt('--sage',action='store_const',dest='mode',const='sage',
288 help='SAGE interactive runner.')
296 help='SAGE interactive runner.')
289
297
290 opts,args = parser.parse_args()
298 opts,args = parser.parse_args()
291 runners = dict(ipython=IPythonRunner,
299 runners = dict(ipython=IPythonRunner,
292 python=PythonRunner,
300 python=PythonRunner,
293 sage=SAGERunner)
301 sage=SAGERunner)
294 runners[opts.mode]().main(args)
302 runners[opts.mode]().main(args)
295
303
296 if __name__ == '__main__':
304 if __name__ == '__main__':
297 main()
305 main()
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now