##// END OF EJS Templates
implement callable (i.e. straight python) aliases and _sh shadow namespace
vivainio -
Show More

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

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