##// END OF EJS Templates
- fix bug where aliases would shadow variables when autocall was fully off....
fperez -
Show More

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

@@ -1,483 +1,486 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 1300 2006-05-15 16:27:36Z vivainio $
9 $Id: OInspect.py 1329 2006-05-26 07:52:45Z fperez $
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 # IPython's own
33 # IPython's own
34 from IPython import PyColorize
34 from IPython import PyColorize
35 from IPython.genutils import page,indent,Term,mkdict
35 from IPython.genutils import page,indent,Term,mkdict
36 from IPython.Itpl import itpl
36 from IPython.Itpl import itpl
37 from IPython.wildcard import list_namespace
37 from IPython.wildcard import list_namespace
38 from IPython.ColorANSI import *
38 from IPython.ColorANSI import *
39
39
40 #****************************************************************************
40 #****************************************************************************
41 # Builtin color schemes
41 # Builtin color schemes
42
42
43 Colors = TermColors # just a shorthand
43 Colors = TermColors # just a shorthand
44
44
45 # Build a few color schemes
45 # Build a few color schemes
46 NoColor = ColorScheme(
46 NoColor = ColorScheme(
47 'NoColor',{
47 'NoColor',{
48 'header' : Colors.NoColor,
48 'header' : Colors.NoColor,
49 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
49 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
50 } )
50 } )
51
51
52 LinuxColors = ColorScheme(
52 LinuxColors = ColorScheme(
53 'Linux',{
53 'Linux',{
54 'header' : Colors.LightRed,
54 'header' : Colors.LightRed,
55 'normal' : Colors.Normal # color off (usu. Colors.Normal)
55 'normal' : Colors.Normal # color off (usu. Colors.Normal)
56 } )
56 } )
57
57
58 LightBGColors = ColorScheme(
58 LightBGColors = ColorScheme(
59 'LightBG',{
59 'LightBG',{
60 'header' : Colors.Red,
60 'header' : Colors.Red,
61 'normal' : Colors.Normal # color off (usu. Colors.Normal)
61 'normal' : Colors.Normal # color off (usu. Colors.Normal)
62 } )
62 } )
63
63
64 # Build table of color schemes (needed by the parser)
64 # Build table of color schemes (needed by the parser)
65 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
65 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
66 'Linux')
66 'Linux')
67
67
68 #****************************************************************************
68 #****************************************************************************
69 # Auxiliary functions
69 # Auxiliary functions
70 def getdoc(obj):
70 def getdoc(obj):
71 """Stable wrapper around inspect.getdoc.
71 """Stable wrapper around inspect.getdoc.
72
72
73 This can't crash because of attribute problems.
73 This can't crash because of attribute problems.
74
74
75 It also attempts to call a getdoc() method on the given object. This
75 It also attempts to call a getdoc() method on the given object. This
76 allows objects which provide their docstrings via non-standard mechanisms
76 allows objects which provide their docstrings via non-standard mechanisms
77 (like Pyro proxies) to still be inspected by ipython's ? system."""
77 (like Pyro proxies) to still be inspected by ipython's ? system."""
78
78
79 ds = None # default return value
79 ds = None # default return value
80 try:
80 try:
81 ds = inspect.getdoc(obj)
81 ds = inspect.getdoc(obj)
82 except:
82 except:
83 # Harden against an inspect failure, which can occur with
83 # Harden against an inspect failure, which can occur with
84 # SWIG-wrapped extensions.
84 # SWIG-wrapped extensions.
85 pass
85 pass
86 # Allow objects to offer customized documentation via a getdoc method:
86 # Allow objects to offer customized documentation via a getdoc method:
87 try:
87 try:
88 ds2 = obj.getdoc()
88 ds2 = obj.getdoc()
89 except:
89 except:
90 pass
90 pass
91 else:
91 else:
92 # if we get extra info, we add it to the normal docstring.
92 # if we get extra info, we add it to the normal docstring.
93 if ds is None:
93 if ds is None:
94 ds = ds2
94 ds = ds2
95 else:
95 else:
96 ds = '%s\n%s' % (ds,ds2)
96 ds = '%s\n%s' % (ds,ds2)
97 return ds
97 return ds
98
98
99 #****************************************************************************
99 #****************************************************************************
100 # Class definitions
100 # Class definitions
101
101
102 class myStringIO(StringIO.StringIO):
102 class myStringIO(StringIO.StringIO):
103 """Adds a writeln method to normal StringIO."""
103 """Adds a writeln method to normal StringIO."""
104 def writeln(self,*arg,**kw):
104 def writeln(self,*arg,**kw):
105 """Does a write() and then a write('\n')"""
105 """Does a write() and then a write('\n')"""
106 self.write(*arg,**kw)
106 self.write(*arg,**kw)
107 self.write('\n')
107 self.write('\n')
108
108
109 class Inspector:
109 class Inspector:
110 def __init__(self,color_table,code_color_table,scheme):
110 def __init__(self,color_table,code_color_table,scheme,
111 str_detail_level=0):
111 self.color_table = color_table
112 self.color_table = color_table
112 self.parser = PyColorize.Parser(code_color_table,out='str')
113 self.parser = PyColorize.Parser(code_color_table,out='str')
113 self.format = self.parser.format
114 self.format = self.parser.format
115 self.str_detail_level = str_detail_level
114 self.set_active_scheme(scheme)
116 self.set_active_scheme(scheme)
115
117
116 def __getargspec(self,obj):
118 def __getargspec(self,obj):
117 """Get the names and default values of a function's arguments.
119 """Get the names and default values of a function's arguments.
118
120
119 A tuple of four things is returned: (args, varargs, varkw, defaults).
121 A tuple of four things is returned: (args, varargs, varkw, defaults).
120 'args' is a list of the argument names (it may contain nested lists).
122 'args' is a list of the argument names (it may contain nested lists).
121 'varargs' and 'varkw' are the names of the * and ** arguments or None.
123 'varargs' and 'varkw' are the names of the * and ** arguments or None.
122 'defaults' is an n-tuple of the default values of the last n arguments.
124 'defaults' is an n-tuple of the default values of the last n arguments.
123
125
124 Modified version of inspect.getargspec from the Python Standard
126 Modified version of inspect.getargspec from the Python Standard
125 Library."""
127 Library."""
126
128
127 if inspect.isfunction(obj):
129 if inspect.isfunction(obj):
128 func_obj = obj
130 func_obj = obj
129 elif inspect.ismethod(obj):
131 elif inspect.ismethod(obj):
130 func_obj = obj.im_func
132 func_obj = obj.im_func
131 else:
133 else:
132 raise TypeError, 'arg is not a Python function'
134 raise TypeError, 'arg is not a Python function'
133 args, varargs, varkw = inspect.getargs(func_obj.func_code)
135 args, varargs, varkw = inspect.getargs(func_obj.func_code)
134 return args, varargs, varkw, func_obj.func_defaults
136 return args, varargs, varkw, func_obj.func_defaults
135
137
136 def __getdef(self,obj,oname=''):
138 def __getdef(self,obj,oname=''):
137 """Return the definition header for any callable object.
139 """Return the definition header for any callable object.
138
140
139 If any exception is generated, None is returned instead and the
141 If any exception is generated, None is returned instead and the
140 exception is suppressed."""
142 exception is suppressed."""
141
143
142 try:
144 try:
143 return oname + inspect.formatargspec(*self.__getargspec(obj))
145 return oname + inspect.formatargspec(*self.__getargspec(obj))
144 except:
146 except:
145 return None
147 return None
146
148
147 def __head(self,h):
149 def __head(self,h):
148 """Return a header string with proper colors."""
150 """Return a header string with proper colors."""
149 return '%s%s%s' % (self.color_table.active_colors.header,h,
151 return '%s%s%s' % (self.color_table.active_colors.header,h,
150 self.color_table.active_colors.normal)
152 self.color_table.active_colors.normal)
151
153
152 def set_active_scheme(self,scheme):
154 def set_active_scheme(self,scheme):
153 self.color_table.set_active_scheme(scheme)
155 self.color_table.set_active_scheme(scheme)
154 self.parser.color_table.set_active_scheme(scheme)
156 self.parser.color_table.set_active_scheme(scheme)
155
157
156 def noinfo(self,msg,oname):
158 def noinfo(self,msg,oname):
157 """Generic message when no information is found."""
159 """Generic message when no information is found."""
158 print 'No %s found' % msg,
160 print 'No %s found' % msg,
159 if oname:
161 if oname:
160 print 'for %s' % oname
162 print 'for %s' % oname
161 else:
163 else:
162 print
164 print
163
165
164 def pdef(self,obj,oname=''):
166 def pdef(self,obj,oname=''):
165 """Print the definition header for any callable object.
167 """Print the definition header for any callable object.
166
168
167 If the object is a class, print the constructor information."""
169 If the object is a class, print the constructor information."""
168
170
169 if not callable(obj):
171 if not callable(obj):
170 print 'Object is not callable.'
172 print 'Object is not callable.'
171 return
173 return
172
174
173 header = ''
175 header = ''
174 if type(obj) is types.ClassType:
176 if type(obj) is types.ClassType:
175 header = self.__head('Class constructor information:\n')
177 header = self.__head('Class constructor information:\n')
176 obj = obj.__init__
178 obj = obj.__init__
177 elif type(obj) is types.InstanceType:
179 elif type(obj) is types.InstanceType:
178 obj = obj.__call__
180 obj = obj.__call__
179
181
180 output = self.__getdef(obj,oname)
182 output = self.__getdef(obj,oname)
181 if output is None:
183 if output is None:
182 self.noinfo('definition header',oname)
184 self.noinfo('definition header',oname)
183 else:
185 else:
184 print >>Term.cout, header,self.format(output),
186 print >>Term.cout, header,self.format(output),
185
187
186 def pdoc(self,obj,oname='',formatter = None):
188 def pdoc(self,obj,oname='',formatter = None):
187 """Print the docstring for any object.
189 """Print the docstring for any object.
188
190
189 Optional:
191 Optional:
190 -formatter: a function to run the docstring through for specially
192 -formatter: a function to run the docstring through for specially
191 formatted docstrings."""
193 formatted docstrings."""
192
194
193 head = self.__head # so that itpl can find it even if private
195 head = self.__head # so that itpl can find it even if private
194 ds = getdoc(obj)
196 ds = getdoc(obj)
195 if formatter:
197 if formatter:
196 ds = formatter(ds)
198 ds = formatter(ds)
197 if type(obj) is types.ClassType:
199 if type(obj) is types.ClassType:
198 init_ds = getdoc(obj.__init__)
200 init_ds = getdoc(obj.__init__)
199 output = itpl('$head("Class Docstring:")\n'
201 output = itpl('$head("Class Docstring:")\n'
200 '$indent(ds)\n'
202 '$indent(ds)\n'
201 '$head("Constructor Docstring"):\n'
203 '$head("Constructor Docstring"):\n'
202 '$indent(init_ds)')
204 '$indent(init_ds)')
203 elif type(obj) is types.InstanceType and hasattr(obj,'__call__'):
205 elif type(obj) is types.InstanceType and hasattr(obj,'__call__'):
204 call_ds = getdoc(obj.__call__)
206 call_ds = getdoc(obj.__call__)
205 if call_ds:
207 if call_ds:
206 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
208 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
207 '$head("Calling Docstring:")\n$indent(call_ds)')
209 '$head("Calling Docstring:")\n$indent(call_ds)')
208 else:
210 else:
209 output = ds
211 output = ds
210 else:
212 else:
211 output = ds
213 output = ds
212 if output is None:
214 if output is None:
213 self.noinfo('documentation',oname)
215 self.noinfo('documentation',oname)
214 return
216 return
215 page(output)
217 page(output)
216
218
217 def psource(self,obj,oname=''):
219 def psource(self,obj,oname=''):
218 """Print the source code for an object."""
220 """Print the source code for an object."""
219
221
220 # Flush the source cache because inspect can return out-of-date source
222 # Flush the source cache because inspect can return out-of-date source
221 linecache.checkcache()
223 linecache.checkcache()
222 try:
224 try:
223 src = inspect.getsource(obj)
225 src = inspect.getsource(obj)
224 except:
226 except:
225 self.noinfo('source',oname)
227 self.noinfo('source',oname)
226 else:
228 else:
227 page(self.format(src))
229 page(self.format(src))
228
230
229 def pfile(self,obj,oname=''):
231 def pfile(self,obj,oname=''):
230 """Show the whole file where an object was defined."""
232 """Show the whole file where an object was defined."""
231 try:
233 try:
232 sourcelines,lineno = inspect.getsourcelines(obj)
234 sourcelines,lineno = inspect.getsourcelines(obj)
233 except:
235 except:
234 self.noinfo('file',oname)
236 self.noinfo('file',oname)
235 else:
237 else:
236 # run contents of file through pager starting at line
238 # run contents of file through pager starting at line
237 # where the object is defined
239 # where the object is defined
238 ofile = inspect.getabsfile(obj)
240 ofile = inspect.getabsfile(obj)
239
241
240 if (ofile.endswith('.so') or ofile.endswith('.dll')):
242 if (ofile.endswith('.so') or ofile.endswith('.dll')):
241 print 'File %r is binary, not printing.' % ofile
243 print 'File %r is binary, not printing.' % ofile
242 elif not os.path.isfile(ofile):
244 elif not os.path.isfile(ofile):
243 print 'File %r does not exist, not printing.' % ofile
245 print 'File %r does not exist, not printing.' % ofile
244 else:
246 else:
245 # Print only text files, not extension binaries.
247 # Print only text files, not extension binaries.
246 page(self.format(open(ofile).read()),lineno)
248 page(self.format(open(ofile).read()),lineno)
247 #page(self.format(open(inspect.getabsfile(obj)).read()),lineno)
249 #page(self.format(open(inspect.getabsfile(obj)).read()),lineno)
248
250
249 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
251 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
250 """Show detailed information about an object.
252 """Show detailed information about an object.
251
253
252 Optional arguments:
254 Optional arguments:
253
255
254 - oname: name of the variable pointing to the object.
256 - oname: name of the variable pointing to the object.
255
257
256 - formatter: special formatter for docstrings (see pdoc)
258 - formatter: special formatter for docstrings (see pdoc)
257
259
258 - info: a structure with some information fields which may have been
260 - info: a structure with some information fields which may have been
259 precomputed already.
261 precomputed already.
260
262
261 - detail_level: if set to 1, more information is given.
263 - detail_level: if set to 1, more information is given.
262 """
264 """
263
265
264 obj_type = type(obj)
266 obj_type = type(obj)
265
267
266 header = self.__head
268 header = self.__head
267 if info is None:
269 if info is None:
268 ismagic = 0
270 ismagic = 0
269 isalias = 0
271 isalias = 0
270 ospace = ''
272 ospace = ''
271 else:
273 else:
272 ismagic = info.ismagic
274 ismagic = info.ismagic
273 isalias = info.isalias
275 isalias = info.isalias
274 ospace = info.namespace
276 ospace = info.namespace
275 # Get docstring, special-casing aliases:
277 # Get docstring, special-casing aliases:
276 if isalias:
278 if isalias:
277 ds = "Alias to the system command:\n %s" % obj[1]
279 ds = "Alias to the system command:\n %s" % obj[1]
278 else:
280 else:
279 ds = getdoc(obj)
281 ds = getdoc(obj)
280 if ds is None:
282 if ds is None:
281 ds = '<no docstring>'
283 ds = '<no docstring>'
282 if formatter is not None:
284 if formatter is not None:
283 ds = formatter(ds)
285 ds = formatter(ds)
284
286
285 # store output in a list which gets joined with \n at the end.
287 # store output in a list which gets joined with \n at the end.
286 out = myStringIO()
288 out = myStringIO()
287
289
288 string_max = 200 # max size of strings to show (snipped if longer)
290 string_max = 200 # max size of strings to show (snipped if longer)
289 shalf = int((string_max -5)/2)
291 shalf = int((string_max -5)/2)
290
292
291 if ismagic:
293 if ismagic:
292 obj_type_name = 'Magic function'
294 obj_type_name = 'Magic function'
293 elif isalias:
295 elif isalias:
294 obj_type_name = 'System alias'
296 obj_type_name = 'System alias'
295 else:
297 else:
296 obj_type_name = obj_type.__name__
298 obj_type_name = obj_type.__name__
297 out.writeln(header('Type:\t\t')+obj_type_name)
299 out.writeln(header('Type:\t\t')+obj_type_name)
298
300
299 try:
301 try:
300 bclass = obj.__class__
302 bclass = obj.__class__
301 out.writeln(header('Base Class:\t')+str(bclass))
303 out.writeln(header('Base Class:\t')+str(bclass))
302 except: pass
304 except: pass
303
305
304 # String form, but snip if too long in ? form (full in ??)
306 # String form, but snip if too long in ? form (full in ??)
305 try:
307 if detail_level >= self.str_detail_level:
306 ostr = str(obj)
308 try:
307 str_head = 'String Form:'
309 ostr = str(obj)
308 if not detail_level and len(ostr)>string_max:
310 str_head = 'String Form:'
309 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
311 if not detail_level and len(ostr)>string_max:
310 ostr = ("\n" + " " * len(str_head.expandtabs())).\
312 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
311 join(map(string.strip,ostr.split("\n")))
313 ostr = ("\n" + " " * len(str_head.expandtabs())).\
312 if ostr.find('\n') > -1:
314 join(map(string.strip,ostr.split("\n")))
313 # Print multi-line strings starting at the next line.
315 if ostr.find('\n') > -1:
314 str_sep = '\n'
316 # Print multi-line strings starting at the next line.
315 else:
317 str_sep = '\n'
316 str_sep = '\t'
318 else:
317 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
319 str_sep = '\t'
318 except:
320 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
319 pass
321 except:
322 pass
320
323
321 if ospace:
324 if ospace:
322 out.writeln(header('Namespace:\t')+ospace)
325 out.writeln(header('Namespace:\t')+ospace)
323
326
324 # Length (for strings and lists)
327 # Length (for strings and lists)
325 try:
328 try:
326 length = str(len(obj))
329 length = str(len(obj))
327 out.writeln(header('Length:\t\t')+length)
330 out.writeln(header('Length:\t\t')+length)
328 except: pass
331 except: pass
329
332
330 # Filename where object was defined
333 # Filename where object was defined
331 binary_file = False
334 binary_file = False
332 try:
335 try:
333 fname = inspect.getabsfile(obj)
336 fname = inspect.getabsfile(obj)
334 if fname.endswith('<string>'):
337 if fname.endswith('<string>'):
335 fname = 'Dynamically generated function. No source code available.'
338 fname = 'Dynamically generated function. No source code available.'
336 if (fname.endswith('.so') or fname.endswith('.dll') or
339 if (fname.endswith('.so') or fname.endswith('.dll') or
337 not os.path.isfile(fname)):
340 not os.path.isfile(fname)):
338 binary_file = True
341 binary_file = True
339 out.writeln(header('File:\t\t')+fname)
342 out.writeln(header('File:\t\t')+fname)
340 except:
343 except:
341 # if anything goes wrong, we don't want to show source, so it's as
344 # if anything goes wrong, we don't want to show source, so it's as
342 # if the file was binary
345 # if the file was binary
343 binary_file = True
346 binary_file = True
344
347
345 # reconstruct the function definition and print it:
348 # reconstruct the function definition and print it:
346 defln = self.__getdef(obj,oname)
349 defln = self.__getdef(obj,oname)
347 if defln:
350 if defln:
348 out.write(header('Definition:\t')+self.format(defln))
351 out.write(header('Definition:\t')+self.format(defln))
349
352
350 # Docstrings only in detail 0 mode, since source contains them (we
353 # Docstrings only in detail 0 mode, since source contains them (we
351 # avoid repetitions). If source fails, we add them back, see below.
354 # avoid repetitions). If source fails, we add them back, see below.
352 if ds and detail_level == 0:
355 if ds and detail_level == 0:
353 out.writeln(header('Docstring:\n') + indent(ds))
356 out.writeln(header('Docstring:\n') + indent(ds))
354
357
355
358
356 # Original source code for any callable
359 # Original source code for any callable
357 if detail_level:
360 if detail_level:
358 # Flush the source cache because inspect can return out-of-date source
361 # Flush the source cache because inspect can return out-of-date source
359 linecache.checkcache()
362 linecache.checkcache()
360 source_success = False
363 source_success = False
361 try:
364 try:
362 if not binary_file:
365 if not binary_file:
363 source = self.format(inspect.getsource(obj))
366 source = self.format(inspect.getsource(obj))
364 out.write(header('Source:\n')+source.rstrip())
367 out.write(header('Source:\n')+source.rstrip())
365 source_success = True
368 source_success = True
366 except:
369 except:
367 pass
370 pass
368
371
369 if ds and not source_success:
372 if ds and not source_success:
370 out.writeln(header('Docstring [source file open failed]:\n') + indent(ds))
373 out.writeln(header('Docstring [source file open failed]:\n') + indent(ds))
371
374
372 # Constructor docstring for classes
375 # Constructor docstring for classes
373 if obj_type is types.ClassType:
376 if obj_type is types.ClassType:
374 # reconstruct the function definition and print it:
377 # reconstruct the function definition and print it:
375 try:
378 try:
376 obj_init = obj.__init__
379 obj_init = obj.__init__
377 except AttributeError:
380 except AttributeError:
378 init_def = init_ds = None
381 init_def = init_ds = None
379 else:
382 else:
380 init_def = self.__getdef(obj_init,oname)
383 init_def = self.__getdef(obj_init,oname)
381 init_ds = getdoc(obj_init)
384 init_ds = getdoc(obj_init)
382
385
383 if init_def or init_ds:
386 if init_def or init_ds:
384 out.writeln(header('\nConstructor information:'))
387 out.writeln(header('\nConstructor information:'))
385 if init_def:
388 if init_def:
386 out.write(header('Definition:\t')+ self.format(init_def))
389 out.write(header('Definition:\t')+ self.format(init_def))
387 if init_ds:
390 if init_ds:
388 out.writeln(header('Docstring:\n') + indent(init_ds))
391 out.writeln(header('Docstring:\n') + indent(init_ds))
389 # and class docstring for instances:
392 # and class docstring for instances:
390 elif obj_type is types.InstanceType:
393 elif obj_type is types.InstanceType:
391
394
392 # First, check whether the instance docstring is identical to the
395 # First, check whether the instance docstring is identical to the
393 # class one, and print it separately if they don't coincide. In
396 # class one, and print it separately if they don't coincide. In
394 # most cases they will, but it's nice to print all the info for
397 # most cases they will, but it's nice to print all the info for
395 # objects which use instance-customized docstrings.
398 # objects which use instance-customized docstrings.
396 if ds:
399 if ds:
397 class_ds = getdoc(obj.__class__)
400 class_ds = getdoc(obj.__class__)
398 if class_ds and ds != class_ds:
401 if class_ds and ds != class_ds:
399 out.writeln(header('Class Docstring:\n') +
402 out.writeln(header('Class Docstring:\n') +
400 indent(class_ds))
403 indent(class_ds))
401
404
402 # Next, try to show constructor docstrings
405 # Next, try to show constructor docstrings
403 try:
406 try:
404 init_ds = getdoc(obj.__init__)
407 init_ds = getdoc(obj.__init__)
405 except AttributeError:
408 except AttributeError:
406 init_ds = None
409 init_ds = None
407 if init_ds:
410 if init_ds:
408 out.writeln(header('Constructor Docstring:\n') +
411 out.writeln(header('Constructor Docstring:\n') +
409 indent(init_ds))
412 indent(init_ds))
410
413
411 # Call form docstring for callable instances
414 # Call form docstring for callable instances
412 if hasattr(obj,'__call__'):
415 if hasattr(obj,'__call__'):
413 out.writeln(header('Callable:\t')+'Yes')
416 out.writeln(header('Callable:\t')+'Yes')
414 call_def = self.__getdef(obj.__call__,oname)
417 call_def = self.__getdef(obj.__call__,oname)
415 if call_def is None:
418 if call_def is None:
416 out.write(header('Call def:\t')+
419 out.write(header('Call def:\t')+
417 'Calling definition not available.')
420 'Calling definition not available.')
418 else:
421 else:
419 out.write(header('Call def:\t')+self.format(call_def))
422 out.write(header('Call def:\t')+self.format(call_def))
420 call_ds = getdoc(obj.__call__)
423 call_ds = getdoc(obj.__call__)
421 if call_ds:
424 if call_ds:
422 out.writeln(header('Call docstring:\n') + indent(call_ds))
425 out.writeln(header('Call docstring:\n') + indent(call_ds))
423
426
424 # Finally send to printer/pager
427 # Finally send to printer/pager
425 output = out.getvalue()
428 output = out.getvalue()
426 if output:
429 if output:
427 page(output)
430 page(output)
428 # end pinfo
431 # end pinfo
429
432
430 def psearch(self,pattern,ns_table,ns_search=[],
433 def psearch(self,pattern,ns_table,ns_search=[],
431 ignore_case=False,show_all=False):
434 ignore_case=False,show_all=False):
432 """Search namespaces with wildcards for objects.
435 """Search namespaces with wildcards for objects.
433
436
434 Arguments:
437 Arguments:
435
438
436 - pattern: string containing shell-like wildcards to use in namespace
439 - pattern: string containing shell-like wildcards to use in namespace
437 searches and optionally a type specification to narrow the search to
440 searches and optionally a type specification to narrow the search to
438 objects of that type.
441 objects of that type.
439
442
440 - ns_table: dict of name->namespaces for search.
443 - ns_table: dict of name->namespaces for search.
441
444
442 Optional arguments:
445 Optional arguments:
443
446
444 - ns_search: list of namespace names to include in search.
447 - ns_search: list of namespace names to include in search.
445
448
446 - ignore_case(False): make the search case-insensitive.
449 - ignore_case(False): make the search case-insensitive.
447
450
448 - show_all(False): show all names, including those starting with
451 - show_all(False): show all names, including those starting with
449 underscores.
452 underscores.
450 """
453 """
451 # defaults
454 # defaults
452 type_pattern = 'all'
455 type_pattern = 'all'
453 filter = ''
456 filter = ''
454
457
455 cmds = pattern.split()
458 cmds = pattern.split()
456 len_cmds = len(cmds)
459 len_cmds = len(cmds)
457 if len_cmds == 1:
460 if len_cmds == 1:
458 # Only filter pattern given
461 # Only filter pattern given
459 filter = cmds[0]
462 filter = cmds[0]
460 elif len_cmds == 2:
463 elif len_cmds == 2:
461 # Both filter and type specified
464 # Both filter and type specified
462 filter,type_pattern = cmds
465 filter,type_pattern = cmds
463 else:
466 else:
464 raise ValueError('invalid argument string for psearch: <%s>' %
467 raise ValueError('invalid argument string for psearch: <%s>' %
465 pattern)
468 pattern)
466
469
467 # filter search namespaces
470 # filter search namespaces
468 for name in ns_search:
471 for name in ns_search:
469 if name not in ns_table:
472 if name not in ns_table:
470 raise ValueError('invalid namespace <%s>. Valid names: %s' %
473 raise ValueError('invalid namespace <%s>. Valid names: %s' %
471 (name,ns_table.keys()))
474 (name,ns_table.keys()))
472
475
473 #print 'type_pattern:',type_pattern # dbg
476 #print 'type_pattern:',type_pattern # dbg
474 search_result = []
477 search_result = []
475 for ns_name in ns_search:
478 for ns_name in ns_search:
476 ns = ns_table[ns_name]
479 ns = ns_table[ns_name]
477 tmp_res = list(list_namespace(ns,type_pattern,filter,
480 tmp_res = list(list_namespace(ns,type_pattern,filter,
478 ignore_case=ignore_case,
481 ignore_case=ignore_case,
479 show_all=show_all))
482 show_all=show_all))
480 search_result.extend(tmp_res)
483 search_result.extend(tmp_res)
481 search_result.sort()
484 search_result.sort()
482
485
483 page('\n'.join(search_result))
486 page('\n'.join(search_result))
@@ -1,597 +1,607 b''
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 # $Id: ipythonrc 1324 2006-05-24 20:25:11Z fperez $
2 # $Id: ipythonrc 1329 2006-05-26 07:52:45Z fperez $
3
3
4 #***************************************************************************
4 #***************************************************************************
5 #
5 #
6 # Configuration file for IPython -- ipythonrc format
6 # Configuration file for IPython -- ipythonrc format
7 #
7 #
8 # The format of this file is simply one of 'key value' lines.
8 # The format of this file is simply one of 'key value' lines.
9 # Lines containing only whitespace at the beginning and then a # are ignored
9 # Lines containing only whitespace at the beginning and then a # are ignored
10 # as comments. But comments can NOT be put on lines with data.
10 # as comments. But comments can NOT be put on lines with data.
11
11
12 # The meaning and use of each key are explained below.
12 # The meaning and use of each key are explained below.
13
13
14 #---------------------------------------------------------------------------
14 #---------------------------------------------------------------------------
15 # Section: included files
15 # Section: included files
16
16
17 # Put one or more *config* files (with the syntax of this file) you want to
17 # Put one or more *config* files (with the syntax of this file) you want to
18 # include. For keys with a unique value the outermost file has precedence. For
18 # include. For keys with a unique value the outermost file has precedence. For
19 # keys with multiple values, they all get assembled into a list which then
19 # keys with multiple values, they all get assembled into a list which then
20 # gets loaded by IPython.
20 # gets loaded by IPython.
21
21
22 # In this file, all lists of things should simply be space-separated.
22 # In this file, all lists of things should simply be space-separated.
23
23
24 # This allows you to build hierarchies of files which recursively load
24 # This allows you to build hierarchies of files which recursively load
25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
25 # lower-level services. If this is your main ~/.ipython/ipythonrc file, you
26 # should only keep here basic things you always want available. Then you can
26 # should only keep here basic things you always want available. Then you can
27 # include it in every other special-purpose config file you create.
27 # include it in every other special-purpose config file you create.
28 include
28 include
29
29
30 #---------------------------------------------------------------------------
30 #---------------------------------------------------------------------------
31 # Section: startup setup
31 # Section: startup setup
32
32
33 # These are mostly things which parallel a command line option of the same
33 # These are mostly things which parallel a command line option of the same
34 # name.
34 # name.
35
35
36 # Keys in this section should only appear once. If any key from this section
36 # Keys in this section should only appear once. If any key from this section
37 # is encountered more than once, the last value remains, all earlier ones get
37 # is encountered more than once, the last value remains, all earlier ones get
38 # discarded.
38 # discarded.
39
39
40
40
41 # Automatic calling of callable objects. If set to 1 or 2, callable objects
41 # Automatic calling of callable objects. If set to 1 or 2, callable objects
42 # are automatically called when invoked at the command line, even if you don't
42 # are automatically called when invoked at the command line, even if you don't
43 # type parentheses. IPython adds the parentheses for you. For example:
43 # type parentheses. IPython adds the parentheses for you. For example:
44
44
45 #In [1]: str 45
45 #In [1]: str 45
46 #------> str(45)
46 #------> str(45)
47 #Out[1]: '45'
47 #Out[1]: '45'
48
48
49 # IPython reprints your line with '---->' indicating that it added
49 # IPython reprints your line with '---->' indicating that it added
50 # parentheses. While this option is very convenient for interactive use, it
50 # parentheses. While this option is very convenient for interactive use, it
51 # may occasionally cause problems with objects which have side-effects if
51 # may occasionally cause problems with objects which have side-effects if
52 # called unexpectedly.
52 # called unexpectedly.
53
53
54 # The valid values for autocall are:
54 # The valid values for autocall are:
55
55
56 # autocall 0 -> disabled (you can toggle it at runtime with the %autocall magic)
56 # autocall 0 -> disabled (you can toggle it at runtime with the %autocall magic)
57
57
58 # autocall 1 -> active, but do not apply if there are no arguments on the line.
58 # autocall 1 -> active, but do not apply if there are no arguments on the line.
59
59
60 # In this mode, you get:
60 # In this mode, you get:
61
61
62 #In [1]: callable
62 #In [1]: callable
63 #Out[1]: <built-in function callable>
63 #Out[1]: <built-in function callable>
64
64
65 #In [2]: callable 'hello'
65 #In [2]: callable 'hello'
66 #------> callable('hello')
66 #------> callable('hello')
67 #Out[2]: False
67 #Out[2]: False
68
68
69 # 2 -> Active always. Even if no arguments are present, the callable object
69 # 2 -> Active always. Even if no arguments are present, the callable object
70 # is called:
70 # is called:
71
71
72 #In [4]: callable
72 #In [4]: callable
73 #------> callable()
73 #------> callable()
74
74
75 # Note that even with autocall off, you can still use '/' at the start of a
75 # Note that even with autocall off, you can still use '/' at the start of a
76 # line to treat the first argument on the command line as a function and add
76 # line to treat the first argument on the command line as a function and add
77 # parentheses to it:
77 # parentheses to it:
78
78
79 #In [8]: /str 43
79 #In [8]: /str 43
80 #------> str(43)
80 #------> str(43)
81 #Out[8]: '43'
81 #Out[8]: '43'
82
82
83 autocall 1
83 autocall 1
84
84
85 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
85 # Auto-edit syntax errors. When you use the %edit magic in ipython to edit
86 # source code (see the 'editor' variable below), it is possible that you save
86 # source code (see the 'editor' variable below), it is possible that you save
87 # a file with syntax errors in it. If this variable is true, IPython will ask
87 # a file with syntax errors in it. If this variable is true, IPython will ask
88 # you whether to re-open the editor immediately to correct such an error.
88 # you whether to re-open the editor immediately to correct such an error.
89
89
90 autoedit_syntax 0
90 autoedit_syntax 0
91
91
92 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
92 # Auto-indent. IPython can recognize lines ending in ':' and indent the next
93 # line, while also un-indenting automatically after 'raise' or 'return'.
93 # line, while also un-indenting automatically after 'raise' or 'return'.
94
94
95 # This feature uses the readline library, so it will honor your ~/.inputrc
95 # This feature uses the readline library, so it will honor your ~/.inputrc
96 # configuration (or whatever file your INPUTRC variable points to). Adding
96 # configuration (or whatever file your INPUTRC variable points to). Adding
97 # the following lines to your .inputrc file can make indent/unindenting more
97 # the following lines to your .inputrc file can make indent/unindenting more
98 # convenient (M-i indents, M-u unindents):
98 # convenient (M-i indents, M-u unindents):
99
99
100 # $if Python
100 # $if Python
101 # "\M-i": " "
101 # "\M-i": " "
102 # "\M-u": "\d\d\d\d"
102 # "\M-u": "\d\d\d\d"
103 # $endif
103 # $endif
104
104
105 # The feature is potentially a bit dangerous, because it can cause problems
105 # The feature is potentially a bit dangerous, because it can cause problems
106 # with pasting of indented code (the pasted code gets re-indented on each
106 # with pasting of indented code (the pasted code gets re-indented on each
107 # line). But it's a huge time-saver when working interactively. The magic
107 # line). But it's a huge time-saver when working interactively. The magic
108 # function %autoindent allows you to toggle it on/off at runtime.
108 # function %autoindent allows you to toggle it on/off at runtime.
109
109
110 autoindent 1
110 autoindent 1
111
111
112 # Auto-magic. This gives you access to all the magic functions without having
112 # Auto-magic. This gives you access to all the magic functions without having
113 # to prepend them with an % sign. If you define a variable with the same name
113 # to prepend them with an % sign. If you define a variable with the same name
114 # as a magic function (say who=1), you will need to access the magic function
114 # as a magic function (say who=1), you will need to access the magic function
115 # with % (%who in this example). However, if later you delete your variable
115 # with % (%who in this example). However, if later you delete your variable
116 # (del who), you'll recover the automagic calling form.
116 # (del who), you'll recover the automagic calling form.
117
117
118 # Considering that many magic functions provide a lot of shell-like
118 # Considering that many magic functions provide a lot of shell-like
119 # functionality, automagic gives you something close to a full Python+system
119 # functionality, automagic gives you something close to a full Python+system
120 # shell environment (and you can extend it further if you want).
120 # shell environment (and you can extend it further if you want).
121
121
122 automagic 1
122 automagic 1
123
123
124 # Size of the output cache. After this many entries are stored, the cache will
124 # Size of the output cache. After this many entries are stored, the cache will
125 # get flushed. Depending on the size of your intermediate calculations, you
125 # get flushed. Depending on the size of your intermediate calculations, you
126 # may have memory problems if you make it too big, since keeping things in the
126 # may have memory problems if you make it too big, since keeping things in the
127 # cache prevents Python from reclaiming the memory for old results. Experiment
127 # cache prevents Python from reclaiming the memory for old results. Experiment
128 # with a value that works well for you.
128 # with a value that works well for you.
129
129
130 # If you choose cache_size 0 IPython will revert to python's regular >>>
130 # If you choose cache_size 0 IPython will revert to python's regular >>>
131 # unnumbered prompt. You will still have _, __ and ___ for your last three
131 # unnumbered prompt. You will still have _, __ and ___ for your last three
132 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
132 # results, but that will be it. No dynamic _1, _2, etc. will be created. If
133 # you are running on a slow machine or with very limited memory, this may
133 # you are running on a slow machine or with very limited memory, this may
134 # help.
134 # help.
135
135
136 cache_size 1000
136 cache_size 1000
137
137
138 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
138 # Classic mode: Setting 'classic 1' you lose many of IPython niceties,
139 # but that's your choice! Classic 1 -> same as IPython -classic.
139 # but that's your choice! Classic 1 -> same as IPython -classic.
140 # Note that this is _not_ the normal python interpreter, it's simply
140 # Note that this is _not_ the normal python interpreter, it's simply
141 # IPython emulating most of the classic interpreter's behavior.
141 # IPython emulating most of the classic interpreter's behavior.
142 classic 0
142 classic 0
143
143
144 # colors - Coloring option for prompts and traceback printouts.
144 # colors - Coloring option for prompts and traceback printouts.
145
145
146 # Currently available schemes: NoColor, Linux, LightBG.
146 # Currently available schemes: NoColor, Linux, LightBG.
147
147
148 # This option allows coloring the prompts and traceback printouts. This
148 # This option allows coloring the prompts and traceback printouts. This
149 # requires a terminal which can properly handle color escape sequences. If you
149 # requires a terminal which can properly handle color escape sequences. If you
150 # are having problems with this, use the NoColor scheme (uses no color escapes
150 # are having problems with this, use the NoColor scheme (uses no color escapes
151 # at all).
151 # at all).
152
152
153 # The Linux option works well in linux console type environments: dark
153 # The Linux option works well in linux console type environments: dark
154 # background with light fonts.
154 # background with light fonts.
155
155
156 # LightBG is similar to Linux but swaps dark/light colors to be more readable
156 # LightBG is similar to Linux but swaps dark/light colors to be more readable
157 # in light background terminals.
157 # in light background terminals.
158
158
159 # keep uncommented only the one you want:
159 # keep uncommented only the one you want:
160 colors Linux
160 colors Linux
161 #colors LightBG
161 #colors LightBG
162 #colors NoColor
162 #colors NoColor
163
163
164 ########################
164 ########################
165 # Note to Windows users
165 # Note to Windows users
166 #
166 #
167 # Color and readline support is avaialble to Windows users via Gary Bishop's
167 # Color and readline support is avaialble to Windows users via Gary Bishop's
168 # readline library. You can find Gary's tools at
168 # readline library. You can find Gary's tools at
169 # http://sourceforge.net/projects/uncpythontools.
169 # http://sourceforge.net/projects/uncpythontools.
170 # Note that his readline module requires in turn the ctypes library, available
170 # Note that his readline module requires in turn the ctypes library, available
171 # at http://starship.python.net/crew/theller/ctypes.
171 # at http://starship.python.net/crew/theller/ctypes.
172 ########################
172 ########################
173
173
174 # color_info: IPython can display information about objects via a set of
174 # color_info: IPython can display information about objects via a set of
175 # functions, and optionally can use colors for this, syntax highlighting
175 # functions, and optionally can use colors for this, syntax highlighting
176 # source code and various other elements. This information is passed through a
176 # source code and various other elements. This information is passed through a
177 # pager (it defaults to 'less' if $PAGER is not set).
177 # pager (it defaults to 'less' if $PAGER is not set).
178
178
179 # If your pager has problems, try to setting it to properly handle escapes
179 # If your pager has problems, try to setting it to properly handle escapes
180 # (see the less manpage for detail), or disable this option. The magic
180 # (see the less manpage for detail), or disable this option. The magic
181 # function %color_info allows you to toggle this interactively for testing.
181 # function %color_info allows you to toggle this interactively for testing.
182
182
183 color_info 1
183 color_info 1
184
184
185 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
185 # confirm_exit: set to 1 if you want IPython to confirm when you try to exit
186 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
186 # with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
187 # the magic functions %Exit or %Quit you can force a direct exit, bypassing
187 # the magic functions %Exit or %Quit you can force a direct exit, bypassing
188 # any confirmation.
188 # any confirmation.
189
189
190 confirm_exit 1
190 confirm_exit 1
191
191
192 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
192 # Use deep_reload() as a substitute for reload() by default. deep_reload() is
193 # still available as dreload() and appears as a builtin.
193 # still available as dreload() and appears as a builtin.
194
194
195 deep_reload 0
195 deep_reload 0
196
196
197 # Which editor to use with the %edit command. If you leave this at 0, IPython
197 # Which editor to use with the %edit command. If you leave this at 0, IPython
198 # will honor your EDITOR environment variable. Since this editor is invoked on
198 # will honor your EDITOR environment variable. Since this editor is invoked on
199 # the fly by ipython and is meant for editing small code snippets, you may
199 # the fly by ipython and is meant for editing small code snippets, you may
200 # want to use a small, lightweight editor here.
200 # want to use a small, lightweight editor here.
201
201
202 # For Emacs users, setting up your Emacs server properly as described in the
202 # For Emacs users, setting up your Emacs server properly as described in the
203 # manual is a good idea. An alternative is to use jed, a very light editor
203 # manual is a good idea. An alternative is to use jed, a very light editor
204 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
204 # with much of the feel of Emacs (though not as powerful for heavy-duty work).
205
205
206 editor 0
206 editor 0
207
207
208 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
208 # log 1 -> same as ipython -log. This automatically logs to ./ipython.log
209 log 0
209 log 0
210
210
211 # Same as ipython -Logfile YourLogfileName.
211 # Same as ipython -Logfile YourLogfileName.
212 # Don't use with log 1 (use one or the other)
212 # Don't use with log 1 (use one or the other)
213 logfile ''
213 logfile ''
214
214
215 # banner 0 -> same as ipython -nobanner
215 # banner 0 -> same as ipython -nobanner
216 banner 1
216 banner 1
217
217
218 # messages 0 -> same as ipython -nomessages
218 # messages 0 -> same as ipython -nomessages
219 messages 1
219 messages 1
220
220
221 # Automatically call the pdb debugger after every uncaught exception. If you
221 # Automatically call the pdb debugger after every uncaught exception. If you
222 # are used to debugging using pdb, this puts you automatically inside of it
222 # are used to debugging using pdb, this puts you automatically inside of it
223 # after any call (either in IPython or in code called by it) which triggers an
223 # after any call (either in IPython or in code called by it) which triggers an
224 # exception which goes uncaught.
224 # exception which goes uncaught.
225 pdb 0
225 pdb 0
226
226
227 # Enable the pprint module for printing. pprint tends to give a more readable
227 # Enable the pprint module for printing. pprint tends to give a more readable
228 # display (than print) for complex nested data structures.
228 # display (than print) for complex nested data structures.
229 pprint 1
229 pprint 1
230
230
231 # Prompt strings
231 # Prompt strings
232
232
233 # Most bash-like escapes can be used to customize IPython's prompts, as well as
233 # Most bash-like escapes can be used to customize IPython's prompts, as well as
234 # a few additional ones which are IPython-specific. All valid prompt escapes
234 # a few additional ones which are IPython-specific. All valid prompt escapes
235 # are described in detail in the Customization section of the IPython HTML/PDF
235 # are described in detail in the Customization section of the IPython HTML/PDF
236 # manual.
236 # manual.
237
237
238 # Use \# to represent the current prompt number, and quote them to protect
238 # Use \# to represent the current prompt number, and quote them to protect
239 # spaces.
239 # spaces.
240 prompt_in1 'In [\#]: '
240 prompt_in1 'In [\#]: '
241
241
242 # \D is replaced by as many dots as there are digits in the
242 # \D is replaced by as many dots as there are digits in the
243 # current value of \#.
243 # current value of \#.
244 prompt_in2 ' .\D.: '
244 prompt_in2 ' .\D.: '
245
245
246 prompt_out 'Out[\#]: '
246 prompt_out 'Out[\#]: '
247
247
248 # Select whether to left-pad the output prompts to match the length of the
248 # Select whether to left-pad the output prompts to match the length of the
249 # input ones. This allows you for example to use a simple '>' as an output
249 # input ones. This allows you for example to use a simple '>' as an output
250 # prompt, and yet have the output line up with the input. If set to false,
250 # prompt, and yet have the output line up with the input. If set to false,
251 # the output prompts will be unpadded (flush left).
251 # the output prompts will be unpadded (flush left).
252 prompts_pad_left 1
252 prompts_pad_left 1
253
253
254 # quick 1 -> same as ipython -quick
254 # quick 1 -> same as ipython -quick
255 quick 0
255 quick 0
256
256
257 # Use the readline library (1) or not (0). Most users will want this on, but
257 # Use the readline library (1) or not (0). Most users will want this on, but
258 # if you experience strange problems with line management (mainly when using
258 # if you experience strange problems with line management (mainly when using
259 # IPython inside Emacs buffers) you may try disabling it. Not having it on
259 # IPython inside Emacs buffers) you may try disabling it. Not having it on
260 # prevents you from getting command history with the arrow keys, searching and
260 # prevents you from getting command history with the arrow keys, searching and
261 # name completion using TAB.
261 # name completion using TAB.
262
262
263 readline 1
263 readline 1
264
264
265 # Screen Length: number of lines of your screen. This is used to control
265 # Screen Length: number of lines of your screen. This is used to control
266 # printing of very long strings. Strings longer than this number of lines will
266 # printing of very long strings. Strings longer than this number of lines will
267 # be paged with the less command instead of directly printed.
267 # be paged with the less command instead of directly printed.
268
268
269 # The default value for this is 0, which means IPython will auto-detect your
269 # The default value for this is 0, which means IPython will auto-detect your
270 # screen size every time it needs to print. If for some reason this isn't
270 # screen size every time it needs to print. If for some reason this isn't
271 # working well (it needs curses support), specify it yourself. Otherwise don't
271 # working well (it needs curses support), specify it yourself. Otherwise don't
272 # change the default.
272 # change the default.
273
273
274 screen_length 0
274 screen_length 0
275
275
276 # Prompt separators for input and output.
276 # Prompt separators for input and output.
277 # Use \n for newline explicitly, without quotes.
277 # Use \n for newline explicitly, without quotes.
278 # Use 0 (like at the cmd line) to turn off a given separator.
278 # Use 0 (like at the cmd line) to turn off a given separator.
279
279
280 # The structure of prompt printing is:
280 # The structure of prompt printing is:
281 # (SeparateIn)Input....
281 # (SeparateIn)Input....
282 # (SeparateOut)Output...
282 # (SeparateOut)Output...
283 # (SeparateOut2), # that is, no newline is printed after Out2
283 # (SeparateOut2), # that is, no newline is printed after Out2
284 # By choosing these you can organize your output any way you want.
284 # By choosing these you can organize your output any way you want.
285
285
286 separate_in \n
286 separate_in \n
287 separate_out 0
287 separate_out 0
288 separate_out2 0
288 separate_out2 0
289
289
290 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
290 # 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
291 # Simply removes all input/output separators, overriding the choices above.
291 # Simply removes all input/output separators, overriding the choices above.
292 nosep 0
292 nosep 0
293
293
294 # Wildcard searches - IPython has a system for searching names using
294 # Wildcard searches - IPython has a system for searching names using
295 # shell-like wildcards; type %psearch? for details. This variables sets
295 # shell-like wildcards; type %psearch? for details. This variables sets
296 # whether by default such searches should be case sensitive or not. You can
296 # whether by default such searches should be case sensitive or not. You can
297 # always override the default at the system command line or the IPython
297 # always override the default at the system command line or the IPython
298 # prompt.
298 # prompt.
299
299
300 wildcards_case_sensitive 1
300 wildcards_case_sensitive 1
301
301
302 # Object information: at what level of detail to display the string form of an
303 # object. If set to 0, ipython will compute the string form of any object X,
304 # by calling str(X), when X? is typed. If set to 1, str(X) will only be
305 # computed when X?? is given, and if set to 2 or higher, it will never be
306 # computed (there is no X??? level of detail). This is mostly of use to
307 # people who frequently manipulate objects whose string representation is
308 # extremely expensive to compute.
309
310 object_info_string_level 0
311
302 # xmode - Exception reporting mode.
312 # xmode - Exception reporting mode.
303
313
304 # Valid modes: Plain, Context and Verbose.
314 # Valid modes: Plain, Context and Verbose.
305
315
306 # Plain: similar to python's normal traceback printing.
316 # Plain: similar to python's normal traceback printing.
307
317
308 # Context: prints 5 lines of context source code around each line in the
318 # Context: prints 5 lines of context source code around each line in the
309 # traceback.
319 # traceback.
310
320
311 # Verbose: similar to Context, but additionally prints the variables currently
321 # Verbose: similar to Context, but additionally prints the variables currently
312 # visible where the exception happened (shortening their strings if too
322 # visible where the exception happened (shortening their strings if too
313 # long). This can potentially be very slow, if you happen to have a huge data
323 # long). This can potentially be very slow, if you happen to have a huge data
314 # structure whose string representation is complex to compute. Your computer
324 # structure whose string representation is complex to compute. Your computer
315 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
325 # may appear to freeze for a while with cpu usage at 100%. If this occurs, you
316 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
326 # can cancel the traceback with Ctrl-C (maybe hitting it more than once).
317
327
318 #xmode Plain
328 #xmode Plain
319 xmode Context
329 xmode Context
320 #xmode Verbose
330 #xmode Verbose
321
331
322 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
332 # multi_line_specials: if true, allow magics, aliases and shell escapes (via
323 # !cmd) to be used in multi-line input (like for loops). For example, if you
333 # !cmd) to be used in multi-line input (like for loops). For example, if you
324 # have this active, the following is valid in IPython:
334 # have this active, the following is valid in IPython:
325 #
335 #
326 #In [17]: for i in range(3):
336 #In [17]: for i in range(3):
327 # ....: mkdir $i
337 # ....: mkdir $i
328 # ....: !touch $i/hello
338 # ....: !touch $i/hello
329 # ....: ls -l $i
339 # ....: ls -l $i
330
340
331 multi_line_specials 1
341 multi_line_specials 1
332
342
333 # wxversion: request a specific wxPython version (used for -wthread)
343 # wxversion: request a specific wxPython version (used for -wthread)
334
344
335 # Set this to the value of wxPython you want to use, but note that this
345 # Set this to the value of wxPython you want to use, but note that this
336 # feature requires you to have the wxversion Python module to work. If you
346 # feature requires you to have the wxversion Python module to work. If you
337 # don't have the wxversion module (try 'import wxversion' at the prompt to
347 # don't have the wxversion module (try 'import wxversion' at the prompt to
338 # check) or simply want to leave the system to pick up the default, leave this
348 # check) or simply want to leave the system to pick up the default, leave this
339 # variable at 0.
349 # variable at 0.
340
350
341 wxversion 0
351 wxversion 0
342
352
343 #---------------------------------------------------------------------------
353 #---------------------------------------------------------------------------
344 # Section: Readline configuration (readline is not available for MS-Windows)
354 # Section: Readline configuration (readline is not available for MS-Windows)
345
355
346 # This is done via the following options:
356 # This is done via the following options:
347
357
348 # (i) readline_parse_and_bind: this option can appear as many times as you
358 # (i) readline_parse_and_bind: this option can appear as many times as you
349 # want, each time defining a string to be executed via a
359 # want, each time defining a string to be executed via a
350 # readline.parse_and_bind() command. The syntax for valid commands of this
360 # readline.parse_and_bind() command. The syntax for valid commands of this
351 # kind can be found by reading the documentation for the GNU readline library,
361 # kind can be found by reading the documentation for the GNU readline library,
352 # as these commands are of the kind which readline accepts in its
362 # as these commands are of the kind which readline accepts in its
353 # configuration file.
363 # configuration file.
354
364
355 # The TAB key can be used to complete names at the command line in one of two
365 # The TAB key can be used to complete names at the command line in one of two
356 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
366 # ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
357 # completes as much as possible while 'menu-complete' cycles through all
367 # completes as much as possible while 'menu-complete' cycles through all
358 # possible completions. Leave the one you prefer uncommented.
368 # possible completions. Leave the one you prefer uncommented.
359
369
360 readline_parse_and_bind tab: complete
370 readline_parse_and_bind tab: complete
361 #readline_parse_and_bind tab: menu-complete
371 #readline_parse_and_bind tab: menu-complete
362
372
363 # This binds Control-l to printing the list of all possible completions when
373 # This binds Control-l to printing the list of all possible completions when
364 # there is more than one (what 'complete' does when hitting TAB twice, or at
374 # there is more than one (what 'complete' does when hitting TAB twice, or at
365 # the first TAB if show-all-if-ambiguous is on)
375 # the first TAB if show-all-if-ambiguous is on)
366 readline_parse_and_bind "\C-l": possible-completions
376 readline_parse_and_bind "\C-l": possible-completions
367
377
368 # This forces readline to automatically print the above list when tab
378 # This forces readline to automatically print the above list when tab
369 # completion is set to 'complete'. You can still get this list manually by
379 # completion is set to 'complete'. You can still get this list manually by
370 # using the key bound to 'possible-completions' (Control-l by default) or by
380 # using the key bound to 'possible-completions' (Control-l by default) or by
371 # hitting TAB twice. Turning this on makes the printing happen at the first
381 # hitting TAB twice. Turning this on makes the printing happen at the first
372 # TAB.
382 # TAB.
373 readline_parse_and_bind set show-all-if-ambiguous on
383 readline_parse_and_bind set show-all-if-ambiguous on
374
384
375 # If you have TAB set to complete names, you can rebind any key (Control-o by
385 # If you have TAB set to complete names, you can rebind any key (Control-o by
376 # default) to insert a true TAB character.
386 # default) to insert a true TAB character.
377 readline_parse_and_bind "\C-o": tab-insert
387 readline_parse_and_bind "\C-o": tab-insert
378
388
379 # These commands allow you to indent/unindent easily, with the 4-space
389 # These commands allow you to indent/unindent easily, with the 4-space
380 # convention of the Python coding standards. Since IPython's internal
390 # convention of the Python coding standards. Since IPython's internal
381 # auto-indent system also uses 4 spaces, you should not change the number of
391 # auto-indent system also uses 4 spaces, you should not change the number of
382 # spaces in the code below.
392 # spaces in the code below.
383 readline_parse_and_bind "\M-i": " "
393 readline_parse_and_bind "\M-i": " "
384 readline_parse_and_bind "\M-o": "\d\d\d\d"
394 readline_parse_and_bind "\M-o": "\d\d\d\d"
385 readline_parse_and_bind "\M-I": "\d\d\d\d"
395 readline_parse_and_bind "\M-I": "\d\d\d\d"
386
396
387 # Bindings for incremental searches in the history. These searches use the
397 # Bindings for incremental searches in the history. These searches use the
388 # string typed so far on the command line and search anything in the previous
398 # string typed so far on the command line and search anything in the previous
389 # input history containing them.
399 # input history containing them.
390 readline_parse_and_bind "\C-r": reverse-search-history
400 readline_parse_and_bind "\C-r": reverse-search-history
391 readline_parse_and_bind "\C-s": forward-search-history
401 readline_parse_and_bind "\C-s": forward-search-history
392
402
393 # Bindings for completing the current line in the history of previous
403 # Bindings for completing the current line in the history of previous
394 # commands. This allows you to recall any previous command by typing its first
404 # commands. This allows you to recall any previous command by typing its first
395 # few letters and hitting Control-p, bypassing all intermediate commands which
405 # few letters and hitting Control-p, bypassing all intermediate commands which
396 # may be in the history (much faster than hitting up-arrow 50 times!)
406 # may be in the history (much faster than hitting up-arrow 50 times!)
397 readline_parse_and_bind "\C-p": history-search-backward
407 readline_parse_and_bind "\C-p": history-search-backward
398 readline_parse_and_bind "\C-n": history-search-forward
408 readline_parse_and_bind "\C-n": history-search-forward
399
409
400 # I also like to have the same functionality on the plain arrow keys. If you'd
410 # I also like to have the same functionality on the plain arrow keys. If you'd
401 # rather have the arrows use all the history (and not just match what you've
411 # rather have the arrows use all the history (and not just match what you've
402 # typed so far), comment out or delete the next two lines.
412 # typed so far), comment out or delete the next two lines.
403 readline_parse_and_bind "\e[A": history-search-backward
413 readline_parse_and_bind "\e[A": history-search-backward
404 readline_parse_and_bind "\e[B": history-search-forward
414 readline_parse_and_bind "\e[B": history-search-forward
405
415
406 # These are typically on by default under *nix, but not win32.
416 # These are typically on by default under *nix, but not win32.
407 readline_parse_and_bind "\C-k": kill-line
417 readline_parse_and_bind "\C-k": kill-line
408 readline_parse_and_bind "\C-u": unix-line-discard
418 readline_parse_and_bind "\C-u": unix-line-discard
409
419
410 # (ii) readline_remove_delims: a string of characters to be removed from the
420 # (ii) readline_remove_delims: a string of characters to be removed from the
411 # default word-delimiters list used by readline, so that completions may be
421 # default word-delimiters list used by readline, so that completions may be
412 # performed on strings which contain them.
422 # performed on strings which contain them.
413
423
414 readline_remove_delims -/~
424 readline_remove_delims -/~
415
425
416 # (iii) readline_merge_completions: whether to merge the result of all
426 # (iii) readline_merge_completions: whether to merge the result of all
417 # possible completions or not. If true, IPython will complete filenames,
427 # possible completions or not. If true, IPython will complete filenames,
418 # python names and aliases and return all possible completions. If you set it
428 # python names and aliases and return all possible completions. If you set it
419 # to false, each completer is used at a time, and only if it doesn't return
429 # to false, each completer is used at a time, and only if it doesn't return
420 # any completions is the next one used.
430 # any completions is the next one used.
421
431
422 # The default order is: [python_matches, file_matches, alias_matches]
432 # The default order is: [python_matches, file_matches, alias_matches]
423
433
424 readline_merge_completions 1
434 readline_merge_completions 1
425
435
426 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
436 # (iv) readline_omit__names: normally hitting <tab> after a '.' in a name
427 # will complete all attributes of an object, including all the special methods
437 # will complete all attributes of an object, including all the special methods
428 # whose names start with single or double underscores (like __getitem__ or
438 # whose names start with single or double underscores (like __getitem__ or
429 # __class__).
439 # __class__).
430
440
431 # This variable allows you to control this completion behavior:
441 # This variable allows you to control this completion behavior:
432
442
433 # readline_omit__names 1 -> completion will omit showing any names starting
443 # readline_omit__names 1 -> completion will omit showing any names starting
434 # with two __, but it will still show names starting with one _.
444 # with two __, but it will still show names starting with one _.
435
445
436 # readline_omit__names 2 -> completion will omit all names beginning with one
446 # readline_omit__names 2 -> completion will omit all names beginning with one
437 # _ (which obviously means filtering out the double __ ones).
447 # _ (which obviously means filtering out the double __ ones).
438
448
439 # Even when this option is set, you can still see those names by explicitly
449 # Even when this option is set, you can still see those names by explicitly
440 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
450 # typing a _ after the period and hitting <tab>: 'name._<tab>' will always
441 # complete attribute names starting with '_'.
451 # complete attribute names starting with '_'.
442
452
443 # This option is off by default so that new users see all attributes of any
453 # This option is off by default so that new users see all attributes of any
444 # objects they are dealing with.
454 # objects they are dealing with.
445
455
446 readline_omit__names 0
456 readline_omit__names 0
447
457
448 #---------------------------------------------------------------------------
458 #---------------------------------------------------------------------------
449 # Section: modules to be loaded with 'import ...'
459 # Section: modules to be loaded with 'import ...'
450
460
451 # List, separated by spaces, the names of the modules you want to import
461 # List, separated by spaces, the names of the modules you want to import
452
462
453 # Example:
463 # Example:
454 # import_mod sys os
464 # import_mod sys os
455 # will produce internally the statements
465 # will produce internally the statements
456 # import sys
466 # import sys
457 # import os
467 # import os
458
468
459 # Each import is executed in its own try/except block, so if one module
469 # Each import is executed in its own try/except block, so if one module
460 # fails to load the others will still be ok.
470 # fails to load the others will still be ok.
461
471
462 import_mod
472 import_mod
463
473
464 #---------------------------------------------------------------------------
474 #---------------------------------------------------------------------------
465 # Section: modules to import some functions from: 'from ... import ...'
475 # Section: modules to import some functions from: 'from ... import ...'
466
476
467 # List, one per line, the modules for which you want only to import some
477 # List, one per line, the modules for which you want only to import some
468 # functions. Give the module name first and then the name of functions to be
478 # functions. Give the module name first and then the name of functions to be
469 # imported from that module.
479 # imported from that module.
470
480
471 # Example:
481 # Example:
472
482
473 # import_some IPython.genutils timing timings
483 # import_some IPython.genutils timing timings
474 # will produce internally the statement
484 # will produce internally the statement
475 # from IPython.genutils import timing, timings
485 # from IPython.genutils import timing, timings
476
486
477 # timing() and timings() are two IPython utilities for timing the execution of
487 # timing() and timings() are two IPython utilities for timing the execution of
478 # your own functions, which you may find useful. Just commment out the above
488 # your own functions, which you may find useful. Just commment out the above
479 # line if you want to test them.
489 # line if you want to test them.
480
490
481 # If you have more than one modules_some line, each gets its own try/except
491 # If you have more than one modules_some line, each gets its own try/except
482 # block (like modules, see above).
492 # block (like modules, see above).
483
493
484 import_some
494 import_some
485
495
486 #---------------------------------------------------------------------------
496 #---------------------------------------------------------------------------
487 # Section: modules to import all from : 'from ... import *'
497 # Section: modules to import all from : 'from ... import *'
488
498
489 # List (same syntax as import_mod above) those modules for which you want to
499 # List (same syntax as import_mod above) those modules for which you want to
490 # import all functions. Remember, this is a potentially dangerous thing to do,
500 # import all functions. Remember, this is a potentially dangerous thing to do,
491 # since it is very easy to overwrite names of things you need. Use with
501 # since it is very easy to overwrite names of things you need. Use with
492 # caution.
502 # caution.
493
503
494 # Example:
504 # Example:
495 # import_all sys os
505 # import_all sys os
496 # will produce internally the statements
506 # will produce internally the statements
497 # from sys import *
507 # from sys import *
498 # from os import *
508 # from os import *
499
509
500 # As before, each will be called in a separate try/except block.
510 # As before, each will be called in a separate try/except block.
501
511
502 import_all
512 import_all
503
513
504 #---------------------------------------------------------------------------
514 #---------------------------------------------------------------------------
505 # Section: Python code to execute.
515 # Section: Python code to execute.
506
516
507 # Put here code to be explicitly executed (keep it simple!)
517 # Put here code to be explicitly executed (keep it simple!)
508 # Put one line of python code per line. All whitespace is removed (this is a
518 # Put one line of python code per line. All whitespace is removed (this is a
509 # feature, not a bug), so don't get fancy building loops here.
519 # feature, not a bug), so don't get fancy building loops here.
510 # This is just for quick convenient creation of things you want available.
520 # This is just for quick convenient creation of things you want available.
511
521
512 # Example:
522 # Example:
513 # execute x = 1
523 # execute x = 1
514 # execute print 'hello world'; y = z = 'a'
524 # execute print 'hello world'; y = z = 'a'
515 # will produce internally
525 # will produce internally
516 # x = 1
526 # x = 1
517 # print 'hello world'; y = z = 'a'
527 # print 'hello world'; y = z = 'a'
518 # and each *line* (not each statement, we don't do python syntax parsing) is
528 # and each *line* (not each statement, we don't do python syntax parsing) is
519 # executed in its own try/except block.
529 # executed in its own try/except block.
520
530
521 execute
531 execute
522
532
523 # Note for the adventurous: you can use this to define your own names for the
533 # Note for the adventurous: you can use this to define your own names for the
524 # magic functions, by playing some namespace tricks:
534 # magic functions, by playing some namespace tricks:
525
535
526 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
536 # execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
527
537
528 # defines %pf as a new name for %profile.
538 # defines %pf as a new name for %profile.
529
539
530 #---------------------------------------------------------------------------
540 #---------------------------------------------------------------------------
531 # Section: Pyhton files to load and execute.
541 # Section: Pyhton files to load and execute.
532
542
533 # Put here the full names of files you want executed with execfile(file). If
543 # Put here the full names of files you want executed with execfile(file). If
534 # you want complicated initialization, just write whatever you want in a
544 # you want complicated initialization, just write whatever you want in a
535 # regular python file and load it from here.
545 # regular python file and load it from here.
536
546
537 # Filenames defined here (which *must* include the extension) are searched for
547 # Filenames defined here (which *must* include the extension) are searched for
538 # through all of sys.path. Since IPython adds your .ipython directory to
548 # through all of sys.path. Since IPython adds your .ipython directory to
539 # sys.path, they can also be placed in your .ipython dir and will be
549 # sys.path, they can also be placed in your .ipython dir and will be
540 # found. Otherwise (if you want to execute things not in .ipyton nor in
550 # found. Otherwise (if you want to execute things not in .ipyton nor in
541 # sys.path) give a full path (you can use ~, it gets expanded)
551 # sys.path) give a full path (you can use ~, it gets expanded)
542
552
543 # Example:
553 # Example:
544 # execfile file1.py ~/file2.py
554 # execfile file1.py ~/file2.py
545 # will generate
555 # will generate
546 # execfile('file1.py')
556 # execfile('file1.py')
547 # execfile('_path_to_your_home/file2.py')
557 # execfile('_path_to_your_home/file2.py')
548
558
549 # As before, each file gets its own try/except block.
559 # As before, each file gets its own try/except block.
550
560
551 execfile
561 execfile
552
562
553 # If you are feeling adventurous, you can even add functionality to IPython
563 # If you are feeling adventurous, you can even add functionality to IPython
554 # through here. IPython works through a global variable called __ip which
564 # through here. IPython works through a global variable called __ip which
555 # exists at the time when these files are read. If you know what you are doing
565 # exists at the time when these files are read. If you know what you are doing
556 # (read the source) you can add functions to __ip in files loaded here.
566 # (read the source) you can add functions to __ip in files loaded here.
557
567
558 # The file example-magic.py contains a simple but correct example. Try it:
568 # The file example-magic.py contains a simple but correct example. Try it:
559
569
560 # execfile example-magic.py
570 # execfile example-magic.py
561
571
562 # Look at the examples in IPython/iplib.py for more details on how these magic
572 # Look at the examples in IPython/iplib.py for more details on how these magic
563 # functions need to process their arguments.
573 # functions need to process their arguments.
564
574
565 #---------------------------------------------------------------------------
575 #---------------------------------------------------------------------------
566 # Section: aliases for system shell commands
576 # Section: aliases for system shell commands
567
577
568 # Here you can define your own names for system commands. The syntax is
578 # Here you can define your own names for system commands. The syntax is
569 # similar to that of the builtin %alias function:
579 # similar to that of the builtin %alias function:
570
580
571 # alias alias_name command_string
581 # alias alias_name command_string
572
582
573 # The resulting aliases are auto-generated magic functions (hence usable as
583 # The resulting aliases are auto-generated magic functions (hence usable as
574 # %alias_name)
584 # %alias_name)
575
585
576 # For example:
586 # For example:
577
587
578 # alias myls ls -la
588 # alias myls ls -la
579
589
580 # will define 'myls' as an alias for executing the system command 'ls -la'.
590 # will define 'myls' as an alias for executing the system command 'ls -la'.
581 # This allows you to customize IPython's environment to have the same aliases
591 # This allows you to customize IPython's environment to have the same aliases
582 # you are accustomed to from your own shell.
592 # you are accustomed to from your own shell.
583
593
584 # You can also define aliases with parameters using %s specifiers (one per
594 # You can also define aliases with parameters using %s specifiers (one per
585 # parameter):
595 # parameter):
586
596
587 # alias parts echo first %s second %s
597 # alias parts echo first %s second %s
588
598
589 # will give you in IPython:
599 # will give you in IPython:
590 # >>> %parts A B
600 # >>> %parts A B
591 # first A second B
601 # first A second B
592
602
593 # Use one 'alias' statement per alias you wish to define.
603 # Use one 'alias' statement per alias you wish to define.
594
604
595 # alias
605 # alias
596
606
597 #************************* end of file <ipythonrc> ************************
607 #************************* end of file <ipythonrc> ************************
@@ -1,2291 +1,2300 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 1326 2006-05-25 02:07:11Z fperez $
9 $Id: iplib.py 1329 2006-05-26 07:52:45Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from IPython import Release
31 from IPython import Release
32 __author__ = '%s <%s>\n%s <%s>' % \
32 __author__ = '%s <%s>\n%s <%s>' % \
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 __license__ = Release.license
34 __license__ = Release.license
35 __version__ = Release.version
35 __version__ = Release.version
36
36
37 # Python standard modules
37 # Python standard modules
38 import __main__
38 import __main__
39 import __builtin__
39 import __builtin__
40 import StringIO
40 import StringIO
41 import bdb
41 import bdb
42 import cPickle as pickle
42 import cPickle as pickle
43 import codeop
43 import codeop
44 import exceptions
44 import exceptions
45 import glob
45 import glob
46 import inspect
46 import inspect
47 import keyword
47 import keyword
48 import new
48 import new
49 import os
49 import os
50 import pdb
50 import pdb
51 import pydoc
51 import pydoc
52 import re
52 import re
53 import shutil
53 import shutil
54 import string
54 import string
55 import sys
55 import sys
56 import tempfile
56 import tempfile
57 import traceback
57 import traceback
58 import types
58 import types
59 import pickleshare
59 import pickleshare
60
60
61 from pprint import pprint, pformat
61 from pprint import pprint, pformat
62
62
63 # IPython's own modules
63 # IPython's own modules
64 import IPython
64 import IPython
65 from IPython import OInspect,PyColorize,ultraTB
65 from IPython import OInspect,PyColorize,ultraTB
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.FakeModule import FakeModule
67 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
69 from IPython.Logger import Logger
70 from IPython.Magic import Magic
70 from IPython.Magic import Magic
71 from IPython.Prompts import CachedOutput
71 from IPython.Prompts import CachedOutput
72 from IPython.ipstruct import Struct
72 from IPython.ipstruct import Struct
73 from IPython.background_jobs import BackgroundJobManager
73 from IPython.background_jobs import BackgroundJobManager
74 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.genutils import *
75 from IPython.genutils import *
76 import IPython.ipapi
76 import IPython.ipapi
77
77
78 # Globals
78 # Globals
79
79
80 # store the builtin raw_input globally, and use this always, in case user code
80 # store the builtin raw_input globally, and use this always, in case user code
81 # overwrites it (like wx.py.PyShell does)
81 # overwrites it (like wx.py.PyShell does)
82 raw_input_original = raw_input
82 raw_input_original = raw_input
83
83
84 # compiled regexps for autoindent management
84 # compiled regexps for autoindent management
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86
86
87
87
88 #****************************************************************************
88 #****************************************************************************
89 # Some utility function definitions
89 # Some utility function definitions
90
90
91 ini_spaces_re = re.compile(r'^(\s+)')
91 ini_spaces_re = re.compile(r'^(\s+)')
92
92
93 def num_ini_spaces(strng):
93 def num_ini_spaces(strng):
94 """Return the number of initial spaces in a string"""
94 """Return the number of initial spaces in a string"""
95
95
96 ini_spaces = ini_spaces_re.match(strng)
96 ini_spaces = ini_spaces_re.match(strng)
97 if ini_spaces:
97 if ini_spaces:
98 return ini_spaces.end()
98 return ini_spaces.end()
99 else:
99 else:
100 return 0
100 return 0
101
101
102 def softspace(file, newvalue):
102 def softspace(file, newvalue):
103 """Copied from code.py, to remove the dependency"""
103 """Copied from code.py, to remove the dependency"""
104
104
105 oldvalue = 0
105 oldvalue = 0
106 try:
106 try:
107 oldvalue = file.softspace
107 oldvalue = file.softspace
108 except AttributeError:
108 except AttributeError:
109 pass
109 pass
110 try:
110 try:
111 file.softspace = newvalue
111 file.softspace = newvalue
112 except (AttributeError, TypeError):
112 except (AttributeError, TypeError):
113 # "attribute-less object" or "read-only attributes"
113 # "attribute-less object" or "read-only attributes"
114 pass
114 pass
115 return oldvalue
115 return oldvalue
116
116
117
117
118 #****************************************************************************
118 #****************************************************************************
119 # Local use exceptions
119 # Local use exceptions
120 class SpaceInInput(exceptions.Exception): pass
120 class SpaceInInput(exceptions.Exception): pass
121
121
122
122
123 #****************************************************************************
123 #****************************************************************************
124 # Local use classes
124 # Local use classes
125 class Bunch: pass
125 class Bunch: pass
126
126
127 class Undefined: pass
127 class Undefined: pass
128
128
129 class InputList(list):
129 class InputList(list):
130 """Class to store user input.
130 """Class to store user input.
131
131
132 It's basically a list, but slices return a string instead of a list, thus
132 It's basically a list, but slices return a string instead of a list, thus
133 allowing things like (assuming 'In' is an instance):
133 allowing things like (assuming 'In' is an instance):
134
134
135 exec In[4:7]
135 exec In[4:7]
136
136
137 or
137 or
138
138
139 exec In[5:9] + In[14] + In[21:25]"""
139 exec In[5:9] + In[14] + In[21:25]"""
140
140
141 def __getslice__(self,i,j):
141 def __getslice__(self,i,j):
142 return ''.join(list.__getslice__(self,i,j))
142 return ''.join(list.__getslice__(self,i,j))
143
143
144 class SyntaxTB(ultraTB.ListTB):
144 class SyntaxTB(ultraTB.ListTB):
145 """Extension which holds some state: the last exception value"""
145 """Extension which holds some state: the last exception value"""
146
146
147 def __init__(self,color_scheme = 'NoColor'):
147 def __init__(self,color_scheme = 'NoColor'):
148 ultraTB.ListTB.__init__(self,color_scheme)
148 ultraTB.ListTB.__init__(self,color_scheme)
149 self.last_syntax_error = None
149 self.last_syntax_error = None
150
150
151 def __call__(self, etype, value, elist):
151 def __call__(self, etype, value, elist):
152 self.last_syntax_error = value
152 self.last_syntax_error = value
153 ultraTB.ListTB.__call__(self,etype,value,elist)
153 ultraTB.ListTB.__call__(self,etype,value,elist)
154
154
155 def clear_err_state(self):
155 def clear_err_state(self):
156 """Return the current error state and clear it"""
156 """Return the current error state and clear it"""
157 e = self.last_syntax_error
157 e = self.last_syntax_error
158 self.last_syntax_error = None
158 self.last_syntax_error = None
159 return e
159 return e
160
160
161 #****************************************************************************
161 #****************************************************************************
162 # Main IPython class
162 # Main IPython class
163
163
164 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
164 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
165 # until a full rewrite is made. I've cleaned all cross-class uses of
165 # until a full rewrite is made. I've cleaned all cross-class uses of
166 # attributes and methods, but too much user code out there relies on the
166 # attributes and methods, but too much user code out there relies on the
167 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
167 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
168 #
168 #
169 # But at least now, all the pieces have been separated and we could, in
169 # But at least now, all the pieces have been separated and we could, in
170 # principle, stop using the mixin. This will ease the transition to the
170 # principle, stop using the mixin. This will ease the transition to the
171 # chainsaw branch.
171 # chainsaw branch.
172
172
173 # For reference, the following is the list of 'self.foo' uses in the Magic
173 # For reference, the following is the list of 'self.foo' uses in the Magic
174 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
174 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
175 # class, to prevent clashes.
175 # class, to prevent clashes.
176
176
177 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
177 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
178 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
178 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
179 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
179 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
180 # 'self.value']
180 # 'self.value']
181
181
182 class InteractiveShell(object,Magic):
182 class InteractiveShell(object,Magic):
183 """An enhanced console for Python."""
183 """An enhanced console for Python."""
184
184
185 # class attribute to indicate whether the class supports threads or not.
185 # class attribute to indicate whether the class supports threads or not.
186 # Subclasses with thread support should override this as needed.
186 # Subclasses with thread support should override this as needed.
187 isthreaded = False
187 isthreaded = False
188
188
189 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
189 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
190 user_ns = None,user_global_ns=None,banner2='',
190 user_ns = None,user_global_ns=None,banner2='',
191 custom_exceptions=((),None),embedded=False):
191 custom_exceptions=((),None),embedded=False):
192
192
193
193
194 # log system
194 # log system
195 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
195 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
196
196
197 # some minimal strict typechecks. For some core data structures, I
197 # some minimal strict typechecks. For some core data structures, I
198 # want actual basic python types, not just anything that looks like
198 # want actual basic python types, not just anything that looks like
199 # one. This is especially true for namespaces.
199 # one. This is especially true for namespaces.
200 for ns in (user_ns,user_global_ns):
200 for ns in (user_ns,user_global_ns):
201 if ns is not None and type(ns) != types.DictType:
201 if ns is not None and type(ns) != types.DictType:
202 raise TypeError,'namespace must be a dictionary'
202 raise TypeError,'namespace must be a dictionary'
203
203
204 # Job manager (for jobs run as background threads)
204 # Job manager (for jobs run as background threads)
205 self.jobs = BackgroundJobManager()
205 self.jobs = BackgroundJobManager()
206
206
207 # Store the actual shell's name
207 # Store the actual shell's name
208 self.name = name
208 self.name = name
209
209
210 # We need to know whether the instance is meant for embedding, since
210 # We need to know whether the instance is meant for embedding, since
211 # global/local namespaces need to be handled differently in that case
211 # global/local namespaces need to be handled differently in that case
212 self.embedded = embedded
212 self.embedded = embedded
213
213
214 # command compiler
214 # command compiler
215 self.compile = codeop.CommandCompiler()
215 self.compile = codeop.CommandCompiler()
216
216
217 # User input buffer
217 # User input buffer
218 self.buffer = []
218 self.buffer = []
219
219
220 # Default name given in compilation of code
220 # Default name given in compilation of code
221 self.filename = '<ipython console>'
221 self.filename = '<ipython console>'
222
222
223 # Make an empty namespace, which extension writers can rely on both
223 # Make an empty namespace, which extension writers can rely on both
224 # existing and NEVER being used by ipython itself. This gives them a
224 # existing and NEVER being used by ipython itself. This gives them a
225 # convenient location for storing additional information and state
225 # convenient location for storing additional information and state
226 # their extensions may require, without fear of collisions with other
226 # their extensions may require, without fear of collisions with other
227 # ipython names that may develop later.
227 # ipython names that may develop later.
228 self.meta = Struct()
228 self.meta = Struct()
229
229
230 # Create the namespace where the user will operate. user_ns is
230 # Create the namespace where the user will operate. user_ns is
231 # normally the only one used, and it is passed to the exec calls as
231 # normally the only one used, and it is passed to the exec calls as
232 # the locals argument. But we do carry a user_global_ns namespace
232 # the locals argument. But we do carry a user_global_ns namespace
233 # given as the exec 'globals' argument, This is useful in embedding
233 # given as the exec 'globals' argument, This is useful in embedding
234 # situations where the ipython shell opens in a context where the
234 # situations where the ipython shell opens in a context where the
235 # distinction between locals and globals is meaningful.
235 # distinction between locals and globals is meaningful.
236
236
237 # FIXME. For some strange reason, __builtins__ is showing up at user
237 # FIXME. For some strange reason, __builtins__ is showing up at user
238 # level as a dict instead of a module. This is a manual fix, but I
238 # level as a dict instead of a module. This is a manual fix, but I
239 # should really track down where the problem is coming from. Alex
239 # should really track down where the problem is coming from. Alex
240 # Schmolck reported this problem first.
240 # Schmolck reported this problem first.
241
241
242 # A useful post by Alex Martelli on this topic:
242 # A useful post by Alex Martelli on this topic:
243 # Re: inconsistent value from __builtins__
243 # Re: inconsistent value from __builtins__
244 # Von: Alex Martelli <aleaxit@yahoo.com>
244 # Von: Alex Martelli <aleaxit@yahoo.com>
245 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
245 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
246 # Gruppen: comp.lang.python
246 # Gruppen: comp.lang.python
247
247
248 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
248 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
249 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
249 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
250 # > <type 'dict'>
250 # > <type 'dict'>
251 # > >>> print type(__builtins__)
251 # > >>> print type(__builtins__)
252 # > <type 'module'>
252 # > <type 'module'>
253 # > Is this difference in return value intentional?
253 # > Is this difference in return value intentional?
254
254
255 # Well, it's documented that '__builtins__' can be either a dictionary
255 # Well, it's documented that '__builtins__' can be either a dictionary
256 # or a module, and it's been that way for a long time. Whether it's
256 # or a module, and it's been that way for a long time. Whether it's
257 # intentional (or sensible), I don't know. In any case, the idea is
257 # intentional (or sensible), I don't know. In any case, the idea is
258 # that if you need to access the built-in namespace directly, you
258 # that if you need to access the built-in namespace directly, you
259 # should start with "import __builtin__" (note, no 's') which will
259 # should start with "import __builtin__" (note, no 's') which will
260 # definitely give you a module. Yeah, it's somewhat confusing:-(.
260 # definitely give you a module. Yeah, it's somewhat confusing:-(.
261
261
262 # These routines return properly built dicts as needed by the rest of
262 # These routines return properly built dicts as needed by the rest of
263 # the code, and can also be used by extension writers to generate
263 # the code, and can also be used by extension writers to generate
264 # properly initialized namespaces.
264 # properly initialized namespaces.
265 user_ns = IPython.ipapi.make_user_ns(user_ns)
265 user_ns = IPython.ipapi.make_user_ns(user_ns)
266 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
266 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
267
267
268 # Assign namespaces
268 # Assign namespaces
269 # This is the namespace where all normal user variables live
269 # This is the namespace where all normal user variables live
270 self.user_ns = user_ns
270 self.user_ns = user_ns
271 # Embedded instances require a separate namespace for globals.
271 # Embedded instances require a separate namespace for globals.
272 # Normally this one is unused by non-embedded instances.
272 # Normally this one is unused by non-embedded instances.
273 self.user_global_ns = user_global_ns
273 self.user_global_ns = user_global_ns
274 # A namespace to keep track of internal data structures to prevent
274 # A namespace to keep track of internal data structures to prevent
275 # them from cluttering user-visible stuff. Will be updated later
275 # them from cluttering user-visible stuff. Will be updated later
276 self.internal_ns = {}
276 self.internal_ns = {}
277
277
278 # Namespace of system aliases. Each entry in the alias
278 # Namespace of system aliases. Each entry in the alias
279 # table must be a 2-tuple of the form (N,name), where N is the number
279 # table must be a 2-tuple of the form (N,name), where N is the number
280 # of positional arguments of the alias.
280 # of positional arguments of the alias.
281 self.alias_table = {}
281 self.alias_table = {}
282
282
283 # A table holding all the namespaces IPython deals with, so that
283 # A table holding all the namespaces IPython deals with, so that
284 # introspection facilities can search easily.
284 # introspection facilities can search easily.
285 self.ns_table = {'user':user_ns,
285 self.ns_table = {'user':user_ns,
286 'user_global':user_global_ns,
286 'user_global':user_global_ns,
287 'alias':self.alias_table,
287 'alias':self.alias_table,
288 'internal':self.internal_ns,
288 'internal':self.internal_ns,
289 'builtin':__builtin__.__dict__
289 'builtin':__builtin__.__dict__
290 }
290 }
291
291
292 # The user namespace MUST have a pointer to the shell itself.
292 # The user namespace MUST have a pointer to the shell itself.
293 self.user_ns[name] = self
293 self.user_ns[name] = self
294
294
295 # We need to insert into sys.modules something that looks like a
295 # We need to insert into sys.modules something that looks like a
296 # module but which accesses the IPython namespace, for shelve and
296 # module but which accesses the IPython namespace, for shelve and
297 # pickle to work interactively. Normally they rely on getting
297 # pickle to work interactively. Normally they rely on getting
298 # everything out of __main__, but for embedding purposes each IPython
298 # everything out of __main__, but for embedding purposes each IPython
299 # instance has its own private namespace, so we can't go shoving
299 # instance has its own private namespace, so we can't go shoving
300 # everything into __main__.
300 # everything into __main__.
301
301
302 # note, however, that we should only do this for non-embedded
302 # note, however, that we should only do this for non-embedded
303 # ipythons, which really mimic the __main__.__dict__ with their own
303 # ipythons, which really mimic the __main__.__dict__ with their own
304 # namespace. Embedded instances, on the other hand, should not do
304 # namespace. Embedded instances, on the other hand, should not do
305 # this because they need to manage the user local/global namespaces
305 # this because they need to manage the user local/global namespaces
306 # only, but they live within a 'normal' __main__ (meaning, they
306 # only, but they live within a 'normal' __main__ (meaning, they
307 # shouldn't overtake the execution environment of the script they're
307 # shouldn't overtake the execution environment of the script they're
308 # embedded in).
308 # embedded in).
309
309
310 if not embedded:
310 if not embedded:
311 try:
311 try:
312 main_name = self.user_ns['__name__']
312 main_name = self.user_ns['__name__']
313 except KeyError:
313 except KeyError:
314 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
314 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
315 else:
315 else:
316 #print "pickle hack in place" # dbg
316 #print "pickle hack in place" # dbg
317 #print 'main_name:',main_name # dbg
317 #print 'main_name:',main_name # dbg
318 sys.modules[main_name] = FakeModule(self.user_ns)
318 sys.modules[main_name] = FakeModule(self.user_ns)
319
319
320 # List of input with multi-line handling.
320 # List of input with multi-line handling.
321 # Fill its zero entry, user counter starts at 1
321 # Fill its zero entry, user counter starts at 1
322 self.input_hist = InputList(['\n'])
322 self.input_hist = InputList(['\n'])
323 # This one will hold the 'raw' input history, without any
323 # This one will hold the 'raw' input history, without any
324 # pre-processing. This will allow users to retrieve the input just as
324 # pre-processing. This will allow users to retrieve the input just as
325 # it was exactly typed in by the user, with %hist -r.
325 # it was exactly typed in by the user, with %hist -r.
326 self.input_hist_raw = InputList(['\n'])
326 self.input_hist_raw = InputList(['\n'])
327
327
328 # list of visited directories
328 # list of visited directories
329 try:
329 try:
330 self.dir_hist = [os.getcwd()]
330 self.dir_hist = [os.getcwd()]
331 except IOError, e:
331 except IOError, e:
332 self.dir_hist = []
332 self.dir_hist = []
333
333
334 # dict of output history
334 # dict of output history
335 self.output_hist = {}
335 self.output_hist = {}
336
336
337 # dict of things NOT to alias (keywords, builtins and some magics)
337 # dict of things NOT to alias (keywords, builtins and some magics)
338 no_alias = {}
338 no_alias = {}
339 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
339 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
340 for key in keyword.kwlist + no_alias_magics:
340 for key in keyword.kwlist + no_alias_magics:
341 no_alias[key] = 1
341 no_alias[key] = 1
342 no_alias.update(__builtin__.__dict__)
342 no_alias.update(__builtin__.__dict__)
343 self.no_alias = no_alias
343 self.no_alias = no_alias
344
344
345 # make global variables for user access to these
345 # make global variables for user access to these
346 self.user_ns['_ih'] = self.input_hist
346 self.user_ns['_ih'] = self.input_hist
347 self.user_ns['_oh'] = self.output_hist
347 self.user_ns['_oh'] = self.output_hist
348 self.user_ns['_dh'] = self.dir_hist
348 self.user_ns['_dh'] = self.dir_hist
349
349
350 # user aliases to input and output histories
350 # user aliases to input and output histories
351 self.user_ns['In'] = self.input_hist
351 self.user_ns['In'] = self.input_hist
352 self.user_ns['Out'] = self.output_hist
352 self.user_ns['Out'] = self.output_hist
353
353
354 # Object variable to store code object waiting execution. This is
354 # Object variable to store code object waiting execution. This is
355 # used mainly by the multithreaded shells, but it can come in handy in
355 # used mainly by the multithreaded shells, but it can come in handy in
356 # other situations. No need to use a Queue here, since it's a single
356 # other situations. No need to use a Queue here, since it's a single
357 # item which gets cleared once run.
357 # item which gets cleared once run.
358 self.code_to_run = None
358 self.code_to_run = None
359
359
360 # escapes for automatic behavior on the command line
360 # escapes for automatic behavior on the command line
361 self.ESC_SHELL = '!'
361 self.ESC_SHELL = '!'
362 self.ESC_HELP = '?'
362 self.ESC_HELP = '?'
363 self.ESC_MAGIC = '%'
363 self.ESC_MAGIC = '%'
364 self.ESC_QUOTE = ','
364 self.ESC_QUOTE = ','
365 self.ESC_QUOTE2 = ';'
365 self.ESC_QUOTE2 = ';'
366 self.ESC_PAREN = '/'
366 self.ESC_PAREN = '/'
367
367
368 # And their associated handlers
368 # And their associated handlers
369 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
369 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
370 self.ESC_QUOTE : self.handle_auto,
370 self.ESC_QUOTE : self.handle_auto,
371 self.ESC_QUOTE2 : self.handle_auto,
371 self.ESC_QUOTE2 : self.handle_auto,
372 self.ESC_MAGIC : self.handle_magic,
372 self.ESC_MAGIC : self.handle_magic,
373 self.ESC_HELP : self.handle_help,
373 self.ESC_HELP : self.handle_help,
374 self.ESC_SHELL : self.handle_shell_escape,
374 self.ESC_SHELL : self.handle_shell_escape,
375 }
375 }
376
376
377 # class initializations
377 # class initializations
378 Magic.__init__(self,self)
378 Magic.__init__(self,self)
379
379
380 # Python source parser/formatter for syntax highlighting
380 # Python source parser/formatter for syntax highlighting
381 pyformat = PyColorize.Parser().format
381 pyformat = PyColorize.Parser().format
382 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
382 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
383
383
384 # hooks holds pointers used for user-side customizations
384 # hooks holds pointers used for user-side customizations
385 self.hooks = Struct()
385 self.hooks = Struct()
386
386
387 # Set all default hooks, defined in the IPython.hooks module.
387 # Set all default hooks, defined in the IPython.hooks module.
388 hooks = IPython.hooks
388 hooks = IPython.hooks
389 for hook_name in hooks.__all__:
389 for hook_name in hooks.__all__:
390 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
390 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
391 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
391 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
392 #print "bound hook",hook_name
392 #print "bound hook",hook_name
393
393
394 # Flag to mark unconditional exit
394 # Flag to mark unconditional exit
395 self.exit_now = False
395 self.exit_now = False
396
396
397 self.usage_min = """\
397 self.usage_min = """\
398 An enhanced console for Python.
398 An enhanced console for Python.
399 Some of its features are:
399 Some of its features are:
400 - Readline support if the readline library is present.
400 - Readline support if the readline library is present.
401 - Tab completion in the local namespace.
401 - Tab completion in the local namespace.
402 - Logging of input, see command-line options.
402 - Logging of input, see command-line options.
403 - System shell escape via ! , eg !ls.
403 - System shell escape via ! , eg !ls.
404 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
404 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
405 - Keeps track of locally defined variables via %who, %whos.
405 - Keeps track of locally defined variables via %who, %whos.
406 - Show object information with a ? eg ?x or x? (use ?? for more info).
406 - Show object information with a ? eg ?x or x? (use ?? for more info).
407 """
407 """
408 if usage: self.usage = usage
408 if usage: self.usage = usage
409 else: self.usage = self.usage_min
409 else: self.usage = self.usage_min
410
410
411 # Storage
411 # Storage
412 self.rc = rc # This will hold all configuration information
412 self.rc = rc # This will hold all configuration information
413 self.pager = 'less'
413 self.pager = 'less'
414 # temporary files used for various purposes. Deleted at exit.
414 # temporary files used for various purposes. Deleted at exit.
415 self.tempfiles = []
415 self.tempfiles = []
416
416
417 # Keep track of readline usage (later set by init_readline)
417 # Keep track of readline usage (later set by init_readline)
418 self.has_readline = False
418 self.has_readline = False
419
419
420 # template for logfile headers. It gets resolved at runtime by the
420 # template for logfile headers. It gets resolved at runtime by the
421 # logstart method.
421 # logstart method.
422 self.loghead_tpl = \
422 self.loghead_tpl = \
423 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
423 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
424 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
424 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
425 #log# opts = %s
425 #log# opts = %s
426 #log# args = %s
426 #log# args = %s
427 #log# It is safe to make manual edits below here.
427 #log# It is safe to make manual edits below here.
428 #log#-----------------------------------------------------------------------
428 #log#-----------------------------------------------------------------------
429 """
429 """
430 # for pushd/popd management
430 # for pushd/popd management
431 try:
431 try:
432 self.home_dir = get_home_dir()
432 self.home_dir = get_home_dir()
433 except HomeDirError,msg:
433 except HomeDirError,msg:
434 fatal(msg)
434 fatal(msg)
435
435
436 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
436 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
437
437
438 # Functions to call the underlying shell.
438 # Functions to call the underlying shell.
439
439
440 # utility to expand user variables via Itpl
440 # utility to expand user variables via Itpl
441 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
441 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
442 self.user_ns))
442 self.user_ns))
443 # The first is similar to os.system, but it doesn't return a value,
443 # The first is similar to os.system, but it doesn't return a value,
444 # and it allows interpolation of variables in the user's namespace.
444 # and it allows interpolation of variables in the user's namespace.
445 self.system = lambda cmd: shell(self.var_expand(cmd),
445 self.system = lambda cmd: shell(self.var_expand(cmd),
446 header='IPython system call: ',
446 header='IPython system call: ',
447 verbose=self.rc.system_verbose)
447 verbose=self.rc.system_verbose)
448 # These are for getoutput and getoutputerror:
448 # These are for getoutput and getoutputerror:
449 self.getoutput = lambda cmd: \
449 self.getoutput = lambda cmd: \
450 getoutput(self.var_expand(cmd),
450 getoutput(self.var_expand(cmd),
451 header='IPython system call: ',
451 header='IPython system call: ',
452 verbose=self.rc.system_verbose)
452 verbose=self.rc.system_verbose)
453 self.getoutputerror = lambda cmd: \
453 self.getoutputerror = lambda cmd: \
454 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
454 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
455 self.user_ns)),
455 self.user_ns)),
456 header='IPython system call: ',
456 header='IPython system call: ',
457 verbose=self.rc.system_verbose)
457 verbose=self.rc.system_verbose)
458
458
459 # RegExp for splitting line contents into pre-char//first
459 # RegExp for splitting line contents into pre-char//first
460 # word-method//rest. For clarity, each group in on one line.
460 # word-method//rest. For clarity, each group in on one line.
461
461
462 # WARNING: update the regexp if the above escapes are changed, as they
462 # WARNING: update the regexp if the above escapes are changed, as they
463 # are hardwired in.
463 # are hardwired in.
464
464
465 # Don't get carried away with trying to make the autocalling catch too
465 # Don't get carried away with trying to make the autocalling catch too
466 # much: it's better to be conservative rather than to trigger hidden
466 # much: it's better to be conservative rather than to trigger hidden
467 # evals() somewhere and end up causing side effects.
467 # evals() somewhere and end up causing side effects.
468
468
469 self.line_split = re.compile(r'^([\s*,;/])'
469 self.line_split = re.compile(r'^([\s*,;/])'
470 r'([\?\w\.]+\w*\s*)'
470 r'([\?\w\.]+\w*\s*)'
471 r'(\(?.*$)')
471 r'(\(?.*$)')
472
472
473 # Original re, keep around for a while in case changes break something
473 # Original re, keep around for a while in case changes break something
474 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
474 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
475 # r'(\s*[\?\w\.]+\w*\s*)'
475 # r'(\s*[\?\w\.]+\w*\s*)'
476 # r'(\(?.*$)')
476 # r'(\(?.*$)')
477
477
478 # RegExp to identify potential function names
478 # RegExp to identify potential function names
479 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
479 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
480
480
481 # RegExp to exclude strings with this start from autocalling. In
481 # RegExp to exclude strings with this start from autocalling. In
482 # particular, all binary operators should be excluded, so that if foo
482 # particular, all binary operators should be excluded, so that if foo
483 # is callable, foo OP bar doesn't become foo(OP bar), which is
483 # is callable, foo OP bar doesn't become foo(OP bar), which is
484 # invalid. The characters '!=()' don't need to be checked for, as the
484 # invalid. The characters '!=()' don't need to be checked for, as the
485 # _prefilter routine explicitely does so, to catch direct calls and
485 # _prefilter routine explicitely does so, to catch direct calls and
486 # rebindings of existing names.
486 # rebindings of existing names.
487
487
488 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
488 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
489 # it affects the rest of the group in square brackets.
489 # it affects the rest of the group in square brackets.
490 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
490 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
491 '|^is |^not |^in |^and |^or ')
491 '|^is |^not |^in |^and |^or ')
492
492
493 # try to catch also methods for stuff in lists/tuples/dicts: off
493 # try to catch also methods for stuff in lists/tuples/dicts: off
494 # (experimental). For this to work, the line_split regexp would need
494 # (experimental). For this to work, the line_split regexp would need
495 # to be modified so it wouldn't break things at '['. That line is
495 # to be modified so it wouldn't break things at '['. That line is
496 # nasty enough that I shouldn't change it until I can test it _well_.
496 # nasty enough that I shouldn't change it until I can test it _well_.
497 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
497 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
498
498
499 # keep track of where we started running (mainly for crash post-mortem)
499 # keep track of where we started running (mainly for crash post-mortem)
500 self.starting_dir = os.getcwd()
500 self.starting_dir = os.getcwd()
501
501
502 # Various switches which can be set
502 # Various switches which can be set
503 self.CACHELENGTH = 5000 # this is cheap, it's just text
503 self.CACHELENGTH = 5000 # this is cheap, it's just text
504 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
504 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
505 self.banner2 = banner2
505 self.banner2 = banner2
506
506
507 # TraceBack handlers:
507 # TraceBack handlers:
508
508
509 # Syntax error handler.
509 # Syntax error handler.
510 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
510 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
511
511
512 # The interactive one is initialized with an offset, meaning we always
512 # The interactive one is initialized with an offset, meaning we always
513 # want to remove the topmost item in the traceback, which is our own
513 # want to remove the topmost item in the traceback, which is our own
514 # internal code. Valid modes: ['Plain','Context','Verbose']
514 # internal code. Valid modes: ['Plain','Context','Verbose']
515 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
515 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
516 color_scheme='NoColor',
516 color_scheme='NoColor',
517 tb_offset = 1)
517 tb_offset = 1)
518
518
519 # IPython itself shouldn't crash. This will produce a detailed
519 # IPython itself shouldn't crash. This will produce a detailed
520 # post-mortem if it does. But we only install the crash handler for
520 # post-mortem if it does. But we only install the crash handler for
521 # non-threaded shells, the threaded ones use a normal verbose reporter
521 # non-threaded shells, the threaded ones use a normal verbose reporter
522 # and lose the crash handler. This is because exceptions in the main
522 # and lose the crash handler. This is because exceptions in the main
523 # thread (such as in GUI code) propagate directly to sys.excepthook,
523 # thread (such as in GUI code) propagate directly to sys.excepthook,
524 # and there's no point in printing crash dumps for every user exception.
524 # and there's no point in printing crash dumps for every user exception.
525 if self.isthreaded:
525 if self.isthreaded:
526 sys.excepthook = ultraTB.FormattedTB()
526 sys.excepthook = ultraTB.FormattedTB()
527 else:
527 else:
528 from IPython import CrashHandler
528 from IPython import CrashHandler
529 sys.excepthook = CrashHandler.CrashHandler(self)
529 sys.excepthook = CrashHandler.CrashHandler(self)
530
530
531 # The instance will store a pointer to this, so that runtime code
531 # The instance will store a pointer to this, so that runtime code
532 # (such as magics) can access it. This is because during the
532 # (such as magics) can access it. This is because during the
533 # read-eval loop, it gets temporarily overwritten (to deal with GUI
533 # read-eval loop, it gets temporarily overwritten (to deal with GUI
534 # frameworks).
534 # frameworks).
535 self.sys_excepthook = sys.excepthook
535 self.sys_excepthook = sys.excepthook
536
536
537 # and add any custom exception handlers the user may have specified
537 # and add any custom exception handlers the user may have specified
538 self.set_custom_exc(*custom_exceptions)
538 self.set_custom_exc(*custom_exceptions)
539
539
540 # Object inspector
541 self.inspector = OInspect.Inspector(OInspect.InspectColors,
542 PyColorize.ANSICodeColors,
543 'NoColor')
544 # indentation management
540 # indentation management
545 self.autoindent = False
541 self.autoindent = False
546 self.indent_current_nsp = 0
542 self.indent_current_nsp = 0
547
543
548 # Make some aliases automatically
544 # Make some aliases automatically
549 # Prepare list of shell aliases to auto-define
545 # Prepare list of shell aliases to auto-define
550 if os.name == 'posix':
546 if os.name == 'posix':
551 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
547 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
552 'mv mv -i','rm rm -i','cp cp -i',
548 'mv mv -i','rm rm -i','cp cp -i',
553 'cat cat','less less','clear clear',
549 'cat cat','less less','clear clear',
554 # a better ls
550 # a better ls
555 'ls ls -F',
551 'ls ls -F',
556 # long ls
552 # long ls
557 'll ls -lF',
553 'll ls -lF',
558 # color ls
554 # color ls
559 'lc ls -F -o --color',
555 'lc ls -F -o --color',
560 # ls normal files only
556 # ls normal files only
561 'lf ls -F -o --color %l | grep ^-',
557 'lf ls -F -o --color %l | grep ^-',
562 # ls symbolic links
558 # ls symbolic links
563 'lk ls -F -o --color %l | grep ^l',
559 'lk ls -F -o --color %l | grep ^l',
564 # directories or links to directories,
560 # directories or links to directories,
565 'ldir ls -F -o --color %l | grep /$',
561 'ldir ls -F -o --color %l | grep /$',
566 # things which are executable
562 # things which are executable
567 'lx ls -F -o --color %l | grep ^-..x',
563 'lx ls -F -o --color %l | grep ^-..x',
568 )
564 )
569 elif os.name in ['nt','dos']:
565 elif os.name in ['nt','dos']:
570 auto_alias = ('dir dir /on', 'ls dir /on',
566 auto_alias = ('dir dir /on', 'ls dir /on',
571 'ddir dir /ad /on', 'ldir dir /ad /on',
567 'ddir dir /ad /on', 'ldir dir /ad /on',
572 'mkdir mkdir','rmdir rmdir','echo echo',
568 'mkdir mkdir','rmdir rmdir','echo echo',
573 'ren ren','cls cls','copy copy')
569 'ren ren','cls cls','copy copy')
574 else:
570 else:
575 auto_alias = ()
571 auto_alias = ()
576 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
572 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
577 # Call the actual (public) initializer
573 # Call the actual (public) initializer
578 self.init_auto_alias()
574 self.init_auto_alias()
579
575
580 # Produce a public API instance
576 # Produce a public API instance
581 self.api = IPython.ipapi.IPApi(self)
577 self.api = IPython.ipapi.IPApi(self)
582
578
583 # track which builtins we add, so we can clean up later
579 # track which builtins we add, so we can clean up later
584 self.builtins_added = {}
580 self.builtins_added = {}
585 # This method will add the necessary builtins for operation, but
581 # This method will add the necessary builtins for operation, but
586 # tracking what it did via the builtins_added dict.
582 # tracking what it did via the builtins_added dict.
587 self.add_builtins()
583 self.add_builtins()
588
584
589 # end __init__
585 # end __init__
590
586
591 def pre_config_initialization(self):
587 def pre_config_initialization(self):
592 """Pre-configuration init method
588 """Pre-configuration init method
593
589
594 This is called before the configuration files are processed to
590 This is called before the configuration files are processed to
595 prepare the services the config files might need.
591 prepare the services the config files might need.
596
592
597 self.rc already has reasonable default values at this point.
593 self.rc already has reasonable default values at this point.
598 """
594 """
599 rc = self.rc
595 rc = self.rc
600
596
601 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
597 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
602
598
603 def post_config_initialization(self):
599 def post_config_initialization(self):
604 """Post configuration init method
600 """Post configuration init method
605
601
606 This is called after the configuration files have been processed to
602 This is called after the configuration files have been processed to
607 'finalize' the initialization."""
603 'finalize' the initialization."""
608
604
609 rc = self.rc
605 rc = self.rc
606
607 # Object inspector
608 self.inspector = OInspect.Inspector(OInspect.InspectColors,
609 PyColorize.ANSICodeColors,
610 'NoColor',
611 rc.object_info_string_level)
610
612
611 # Load readline proper
613 # Load readline proper
612 if rc.readline:
614 if rc.readline:
613 self.init_readline()
615 self.init_readline()
614
616
615 # local shortcut, this is used a LOT
617 # local shortcut, this is used a LOT
616 self.log = self.logger.log
618 self.log = self.logger.log
617
619
618 # Initialize cache, set in/out prompts and printing system
620 # Initialize cache, set in/out prompts and printing system
619 self.outputcache = CachedOutput(self,
621 self.outputcache = CachedOutput(self,
620 rc.cache_size,
622 rc.cache_size,
621 rc.pprint,
623 rc.pprint,
622 input_sep = rc.separate_in,
624 input_sep = rc.separate_in,
623 output_sep = rc.separate_out,
625 output_sep = rc.separate_out,
624 output_sep2 = rc.separate_out2,
626 output_sep2 = rc.separate_out2,
625 ps1 = rc.prompt_in1,
627 ps1 = rc.prompt_in1,
626 ps2 = rc.prompt_in2,
628 ps2 = rc.prompt_in2,
627 ps_out = rc.prompt_out,
629 ps_out = rc.prompt_out,
628 pad_left = rc.prompts_pad_left)
630 pad_left = rc.prompts_pad_left)
629
631
630 # user may have over-ridden the default print hook:
632 # user may have over-ridden the default print hook:
631 try:
633 try:
632 self.outputcache.__class__.display = self.hooks.display
634 self.outputcache.__class__.display = self.hooks.display
633 except AttributeError:
635 except AttributeError:
634 pass
636 pass
635
637
636 # I don't like assigning globally to sys, because it means when embedding
638 # I don't like assigning globally to sys, because it means when embedding
637 # instances, each embedded instance overrides the previous choice. But
639 # instances, each embedded instance overrides the previous choice. But
638 # sys.displayhook seems to be called internally by exec, so I don't see a
640 # sys.displayhook seems to be called internally by exec, so I don't see a
639 # way around it.
641 # way around it.
640 sys.displayhook = self.outputcache
642 sys.displayhook = self.outputcache
641
643
642 # Set user colors (don't do it in the constructor above so that it
644 # Set user colors (don't do it in the constructor above so that it
643 # doesn't crash if colors option is invalid)
645 # doesn't crash if colors option is invalid)
644 self.magic_colors(rc.colors)
646 self.magic_colors(rc.colors)
645
647
646 # Set calling of pdb on exceptions
648 # Set calling of pdb on exceptions
647 self.call_pdb = rc.pdb
649 self.call_pdb = rc.pdb
648
650
649 # Load user aliases
651 # Load user aliases
650 for alias in rc.alias:
652 for alias in rc.alias:
651 self.magic_alias(alias)
653 self.magic_alias(alias)
652 self.hooks.late_startup_hook()
654 self.hooks.late_startup_hook()
653
655
654 for batchfile in [path(arg) for arg in self.rc.args
656 for batchfile in [path(arg) for arg in self.rc.args
655 if arg.lower().endswith('.ipy')]:
657 if arg.lower().endswith('.ipy')]:
656 if not batchfile.isfile():
658 if not batchfile.isfile():
657 print "No such batch file:", batchfile
659 print "No such batch file:", batchfile
658 continue
660 continue
659 self.api.runlines(batchfile.text())
661 self.api.runlines(batchfile.text())
660
662
661 def add_builtins(self):
663 def add_builtins(self):
662 """Store ipython references into the builtin namespace.
664 """Store ipython references into the builtin namespace.
663
665
664 Some parts of ipython operate via builtins injected here, which hold a
666 Some parts of ipython operate via builtins injected here, which hold a
665 reference to IPython itself."""
667 reference to IPython itself."""
666
668
667 # TODO: deprecate all except _ip; 'jobs' should be installed
669 # TODO: deprecate all except _ip; 'jobs' should be installed
668 # by an extension and the rest are under _ip, ipalias is redundant
670 # by an extension and the rest are under _ip, ipalias is redundant
669 builtins_new = dict(__IPYTHON__ = self,
671 builtins_new = dict(__IPYTHON__ = self,
670 ip_set_hook = self.set_hook,
672 ip_set_hook = self.set_hook,
671 jobs = self.jobs,
673 jobs = self.jobs,
672 ipmagic = self.ipmagic,
674 ipmagic = self.ipmagic,
673 ipalias = self.ipalias,
675 ipalias = self.ipalias,
674 ipsystem = self.ipsystem,
676 ipsystem = self.ipsystem,
675 _ip = self.api
677 _ip = self.api
676 )
678 )
677 for biname,bival in builtins_new.items():
679 for biname,bival in builtins_new.items():
678 try:
680 try:
679 # store the orignal value so we can restore it
681 # store the orignal value so we can restore it
680 self.builtins_added[biname] = __builtin__.__dict__[biname]
682 self.builtins_added[biname] = __builtin__.__dict__[biname]
681 except KeyError:
683 except KeyError:
682 # or mark that it wasn't defined, and we'll just delete it at
684 # or mark that it wasn't defined, and we'll just delete it at
683 # cleanup
685 # cleanup
684 self.builtins_added[biname] = Undefined
686 self.builtins_added[biname] = Undefined
685 __builtin__.__dict__[biname] = bival
687 __builtin__.__dict__[biname] = bival
686
688
687 # Keep in the builtins a flag for when IPython is active. We set it
689 # Keep in the builtins a flag for when IPython is active. We set it
688 # with setdefault so that multiple nested IPythons don't clobber one
690 # with setdefault so that multiple nested IPythons don't clobber one
689 # another. Each will increase its value by one upon being activated,
691 # another. Each will increase its value by one upon being activated,
690 # which also gives us a way to determine the nesting level.
692 # which also gives us a way to determine the nesting level.
691 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
693 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
692
694
693 def clean_builtins(self):
695 def clean_builtins(self):
694 """Remove any builtins which might have been added by add_builtins, or
696 """Remove any builtins which might have been added by add_builtins, or
695 restore overwritten ones to their previous values."""
697 restore overwritten ones to their previous values."""
696 for biname,bival in self.builtins_added.items():
698 for biname,bival in self.builtins_added.items():
697 if bival is Undefined:
699 if bival is Undefined:
698 del __builtin__.__dict__[biname]
700 del __builtin__.__dict__[biname]
699 else:
701 else:
700 __builtin__.__dict__[biname] = bival
702 __builtin__.__dict__[biname] = bival
701 self.builtins_added.clear()
703 self.builtins_added.clear()
702
704
703 def set_hook(self,name,hook, priority = 50):
705 def set_hook(self,name,hook, priority = 50):
704 """set_hook(name,hook) -> sets an internal IPython hook.
706 """set_hook(name,hook) -> sets an internal IPython hook.
705
707
706 IPython exposes some of its internal API as user-modifiable hooks. By
708 IPython exposes some of its internal API as user-modifiable hooks. By
707 adding your function to one of these hooks, you can modify IPython's
709 adding your function to one of these hooks, you can modify IPython's
708 behavior to call at runtime your own routines."""
710 behavior to call at runtime your own routines."""
709
711
710 # At some point in the future, this should validate the hook before it
712 # At some point in the future, this should validate the hook before it
711 # accepts it. Probably at least check that the hook takes the number
713 # accepts it. Probably at least check that the hook takes the number
712 # of args it's supposed to.
714 # of args it's supposed to.
713 dp = getattr(self.hooks, name, None)
715 dp = getattr(self.hooks, name, None)
714 if name not in IPython.hooks.__all__:
716 if name not in IPython.hooks.__all__:
715 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
717 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
716 if not dp:
718 if not dp:
717 dp = IPython.hooks.CommandChainDispatcher()
719 dp = IPython.hooks.CommandChainDispatcher()
718
720
719 f = new.instancemethod(hook,self,self.__class__)
721 f = new.instancemethod(hook,self,self.__class__)
720 try:
722 try:
721 dp.add(f,priority)
723 dp.add(f,priority)
722 except AttributeError:
724 except AttributeError:
723 # it was not commandchain, plain old func - replace
725 # it was not commandchain, plain old func - replace
724 dp = f
726 dp = f
725
727
726 setattr(self.hooks,name, dp)
728 setattr(self.hooks,name, dp)
727
729
728
730
729 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
731 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
730
732
731 def set_custom_exc(self,exc_tuple,handler):
733 def set_custom_exc(self,exc_tuple,handler):
732 """set_custom_exc(exc_tuple,handler)
734 """set_custom_exc(exc_tuple,handler)
733
735
734 Set a custom exception handler, which will be called if any of the
736 Set a custom exception handler, which will be called if any of the
735 exceptions in exc_tuple occur in the mainloop (specifically, in the
737 exceptions in exc_tuple occur in the mainloop (specifically, in the
736 runcode() method.
738 runcode() method.
737
739
738 Inputs:
740 Inputs:
739
741
740 - exc_tuple: a *tuple* of valid exceptions to call the defined
742 - exc_tuple: a *tuple* of valid exceptions to call the defined
741 handler for. It is very important that you use a tuple, and NOT A
743 handler for. It is very important that you use a tuple, and NOT A
742 LIST here, because of the way Python's except statement works. If
744 LIST here, because of the way Python's except statement works. If
743 you only want to trap a single exception, use a singleton tuple:
745 you only want to trap a single exception, use a singleton tuple:
744
746
745 exc_tuple == (MyCustomException,)
747 exc_tuple == (MyCustomException,)
746
748
747 - handler: this must be defined as a function with the following
749 - handler: this must be defined as a function with the following
748 basic interface: def my_handler(self,etype,value,tb).
750 basic interface: def my_handler(self,etype,value,tb).
749
751
750 This will be made into an instance method (via new.instancemethod)
752 This will be made into an instance method (via new.instancemethod)
751 of IPython itself, and it will be called if any of the exceptions
753 of IPython itself, and it will be called if any of the exceptions
752 listed in the exc_tuple are caught. If the handler is None, an
754 listed in the exc_tuple are caught. If the handler is None, an
753 internal basic one is used, which just prints basic info.
755 internal basic one is used, which just prints basic info.
754
756
755 WARNING: by putting in your own exception handler into IPython's main
757 WARNING: by putting in your own exception handler into IPython's main
756 execution loop, you run a very good chance of nasty crashes. This
758 execution loop, you run a very good chance of nasty crashes. This
757 facility should only be used if you really know what you are doing."""
759 facility should only be used if you really know what you are doing."""
758
760
759 assert type(exc_tuple)==type(()) , \
761 assert type(exc_tuple)==type(()) , \
760 "The custom exceptions must be given AS A TUPLE."
762 "The custom exceptions must be given AS A TUPLE."
761
763
762 def dummy_handler(self,etype,value,tb):
764 def dummy_handler(self,etype,value,tb):
763 print '*** Simple custom exception handler ***'
765 print '*** Simple custom exception handler ***'
764 print 'Exception type :',etype
766 print 'Exception type :',etype
765 print 'Exception value:',value
767 print 'Exception value:',value
766 print 'Traceback :',tb
768 print 'Traceback :',tb
767 print 'Source code :','\n'.join(self.buffer)
769 print 'Source code :','\n'.join(self.buffer)
768
770
769 if handler is None: handler = dummy_handler
771 if handler is None: handler = dummy_handler
770
772
771 self.CustomTB = new.instancemethod(handler,self,self.__class__)
773 self.CustomTB = new.instancemethod(handler,self,self.__class__)
772 self.custom_exceptions = exc_tuple
774 self.custom_exceptions = exc_tuple
773
775
774 def set_custom_completer(self,completer,pos=0):
776 def set_custom_completer(self,completer,pos=0):
775 """set_custom_completer(completer,pos=0)
777 """set_custom_completer(completer,pos=0)
776
778
777 Adds a new custom completer function.
779 Adds a new custom completer function.
778
780
779 The position argument (defaults to 0) is the index in the completers
781 The position argument (defaults to 0) is the index in the completers
780 list where you want the completer to be inserted."""
782 list where you want the completer to be inserted."""
781
783
782 newcomp = new.instancemethod(completer,self.Completer,
784 newcomp = new.instancemethod(completer,self.Completer,
783 self.Completer.__class__)
785 self.Completer.__class__)
784 self.Completer.matchers.insert(pos,newcomp)
786 self.Completer.matchers.insert(pos,newcomp)
785
787
786 def _get_call_pdb(self):
788 def _get_call_pdb(self):
787 return self._call_pdb
789 return self._call_pdb
788
790
789 def _set_call_pdb(self,val):
791 def _set_call_pdb(self,val):
790
792
791 if val not in (0,1,False,True):
793 if val not in (0,1,False,True):
792 raise ValueError,'new call_pdb value must be boolean'
794 raise ValueError,'new call_pdb value must be boolean'
793
795
794 # store value in instance
796 # store value in instance
795 self._call_pdb = val
797 self._call_pdb = val
796
798
797 # notify the actual exception handlers
799 # notify the actual exception handlers
798 self.InteractiveTB.call_pdb = val
800 self.InteractiveTB.call_pdb = val
799 if self.isthreaded:
801 if self.isthreaded:
800 try:
802 try:
801 self.sys_excepthook.call_pdb = val
803 self.sys_excepthook.call_pdb = val
802 except:
804 except:
803 warn('Failed to activate pdb for threaded exception handler')
805 warn('Failed to activate pdb for threaded exception handler')
804
806
805 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
807 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
806 'Control auto-activation of pdb at exceptions')
808 'Control auto-activation of pdb at exceptions')
807
809
808
810
809 # These special functions get installed in the builtin namespace, to
811 # These special functions get installed in the builtin namespace, to
810 # provide programmatic (pure python) access to magics, aliases and system
812 # provide programmatic (pure python) access to magics, aliases and system
811 # calls. This is important for logging, user scripting, and more.
813 # calls. This is important for logging, user scripting, and more.
812
814
813 # We are basically exposing, via normal python functions, the three
815 # We are basically exposing, via normal python functions, the three
814 # mechanisms in which ipython offers special call modes (magics for
816 # mechanisms in which ipython offers special call modes (magics for
815 # internal control, aliases for direct system access via pre-selected
817 # internal control, aliases for direct system access via pre-selected
816 # names, and !cmd for calling arbitrary system commands).
818 # names, and !cmd for calling arbitrary system commands).
817
819
818 def ipmagic(self,arg_s):
820 def ipmagic(self,arg_s):
819 """Call a magic function by name.
821 """Call a magic function by name.
820
822
821 Input: a string containing the name of the magic function to call and any
823 Input: a string containing the name of the magic function to call and any
822 additional arguments to be passed to the magic.
824 additional arguments to be passed to the magic.
823
825
824 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
826 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
825 prompt:
827 prompt:
826
828
827 In[1]: %name -opt foo bar
829 In[1]: %name -opt foo bar
828
830
829 To call a magic without arguments, simply use ipmagic('name').
831 To call a magic without arguments, simply use ipmagic('name').
830
832
831 This provides a proper Python function to call IPython's magics in any
833 This provides a proper Python function to call IPython's magics in any
832 valid Python code you can type at the interpreter, including loops and
834 valid Python code you can type at the interpreter, including loops and
833 compound statements. It is added by IPython to the Python builtin
835 compound statements. It is added by IPython to the Python builtin
834 namespace upon initialization."""
836 namespace upon initialization."""
835
837
836 args = arg_s.split(' ',1)
838 args = arg_s.split(' ',1)
837 magic_name = args[0]
839 magic_name = args[0]
838 magic_name = magic_name.lstrip(self.ESC_MAGIC)
840 magic_name = magic_name.lstrip(self.ESC_MAGIC)
839
841
840 try:
842 try:
841 magic_args = args[1]
843 magic_args = args[1]
842 except IndexError:
844 except IndexError:
843 magic_args = ''
845 magic_args = ''
844 fn = getattr(self,'magic_'+magic_name,None)
846 fn = getattr(self,'magic_'+magic_name,None)
845 if fn is None:
847 if fn is None:
846 error("Magic function `%s` not found." % magic_name)
848 error("Magic function `%s` not found." % magic_name)
847 else:
849 else:
848 magic_args = self.var_expand(magic_args)
850 magic_args = self.var_expand(magic_args)
849 return fn(magic_args)
851 return fn(magic_args)
850
852
851 def ipalias(self,arg_s):
853 def ipalias(self,arg_s):
852 """Call an alias by name.
854 """Call an alias by name.
853
855
854 Input: a string containing the name of the alias to call and any
856 Input: a string containing the name of the alias to call and any
855 additional arguments to be passed to the magic.
857 additional arguments to be passed to the magic.
856
858
857 ipalias('name -opt foo bar') is equivalent to typing at the ipython
859 ipalias('name -opt foo bar') is equivalent to typing at the ipython
858 prompt:
860 prompt:
859
861
860 In[1]: name -opt foo bar
862 In[1]: name -opt foo bar
861
863
862 To call an alias without arguments, simply use ipalias('name').
864 To call an alias without arguments, simply use ipalias('name').
863
865
864 This provides a proper Python function to call IPython's aliases in any
866 This provides a proper Python function to call IPython's aliases in any
865 valid Python code you can type at the interpreter, including loops and
867 valid Python code you can type at the interpreter, including loops and
866 compound statements. It is added by IPython to the Python builtin
868 compound statements. It is added by IPython to the Python builtin
867 namespace upon initialization."""
869 namespace upon initialization."""
868
870
869 args = arg_s.split(' ',1)
871 args = arg_s.split(' ',1)
870 alias_name = args[0]
872 alias_name = args[0]
871 try:
873 try:
872 alias_args = args[1]
874 alias_args = args[1]
873 except IndexError:
875 except IndexError:
874 alias_args = ''
876 alias_args = ''
875 if alias_name in self.alias_table:
877 if alias_name in self.alias_table:
876 self.call_alias(alias_name,alias_args)
878 self.call_alias(alias_name,alias_args)
877 else:
879 else:
878 error("Alias `%s` not found." % alias_name)
880 error("Alias `%s` not found." % alias_name)
879
881
880 def ipsystem(self,arg_s):
882 def ipsystem(self,arg_s):
881 """Make a system call, using IPython."""
883 """Make a system call, using IPython."""
882
884
883 self.system(arg_s)
885 self.system(arg_s)
884
886
885 def complete(self,text):
887 def complete(self,text):
886 """Return a sorted list of all possible completions on text.
888 """Return a sorted list of all possible completions on text.
887
889
888 Inputs:
890 Inputs:
889
891
890 - text: a string of text to be completed on.
892 - text: a string of text to be completed on.
891
893
892 This is a wrapper around the completion mechanism, similar to what
894 This is a wrapper around the completion mechanism, similar to what
893 readline does at the command line when the TAB key is hit. By
895 readline does at the command line when the TAB key is hit. By
894 exposing it as a method, it can be used by other non-readline
896 exposing it as a method, it can be used by other non-readline
895 environments (such as GUIs) for text completion.
897 environments (such as GUIs) for text completion.
896
898
897 Simple usage example:
899 Simple usage example:
898
900
899 In [1]: x = 'hello'
901 In [1]: x = 'hello'
900
902
901 In [2]: __IP.complete('x.l')
903 In [2]: __IP.complete('x.l')
902 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
904 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
903
905
904 complete = self.Completer.complete
906 complete = self.Completer.complete
905 state = 0
907 state = 0
906 # use a dict so we get unique keys, since ipyhton's multiple
908 # use a dict so we get unique keys, since ipyhton's multiple
907 # completers can return duplicates.
909 # completers can return duplicates.
908 comps = {}
910 comps = {}
909 while True:
911 while True:
910 newcomp = complete(text,state)
912 newcomp = complete(text,state)
911 if newcomp is None:
913 if newcomp is None:
912 break
914 break
913 comps[newcomp] = 1
915 comps[newcomp] = 1
914 state += 1
916 state += 1
915 outcomps = comps.keys()
917 outcomps = comps.keys()
916 outcomps.sort()
918 outcomps.sort()
917 return outcomps
919 return outcomps
918
920
919 def set_completer_frame(self, frame=None):
921 def set_completer_frame(self, frame=None):
920 if frame:
922 if frame:
921 self.Completer.namespace = frame.f_locals
923 self.Completer.namespace = frame.f_locals
922 self.Completer.global_namespace = frame.f_globals
924 self.Completer.global_namespace = frame.f_globals
923 else:
925 else:
924 self.Completer.namespace = self.user_ns
926 self.Completer.namespace = self.user_ns
925 self.Completer.global_namespace = self.user_global_ns
927 self.Completer.global_namespace = self.user_global_ns
926
928
927 def init_auto_alias(self):
929 def init_auto_alias(self):
928 """Define some aliases automatically.
930 """Define some aliases automatically.
929
931
930 These are ALL parameter-less aliases"""
932 These are ALL parameter-less aliases"""
931
933
932 for alias,cmd in self.auto_alias:
934 for alias,cmd in self.auto_alias:
933 self.alias_table[alias] = (0,cmd)
935 self.alias_table[alias] = (0,cmd)
934
936
935 def alias_table_validate(self,verbose=0):
937 def alias_table_validate(self,verbose=0):
936 """Update information about the alias table.
938 """Update information about the alias table.
937
939
938 In particular, make sure no Python keywords/builtins are in it."""
940 In particular, make sure no Python keywords/builtins are in it."""
939
941
940 no_alias = self.no_alias
942 no_alias = self.no_alias
941 for k in self.alias_table.keys():
943 for k in self.alias_table.keys():
942 if k in no_alias:
944 if k in no_alias:
943 del self.alias_table[k]
945 del self.alias_table[k]
944 if verbose:
946 if verbose:
945 print ("Deleting alias <%s>, it's a Python "
947 print ("Deleting alias <%s>, it's a Python "
946 "keyword or builtin." % k)
948 "keyword or builtin." % k)
947
949
948 def set_autoindent(self,value=None):
950 def set_autoindent(self,value=None):
949 """Set the autoindent flag, checking for readline support.
951 """Set the autoindent flag, checking for readline support.
950
952
951 If called with no arguments, it acts as a toggle."""
953 If called with no arguments, it acts as a toggle."""
952
954
953 if not self.has_readline:
955 if not self.has_readline:
954 if os.name == 'posix':
956 if os.name == 'posix':
955 warn("The auto-indent feature requires the readline library")
957 warn("The auto-indent feature requires the readline library")
956 self.autoindent = 0
958 self.autoindent = 0
957 return
959 return
958 if value is None:
960 if value is None:
959 self.autoindent = not self.autoindent
961 self.autoindent = not self.autoindent
960 else:
962 else:
961 self.autoindent = value
963 self.autoindent = value
962
964
963 def rc_set_toggle(self,rc_field,value=None):
965 def rc_set_toggle(self,rc_field,value=None):
964 """Set or toggle a field in IPython's rc config. structure.
966 """Set or toggle a field in IPython's rc config. structure.
965
967
966 If called with no arguments, it acts as a toggle.
968 If called with no arguments, it acts as a toggle.
967
969
968 If called with a non-existent field, the resulting AttributeError
970 If called with a non-existent field, the resulting AttributeError
969 exception will propagate out."""
971 exception will propagate out."""
970
972
971 rc_val = getattr(self.rc,rc_field)
973 rc_val = getattr(self.rc,rc_field)
972 if value is None:
974 if value is None:
973 value = not rc_val
975 value = not rc_val
974 setattr(self.rc,rc_field,value)
976 setattr(self.rc,rc_field,value)
975
977
976 def user_setup(self,ipythondir,rc_suffix,mode='install'):
978 def user_setup(self,ipythondir,rc_suffix,mode='install'):
977 """Install the user configuration directory.
979 """Install the user configuration directory.
978
980
979 Can be called when running for the first time or to upgrade the user's
981 Can be called when running for the first time or to upgrade the user's
980 .ipython/ directory with the mode parameter. Valid modes are 'install'
982 .ipython/ directory with the mode parameter. Valid modes are 'install'
981 and 'upgrade'."""
983 and 'upgrade'."""
982
984
983 def wait():
985 def wait():
984 try:
986 try:
985 raw_input("Please press <RETURN> to start IPython.")
987 raw_input("Please press <RETURN> to start IPython.")
986 except EOFError:
988 except EOFError:
987 print >> Term.cout
989 print >> Term.cout
988 print '*'*70
990 print '*'*70
989
991
990 cwd = os.getcwd() # remember where we started
992 cwd = os.getcwd() # remember where we started
991 glb = glob.glob
993 glb = glob.glob
992 print '*'*70
994 print '*'*70
993 if mode == 'install':
995 if mode == 'install':
994 print \
996 print \
995 """Welcome to IPython. I will try to create a personal configuration directory
997 """Welcome to IPython. I will try to create a personal configuration directory
996 where you can customize many aspects of IPython's functionality in:\n"""
998 where you can customize many aspects of IPython's functionality in:\n"""
997 else:
999 else:
998 print 'I am going to upgrade your configuration in:'
1000 print 'I am going to upgrade your configuration in:'
999
1001
1000 print ipythondir
1002 print ipythondir
1001
1003
1002 rcdirend = os.path.join('IPython','UserConfig')
1004 rcdirend = os.path.join('IPython','UserConfig')
1003 cfg = lambda d: os.path.join(d,rcdirend)
1005 cfg = lambda d: os.path.join(d,rcdirend)
1004 try:
1006 try:
1005 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1007 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1006 except IOError:
1008 except IOError:
1007 warning = """
1009 warning = """
1008 Installation error. IPython's directory was not found.
1010 Installation error. IPython's directory was not found.
1009
1011
1010 Check the following:
1012 Check the following:
1011
1013
1012 The ipython/IPython directory should be in a directory belonging to your
1014 The ipython/IPython directory should be in a directory belonging to your
1013 PYTHONPATH environment variable (that is, it should be in a directory
1015 PYTHONPATH environment variable (that is, it should be in a directory
1014 belonging to sys.path). You can copy it explicitly there or just link to it.
1016 belonging to sys.path). You can copy it explicitly there or just link to it.
1015
1017
1016 IPython will proceed with builtin defaults.
1018 IPython will proceed with builtin defaults.
1017 """
1019 """
1018 warn(warning)
1020 warn(warning)
1019 wait()
1021 wait()
1020 return
1022 return
1021
1023
1022 if mode == 'install':
1024 if mode == 'install':
1023 try:
1025 try:
1024 shutil.copytree(rcdir,ipythondir)
1026 shutil.copytree(rcdir,ipythondir)
1025 os.chdir(ipythondir)
1027 os.chdir(ipythondir)
1026 rc_files = glb("ipythonrc*")
1028 rc_files = glb("ipythonrc*")
1027 for rc_file in rc_files:
1029 for rc_file in rc_files:
1028 os.rename(rc_file,rc_file+rc_suffix)
1030 os.rename(rc_file,rc_file+rc_suffix)
1029 except:
1031 except:
1030 warning = """
1032 warning = """
1031
1033
1032 There was a problem with the installation:
1034 There was a problem with the installation:
1033 %s
1035 %s
1034 Try to correct it or contact the developers if you think it's a bug.
1036 Try to correct it or contact the developers if you think it's a bug.
1035 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1037 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1036 warn(warning)
1038 warn(warning)
1037 wait()
1039 wait()
1038 return
1040 return
1039
1041
1040 elif mode == 'upgrade':
1042 elif mode == 'upgrade':
1041 try:
1043 try:
1042 os.chdir(ipythondir)
1044 os.chdir(ipythondir)
1043 except:
1045 except:
1044 print """
1046 print """
1045 Can not upgrade: changing to directory %s failed. Details:
1047 Can not upgrade: changing to directory %s failed. Details:
1046 %s
1048 %s
1047 """ % (ipythondir,sys.exc_info()[1])
1049 """ % (ipythondir,sys.exc_info()[1])
1048 wait()
1050 wait()
1049 return
1051 return
1050 else:
1052 else:
1051 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1053 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1052 for new_full_path in sources:
1054 for new_full_path in sources:
1053 new_filename = os.path.basename(new_full_path)
1055 new_filename = os.path.basename(new_full_path)
1054 if new_filename.startswith('ipythonrc'):
1056 if new_filename.startswith('ipythonrc'):
1055 new_filename = new_filename + rc_suffix
1057 new_filename = new_filename + rc_suffix
1056 # The config directory should only contain files, skip any
1058 # The config directory should only contain files, skip any
1057 # directories which may be there (like CVS)
1059 # directories which may be there (like CVS)
1058 if os.path.isdir(new_full_path):
1060 if os.path.isdir(new_full_path):
1059 continue
1061 continue
1060 if os.path.exists(new_filename):
1062 if os.path.exists(new_filename):
1061 old_file = new_filename+'.old'
1063 old_file = new_filename+'.old'
1062 if os.path.exists(old_file):
1064 if os.path.exists(old_file):
1063 os.remove(old_file)
1065 os.remove(old_file)
1064 os.rename(new_filename,old_file)
1066 os.rename(new_filename,old_file)
1065 shutil.copy(new_full_path,new_filename)
1067 shutil.copy(new_full_path,new_filename)
1066 else:
1068 else:
1067 raise ValueError,'unrecognized mode for install:',`mode`
1069 raise ValueError,'unrecognized mode for install:',`mode`
1068
1070
1069 # Fix line-endings to those native to each platform in the config
1071 # Fix line-endings to those native to each platform in the config
1070 # directory.
1072 # directory.
1071 try:
1073 try:
1072 os.chdir(ipythondir)
1074 os.chdir(ipythondir)
1073 except:
1075 except:
1074 print """
1076 print """
1075 Problem: changing to directory %s failed.
1077 Problem: changing to directory %s failed.
1076 Details:
1078 Details:
1077 %s
1079 %s
1078
1080
1079 Some configuration files may have incorrect line endings. This should not
1081 Some configuration files may have incorrect line endings. This should not
1080 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1082 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1081 wait()
1083 wait()
1082 else:
1084 else:
1083 for fname in glb('ipythonrc*'):
1085 for fname in glb('ipythonrc*'):
1084 try:
1086 try:
1085 native_line_ends(fname,backup=0)
1087 native_line_ends(fname,backup=0)
1086 except IOError:
1088 except IOError:
1087 pass
1089 pass
1088
1090
1089 if mode == 'install':
1091 if mode == 'install':
1090 print """
1092 print """
1091 Successful installation!
1093 Successful installation!
1092
1094
1093 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1095 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1094 IPython manual (there are both HTML and PDF versions supplied with the
1096 IPython manual (there are both HTML and PDF versions supplied with the
1095 distribution) to make sure that your system environment is properly configured
1097 distribution) to make sure that your system environment is properly configured
1096 to take advantage of IPython's features.
1098 to take advantage of IPython's features.
1097
1099
1098 Important note: the configuration system has changed! The old system is
1100 Important note: the configuration system has changed! The old system is
1099 still in place, but its setting may be partly overridden by the settings in
1101 still in place, but its setting may be partly overridden by the settings in
1100 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1102 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1101 if some of the new settings bother you.
1103 if some of the new settings bother you.
1102
1104
1103 """
1105 """
1104 else:
1106 else:
1105 print """
1107 print """
1106 Successful upgrade!
1108 Successful upgrade!
1107
1109
1108 All files in your directory:
1110 All files in your directory:
1109 %(ipythondir)s
1111 %(ipythondir)s
1110 which would have been overwritten by the upgrade were backed up with a .old
1112 which would have been overwritten by the upgrade were backed up with a .old
1111 extension. If you had made particular customizations in those files you may
1113 extension. If you had made particular customizations in those files you may
1112 want to merge them back into the new files.""" % locals()
1114 want to merge them back into the new files.""" % locals()
1113 wait()
1115 wait()
1114 os.chdir(cwd)
1116 os.chdir(cwd)
1115 # end user_setup()
1117 # end user_setup()
1116
1118
1117 def atexit_operations(self):
1119 def atexit_operations(self):
1118 """This will be executed at the time of exit.
1120 """This will be executed at the time of exit.
1119
1121
1120 Saving of persistent data should be performed here. """
1122 Saving of persistent data should be performed here. """
1121
1123
1122 #print '*** IPython exit cleanup ***' # dbg
1124 #print '*** IPython exit cleanup ***' # dbg
1123 # input history
1125 # input history
1124 self.savehist()
1126 self.savehist()
1125
1127
1126 # Cleanup all tempfiles left around
1128 # Cleanup all tempfiles left around
1127 for tfile in self.tempfiles:
1129 for tfile in self.tempfiles:
1128 try:
1130 try:
1129 os.unlink(tfile)
1131 os.unlink(tfile)
1130 except OSError:
1132 except OSError:
1131 pass
1133 pass
1132
1134
1133 # save the "persistent data" catch-all dictionary
1135 # save the "persistent data" catch-all dictionary
1134 self.hooks.shutdown_hook()
1136 self.hooks.shutdown_hook()
1135
1137
1136 def savehist(self):
1138 def savehist(self):
1137 """Save input history to a file (via readline library)."""
1139 """Save input history to a file (via readline library)."""
1138 try:
1140 try:
1139 self.readline.write_history_file(self.histfile)
1141 self.readline.write_history_file(self.histfile)
1140 except:
1142 except:
1141 print 'Unable to save IPython command history to file: ' + \
1143 print 'Unable to save IPython command history to file: ' + \
1142 `self.histfile`
1144 `self.histfile`
1143
1145
1144 def pre_readline(self):
1146 def pre_readline(self):
1145 """readline hook to be used at the start of each line.
1147 """readline hook to be used at the start of each line.
1146
1148
1147 Currently it handles auto-indent only."""
1149 Currently it handles auto-indent only."""
1148
1150
1149 #debugx('self.indent_current_nsp','pre_readline:')
1151 #debugx('self.indent_current_nsp','pre_readline:')
1150 self.readline.insert_text(self.indent_current_str())
1152 self.readline.insert_text(self.indent_current_str())
1151
1153
1152 def init_readline(self):
1154 def init_readline(self):
1153 """Command history completion/saving/reloading."""
1155 """Command history completion/saving/reloading."""
1154
1156
1155 import IPython.rlineimpl as readline
1157 import IPython.rlineimpl as readline
1156 if not readline.have_readline:
1158 if not readline.have_readline:
1157 self.has_readline = 0
1159 self.has_readline = 0
1158 self.readline = None
1160 self.readline = None
1159 # no point in bugging windows users with this every time:
1161 # no point in bugging windows users with this every time:
1160 warn('Readline services not available on this platform.')
1162 warn('Readline services not available on this platform.')
1161 else:
1163 else:
1162 sys.modules['readline'] = readline
1164 sys.modules['readline'] = readline
1163 import atexit
1165 import atexit
1164 from IPython.completer import IPCompleter
1166 from IPython.completer import IPCompleter
1165 self.Completer = IPCompleter(self,
1167 self.Completer = IPCompleter(self,
1166 self.user_ns,
1168 self.user_ns,
1167 self.user_global_ns,
1169 self.user_global_ns,
1168 self.rc.readline_omit__names,
1170 self.rc.readline_omit__names,
1169 self.alias_table)
1171 self.alias_table)
1170
1172
1171 # Platform-specific configuration
1173 # Platform-specific configuration
1172 if os.name == 'nt':
1174 if os.name == 'nt':
1173 self.readline_startup_hook = readline.set_pre_input_hook
1175 self.readline_startup_hook = readline.set_pre_input_hook
1174 else:
1176 else:
1175 self.readline_startup_hook = readline.set_startup_hook
1177 self.readline_startup_hook = readline.set_startup_hook
1176
1178
1177 # Load user's initrc file (readline config)
1179 # Load user's initrc file (readline config)
1178 inputrc_name = os.environ.get('INPUTRC')
1180 inputrc_name = os.environ.get('INPUTRC')
1179 if inputrc_name is None:
1181 if inputrc_name is None:
1180 home_dir = get_home_dir()
1182 home_dir = get_home_dir()
1181 if home_dir is not None:
1183 if home_dir is not None:
1182 inputrc_name = os.path.join(home_dir,'.inputrc')
1184 inputrc_name = os.path.join(home_dir,'.inputrc')
1183 if os.path.isfile(inputrc_name):
1185 if os.path.isfile(inputrc_name):
1184 try:
1186 try:
1185 readline.read_init_file(inputrc_name)
1187 readline.read_init_file(inputrc_name)
1186 except:
1188 except:
1187 warn('Problems reading readline initialization file <%s>'
1189 warn('Problems reading readline initialization file <%s>'
1188 % inputrc_name)
1190 % inputrc_name)
1189
1191
1190 self.has_readline = 1
1192 self.has_readline = 1
1191 self.readline = readline
1193 self.readline = readline
1192 # save this in sys so embedded copies can restore it properly
1194 # save this in sys so embedded copies can restore it properly
1193 sys.ipcompleter = self.Completer.complete
1195 sys.ipcompleter = self.Completer.complete
1194 readline.set_completer(self.Completer.complete)
1196 readline.set_completer(self.Completer.complete)
1195
1197
1196 # Configure readline according to user's prefs
1198 # Configure readline according to user's prefs
1197 for rlcommand in self.rc.readline_parse_and_bind:
1199 for rlcommand in self.rc.readline_parse_and_bind:
1198 readline.parse_and_bind(rlcommand)
1200 readline.parse_and_bind(rlcommand)
1199
1201
1200 # remove some chars from the delimiters list
1202 # remove some chars from the delimiters list
1201 delims = readline.get_completer_delims()
1203 delims = readline.get_completer_delims()
1202 delims = delims.translate(string._idmap,
1204 delims = delims.translate(string._idmap,
1203 self.rc.readline_remove_delims)
1205 self.rc.readline_remove_delims)
1204 readline.set_completer_delims(delims)
1206 readline.set_completer_delims(delims)
1205 # otherwise we end up with a monster history after a while:
1207 # otherwise we end up with a monster history after a while:
1206 readline.set_history_length(1000)
1208 readline.set_history_length(1000)
1207 try:
1209 try:
1208 #print '*** Reading readline history' # dbg
1210 #print '*** Reading readline history' # dbg
1209 readline.read_history_file(self.histfile)
1211 readline.read_history_file(self.histfile)
1210 except IOError:
1212 except IOError:
1211 pass # It doesn't exist yet.
1213 pass # It doesn't exist yet.
1212
1214
1213 atexit.register(self.atexit_operations)
1215 atexit.register(self.atexit_operations)
1214 del atexit
1216 del atexit
1215
1217
1216 # Configure auto-indent for all platforms
1218 # Configure auto-indent for all platforms
1217 self.set_autoindent(self.rc.autoindent)
1219 self.set_autoindent(self.rc.autoindent)
1218
1220
1219 def _should_recompile(self,e):
1221 def _should_recompile(self,e):
1220 """Utility routine for edit_syntax_error"""
1222 """Utility routine for edit_syntax_error"""
1221
1223
1222 if e.filename in ('<ipython console>','<input>','<string>',
1224 if e.filename in ('<ipython console>','<input>','<string>',
1223 '<console>','<BackgroundJob compilation>',
1225 '<console>','<BackgroundJob compilation>',
1224 None):
1226 None):
1225
1227
1226 return False
1228 return False
1227 try:
1229 try:
1228 if (self.rc.autoedit_syntax and
1230 if (self.rc.autoedit_syntax and
1229 not ask_yes_no('Return to editor to correct syntax error? '
1231 not ask_yes_no('Return to editor to correct syntax error? '
1230 '[Y/n] ','y')):
1232 '[Y/n] ','y')):
1231 return False
1233 return False
1232 except EOFError:
1234 except EOFError:
1233 return False
1235 return False
1234
1236
1235 def int0(x):
1237 def int0(x):
1236 try:
1238 try:
1237 return int(x)
1239 return int(x)
1238 except TypeError:
1240 except TypeError:
1239 return 0
1241 return 0
1240 # always pass integer line and offset values to editor hook
1242 # always pass integer line and offset values to editor hook
1241 self.hooks.fix_error_editor(e.filename,
1243 self.hooks.fix_error_editor(e.filename,
1242 int0(e.lineno),int0(e.offset),e.msg)
1244 int0(e.lineno),int0(e.offset),e.msg)
1243 return True
1245 return True
1244
1246
1245 def edit_syntax_error(self):
1247 def edit_syntax_error(self):
1246 """The bottom half of the syntax error handler called in the main loop.
1248 """The bottom half of the syntax error handler called in the main loop.
1247
1249
1248 Loop until syntax error is fixed or user cancels.
1250 Loop until syntax error is fixed or user cancels.
1249 """
1251 """
1250
1252
1251 while self.SyntaxTB.last_syntax_error:
1253 while self.SyntaxTB.last_syntax_error:
1252 # copy and clear last_syntax_error
1254 # copy and clear last_syntax_error
1253 err = self.SyntaxTB.clear_err_state()
1255 err = self.SyntaxTB.clear_err_state()
1254 if not self._should_recompile(err):
1256 if not self._should_recompile(err):
1255 return
1257 return
1256 try:
1258 try:
1257 # may set last_syntax_error again if a SyntaxError is raised
1259 # may set last_syntax_error again if a SyntaxError is raised
1258 self.safe_execfile(err.filename,self.shell.user_ns)
1260 self.safe_execfile(err.filename,self.shell.user_ns)
1259 except:
1261 except:
1260 self.showtraceback()
1262 self.showtraceback()
1261 else:
1263 else:
1262 try:
1264 try:
1263 f = file(err.filename)
1265 f = file(err.filename)
1264 try:
1266 try:
1265 sys.displayhook(f.read())
1267 sys.displayhook(f.read())
1266 finally:
1268 finally:
1267 f.close()
1269 f.close()
1268 except:
1270 except:
1269 self.showtraceback()
1271 self.showtraceback()
1270
1272
1271 def showsyntaxerror(self, filename=None):
1273 def showsyntaxerror(self, filename=None):
1272 """Display the syntax error that just occurred.
1274 """Display the syntax error that just occurred.
1273
1275
1274 This doesn't display a stack trace because there isn't one.
1276 This doesn't display a stack trace because there isn't one.
1275
1277
1276 If a filename is given, it is stuffed in the exception instead
1278 If a filename is given, it is stuffed in the exception instead
1277 of what was there before (because Python's parser always uses
1279 of what was there before (because Python's parser always uses
1278 "<string>" when reading from a string).
1280 "<string>" when reading from a string).
1279 """
1281 """
1280 etype, value, last_traceback = sys.exc_info()
1282 etype, value, last_traceback = sys.exc_info()
1281
1283
1282 # See note about these variables in showtraceback() below
1284 # See note about these variables in showtraceback() below
1283 sys.last_type = etype
1285 sys.last_type = etype
1284 sys.last_value = value
1286 sys.last_value = value
1285 sys.last_traceback = last_traceback
1287 sys.last_traceback = last_traceback
1286
1288
1287 if filename and etype is SyntaxError:
1289 if filename and etype is SyntaxError:
1288 # Work hard to stuff the correct filename in the exception
1290 # Work hard to stuff the correct filename in the exception
1289 try:
1291 try:
1290 msg, (dummy_filename, lineno, offset, line) = value
1292 msg, (dummy_filename, lineno, offset, line) = value
1291 except:
1293 except:
1292 # Not the format we expect; leave it alone
1294 # Not the format we expect; leave it alone
1293 pass
1295 pass
1294 else:
1296 else:
1295 # Stuff in the right filename
1297 # Stuff in the right filename
1296 try:
1298 try:
1297 # Assume SyntaxError is a class exception
1299 # Assume SyntaxError is a class exception
1298 value = SyntaxError(msg, (filename, lineno, offset, line))
1300 value = SyntaxError(msg, (filename, lineno, offset, line))
1299 except:
1301 except:
1300 # If that failed, assume SyntaxError is a string
1302 # If that failed, assume SyntaxError is a string
1301 value = msg, (filename, lineno, offset, line)
1303 value = msg, (filename, lineno, offset, line)
1302 self.SyntaxTB(etype,value,[])
1304 self.SyntaxTB(etype,value,[])
1303
1305
1304 def debugger(self):
1306 def debugger(self):
1305 """Call the pdb debugger."""
1307 """Call the pdb debugger."""
1306
1308
1307 if not self.rc.pdb:
1309 if not self.rc.pdb:
1308 return
1310 return
1309 pdb.pm()
1311 pdb.pm()
1310
1312
1311 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1313 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1312 """Display the exception that just occurred.
1314 """Display the exception that just occurred.
1313
1315
1314 If nothing is known about the exception, this is the method which
1316 If nothing is known about the exception, this is the method which
1315 should be used throughout the code for presenting user tracebacks,
1317 should be used throughout the code for presenting user tracebacks,
1316 rather than directly invoking the InteractiveTB object.
1318 rather than directly invoking the InteractiveTB object.
1317
1319
1318 A specific showsyntaxerror() also exists, but this method can take
1320 A specific showsyntaxerror() also exists, but this method can take
1319 care of calling it if needed, so unless you are explicitly catching a
1321 care of calling it if needed, so unless you are explicitly catching a
1320 SyntaxError exception, don't try to analyze the stack manually and
1322 SyntaxError exception, don't try to analyze the stack manually and
1321 simply call this method."""
1323 simply call this method."""
1322
1324
1323 # Though this won't be called by syntax errors in the input line,
1325 # Though this won't be called by syntax errors in the input line,
1324 # there may be SyntaxError cases whith imported code.
1326 # there may be SyntaxError cases whith imported code.
1325 if exc_tuple is None:
1327 if exc_tuple is None:
1326 etype, value, tb = sys.exc_info()
1328 etype, value, tb = sys.exc_info()
1327 else:
1329 else:
1328 etype, value, tb = exc_tuple
1330 etype, value, tb = exc_tuple
1329 if etype is SyntaxError:
1331 if etype is SyntaxError:
1330 self.showsyntaxerror(filename)
1332 self.showsyntaxerror(filename)
1331 else:
1333 else:
1332 # WARNING: these variables are somewhat deprecated and not
1334 # WARNING: these variables are somewhat deprecated and not
1333 # necessarily safe to use in a threaded environment, but tools
1335 # necessarily safe to use in a threaded environment, but tools
1334 # like pdb depend on their existence, so let's set them. If we
1336 # like pdb depend on their existence, so let's set them. If we
1335 # find problems in the field, we'll need to revisit their use.
1337 # find problems in the field, we'll need to revisit their use.
1336 sys.last_type = etype
1338 sys.last_type = etype
1337 sys.last_value = value
1339 sys.last_value = value
1338 sys.last_traceback = tb
1340 sys.last_traceback = tb
1339
1341
1340 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1342 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1341 if self.InteractiveTB.call_pdb and self.has_readline:
1343 if self.InteractiveTB.call_pdb and self.has_readline:
1342 # pdb mucks up readline, fix it back
1344 # pdb mucks up readline, fix it back
1343 self.readline.set_completer(self.Completer.complete)
1345 self.readline.set_completer(self.Completer.complete)
1344
1346
1345 def mainloop(self,banner=None):
1347 def mainloop(self,banner=None):
1346 """Creates the local namespace and starts the mainloop.
1348 """Creates the local namespace and starts the mainloop.
1347
1349
1348 If an optional banner argument is given, it will override the
1350 If an optional banner argument is given, it will override the
1349 internally created default banner."""
1351 internally created default banner."""
1350
1352
1351 if self.rc.c: # Emulate Python's -c option
1353 if self.rc.c: # Emulate Python's -c option
1352 self.exec_init_cmd()
1354 self.exec_init_cmd()
1353 if banner is None:
1355 if banner is None:
1354 if not self.rc.banner:
1356 if not self.rc.banner:
1355 banner = ''
1357 banner = ''
1356 # banner is string? Use it directly!
1358 # banner is string? Use it directly!
1357 elif isinstance(self.rc.banner,basestring):
1359 elif isinstance(self.rc.banner,basestring):
1358 banner = self.rc.banner
1360 banner = self.rc.banner
1359 else:
1361 else:
1360 banner = self.BANNER+self.banner2
1362 banner = self.BANNER+self.banner2
1361
1363
1362 self.interact(banner)
1364 self.interact(banner)
1363
1365
1364 def exec_init_cmd(self):
1366 def exec_init_cmd(self):
1365 """Execute a command given at the command line.
1367 """Execute a command given at the command line.
1366
1368
1367 This emulates Python's -c option."""
1369 This emulates Python's -c option."""
1368
1370
1369 #sys.argv = ['-c']
1371 #sys.argv = ['-c']
1370 self.push(self.rc.c)
1372 self.push(self.rc.c)
1371
1373
1372 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1374 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1373 """Embeds IPython into a running python program.
1375 """Embeds IPython into a running python program.
1374
1376
1375 Input:
1377 Input:
1376
1378
1377 - header: An optional header message can be specified.
1379 - header: An optional header message can be specified.
1378
1380
1379 - local_ns, global_ns: working namespaces. If given as None, the
1381 - local_ns, global_ns: working namespaces. If given as None, the
1380 IPython-initialized one is updated with __main__.__dict__, so that
1382 IPython-initialized one is updated with __main__.__dict__, so that
1381 program variables become visible but user-specific configuration
1383 program variables become visible but user-specific configuration
1382 remains possible.
1384 remains possible.
1383
1385
1384 - stack_depth: specifies how many levels in the stack to go to
1386 - stack_depth: specifies how many levels in the stack to go to
1385 looking for namespaces (when local_ns and global_ns are None). This
1387 looking for namespaces (when local_ns and global_ns are None). This
1386 allows an intermediate caller to make sure that this function gets
1388 allows an intermediate caller to make sure that this function gets
1387 the namespace from the intended level in the stack. By default (0)
1389 the namespace from the intended level in the stack. By default (0)
1388 it will get its locals and globals from the immediate caller.
1390 it will get its locals and globals from the immediate caller.
1389
1391
1390 Warning: it's possible to use this in a program which is being run by
1392 Warning: it's possible to use this in a program which is being run by
1391 IPython itself (via %run), but some funny things will happen (a few
1393 IPython itself (via %run), but some funny things will happen (a few
1392 globals get overwritten). In the future this will be cleaned up, as
1394 globals get overwritten). In the future this will be cleaned up, as
1393 there is no fundamental reason why it can't work perfectly."""
1395 there is no fundamental reason why it can't work perfectly."""
1394
1396
1395 # Get locals and globals from caller
1397 # Get locals and globals from caller
1396 if local_ns is None or global_ns is None:
1398 if local_ns is None or global_ns is None:
1397 call_frame = sys._getframe(stack_depth).f_back
1399 call_frame = sys._getframe(stack_depth).f_back
1398
1400
1399 if local_ns is None:
1401 if local_ns is None:
1400 local_ns = call_frame.f_locals
1402 local_ns = call_frame.f_locals
1401 if global_ns is None:
1403 if global_ns is None:
1402 global_ns = call_frame.f_globals
1404 global_ns = call_frame.f_globals
1403
1405
1404 # Update namespaces and fire up interpreter
1406 # Update namespaces and fire up interpreter
1405
1407
1406 # The global one is easy, we can just throw it in
1408 # The global one is easy, we can just throw it in
1407 self.user_global_ns = global_ns
1409 self.user_global_ns = global_ns
1408
1410
1409 # but the user/local one is tricky: ipython needs it to store internal
1411 # but the user/local one is tricky: ipython needs it to store internal
1410 # data, but we also need the locals. We'll copy locals in the user
1412 # data, but we also need the locals. We'll copy locals in the user
1411 # one, but will track what got copied so we can delete them at exit.
1413 # one, but will track what got copied so we can delete them at exit.
1412 # This is so that a later embedded call doesn't see locals from a
1414 # This is so that a later embedded call doesn't see locals from a
1413 # previous call (which most likely existed in a separate scope).
1415 # previous call (which most likely existed in a separate scope).
1414 local_varnames = local_ns.keys()
1416 local_varnames = local_ns.keys()
1415 self.user_ns.update(local_ns)
1417 self.user_ns.update(local_ns)
1416
1418
1417 # Patch for global embedding to make sure that things don't overwrite
1419 # Patch for global embedding to make sure that things don't overwrite
1418 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1420 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1419 # FIXME. Test this a bit more carefully (the if.. is new)
1421 # FIXME. Test this a bit more carefully (the if.. is new)
1420 if local_ns is None and global_ns is None:
1422 if local_ns is None and global_ns is None:
1421 self.user_global_ns.update(__main__.__dict__)
1423 self.user_global_ns.update(__main__.__dict__)
1422
1424
1423 # make sure the tab-completer has the correct frame information, so it
1425 # make sure the tab-completer has the correct frame information, so it
1424 # actually completes using the frame's locals/globals
1426 # actually completes using the frame's locals/globals
1425 self.set_completer_frame()
1427 self.set_completer_frame()
1426
1428
1427 # before activating the interactive mode, we need to make sure that
1429 # before activating the interactive mode, we need to make sure that
1428 # all names in the builtin namespace needed by ipython point to
1430 # all names in the builtin namespace needed by ipython point to
1429 # ourselves, and not to other instances.
1431 # ourselves, and not to other instances.
1430 self.add_builtins()
1432 self.add_builtins()
1431
1433
1432 self.interact(header)
1434 self.interact(header)
1433
1435
1434 # now, purge out the user namespace from anything we might have added
1436 # now, purge out the user namespace from anything we might have added
1435 # from the caller's local namespace
1437 # from the caller's local namespace
1436 delvar = self.user_ns.pop
1438 delvar = self.user_ns.pop
1437 for var in local_varnames:
1439 for var in local_varnames:
1438 delvar(var,None)
1440 delvar(var,None)
1439 # and clean builtins we may have overridden
1441 # and clean builtins we may have overridden
1440 self.clean_builtins()
1442 self.clean_builtins()
1441
1443
1442 def interact(self, banner=None):
1444 def interact(self, banner=None):
1443 """Closely emulate the interactive Python console.
1445 """Closely emulate the interactive Python console.
1444
1446
1445 The optional banner argument specify the banner to print
1447 The optional banner argument specify the banner to print
1446 before the first interaction; by default it prints a banner
1448 before the first interaction; by default it prints a banner
1447 similar to the one printed by the real Python interpreter,
1449 similar to the one printed by the real Python interpreter,
1448 followed by the current class name in parentheses (so as not
1450 followed by the current class name in parentheses (so as not
1449 to confuse this with the real interpreter -- since it's so
1451 to confuse this with the real interpreter -- since it's so
1450 close!).
1452 close!).
1451
1453
1452 """
1454 """
1453 cprt = 'Type "copyright", "credits" or "license" for more information.'
1455 cprt = 'Type "copyright", "credits" or "license" for more information.'
1454 if banner is None:
1456 if banner is None:
1455 self.write("Python %s on %s\n%s\n(%s)\n" %
1457 self.write("Python %s on %s\n%s\n(%s)\n" %
1456 (sys.version, sys.platform, cprt,
1458 (sys.version, sys.platform, cprt,
1457 self.__class__.__name__))
1459 self.__class__.__name__))
1458 else:
1460 else:
1459 self.write(banner)
1461 self.write(banner)
1460
1462
1461 more = 0
1463 more = 0
1462
1464
1463 # Mark activity in the builtins
1465 # Mark activity in the builtins
1464 __builtin__.__dict__['__IPYTHON__active'] += 1
1466 __builtin__.__dict__['__IPYTHON__active'] += 1
1465
1467
1466 # exit_now is set by a call to %Exit or %Quit
1468 # exit_now is set by a call to %Exit or %Quit
1467 self.exit_now = False
1469 self.exit_now = False
1468 while not self.exit_now:
1470 while not self.exit_now:
1469 if more:
1471 if more:
1470 prompt = self.outputcache.prompt2
1472 prompt = self.outputcache.prompt2
1471 if self.autoindent:
1473 if self.autoindent:
1472 self.readline_startup_hook(self.pre_readline)
1474 self.readline_startup_hook(self.pre_readline)
1473 else:
1475 else:
1474 prompt = self.outputcache.prompt1
1476 prompt = self.outputcache.prompt1
1475 try:
1477 try:
1476 line = self.raw_input(prompt,more)
1478 line = self.raw_input(prompt,more)
1477 if self.autoindent:
1479 if self.autoindent:
1478 self.readline_startup_hook(None)
1480 self.readline_startup_hook(None)
1479 except KeyboardInterrupt:
1481 except KeyboardInterrupt:
1480 self.write('\nKeyboardInterrupt\n')
1482 self.write('\nKeyboardInterrupt\n')
1481 self.resetbuffer()
1483 self.resetbuffer()
1482 # keep cache in sync with the prompt counter:
1484 # keep cache in sync with the prompt counter:
1483 self.outputcache.prompt_count -= 1
1485 self.outputcache.prompt_count -= 1
1484
1486
1485 if self.autoindent:
1487 if self.autoindent:
1486 self.indent_current_nsp = 0
1488 self.indent_current_nsp = 0
1487 more = 0
1489 more = 0
1488 except EOFError:
1490 except EOFError:
1489 if self.autoindent:
1491 if self.autoindent:
1490 self.readline_startup_hook(None)
1492 self.readline_startup_hook(None)
1491 self.write('\n')
1493 self.write('\n')
1492 self.exit()
1494 self.exit()
1493 except bdb.BdbQuit:
1495 except bdb.BdbQuit:
1494 warn('The Python debugger has exited with a BdbQuit exception.\n'
1496 warn('The Python debugger has exited with a BdbQuit exception.\n'
1495 'Because of how pdb handles the stack, it is impossible\n'
1497 'Because of how pdb handles the stack, it is impossible\n'
1496 'for IPython to properly format this particular exception.\n'
1498 'for IPython to properly format this particular exception.\n'
1497 'IPython will resume normal operation.')
1499 'IPython will resume normal operation.')
1498 except:
1500 except:
1499 # exceptions here are VERY RARE, but they can be triggered
1501 # exceptions here are VERY RARE, but they can be triggered
1500 # asynchronously by signal handlers, for example.
1502 # asynchronously by signal handlers, for example.
1501 self.showtraceback()
1503 self.showtraceback()
1502 else:
1504 else:
1503 more = self.push(line)
1505 more = self.push(line)
1504 if (self.SyntaxTB.last_syntax_error and
1506 if (self.SyntaxTB.last_syntax_error and
1505 self.rc.autoedit_syntax):
1507 self.rc.autoedit_syntax):
1506 self.edit_syntax_error()
1508 self.edit_syntax_error()
1507
1509
1508 # We are off again...
1510 # We are off again...
1509 __builtin__.__dict__['__IPYTHON__active'] -= 1
1511 __builtin__.__dict__['__IPYTHON__active'] -= 1
1510
1512
1511 def excepthook(self, etype, value, tb):
1513 def excepthook(self, etype, value, tb):
1512 """One more defense for GUI apps that call sys.excepthook.
1514 """One more defense for GUI apps that call sys.excepthook.
1513
1515
1514 GUI frameworks like wxPython trap exceptions and call
1516 GUI frameworks like wxPython trap exceptions and call
1515 sys.excepthook themselves. I guess this is a feature that
1517 sys.excepthook themselves. I guess this is a feature that
1516 enables them to keep running after exceptions that would
1518 enables them to keep running after exceptions that would
1517 otherwise kill their mainloop. This is a bother for IPython
1519 otherwise kill their mainloop. This is a bother for IPython
1518 which excepts to catch all of the program exceptions with a try:
1520 which excepts to catch all of the program exceptions with a try:
1519 except: statement.
1521 except: statement.
1520
1522
1521 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1523 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1522 any app directly invokes sys.excepthook, it will look to the user like
1524 any app directly invokes sys.excepthook, it will look to the user like
1523 IPython crashed. In order to work around this, we can disable the
1525 IPython crashed. In order to work around this, we can disable the
1524 CrashHandler and replace it with this excepthook instead, which prints a
1526 CrashHandler and replace it with this excepthook instead, which prints a
1525 regular traceback using our InteractiveTB. In this fashion, apps which
1527 regular traceback using our InteractiveTB. In this fashion, apps which
1526 call sys.excepthook will generate a regular-looking exception from
1528 call sys.excepthook will generate a regular-looking exception from
1527 IPython, and the CrashHandler will only be triggered by real IPython
1529 IPython, and the CrashHandler will only be triggered by real IPython
1528 crashes.
1530 crashes.
1529
1531
1530 This hook should be used sparingly, only in places which are not likely
1532 This hook should be used sparingly, only in places which are not likely
1531 to be true IPython errors.
1533 to be true IPython errors.
1532 """
1534 """
1533 self.showtraceback((etype,value,tb),tb_offset=0)
1535 self.showtraceback((etype,value,tb),tb_offset=0)
1534
1536
1535 def transform_alias(self, alias,rest=''):
1537 def transform_alias(self, alias,rest=''):
1536 """ Transform alias to system command string
1538 """ Transform alias to system command string
1537
1539
1538 """
1540 """
1539 nargs,cmd = self.alias_table[alias]
1541 nargs,cmd = self.alias_table[alias]
1540 if ' ' in cmd and os.path.isfile(cmd):
1542 if ' ' in cmd and os.path.isfile(cmd):
1541 cmd = '"%s"' % cmd
1543 cmd = '"%s"' % cmd
1542
1544
1543 # Expand the %l special to be the user's input line
1545 # Expand the %l special to be the user's input line
1544 if cmd.find('%l') >= 0:
1546 if cmd.find('%l') >= 0:
1545 cmd = cmd.replace('%l',rest)
1547 cmd = cmd.replace('%l',rest)
1546 rest = ''
1548 rest = ''
1547 if nargs==0:
1549 if nargs==0:
1548 # Simple, argument-less aliases
1550 # Simple, argument-less aliases
1549 cmd = '%s %s' % (cmd,rest)
1551 cmd = '%s %s' % (cmd,rest)
1550 else:
1552 else:
1551 # Handle aliases with positional arguments
1553 # Handle aliases with positional arguments
1552 args = rest.split(None,nargs)
1554 args = rest.split(None,nargs)
1553 if len(args)< nargs:
1555 if len(args)< nargs:
1554 error('Alias <%s> requires %s arguments, %s given.' %
1556 error('Alias <%s> requires %s arguments, %s given.' %
1555 (alias,nargs,len(args)))
1557 (alias,nargs,len(args)))
1556 return None
1558 return None
1557 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1559 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1558 # Now call the macro, evaluating in the user's namespace
1560 # Now call the macro, evaluating in the user's namespace
1559
1561
1560 return cmd
1562 return cmd
1561
1563
1562 def call_alias(self,alias,rest=''):
1564 def call_alias(self,alias,rest=''):
1563 """Call an alias given its name and the rest of the line.
1565 """Call an alias given its name and the rest of the line.
1564
1566
1565 This is only used to provide backwards compatibility for users of
1567 This is only used to provide backwards compatibility for users of
1566 ipalias(), use of which is not recommended for anymore."""
1568 ipalias(), use of which is not recommended for anymore."""
1567
1569
1568 # Now call the macro, evaluating in the user's namespace
1570 # Now call the macro, evaluating in the user's namespace
1569 cmd = self.transform_alias(alias, rest)
1571 cmd = self.transform_alias(alias, rest)
1570 try:
1572 try:
1571 self.system(cmd)
1573 self.system(cmd)
1572 except:
1574 except:
1573 self.showtraceback()
1575 self.showtraceback()
1574
1576
1575 def indent_current_str(self):
1577 def indent_current_str(self):
1576 """return the current level of indentation as a string"""
1578 """return the current level of indentation as a string"""
1577 return self.indent_current_nsp * ' '
1579 return self.indent_current_nsp * ' '
1578
1580
1579 def autoindent_update(self,line):
1581 def autoindent_update(self,line):
1580 """Keep track of the indent level."""
1582 """Keep track of the indent level."""
1581
1583
1582 #debugx('line')
1584 #debugx('line')
1583 #debugx('self.indent_current_nsp')
1585 #debugx('self.indent_current_nsp')
1584 if self.autoindent:
1586 if self.autoindent:
1585 if line:
1587 if line:
1586 inisp = num_ini_spaces(line)
1588 inisp = num_ini_spaces(line)
1587 if inisp < self.indent_current_nsp:
1589 if inisp < self.indent_current_nsp:
1588 self.indent_current_nsp = inisp
1590 self.indent_current_nsp = inisp
1589
1591
1590 if line[-1] == ':':
1592 if line[-1] == ':':
1591 self.indent_current_nsp += 4
1593 self.indent_current_nsp += 4
1592 elif dedent_re.match(line):
1594 elif dedent_re.match(line):
1593 self.indent_current_nsp -= 4
1595 self.indent_current_nsp -= 4
1594 else:
1596 else:
1595 self.indent_current_nsp = 0
1597 self.indent_current_nsp = 0
1596
1598
1597 def runlines(self,lines):
1599 def runlines(self,lines):
1598 """Run a string of one or more lines of source.
1600 """Run a string of one or more lines of source.
1599
1601
1600 This method is capable of running a string containing multiple source
1602 This method is capable of running a string containing multiple source
1601 lines, as if they had been entered at the IPython prompt. Since it
1603 lines, as if they had been entered at the IPython prompt. Since it
1602 exposes IPython's processing machinery, the given strings can contain
1604 exposes IPython's processing machinery, the given strings can contain
1603 magic calls (%magic), special shell access (!cmd), etc."""
1605 magic calls (%magic), special shell access (!cmd), etc."""
1604
1606
1605 # We must start with a clean buffer, in case this is run from an
1607 # We must start with a clean buffer, in case this is run from an
1606 # interactive IPython session (via a magic, for example).
1608 # interactive IPython session (via a magic, for example).
1607 self.resetbuffer()
1609 self.resetbuffer()
1608 lines = lines.split('\n')
1610 lines = lines.split('\n')
1609 more = 0
1611 more = 0
1610 for line in lines:
1612 for line in lines:
1611 # skip blank lines so we don't mess up the prompt counter, but do
1613 # skip blank lines so we don't mess up the prompt counter, but do
1612 # NOT skip even a blank line if we are in a code block (more is
1614 # NOT skip even a blank line if we are in a code block (more is
1613 # true)
1615 # true)
1614 if line or more:
1616 if line or more:
1615 more = self.push(self.prefilter(line,more))
1617 more = self.push(self.prefilter(line,more))
1616 # IPython's runsource returns None if there was an error
1618 # IPython's runsource returns None if there was an error
1617 # compiling the code. This allows us to stop processing right
1619 # compiling the code. This allows us to stop processing right
1618 # away, so the user gets the error message at the right place.
1620 # away, so the user gets the error message at the right place.
1619 if more is None:
1621 if more is None:
1620 break
1622 break
1621 # final newline in case the input didn't have it, so that the code
1623 # final newline in case the input didn't have it, so that the code
1622 # actually does get executed
1624 # actually does get executed
1623 if more:
1625 if more:
1624 self.push('\n')
1626 self.push('\n')
1625
1627
1626 def runsource(self, source, filename='<input>', symbol='single'):
1628 def runsource(self, source, filename='<input>', symbol='single'):
1627 """Compile and run some source in the interpreter.
1629 """Compile and run some source in the interpreter.
1628
1630
1629 Arguments are as for compile_command().
1631 Arguments are as for compile_command().
1630
1632
1631 One several things can happen:
1633 One several things can happen:
1632
1634
1633 1) The input is incorrect; compile_command() raised an
1635 1) The input is incorrect; compile_command() raised an
1634 exception (SyntaxError or OverflowError). A syntax traceback
1636 exception (SyntaxError or OverflowError). A syntax traceback
1635 will be printed by calling the showsyntaxerror() method.
1637 will be printed by calling the showsyntaxerror() method.
1636
1638
1637 2) The input is incomplete, and more input is required;
1639 2) The input is incomplete, and more input is required;
1638 compile_command() returned None. Nothing happens.
1640 compile_command() returned None. Nothing happens.
1639
1641
1640 3) The input is complete; compile_command() returned a code
1642 3) The input is complete; compile_command() returned a code
1641 object. The code is executed by calling self.runcode() (which
1643 object. The code is executed by calling self.runcode() (which
1642 also handles run-time exceptions, except for SystemExit).
1644 also handles run-time exceptions, except for SystemExit).
1643
1645
1644 The return value is:
1646 The return value is:
1645
1647
1646 - True in case 2
1648 - True in case 2
1647
1649
1648 - False in the other cases, unless an exception is raised, where
1650 - False in the other cases, unless an exception is raised, where
1649 None is returned instead. This can be used by external callers to
1651 None is returned instead. This can be used by external callers to
1650 know whether to continue feeding input or not.
1652 know whether to continue feeding input or not.
1651
1653
1652 The return value can be used to decide whether to use sys.ps1 or
1654 The return value can be used to decide whether to use sys.ps1 or
1653 sys.ps2 to prompt the next line."""
1655 sys.ps2 to prompt the next line."""
1654
1656
1655 try:
1657 try:
1656 code = self.compile(source,filename,symbol)
1658 code = self.compile(source,filename,symbol)
1657 except (OverflowError, SyntaxError, ValueError):
1659 except (OverflowError, SyntaxError, ValueError):
1658 # Case 1
1660 # Case 1
1659 self.showsyntaxerror(filename)
1661 self.showsyntaxerror(filename)
1660 return None
1662 return None
1661
1663
1662 if code is None:
1664 if code is None:
1663 # Case 2
1665 # Case 2
1664 return True
1666 return True
1665
1667
1666 # Case 3
1668 # Case 3
1667 # We store the code object so that threaded shells and
1669 # We store the code object so that threaded shells and
1668 # custom exception handlers can access all this info if needed.
1670 # custom exception handlers can access all this info if needed.
1669 # The source corresponding to this can be obtained from the
1671 # The source corresponding to this can be obtained from the
1670 # buffer attribute as '\n'.join(self.buffer).
1672 # buffer attribute as '\n'.join(self.buffer).
1671 self.code_to_run = code
1673 self.code_to_run = code
1672 # now actually execute the code object
1674 # now actually execute the code object
1673 if self.runcode(code) == 0:
1675 if self.runcode(code) == 0:
1674 return False
1676 return False
1675 else:
1677 else:
1676 return None
1678 return None
1677
1679
1678 def runcode(self,code_obj):
1680 def runcode(self,code_obj):
1679 """Execute a code object.
1681 """Execute a code object.
1680
1682
1681 When an exception occurs, self.showtraceback() is called to display a
1683 When an exception occurs, self.showtraceback() is called to display a
1682 traceback.
1684 traceback.
1683
1685
1684 Return value: a flag indicating whether the code to be run completed
1686 Return value: a flag indicating whether the code to be run completed
1685 successfully:
1687 successfully:
1686
1688
1687 - 0: successful execution.
1689 - 0: successful execution.
1688 - 1: an error occurred.
1690 - 1: an error occurred.
1689 """
1691 """
1690
1692
1691 # Set our own excepthook in case the user code tries to call it
1693 # Set our own excepthook in case the user code tries to call it
1692 # directly, so that the IPython crash handler doesn't get triggered
1694 # directly, so that the IPython crash handler doesn't get triggered
1693 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1695 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1694
1696
1695 # we save the original sys.excepthook in the instance, in case config
1697 # we save the original sys.excepthook in the instance, in case config
1696 # code (such as magics) needs access to it.
1698 # code (such as magics) needs access to it.
1697 self.sys_excepthook = old_excepthook
1699 self.sys_excepthook = old_excepthook
1698 outflag = 1 # happens in more places, so it's easier as default
1700 outflag = 1 # happens in more places, so it's easier as default
1699 try:
1701 try:
1700 try:
1702 try:
1701 # Embedded instances require separate global/local namespaces
1703 # Embedded instances require separate global/local namespaces
1702 # so they can see both the surrounding (local) namespace and
1704 # so they can see both the surrounding (local) namespace and
1703 # the module-level globals when called inside another function.
1705 # the module-level globals when called inside another function.
1704 if self.embedded:
1706 if self.embedded:
1705 exec code_obj in self.user_global_ns, self.user_ns
1707 exec code_obj in self.user_global_ns, self.user_ns
1706 # Normal (non-embedded) instances should only have a single
1708 # Normal (non-embedded) instances should only have a single
1707 # namespace for user code execution, otherwise functions won't
1709 # namespace for user code execution, otherwise functions won't
1708 # see interactive top-level globals.
1710 # see interactive top-level globals.
1709 else:
1711 else:
1710 exec code_obj in self.user_ns
1712 exec code_obj in self.user_ns
1711 finally:
1713 finally:
1712 # Reset our crash handler in place
1714 # Reset our crash handler in place
1713 sys.excepthook = old_excepthook
1715 sys.excepthook = old_excepthook
1714 except SystemExit:
1716 except SystemExit:
1715 self.resetbuffer()
1717 self.resetbuffer()
1716 self.showtraceback()
1718 self.showtraceback()
1717 warn("Type exit or quit to exit IPython "
1719 warn("Type exit or quit to exit IPython "
1718 "(%Exit or %Quit do so unconditionally).",level=1)
1720 "(%Exit or %Quit do so unconditionally).",level=1)
1719 except self.custom_exceptions:
1721 except self.custom_exceptions:
1720 etype,value,tb = sys.exc_info()
1722 etype,value,tb = sys.exc_info()
1721 self.CustomTB(etype,value,tb)
1723 self.CustomTB(etype,value,tb)
1722 except:
1724 except:
1723 self.showtraceback()
1725 self.showtraceback()
1724 else:
1726 else:
1725 outflag = 0
1727 outflag = 0
1726 if softspace(sys.stdout, 0):
1728 if softspace(sys.stdout, 0):
1727 print
1729 print
1728 # Flush out code object which has been run (and source)
1730 # Flush out code object which has been run (and source)
1729 self.code_to_run = None
1731 self.code_to_run = None
1730 return outflag
1732 return outflag
1731
1733
1732 def push(self, line):
1734 def push(self, line):
1733 """Push a line to the interpreter.
1735 """Push a line to the interpreter.
1734
1736
1735 The line should not have a trailing newline; it may have
1737 The line should not have a trailing newline; it may have
1736 internal newlines. The line is appended to a buffer and the
1738 internal newlines. The line is appended to a buffer and the
1737 interpreter's runsource() method is called with the
1739 interpreter's runsource() method is called with the
1738 concatenated contents of the buffer as source. If this
1740 concatenated contents of the buffer as source. If this
1739 indicates that the command was executed or invalid, the buffer
1741 indicates that the command was executed or invalid, the buffer
1740 is reset; otherwise, the command is incomplete, and the buffer
1742 is reset; otherwise, the command is incomplete, and the buffer
1741 is left as it was after the line was appended. The return
1743 is left as it was after the line was appended. The return
1742 value is 1 if more input is required, 0 if the line was dealt
1744 value is 1 if more input is required, 0 if the line was dealt
1743 with in some way (this is the same as runsource()).
1745 with in some way (this is the same as runsource()).
1744 """
1746 """
1745
1747
1746 # autoindent management should be done here, and not in the
1748 # autoindent management should be done here, and not in the
1747 # interactive loop, since that one is only seen by keyboard input. We
1749 # interactive loop, since that one is only seen by keyboard input. We
1748 # need this done correctly even for code run via runlines (which uses
1750 # need this done correctly even for code run via runlines (which uses
1749 # push).
1751 # push).
1750
1752
1751 #print 'push line: <%s>' % line # dbg
1753 #print 'push line: <%s>' % line # dbg
1752 self.autoindent_update(line)
1754 self.autoindent_update(line)
1753
1755
1754 self.buffer.append(line)
1756 self.buffer.append(line)
1755 more = self.runsource('\n'.join(self.buffer), self.filename)
1757 more = self.runsource('\n'.join(self.buffer), self.filename)
1756 if not more:
1758 if not more:
1757 self.resetbuffer()
1759 self.resetbuffer()
1758 return more
1760 return more
1759
1761
1760 def resetbuffer(self):
1762 def resetbuffer(self):
1761 """Reset the input buffer."""
1763 """Reset the input buffer."""
1762 self.buffer[:] = []
1764 self.buffer[:] = []
1763
1765
1764 def raw_input(self,prompt='',continue_prompt=False):
1766 def raw_input(self,prompt='',continue_prompt=False):
1765 """Write a prompt and read a line.
1767 """Write a prompt and read a line.
1766
1768
1767 The returned line does not include the trailing newline.
1769 The returned line does not include the trailing newline.
1768 When the user enters the EOF key sequence, EOFError is raised.
1770 When the user enters the EOF key sequence, EOFError is raised.
1769
1771
1770 Optional inputs:
1772 Optional inputs:
1771
1773
1772 - prompt(''): a string to be printed to prompt the user.
1774 - prompt(''): a string to be printed to prompt the user.
1773
1775
1774 - continue_prompt(False): whether this line is the first one or a
1776 - continue_prompt(False): whether this line is the first one or a
1775 continuation in a sequence of inputs.
1777 continuation in a sequence of inputs.
1776 """
1778 """
1777
1779
1778 line = raw_input_original(prompt)
1780 line = raw_input_original(prompt)
1779
1781
1780 # Try to be reasonably smart about not re-indenting pasted input more
1782 # Try to be reasonably smart about not re-indenting pasted input more
1781 # than necessary. We do this by trimming out the auto-indent initial
1783 # than necessary. We do this by trimming out the auto-indent initial
1782 # spaces, if the user's actual input started itself with whitespace.
1784 # spaces, if the user's actual input started itself with whitespace.
1783 #debugx('self.buffer[-1]')
1785 #debugx('self.buffer[-1]')
1784
1786
1785 if self.autoindent:
1787 if self.autoindent:
1786 if num_ini_spaces(line) > self.indent_current_nsp:
1788 if num_ini_spaces(line) > self.indent_current_nsp:
1787 line = line[self.indent_current_nsp:]
1789 line = line[self.indent_current_nsp:]
1788 self.indent_current_nsp = 0
1790 self.indent_current_nsp = 0
1789
1791
1790 # store the unfiltered input before the user has any chance to modify
1792 # store the unfiltered input before the user has any chance to modify
1791 # it.
1793 # it.
1792 if line.strip():
1794 if line.strip():
1793 if continue_prompt:
1795 if continue_prompt:
1794 self.input_hist_raw[-1] += '%s\n' % line
1796 self.input_hist_raw[-1] += '%s\n' % line
1795 else:
1797 else:
1796 self.input_hist_raw.append('%s\n' % line)
1798 self.input_hist_raw.append('%s\n' % line)
1797
1799
1798 try:
1800 try:
1799 lineout = self.prefilter(line,continue_prompt)
1801 lineout = self.prefilter(line,continue_prompt)
1800 except:
1802 except:
1801 # blanket except, in case a user-defined prefilter crashes, so it
1803 # blanket except, in case a user-defined prefilter crashes, so it
1802 # can't take all of ipython with it.
1804 # can't take all of ipython with it.
1803 self.showtraceback()
1805 self.showtraceback()
1804 return lineout
1806 return lineout
1805
1807
1806 def split_user_input(self,line):
1808 def split_user_input(self,line):
1807 """Split user input into pre-char, function part and rest."""
1809 """Split user input into pre-char, function part and rest."""
1808
1810
1809 lsplit = self.line_split.match(line)
1811 lsplit = self.line_split.match(line)
1810 if lsplit is None: # no regexp match returns None
1812 if lsplit is None: # no regexp match returns None
1811 try:
1813 try:
1812 iFun,theRest = line.split(None,1)
1814 iFun,theRest = line.split(None,1)
1813 except ValueError:
1815 except ValueError:
1814 iFun,theRest = line,''
1816 iFun,theRest = line,''
1815 pre = re.match('^(\s*)(.*)',line).groups()[0]
1817 pre = re.match('^(\s*)(.*)',line).groups()[0]
1816 else:
1818 else:
1817 pre,iFun,theRest = lsplit.groups()
1819 pre,iFun,theRest = lsplit.groups()
1818
1820
1819 #print 'line:<%s>' % line # dbg
1821 #print 'line:<%s>' % line # dbg
1820 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1822 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1821 return pre,iFun.strip(),theRest
1823 return pre,iFun.strip(),theRest
1822
1824
1823 def _prefilter(self, line, continue_prompt):
1825 def _prefilter(self, line, continue_prompt):
1824 """Calls different preprocessors, depending on the form of line."""
1826 """Calls different preprocessors, depending on the form of line."""
1825
1827
1826 # All handlers *must* return a value, even if it's blank ('').
1828 # All handlers *must* return a value, even if it's blank ('').
1827
1829
1828 # Lines are NOT logged here. Handlers should process the line as
1830 # Lines are NOT logged here. Handlers should process the line as
1829 # needed, update the cache AND log it (so that the input cache array
1831 # needed, update the cache AND log it (so that the input cache array
1830 # stays synced).
1832 # stays synced).
1831
1833
1832 # This function is _very_ delicate, and since it's also the one which
1834 # This function is _very_ delicate, and since it's also the one which
1833 # determines IPython's response to user input, it must be as efficient
1835 # determines IPython's response to user input, it must be as efficient
1834 # as possible. For this reason it has _many_ returns in it, trying
1836 # as possible. For this reason it has _many_ returns in it, trying
1835 # always to exit as quickly as it can figure out what it needs to do.
1837 # always to exit as quickly as it can figure out what it needs to do.
1836
1838
1837 # This function is the main responsible for maintaining IPython's
1839 # This function is the main responsible for maintaining IPython's
1838 # behavior respectful of Python's semantics. So be _very_ careful if
1840 # behavior respectful of Python's semantics. So be _very_ careful if
1839 # making changes to anything here.
1841 # making changes to anything here.
1840
1842
1841 #.....................................................................
1843 #.....................................................................
1842 # Code begins
1844 # Code begins
1843
1845
1844 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1846 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1845
1847
1846 # save the line away in case we crash, so the post-mortem handler can
1848 # save the line away in case we crash, so the post-mortem handler can
1847 # record it
1849 # record it
1848 self._last_input_line = line
1850 self._last_input_line = line
1849
1851
1850 #print '***line: <%s>' % line # dbg
1852 #print '***line: <%s>' % line # dbg
1851
1853
1852 # the input history needs to track even empty lines
1854 # the input history needs to track even empty lines
1853 stripped = line.strip()
1855 stripped = line.strip()
1854
1856
1855 if not stripped:
1857 if not stripped:
1856 if not continue_prompt:
1858 if not continue_prompt:
1857 self.outputcache.prompt_count -= 1
1859 self.outputcache.prompt_count -= 1
1858 return self.handle_normal(line,continue_prompt)
1860 return self.handle_normal(line,continue_prompt)
1859 #return self.handle_normal('',continue_prompt)
1861 #return self.handle_normal('',continue_prompt)
1860
1862
1861 # print '***cont',continue_prompt # dbg
1863 # print '***cont',continue_prompt # dbg
1862 # special handlers are only allowed for single line statements
1864 # special handlers are only allowed for single line statements
1863 if continue_prompt and not self.rc.multi_line_specials:
1865 if continue_prompt and not self.rc.multi_line_specials:
1864 return self.handle_normal(line,continue_prompt)
1866 return self.handle_normal(line,continue_prompt)
1865
1867
1866
1868
1867 # For the rest, we need the structure of the input
1869 # For the rest, we need the structure of the input
1868 pre,iFun,theRest = self.split_user_input(line)
1870 pre,iFun,theRest = self.split_user_input(line)
1869
1871
1870 # See whether any pre-existing handler can take care of it
1872 # See whether any pre-existing handler can take care of it
1871
1873
1872 rewritten = self.hooks.input_prefilter(stripped)
1874 rewritten = self.hooks.input_prefilter(stripped)
1873 if rewritten != stripped: # ok, some prefilter did something
1875 if rewritten != stripped: # ok, some prefilter did something
1874 rewritten = pre + rewritten # add indentation
1876 rewritten = pre + rewritten # add indentation
1875 return self.handle_normal(rewritten)
1877 return self.handle_normal(rewritten)
1876
1878
1877
1878
1879
1880 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1879 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1881
1880
1882 # First check for explicit escapes in the last/first character
1881 # First check for explicit escapes in the last/first character
1883 handler = None
1882 handler = None
1884 if line[-1] == self.ESC_HELP:
1883 if line[-1] == self.ESC_HELP:
1885 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1884 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1886 if handler is None:
1885 if handler is None:
1887 # look at the first character of iFun, NOT of line, so we skip
1886 # look at the first character of iFun, NOT of line, so we skip
1888 # leading whitespace in multiline input
1887 # leading whitespace in multiline input
1889 handler = self.esc_handlers.get(iFun[0:1])
1888 handler = self.esc_handlers.get(iFun[0:1])
1890 if handler is not None:
1889 if handler is not None:
1891 return handler(line,continue_prompt,pre,iFun,theRest)
1890 return handler(line,continue_prompt,pre,iFun,theRest)
1892 # Emacs ipython-mode tags certain input lines
1891 # Emacs ipython-mode tags certain input lines
1893 if line.endswith('# PYTHON-MODE'):
1892 if line.endswith('# PYTHON-MODE'):
1894 return self.handle_emacs(line,continue_prompt)
1893 return self.handle_emacs(line,continue_prompt)
1895
1894
1896 # Next, check if we can automatically execute this thing
1895 # Next, check if we can automatically execute this thing
1897
1896
1898 # Allow ! in multi-line statements if multi_line_specials is on:
1897 # Allow ! in multi-line statements if multi_line_specials is on:
1899 if continue_prompt and self.rc.multi_line_specials and \
1898 if continue_prompt and self.rc.multi_line_specials and \
1900 iFun.startswith(self.ESC_SHELL):
1899 iFun.startswith(self.ESC_SHELL):
1901 return self.handle_shell_escape(line,continue_prompt,
1900 return self.handle_shell_escape(line,continue_prompt,
1902 pre=pre,iFun=iFun,
1901 pre=pre,iFun=iFun,
1903 theRest=theRest)
1902 theRest=theRest)
1904
1903
1905 # Let's try to find if the input line is a magic fn
1904 # Let's try to find if the input line is a magic fn
1906 oinfo = None
1905 oinfo = None
1907 if hasattr(self,'magic_'+iFun):
1906 if hasattr(self,'magic_'+iFun):
1908 # WARNING: _ofind uses getattr(), so it can consume generators and
1907 # WARNING: _ofind uses getattr(), so it can consume generators and
1909 # cause other side effects.
1908 # cause other side effects.
1910 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1909 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1911 if oinfo['ismagic']:
1910 if oinfo['ismagic']:
1912 # Be careful not to call magics when a variable assignment is
1911 # Be careful not to call magics when a variable assignment is
1913 # being made (ls='hi', for example)
1912 # being made (ls='hi', for example)
1914 if self.rc.automagic and \
1913 if self.rc.automagic and \
1915 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1914 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1916 (self.rc.multi_line_specials or not continue_prompt):
1915 (self.rc.multi_line_specials or not continue_prompt):
1917 return self.handle_magic(line,continue_prompt,
1916 return self.handle_magic(line,continue_prompt,
1918 pre,iFun,theRest)
1917 pre,iFun,theRest)
1919 else:
1918 else:
1920 return self.handle_normal(line,continue_prompt)
1919 return self.handle_normal(line,continue_prompt)
1921
1920
1922 # If the rest of the line begins with an (in)equality, assginment or
1921 # If the rest of the line begins with an (in)equality, assginment or
1923 # function call, we should not call _ofind but simply execute it.
1922 # function call, we should not call _ofind but simply execute it.
1924 # This avoids spurious geattr() accesses on objects upon assignment.
1923 # This avoids spurious geattr() accesses on objects upon assignment.
1925 #
1924 #
1926 # It also allows users to assign to either alias or magic names true
1925 # It also allows users to assign to either alias or magic names true
1927 # python variables (the magic/alias systems always take second seat to
1926 # python variables (the magic/alias systems always take second seat to
1928 # true python code).
1927 # true python code).
1929 if theRest and theRest[0] in '!=()':
1928 if theRest and theRest[0] in '!=()':
1930 return self.handle_normal(line,continue_prompt)
1929 return self.handle_normal(line,continue_prompt)
1931
1930
1932 if oinfo is None:
1931 if oinfo is None:
1933 # let's try to ensure that _oinfo is ONLY called when autocall is
1932 # let's try to ensure that _oinfo is ONLY called when autocall is
1934 # on. Since it has inevitable potential side effects, at least
1933 # on. Since it has inevitable potential side effects, at least
1935 # having autocall off should be a guarantee to the user that no
1934 # having autocall off should be a guarantee to the user that no
1936 # weird things will happen.
1935 # weird things will happen.
1937
1936
1938 if self.rc.autocall:
1937 if self.rc.autocall:
1939 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1938 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1940 else:
1939 else:
1941 # in this case, all that's left is either an alias or
1940 # in this case, all that's left is either an alias or
1942 # processing the line normally.
1941 # processing the line normally.
1943 if iFun in self.alias_table:
1942 if iFun in self.alias_table:
1944 return self.handle_alias(line,continue_prompt,
1943 # if autocall is off, by not running _ofind we won't know
1945 pre,iFun,theRest)
1944 # whether the given name may also exist in one of the
1945 # user's namespace. At this point, it's best to do a
1946 # quick check just to be sure that we don't let aliases
1947 # shadow variables.
1948 head = iFun.split('.',1)[0]
1949 if head in self.user_ns or head in self.internal_ns \
1950 or head in __builtin__.__dict__:
1951 return self.handle_normal(line,continue_prompt)
1952 else:
1953 return self.handle_alias(line,continue_prompt,
1954 pre,iFun,theRest)
1946
1955
1947 else:
1956 else:
1948 return self.handle_normal(line,continue_prompt)
1957 return self.handle_normal(line,continue_prompt)
1949
1958
1950 if not oinfo['found']:
1959 if not oinfo['found']:
1951 return self.handle_normal(line,continue_prompt)
1960 return self.handle_normal(line,continue_prompt)
1952 else:
1961 else:
1953 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1962 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1954 if oinfo['isalias']:
1963 if oinfo['isalias']:
1955 return self.handle_alias(line,continue_prompt,
1964 return self.handle_alias(line,continue_prompt,
1956 pre,iFun,theRest)
1965 pre,iFun,theRest)
1957
1966
1958 if (self.rc.autocall
1967 if (self.rc.autocall
1959 and
1968 and
1960 (
1969 (
1961 #only consider exclusion re if not "," or ";" autoquoting
1970 #only consider exclusion re if not "," or ";" autoquoting
1962 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
1971 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
1963 or pre == self.ESC_PAREN) or
1972 or pre == self.ESC_PAREN) or
1964 (not self.re_exclude_auto.match(theRest)))
1973 (not self.re_exclude_auto.match(theRest)))
1965 and
1974 and
1966 self.re_fun_name.match(iFun) and
1975 self.re_fun_name.match(iFun) and
1967 callable(oinfo['obj'])) :
1976 callable(oinfo['obj'])) :
1968 #print 'going auto' # dbg
1977 #print 'going auto' # dbg
1969 return self.handle_auto(line,continue_prompt,
1978 return self.handle_auto(line,continue_prompt,
1970 pre,iFun,theRest,oinfo['obj'])
1979 pre,iFun,theRest,oinfo['obj'])
1971 else:
1980 else:
1972 #print 'was callable?', callable(oinfo['obj']) # dbg
1981 #print 'was callable?', callable(oinfo['obj']) # dbg
1973 return self.handle_normal(line,continue_prompt)
1982 return self.handle_normal(line,continue_prompt)
1974
1983
1975 # If we get here, we have a normal Python line. Log and return.
1984 # If we get here, we have a normal Python line. Log and return.
1976 return self.handle_normal(line,continue_prompt)
1985 return self.handle_normal(line,continue_prompt)
1977
1986
1978 def _prefilter_dumb(self, line, continue_prompt):
1987 def _prefilter_dumb(self, line, continue_prompt):
1979 """simple prefilter function, for debugging"""
1988 """simple prefilter function, for debugging"""
1980 return self.handle_normal(line,continue_prompt)
1989 return self.handle_normal(line,continue_prompt)
1981
1990
1982 # Set the default prefilter() function (this can be user-overridden)
1991 # Set the default prefilter() function (this can be user-overridden)
1983 prefilter = _prefilter
1992 prefilter = _prefilter
1984
1993
1985 def handle_normal(self,line,continue_prompt=None,
1994 def handle_normal(self,line,continue_prompt=None,
1986 pre=None,iFun=None,theRest=None):
1995 pre=None,iFun=None,theRest=None):
1987 """Handle normal input lines. Use as a template for handlers."""
1996 """Handle normal input lines. Use as a template for handlers."""
1988
1997
1989 # With autoindent on, we need some way to exit the input loop, and I
1998 # With autoindent on, we need some way to exit the input loop, and I
1990 # don't want to force the user to have to backspace all the way to
1999 # don't want to force the user to have to backspace all the way to
1991 # clear the line. The rule will be in this case, that either two
2000 # clear the line. The rule will be in this case, that either two
1992 # lines of pure whitespace in a row, or a line of pure whitespace but
2001 # lines of pure whitespace in a row, or a line of pure whitespace but
1993 # of a size different to the indent level, will exit the input loop.
2002 # of a size different to the indent level, will exit the input loop.
1994
2003
1995 if (continue_prompt and self.autoindent and line.isspace() and
2004 if (continue_prompt and self.autoindent and line.isspace() and
1996 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2005 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
1997 (self.buffer[-1]).isspace() )):
2006 (self.buffer[-1]).isspace() )):
1998 line = ''
2007 line = ''
1999
2008
2000 self.log(line,continue_prompt)
2009 self.log(line,continue_prompt)
2001 return line
2010 return line
2002
2011
2003 def handle_alias(self,line,continue_prompt=None,
2012 def handle_alias(self,line,continue_prompt=None,
2004 pre=None,iFun=None,theRest=None):
2013 pre=None,iFun=None,theRest=None):
2005 """Handle alias input lines. """
2014 """Handle alias input lines. """
2006
2015
2007 # pre is needed, because it carries the leading whitespace. Otherwise
2016 # pre is needed, because it carries the leading whitespace. Otherwise
2008 # aliases won't work in indented sections.
2017 # aliases won't work in indented sections.
2009 transformed = self.transform_alias(iFun, theRest)
2018 transformed = self.transform_alias(iFun, theRest)
2010 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2019 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2011 self.log(line_out,continue_prompt)
2020 self.log(line_out,continue_prompt)
2012 return line_out
2021 return line_out
2013
2022
2014 def handle_shell_escape(self, line, continue_prompt=None,
2023 def handle_shell_escape(self, line, continue_prompt=None,
2015 pre=None,iFun=None,theRest=None):
2024 pre=None,iFun=None,theRest=None):
2016 """Execute the line in a shell, empty return value"""
2025 """Execute the line in a shell, empty return value"""
2017
2026
2018 #print 'line in :', `line` # dbg
2027 #print 'line in :', `line` # dbg
2019 # Example of a special handler. Others follow a similar pattern.
2028 # Example of a special handler. Others follow a similar pattern.
2020 if line.lstrip().startswith('!!'):
2029 if line.lstrip().startswith('!!'):
2021 # rewrite iFun/theRest to properly hold the call to %sx and
2030 # rewrite iFun/theRest to properly hold the call to %sx and
2022 # the actual command to be executed, so handle_magic can work
2031 # the actual command to be executed, so handle_magic can work
2023 # correctly
2032 # correctly
2024 theRest = '%s %s' % (iFun[2:],theRest)
2033 theRest = '%s %s' % (iFun[2:],theRest)
2025 iFun = 'sx'
2034 iFun = 'sx'
2026 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2035 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2027 line.lstrip()[2:]),
2036 line.lstrip()[2:]),
2028 continue_prompt,pre,iFun,theRest)
2037 continue_prompt,pre,iFun,theRest)
2029 else:
2038 else:
2030 cmd=line.lstrip().lstrip('!')
2039 cmd=line.lstrip().lstrip('!')
2031 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2040 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2032 # update cache/log and return
2041 # update cache/log and return
2033 self.log(line_out,continue_prompt)
2042 self.log(line_out,continue_prompt)
2034 return line_out
2043 return line_out
2035
2044
2036 def handle_magic(self, line, continue_prompt=None,
2045 def handle_magic(self, line, continue_prompt=None,
2037 pre=None,iFun=None,theRest=None):
2046 pre=None,iFun=None,theRest=None):
2038 """Execute magic functions."""
2047 """Execute magic functions."""
2039
2048
2040
2049
2041 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2050 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2042 self.log(cmd,continue_prompt)
2051 self.log(cmd,continue_prompt)
2043 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2052 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2044 return cmd
2053 return cmd
2045
2054
2046 def handle_auto(self, line, continue_prompt=None,
2055 def handle_auto(self, line, continue_prompt=None,
2047 pre=None,iFun=None,theRest=None,obj=None):
2056 pre=None,iFun=None,theRest=None,obj=None):
2048 """Hande lines which can be auto-executed, quoting if requested."""
2057 """Hande lines which can be auto-executed, quoting if requested."""
2049
2058
2050 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2059 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2051
2060
2052 # This should only be active for single-line input!
2061 # This should only be active for single-line input!
2053 if continue_prompt:
2062 if continue_prompt:
2054 self.log(line,continue_prompt)
2063 self.log(line,continue_prompt)
2055 return line
2064 return line
2056
2065
2057 auto_rewrite = True
2066 auto_rewrite = True
2058
2067
2059 if pre == self.ESC_QUOTE:
2068 if pre == self.ESC_QUOTE:
2060 # Auto-quote splitting on whitespace
2069 # Auto-quote splitting on whitespace
2061 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2070 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2062 elif pre == self.ESC_QUOTE2:
2071 elif pre == self.ESC_QUOTE2:
2063 # Auto-quote whole string
2072 # Auto-quote whole string
2064 newcmd = '%s("%s")' % (iFun,theRest)
2073 newcmd = '%s("%s")' % (iFun,theRest)
2065 elif pre == self.ESC_PAREN:
2074 elif pre == self.ESC_PAREN:
2066 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2075 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2067 else:
2076 else:
2068 # Auto-paren.
2077 # Auto-paren.
2069 # We only apply it to argument-less calls if the autocall
2078 # We only apply it to argument-less calls if the autocall
2070 # parameter is set to 2. We only need to check that autocall is <
2079 # parameter is set to 2. We only need to check that autocall is <
2071 # 2, since this function isn't called unless it's at least 1.
2080 # 2, since this function isn't called unless it's at least 1.
2072 if not theRest and (self.rc.autocall < 2):
2081 if not theRest and (self.rc.autocall < 2):
2073 newcmd = '%s %s' % (iFun,theRest)
2082 newcmd = '%s %s' % (iFun,theRest)
2074 auto_rewrite = False
2083 auto_rewrite = False
2075 else:
2084 else:
2076 if theRest.startswith('['):
2085 if theRest.startswith('['):
2077 if hasattr(obj,'__getitem__'):
2086 if hasattr(obj,'__getitem__'):
2078 # Don't autocall in this case: item access for an object
2087 # Don't autocall in this case: item access for an object
2079 # which is BOTH callable and implements __getitem__.
2088 # which is BOTH callable and implements __getitem__.
2080 newcmd = '%s %s' % (iFun,theRest)
2089 newcmd = '%s %s' % (iFun,theRest)
2081 auto_rewrite = False
2090 auto_rewrite = False
2082 else:
2091 else:
2083 # if the object doesn't support [] access, go ahead and
2092 # if the object doesn't support [] access, go ahead and
2084 # autocall
2093 # autocall
2085 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2094 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2086 elif theRest.endswith(';'):
2095 elif theRest.endswith(';'):
2087 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2096 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2088 else:
2097 else:
2089 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2098 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2090
2099
2091 if auto_rewrite:
2100 if auto_rewrite:
2092 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2101 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2093 # log what is now valid Python, not the actual user input (without the
2102 # log what is now valid Python, not the actual user input (without the
2094 # final newline)
2103 # final newline)
2095 self.log(newcmd,continue_prompt)
2104 self.log(newcmd,continue_prompt)
2096 return newcmd
2105 return newcmd
2097
2106
2098 def handle_help(self, line, continue_prompt=None,
2107 def handle_help(self, line, continue_prompt=None,
2099 pre=None,iFun=None,theRest=None):
2108 pre=None,iFun=None,theRest=None):
2100 """Try to get some help for the object.
2109 """Try to get some help for the object.
2101
2110
2102 obj? or ?obj -> basic information.
2111 obj? or ?obj -> basic information.
2103 obj?? or ??obj -> more details.
2112 obj?? or ??obj -> more details.
2104 """
2113 """
2105
2114
2106 # We need to make sure that we don't process lines which would be
2115 # We need to make sure that we don't process lines which would be
2107 # otherwise valid python, such as "x=1 # what?"
2116 # otherwise valid python, such as "x=1 # what?"
2108 try:
2117 try:
2109 codeop.compile_command(line)
2118 codeop.compile_command(line)
2110 except SyntaxError:
2119 except SyntaxError:
2111 # We should only handle as help stuff which is NOT valid syntax
2120 # We should only handle as help stuff which is NOT valid syntax
2112 if line[0]==self.ESC_HELP:
2121 if line[0]==self.ESC_HELP:
2113 line = line[1:]
2122 line = line[1:]
2114 elif line[-1]==self.ESC_HELP:
2123 elif line[-1]==self.ESC_HELP:
2115 line = line[:-1]
2124 line = line[:-1]
2116 self.log('#?'+line)
2125 self.log('#?'+line)
2117 if line:
2126 if line:
2118 self.magic_pinfo(line)
2127 self.magic_pinfo(line)
2119 else:
2128 else:
2120 page(self.usage,screen_lines=self.rc.screen_length)
2129 page(self.usage,screen_lines=self.rc.screen_length)
2121 return '' # Empty string is needed here!
2130 return '' # Empty string is needed here!
2122 except:
2131 except:
2123 # Pass any other exceptions through to the normal handler
2132 # Pass any other exceptions through to the normal handler
2124 return self.handle_normal(line,continue_prompt)
2133 return self.handle_normal(line,continue_prompt)
2125 else:
2134 else:
2126 # If the code compiles ok, we should handle it normally
2135 # If the code compiles ok, we should handle it normally
2127 return self.handle_normal(line,continue_prompt)
2136 return self.handle_normal(line,continue_prompt)
2128
2137
2129 def getapi(self):
2138 def getapi(self):
2130 """ Get an IPApi object for this shell instance
2139 """ Get an IPApi object for this shell instance
2131
2140
2132 Getting an IPApi object is always preferable to accessing the shell
2141 Getting an IPApi object is always preferable to accessing the shell
2133 directly, but this holds true especially for extensions.
2142 directly, but this holds true especially for extensions.
2134
2143
2135 It should always be possible to implement an extension with IPApi
2144 It should always be possible to implement an extension with IPApi
2136 alone. If not, contact maintainer to request an addition.
2145 alone. If not, contact maintainer to request an addition.
2137
2146
2138 """
2147 """
2139 return self.api
2148 return self.api
2140
2149
2141 def handle_emacs(self,line,continue_prompt=None,
2150 def handle_emacs(self,line,continue_prompt=None,
2142 pre=None,iFun=None,theRest=None):
2151 pre=None,iFun=None,theRest=None):
2143 """Handle input lines marked by python-mode."""
2152 """Handle input lines marked by python-mode."""
2144
2153
2145 # Currently, nothing is done. Later more functionality can be added
2154 # Currently, nothing is done. Later more functionality can be added
2146 # here if needed.
2155 # here if needed.
2147
2156
2148 # The input cache shouldn't be updated
2157 # The input cache shouldn't be updated
2149
2158
2150 return line
2159 return line
2151
2160
2152 def mktempfile(self,data=None):
2161 def mktempfile(self,data=None):
2153 """Make a new tempfile and return its filename.
2162 """Make a new tempfile and return its filename.
2154
2163
2155 This makes a call to tempfile.mktemp, but it registers the created
2164 This makes a call to tempfile.mktemp, but it registers the created
2156 filename internally so ipython cleans it up at exit time.
2165 filename internally so ipython cleans it up at exit time.
2157
2166
2158 Optional inputs:
2167 Optional inputs:
2159
2168
2160 - data(None): if data is given, it gets written out to the temp file
2169 - data(None): if data is given, it gets written out to the temp file
2161 immediately, and the file is closed again."""
2170 immediately, and the file is closed again."""
2162
2171
2163 filename = tempfile.mktemp('.py','ipython_edit_')
2172 filename = tempfile.mktemp('.py','ipython_edit_')
2164 self.tempfiles.append(filename)
2173 self.tempfiles.append(filename)
2165
2174
2166 if data:
2175 if data:
2167 tmp_file = open(filename,'w')
2176 tmp_file = open(filename,'w')
2168 tmp_file.write(data)
2177 tmp_file.write(data)
2169 tmp_file.close()
2178 tmp_file.close()
2170 return filename
2179 return filename
2171
2180
2172 def write(self,data):
2181 def write(self,data):
2173 """Write a string to the default output"""
2182 """Write a string to the default output"""
2174 Term.cout.write(data)
2183 Term.cout.write(data)
2175
2184
2176 def write_err(self,data):
2185 def write_err(self,data):
2177 """Write a string to the default error output"""
2186 """Write a string to the default error output"""
2178 Term.cerr.write(data)
2187 Term.cerr.write(data)
2179
2188
2180 def exit(self):
2189 def exit(self):
2181 """Handle interactive exit.
2190 """Handle interactive exit.
2182
2191
2183 This method sets the exit_now attribute."""
2192 This method sets the exit_now attribute."""
2184
2193
2185 if self.rc.confirm_exit:
2194 if self.rc.confirm_exit:
2186 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2195 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2187 self.exit_now = True
2196 self.exit_now = True
2188 else:
2197 else:
2189 self.exit_now = True
2198 self.exit_now = True
2190 return self.exit_now
2199 return self.exit_now
2191
2200
2192 def safe_execfile(self,fname,*where,**kw):
2201 def safe_execfile(self,fname,*where,**kw):
2193 fname = os.path.expanduser(fname)
2202 fname = os.path.expanduser(fname)
2194
2203
2195 # find things also in current directory
2204 # find things also in current directory
2196 dname = os.path.dirname(fname)
2205 dname = os.path.dirname(fname)
2197 if not sys.path.count(dname):
2206 if not sys.path.count(dname):
2198 sys.path.append(dname)
2207 sys.path.append(dname)
2199
2208
2200 try:
2209 try:
2201 xfile = open(fname)
2210 xfile = open(fname)
2202 except:
2211 except:
2203 print >> Term.cerr, \
2212 print >> Term.cerr, \
2204 'Could not open file <%s> for safe execution.' % fname
2213 'Could not open file <%s> for safe execution.' % fname
2205 return None
2214 return None
2206
2215
2207 kw.setdefault('islog',0)
2216 kw.setdefault('islog',0)
2208 kw.setdefault('quiet',1)
2217 kw.setdefault('quiet',1)
2209 kw.setdefault('exit_ignore',0)
2218 kw.setdefault('exit_ignore',0)
2210 first = xfile.readline()
2219 first = xfile.readline()
2211 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2220 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2212 xfile.close()
2221 xfile.close()
2213 # line by line execution
2222 # line by line execution
2214 if first.startswith(loghead) or kw['islog']:
2223 if first.startswith(loghead) or kw['islog']:
2215 print 'Loading log file <%s> one line at a time...' % fname
2224 print 'Loading log file <%s> one line at a time...' % fname
2216 if kw['quiet']:
2225 if kw['quiet']:
2217 stdout_save = sys.stdout
2226 stdout_save = sys.stdout
2218 sys.stdout = StringIO.StringIO()
2227 sys.stdout = StringIO.StringIO()
2219 try:
2228 try:
2220 globs,locs = where[0:2]
2229 globs,locs = where[0:2]
2221 except:
2230 except:
2222 try:
2231 try:
2223 globs = locs = where[0]
2232 globs = locs = where[0]
2224 except:
2233 except:
2225 globs = locs = globals()
2234 globs = locs = globals()
2226 badblocks = []
2235 badblocks = []
2227
2236
2228 # we also need to identify indented blocks of code when replaying
2237 # we also need to identify indented blocks of code when replaying
2229 # logs and put them together before passing them to an exec
2238 # logs and put them together before passing them to an exec
2230 # statement. This takes a bit of regexp and look-ahead work in the
2239 # statement. This takes a bit of regexp and look-ahead work in the
2231 # file. It's easiest if we swallow the whole thing in memory
2240 # file. It's easiest if we swallow the whole thing in memory
2232 # first, and manually walk through the lines list moving the
2241 # first, and manually walk through the lines list moving the
2233 # counter ourselves.
2242 # counter ourselves.
2234 indent_re = re.compile('\s+\S')
2243 indent_re = re.compile('\s+\S')
2235 xfile = open(fname)
2244 xfile = open(fname)
2236 filelines = xfile.readlines()
2245 filelines = xfile.readlines()
2237 xfile.close()
2246 xfile.close()
2238 nlines = len(filelines)
2247 nlines = len(filelines)
2239 lnum = 0
2248 lnum = 0
2240 while lnum < nlines:
2249 while lnum < nlines:
2241 line = filelines[lnum]
2250 line = filelines[lnum]
2242 lnum += 1
2251 lnum += 1
2243 # don't re-insert logger status info into cache
2252 # don't re-insert logger status info into cache
2244 if line.startswith('#log#'):
2253 if line.startswith('#log#'):
2245 continue
2254 continue
2246 else:
2255 else:
2247 # build a block of code (maybe a single line) for execution
2256 # build a block of code (maybe a single line) for execution
2248 block = line
2257 block = line
2249 try:
2258 try:
2250 next = filelines[lnum] # lnum has already incremented
2259 next = filelines[lnum] # lnum has already incremented
2251 except:
2260 except:
2252 next = None
2261 next = None
2253 while next and indent_re.match(next):
2262 while next and indent_re.match(next):
2254 block += next
2263 block += next
2255 lnum += 1
2264 lnum += 1
2256 try:
2265 try:
2257 next = filelines[lnum]
2266 next = filelines[lnum]
2258 except:
2267 except:
2259 next = None
2268 next = None
2260 # now execute the block of one or more lines
2269 # now execute the block of one or more lines
2261 try:
2270 try:
2262 exec block in globs,locs
2271 exec block in globs,locs
2263 except SystemExit:
2272 except SystemExit:
2264 pass
2273 pass
2265 except:
2274 except:
2266 badblocks.append(block.rstrip())
2275 badblocks.append(block.rstrip())
2267 if kw['quiet']: # restore stdout
2276 if kw['quiet']: # restore stdout
2268 sys.stdout.close()
2277 sys.stdout.close()
2269 sys.stdout = stdout_save
2278 sys.stdout = stdout_save
2270 print 'Finished replaying log file <%s>' % fname
2279 print 'Finished replaying log file <%s>' % fname
2271 if badblocks:
2280 if badblocks:
2272 print >> sys.stderr, ('\nThe following lines/blocks in file '
2281 print >> sys.stderr, ('\nThe following lines/blocks in file '
2273 '<%s> reported errors:' % fname)
2282 '<%s> reported errors:' % fname)
2274
2283
2275 for badline in badblocks:
2284 for badline in badblocks:
2276 print >> sys.stderr, badline
2285 print >> sys.stderr, badline
2277 else: # regular file execution
2286 else: # regular file execution
2278 try:
2287 try:
2279 execfile(fname,*where)
2288 execfile(fname,*where)
2280 except SyntaxError:
2289 except SyntaxError:
2281 self.showsyntaxerror()
2290 self.showsyntaxerror()
2282 warn('Failure executing file: <%s>' % fname)
2291 warn('Failure executing file: <%s>' % fname)
2283 except SystemExit,status:
2292 except SystemExit,status:
2284 if not kw['exit_ignore']:
2293 if not kw['exit_ignore']:
2285 self.showtraceback()
2294 self.showtraceback()
2286 warn('Failure executing file: <%s>' % fname)
2295 warn('Failure executing file: <%s>' % fname)
2287 except:
2296 except:
2288 self.showtraceback()
2297 self.showtraceback()
2289 warn('Failure executing file: <%s>' % fname)
2298 warn('Failure executing file: <%s>' % fname)
2290
2299
2291 #************************* end of file <iplib.py> *****************************
2300 #************************* end of file <iplib.py> *****************************
@@ -1,755 +1,757 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.1 or better.
5 Requires Python 2.1 or better.
6
6
7 This file contains the main make_IPython() starter function.
7 This file contains the main make_IPython() starter function.
8
8
9 $Id: ipmaker.py 1328 2006-05-25 07:47:56Z fperez $"""
9 $Id: ipmaker.py 1329 2006-05-26 07:52:45Z fperez $"""
10
10
11 #*****************************************************************************
11 #*****************************************************************************
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
16 #*****************************************************************************
17
17
18 from IPython import Release
18 from IPython import Release
19 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __license__ = Release.license
20 __license__ = Release.license
21 __version__ = Release.version
21 __version__ = Release.version
22
22
23 credits._Printer__data = """
23 credits._Printer__data = """
24 Python: %s
24 Python: %s
25
25
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 See http://ipython.scipy.org for more information.""" \
27 See http://ipython.scipy.org for more information.""" \
28 % credits._Printer__data
28 % credits._Printer__data
29
29
30 copyright._Printer__data += """
30 copyright._Printer__data += """
31
31
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 All Rights Reserved."""
33 All Rights Reserved."""
34
34
35 #****************************************************************************
35 #****************************************************************************
36 # Required modules
36 # Required modules
37
37
38 # From the standard library
38 # From the standard library
39 import __main__
39 import __main__
40 import __builtin__
40 import __builtin__
41 import os
41 import os
42 import re
42 import re
43 import sys
43 import sys
44 import types
44 import types
45 from pprint import pprint,pformat
45 from pprint import pprint,pformat
46
46
47 # Our own
47 # Our own
48 from IPython import DPyGetOpt
48 from IPython import DPyGetOpt
49 from IPython.ipstruct import Struct
49 from IPython.ipstruct import Struct
50 from IPython.OutputTrap import OutputTrap
50 from IPython.OutputTrap import OutputTrap
51 from IPython.ConfigLoader import ConfigLoader
51 from IPython.ConfigLoader import ConfigLoader
52 from IPython.iplib import InteractiveShell
52 from IPython.iplib import InteractiveShell
53 from IPython.usage import cmd_line_usage,interactive_usage
53 from IPython.usage import cmd_line_usage,interactive_usage
54 from IPython.genutils import *
54 from IPython.genutils import *
55
55
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
57 def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1,
58 rc_override=None,shell_class=InteractiveShell,
58 rc_override=None,shell_class=InteractiveShell,
59 embedded=False,**kw):
59 embedded=False,**kw):
60 """This is a dump of IPython into a single function.
60 """This is a dump of IPython into a single function.
61
61
62 Later it will have to be broken up in a sensible manner.
62 Later it will have to be broken up in a sensible manner.
63
63
64 Arguments:
64 Arguments:
65
65
66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
66 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
67 script name, b/c DPyGetOpt strips the first argument only for the real
67 script name, b/c DPyGetOpt strips the first argument only for the real
68 sys.argv.
68 sys.argv.
69
69
70 - user_ns: a dict to be used as the user's namespace."""
70 - user_ns: a dict to be used as the user's namespace."""
71
71
72 #----------------------------------------------------------------------
72 #----------------------------------------------------------------------
73 # Defaults and initialization
73 # Defaults and initialization
74
74
75 # For developer debugging, deactivates crash handler and uses pdb.
75 # For developer debugging, deactivates crash handler and uses pdb.
76 DEVDEBUG = False
76 DEVDEBUG = False
77
77
78 if argv is None:
78 if argv is None:
79 argv = sys.argv
79 argv = sys.argv
80
80
81 # __IP is the main global that lives throughout and represents the whole
81 # __IP is the main global that lives throughout and represents the whole
82 # application. If the user redefines it, all bets are off as to what
82 # application. If the user redefines it, all bets are off as to what
83 # happens.
83 # happens.
84
84
85 # __IP is the name of he global which the caller will have accessible as
85 # __IP is the name of he global which the caller will have accessible as
86 # __IP.name. We set its name via the first parameter passed to
86 # __IP.name. We set its name via the first parameter passed to
87 # InteractiveShell:
87 # InteractiveShell:
88
88
89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
89 IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns,
90 embedded=embedded,**kw)
90 embedded=embedded,**kw)
91
91
92 # Put 'help' in the user namespace
92 # Put 'help' in the user namespace
93 from site import _Helper
93 from site import _Helper
94 IP.user_ns['help'] = _Helper()
94 IP.user_ns['help'] = _Helper()
95
95
96
96
97 if DEVDEBUG:
97 if DEVDEBUG:
98 # For developer debugging only (global flag)
98 # For developer debugging only (global flag)
99 from IPython import ultraTB
99 from IPython import ultraTB
100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
100 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
101
101
102 IP.BANNER_PARTS = ['Python %s\n'
102 IP.BANNER_PARTS = ['Python %s\n'
103 'Type "copyright", "credits" or "license" '
103 'Type "copyright", "credits" or "license" '
104 'for more information.\n'
104 'for more information.\n'
105 % (sys.version.split('\n')[0],),
105 % (sys.version.split('\n')[0],),
106 "IPython %s -- An enhanced Interactive Python."
106 "IPython %s -- An enhanced Interactive Python."
107 % (__version__,),
107 % (__version__,),
108 """? -> Introduction to IPython's features.
108 """? -> Introduction to IPython's features.
109 %magic -> Information about IPython's 'magic' % functions.
109 %magic -> Information about IPython's 'magic' % functions.
110 help -> Python's own help system.
110 help -> Python's own help system.
111 object? -> Details about 'object'. ?object also works, ?? prints more.
111 object? -> Details about 'object'. ?object also works, ?? prints more.
112 """ ]
112 """ ]
113
113
114 IP.usage = interactive_usage
114 IP.usage = interactive_usage
115
115
116 # Platform-dependent suffix and directory names. We use _ipython instead
116 # Platform-dependent suffix and directory names. We use _ipython instead
117 # of .ipython under win32 b/c there's software that breaks with .named
117 # of .ipython under win32 b/c there's software that breaks with .named
118 # directories on that platform.
118 # directories on that platform.
119 if os.name == 'posix':
119 if os.name == 'posix':
120 rc_suffix = ''
120 rc_suffix = ''
121 ipdir_def = '.ipython'
121 ipdir_def = '.ipython'
122 else:
122 else:
123 rc_suffix = '.ini'
123 rc_suffix = '.ini'
124 ipdir_def = '_ipython'
124 ipdir_def = '_ipython'
125
125
126 # default directory for configuration
126 # default directory for configuration
127 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
127 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
128 os.path.join(IP.home_dir,ipdir_def)))
128 os.path.join(IP.home_dir,ipdir_def)))
129
129
130 # add personal .ipython dir to sys.path so that users can put things in
130 # add personal .ipython dir to sys.path so that users can put things in
131 # there for customization
131 # there for customization
132 sys.path.append(ipythondir)
132 sys.path.append(ipythondir)
133
133
134 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
134 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
135
135
136 # we need the directory where IPython itself is installed
136 # we need the directory where IPython itself is installed
137 import IPython
137 import IPython
138 IPython_dir = os.path.dirname(IPython.__file__)
138 IPython_dir = os.path.dirname(IPython.__file__)
139 del IPython
139 del IPython
140
140
141 #-------------------------------------------------------------------------
141 #-------------------------------------------------------------------------
142 # Command line handling
142 # Command line handling
143
143
144 # Valid command line options (uses DPyGetOpt syntax, like Perl's
144 # Valid command line options (uses DPyGetOpt syntax, like Perl's
145 # GetOpt::Long)
145 # GetOpt::Long)
146
146
147 # Any key not listed here gets deleted even if in the file (like session
147 # Any key not listed here gets deleted even if in the file (like session
148 # or profile). That's deliberate, to maintain the rc namespace clean.
148 # or profile). That's deliberate, to maintain the rc namespace clean.
149
149
150 # Each set of options appears twice: under _conv only the names are
150 # Each set of options appears twice: under _conv only the names are
151 # listed, indicating which type they must be converted to when reading the
151 # listed, indicating which type they must be converted to when reading the
152 # ipythonrc file. And under DPyGetOpt they are listed with the regular
152 # ipythonrc file. And under DPyGetOpt they are listed with the regular
153 # DPyGetOpt syntax (=s,=i,:f,etc).
153 # DPyGetOpt syntax (=s,=i,:f,etc).
154
154
155 # Make sure there's a space before each end of line (they get auto-joined!)
155 # Make sure there's a space before each end of line (they get auto-joined!)
156 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
156 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
157 'c=s classic|cl color_info! colors=s confirm_exit! '
157 'c=s classic|cl color_info! colors=s confirm_exit! '
158 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
158 'debug! deep_reload! editor=s log|l messages! nosep '
159 'object_info_string_level=i pdb! '
159 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
160 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
160 'quick screen_length|sl=i prompts_pad_left=i '
161 'quick screen_length|sl=i prompts_pad_left=i '
161 'logfile|lf=s logplay|lp=s profile|p=s '
162 'logfile|lf=s logplay|lp=s profile|p=s '
162 'readline! readline_merge_completions! '
163 'readline! readline_merge_completions! '
163 'readline_omit__names! '
164 'readline_omit__names! '
164 'rcfile=s separate_in|si=s separate_out|so=s '
165 'rcfile=s separate_in|si=s separate_out|so=s '
165 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
166 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
166 'magic_docstrings system_verbose! '
167 'magic_docstrings system_verbose! '
167 'multi_line_specials! '
168 'multi_line_specials! '
168 'wxversion=s '
169 'wxversion=s '
169 'autoedit_syntax!')
170 'autoedit_syntax!')
170
171
171 # Options that can *only* appear at the cmd line (not in rcfiles).
172 # Options that can *only* appear at the cmd line (not in rcfiles).
172
173
173 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
174 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
174 # the 'C-c !' command in emacs automatically appends a -i option at the end.
175 # the 'C-c !' command in emacs automatically appends a -i option at the end.
175 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
176 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
176 'gthread! qthread! wthread! pylab! tk!')
177 'gthread! qthread! wthread! pylab! tk!')
177
178
178 # Build the actual name list to be used by DPyGetOpt
179 # Build the actual name list to be used by DPyGetOpt
179 opts_names = qw(cmdline_opts) + qw(cmdline_only)
180 opts_names = qw(cmdline_opts) + qw(cmdline_only)
180
181
181 # Set sensible command line defaults.
182 # Set sensible command line defaults.
182 # This should have everything from cmdline_opts and cmdline_only
183 # This should have everything from cmdline_opts and cmdline_only
183 opts_def = Struct(autocall = 1,
184 opts_def = Struct(autocall = 1,
184 autoedit_syntax = 0,
185 autoedit_syntax = 0,
185 autoindent = 0,
186 autoindent = 0,
186 automagic = 1,
187 automagic = 1,
187 banner = 1,
188 banner = 1,
188 cache_size = 1000,
189 cache_size = 1000,
189 c = '',
190 c = '',
190 classic = 0,
191 classic = 0,
191 colors = 'NoColor',
192 colors = 'NoColor',
192 color_info = 0,
193 color_info = 0,
193 confirm_exit = 1,
194 confirm_exit = 1,
194 debug = 0,
195 debug = 0,
195 deep_reload = 0,
196 deep_reload = 0,
196 editor = '0',
197 editor = '0',
197 help = 0,
198 help = 0,
198 ignore = 0,
199 ignore = 0,
199 ipythondir = ipythondir,
200 ipythondir = ipythondir,
200 log = 0,
201 log = 0,
201 logfile = '',
202 logfile = '',
202 logplay = '',
203 logplay = '',
203 multi_line_specials = 1,
204 multi_line_specials = 1,
204 messages = 1,
205 messages = 1,
206 object_info_string_level = 0,
205 nosep = 0,
207 nosep = 0,
206 pdb = 0,
208 pdb = 0,
207 pprint = 0,
209 pprint = 0,
208 profile = '',
210 profile = '',
209 prompt_in1 = 'In [\\#]: ',
211 prompt_in1 = 'In [\\#]: ',
210 prompt_in2 = ' .\\D.: ',
212 prompt_in2 = ' .\\D.: ',
211 prompt_out = 'Out[\\#]: ',
213 prompt_out = 'Out[\\#]: ',
212 prompts_pad_left = 1,
214 prompts_pad_left = 1,
213 quick = 0,
215 quick = 0,
214 readline = 1,
216 readline = 1,
215 readline_merge_completions = 1,
217 readline_merge_completions = 1,
216 readline_omit__names = 0,
218 readline_omit__names = 0,
217 rcfile = 'ipythonrc' + rc_suffix,
219 rcfile = 'ipythonrc' + rc_suffix,
218 screen_length = 0,
220 screen_length = 0,
219 separate_in = '\n',
221 separate_in = '\n',
220 separate_out = '\n',
222 separate_out = '\n',
221 separate_out2 = '',
223 separate_out2 = '',
222 system_verbose = 0,
224 system_verbose = 0,
223 gthread = 0,
225 gthread = 0,
224 qthread = 0,
226 qthread = 0,
225 wthread = 0,
227 wthread = 0,
226 pylab = 0,
228 pylab = 0,
227 tk = 0,
229 tk = 0,
228 upgrade = 0,
230 upgrade = 0,
229 Version = 0,
231 Version = 0,
230 xmode = 'Verbose',
232 xmode = 'Verbose',
231 wildcards_case_sensitive = 1,
233 wildcards_case_sensitive = 1,
232 wxversion = '0',
234 wxversion = '0',
233 magic_docstrings = 0, # undocumented, for doc generation
235 magic_docstrings = 0, # undocumented, for doc generation
234 )
236 )
235
237
236 # Things that will *only* appear in rcfiles (not at the command line).
238 # Things that will *only* appear in rcfiles (not at the command line).
237 # Make sure there's a space before each end of line (they get auto-joined!)
239 # Make sure there's a space before each end of line (they get auto-joined!)
238 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
240 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
239 qw_lol: 'import_some ',
241 qw_lol: 'import_some ',
240 # for things with embedded whitespace:
242 # for things with embedded whitespace:
241 list_strings:'execute alias readline_parse_and_bind ',
243 list_strings:'execute alias readline_parse_and_bind ',
242 # Regular strings need no conversion:
244 # Regular strings need no conversion:
243 None:'readline_remove_delims ',
245 None:'readline_remove_delims ',
244 }
246 }
245 # Default values for these
247 # Default values for these
246 rc_def = Struct(include = [],
248 rc_def = Struct(include = [],
247 import_mod = [],
249 import_mod = [],
248 import_all = [],
250 import_all = [],
249 import_some = [[]],
251 import_some = [[]],
250 execute = [],
252 execute = [],
251 execfile = [],
253 execfile = [],
252 alias = [],
254 alias = [],
253 readline_parse_and_bind = [],
255 readline_parse_and_bind = [],
254 readline_remove_delims = '',
256 readline_remove_delims = '',
255 )
257 )
256
258
257 # Build the type conversion dictionary from the above tables:
259 # Build the type conversion dictionary from the above tables:
258 typeconv = rcfile_opts.copy()
260 typeconv = rcfile_opts.copy()
259 typeconv.update(optstr2types(cmdline_opts))
261 typeconv.update(optstr2types(cmdline_opts))
260
262
261 # FIXME: the None key appears in both, put that back together by hand. Ugly!
263 # FIXME: the None key appears in both, put that back together by hand. Ugly!
262 typeconv[None] += ' ' + rcfile_opts[None]
264 typeconv[None] += ' ' + rcfile_opts[None]
263
265
264 # Remove quotes at ends of all strings (used to protect spaces)
266 # Remove quotes at ends of all strings (used to protect spaces)
265 typeconv[unquote_ends] = typeconv[None]
267 typeconv[unquote_ends] = typeconv[None]
266 del typeconv[None]
268 del typeconv[None]
267
269
268 # Build the list we'll use to make all config decisions with defaults:
270 # Build the list we'll use to make all config decisions with defaults:
269 opts_all = opts_def.copy()
271 opts_all = opts_def.copy()
270 opts_all.update(rc_def)
272 opts_all.update(rc_def)
271
273
272 # Build conflict resolver for recursive loading of config files:
274 # Build conflict resolver for recursive loading of config files:
273 # - preserve means the outermost file maintains the value, it is not
275 # - preserve means the outermost file maintains the value, it is not
274 # overwritten if an included file has the same key.
276 # overwritten if an included file has the same key.
275 # - add_flip applies + to the two values, so it better make sense to add
277 # - add_flip applies + to the two values, so it better make sense to add
276 # those types of keys. But it flips them first so that things loaded
278 # those types of keys. But it flips them first so that things loaded
277 # deeper in the inclusion chain have lower precedence.
279 # deeper in the inclusion chain have lower precedence.
278 conflict = {'preserve': ' '.join([ typeconv[int],
280 conflict = {'preserve': ' '.join([ typeconv[int],
279 typeconv[unquote_ends] ]),
281 typeconv[unquote_ends] ]),
280 'add_flip': ' '.join([ typeconv[qwflat],
282 'add_flip': ' '.join([ typeconv[qwflat],
281 typeconv[qw_lol],
283 typeconv[qw_lol],
282 typeconv[list_strings] ])
284 typeconv[list_strings] ])
283 }
285 }
284
286
285 # Now actually process the command line
287 # Now actually process the command line
286 getopt = DPyGetOpt.DPyGetOpt()
288 getopt = DPyGetOpt.DPyGetOpt()
287 getopt.setIgnoreCase(0)
289 getopt.setIgnoreCase(0)
288
290
289 getopt.parseConfiguration(opts_names)
291 getopt.parseConfiguration(opts_names)
290
292
291 try:
293 try:
292 getopt.processArguments(argv)
294 getopt.processArguments(argv)
293 except:
295 except:
294 print cmd_line_usage
296 print cmd_line_usage
295 warn('\nError in Arguments: ' + `sys.exc_value`)
297 warn('\nError in Arguments: ' + `sys.exc_value`)
296 sys.exit(1)
298 sys.exit(1)
297
299
298 # convert the options dict to a struct for much lighter syntax later
300 # convert the options dict to a struct for much lighter syntax later
299 opts = Struct(getopt.optionValues)
301 opts = Struct(getopt.optionValues)
300 args = getopt.freeValues
302 args = getopt.freeValues
301
303
302 # this is the struct (which has default values at this point) with which
304 # this is the struct (which has default values at this point) with which
303 # we make all decisions:
305 # we make all decisions:
304 opts_all.update(opts)
306 opts_all.update(opts)
305
307
306 # Options that force an immediate exit
308 # Options that force an immediate exit
307 if opts_all.help:
309 if opts_all.help:
308 page(cmd_line_usage)
310 page(cmd_line_usage)
309 sys.exit()
311 sys.exit()
310
312
311 if opts_all.Version:
313 if opts_all.Version:
312 print __version__
314 print __version__
313 sys.exit()
315 sys.exit()
314
316
315 if opts_all.magic_docstrings:
317 if opts_all.magic_docstrings:
316 IP.magic_magic('-latex')
318 IP.magic_magic('-latex')
317 sys.exit()
319 sys.exit()
318
320
319 # Create user config directory if it doesn't exist. This must be done
321 # Create user config directory if it doesn't exist. This must be done
320 # *after* getting the cmd line options.
322 # *after* getting the cmd line options.
321 if not os.path.isdir(opts_all.ipythondir):
323 if not os.path.isdir(opts_all.ipythondir):
322 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
324 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
323
325
324 # upgrade user config files while preserving a copy of the originals
326 # upgrade user config files while preserving a copy of the originals
325 if opts_all.upgrade:
327 if opts_all.upgrade:
326 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
328 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
327
329
328 # check mutually exclusive options in the *original* command line
330 # check mutually exclusive options in the *original* command line
329 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
331 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
330 qw('classic profile'),qw('classic rcfile')])
332 qw('classic profile'),qw('classic rcfile')])
331
333
332 # Fix up sys.argv to omit the ipython call, for consistency with how
334 # Fix up sys.argv to omit the ipython call, for consistency with how
333 # Python itself operates (the inconsistency can break user scripts which
335 # Python itself operates (the inconsistency can break user scripts which
334 # rely on the Python behavior when run under ipython).
336 # rely on the Python behavior when run under ipython).
335 sys.argv[:] = sys.argv[1:]
337 sys.argv[:] = sys.argv[1:]
336
338
337 #---------------------------------------------------------------------------
339 #---------------------------------------------------------------------------
338 # Log replay
340 # Log replay
339
341
340 # if -logplay, we need to 'become' the other session. That basically means
342 # if -logplay, we need to 'become' the other session. That basically means
341 # replacing the current command line environment with that of the old
343 # replacing the current command line environment with that of the old
342 # session and moving on.
344 # session and moving on.
343
345
344 # this is needed so that later we know we're in session reload mode, as
346 # this is needed so that later we know we're in session reload mode, as
345 # opts_all will get overwritten:
347 # opts_all will get overwritten:
346 load_logplay = 0
348 load_logplay = 0
347
349
348 if opts_all.logplay:
350 if opts_all.logplay:
349 load_logplay = opts_all.logplay
351 load_logplay = opts_all.logplay
350 opts_debug_save = opts_all.debug
352 opts_debug_save = opts_all.debug
351 try:
353 try:
352 logplay = open(opts_all.logplay)
354 logplay = open(opts_all.logplay)
353 except IOError:
355 except IOError:
354 if opts_all.debug: IP.InteractiveTB()
356 if opts_all.debug: IP.InteractiveTB()
355 warn('Could not open logplay file '+`opts_all.logplay`)
357 warn('Could not open logplay file '+`opts_all.logplay`)
356 # restore state as if nothing had happened and move on, but make
358 # restore state as if nothing had happened and move on, but make
357 # sure that later we don't try to actually load the session file
359 # sure that later we don't try to actually load the session file
358 logplay = None
360 logplay = None
359 load_logplay = 0
361 load_logplay = 0
360 del opts_all.logplay
362 del opts_all.logplay
361 else:
363 else:
362 try:
364 try:
363 logplay.readline()
365 logplay.readline()
364 logplay.readline();
366 logplay.readline();
365 # this reloads that session's command line
367 # this reloads that session's command line
366 cmd = logplay.readline()[6:]
368 cmd = logplay.readline()[6:]
367 exec cmd
369 exec cmd
368 # restore the true debug flag given so that the process of
370 # restore the true debug flag given so that the process of
369 # session loading itself can be monitored.
371 # session loading itself can be monitored.
370 opts.debug = opts_debug_save
372 opts.debug = opts_debug_save
371 # save the logplay flag so later we don't overwrite the log
373 # save the logplay flag so later we don't overwrite the log
372 opts.logplay = load_logplay
374 opts.logplay = load_logplay
373 # now we must update our own structure with defaults
375 # now we must update our own structure with defaults
374 opts_all.update(opts)
376 opts_all.update(opts)
375 # now load args
377 # now load args
376 cmd = logplay.readline()[6:]
378 cmd = logplay.readline()[6:]
377 exec cmd
379 exec cmd
378 logplay.close()
380 logplay.close()
379 except:
381 except:
380 logplay.close()
382 logplay.close()
381 if opts_all.debug: IP.InteractiveTB()
383 if opts_all.debug: IP.InteractiveTB()
382 warn("Logplay file lacking full configuration information.\n"
384 warn("Logplay file lacking full configuration information.\n"
383 "I'll try to read it, but some things may not work.")
385 "I'll try to read it, but some things may not work.")
384
386
385 #-------------------------------------------------------------------------
387 #-------------------------------------------------------------------------
386 # set up output traps: catch all output from files, being run, modules
388 # set up output traps: catch all output from files, being run, modules
387 # loaded, etc. Then give it to the user in a clean form at the end.
389 # loaded, etc. Then give it to the user in a clean form at the end.
388
390
389 msg_out = 'Output messages. '
391 msg_out = 'Output messages. '
390 msg_err = 'Error messages. '
392 msg_err = 'Error messages. '
391 msg_sep = '\n'
393 msg_sep = '\n'
392 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
394 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
393 msg_err,msg_sep,debug,
395 msg_err,msg_sep,debug,
394 quiet_out=1),
396 quiet_out=1),
395 user_exec = OutputTrap('User File Execution',msg_out,
397 user_exec = OutputTrap('User File Execution',msg_out,
396 msg_err,msg_sep,debug),
398 msg_err,msg_sep,debug),
397 logplay = OutputTrap('Log Loader',msg_out,
399 logplay = OutputTrap('Log Loader',msg_out,
398 msg_err,msg_sep,debug),
400 msg_err,msg_sep,debug),
399 summary = ''
401 summary = ''
400 )
402 )
401
403
402 #-------------------------------------------------------------------------
404 #-------------------------------------------------------------------------
403 # Process user ipythonrc-type configuration files
405 # Process user ipythonrc-type configuration files
404
406
405 # turn on output trapping and log to msg.config
407 # turn on output trapping and log to msg.config
406 # remember that with debug on, trapping is actually disabled
408 # remember that with debug on, trapping is actually disabled
407 msg.config.trap_all()
409 msg.config.trap_all()
408
410
409 # look for rcfile in current or default directory
411 # look for rcfile in current or default directory
410 try:
412 try:
411 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
413 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
412 except IOError:
414 except IOError:
413 if opts_all.debug: IP.InteractiveTB()
415 if opts_all.debug: IP.InteractiveTB()
414 warn('Configuration file %s not found. Ignoring request.'
416 warn('Configuration file %s not found. Ignoring request.'
415 % (opts_all.rcfile) )
417 % (opts_all.rcfile) )
416
418
417 # 'profiles' are a shorthand notation for config filenames
419 # 'profiles' are a shorthand notation for config filenames
418 if opts_all.profile:
420 if opts_all.profile:
419
421
420 try:
422 try:
421 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
423 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
422 + rc_suffix,
424 + rc_suffix,
423 opts_all.ipythondir)
425 opts_all.ipythondir)
424 except IOError:
426 except IOError:
425 if opts_all.debug: IP.InteractiveTB()
427 if opts_all.debug: IP.InteractiveTB()
426 opts.profile = '' # remove profile from options if invalid
428 opts.profile = '' # remove profile from options if invalid
427 # We won't warn anymore, primary method is ipy_profile_PROFNAME
429 # We won't warn anymore, primary method is ipy_profile_PROFNAME
428 # which does trigger a warning.
430 # which does trigger a warning.
429
431
430 # load the config file
432 # load the config file
431 rcfiledata = None
433 rcfiledata = None
432 if opts_all.quick:
434 if opts_all.quick:
433 print 'Launching IPython in quick mode. No config file read.'
435 print 'Launching IPython in quick mode. No config file read.'
434 elif opts_all.classic:
436 elif opts_all.classic:
435 print 'Launching IPython in classic mode. No config file read.'
437 print 'Launching IPython in classic mode. No config file read.'
436 elif opts_all.rcfile:
438 elif opts_all.rcfile:
437 try:
439 try:
438 cfg_loader = ConfigLoader(conflict)
440 cfg_loader = ConfigLoader(conflict)
439 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
441 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
440 'include',opts_all.ipythondir,
442 'include',opts_all.ipythondir,
441 purge = 1,
443 purge = 1,
442 unique = conflict['preserve'])
444 unique = conflict['preserve'])
443 except:
445 except:
444 IP.InteractiveTB()
446 IP.InteractiveTB()
445 warn('Problems loading configuration file '+
447 warn('Problems loading configuration file '+
446 `opts_all.rcfile`+
448 `opts_all.rcfile`+
447 '\nStarting with default -bare bones- configuration.')
449 '\nStarting with default -bare bones- configuration.')
448 else:
450 else:
449 warn('No valid configuration file found in either currrent directory\n'+
451 warn('No valid configuration file found in either currrent directory\n'+
450 'or in the IPython config. directory: '+`opts_all.ipythondir`+
452 'or in the IPython config. directory: '+`opts_all.ipythondir`+
451 '\nProceeding with internal defaults.')
453 '\nProceeding with internal defaults.')
452
454
453 #------------------------------------------------------------------------
455 #------------------------------------------------------------------------
454 # Set exception handlers in mode requested by user.
456 # Set exception handlers in mode requested by user.
455 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
457 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
456 IP.magic_xmode(opts_all.xmode)
458 IP.magic_xmode(opts_all.xmode)
457 otrap.release_out()
459 otrap.release_out()
458
460
459 #------------------------------------------------------------------------
461 #------------------------------------------------------------------------
460 # Execute user config
462 # Execute user config
461
463
462 # Create a valid config structure with the right precedence order:
464 # Create a valid config structure with the right precedence order:
463 # defaults < rcfile < command line. This needs to be in the instance, so
465 # defaults < rcfile < command line. This needs to be in the instance, so
464 # that method calls below that rely on it find it.
466 # that method calls below that rely on it find it.
465 IP.rc = rc_def.copy()
467 IP.rc = rc_def.copy()
466
468
467 # Work with a local alias inside this routine to avoid unnecessary
469 # Work with a local alias inside this routine to avoid unnecessary
468 # attribute lookups.
470 # attribute lookups.
469 IP_rc = IP.rc
471 IP_rc = IP.rc
470
472
471 IP_rc.update(opts_def)
473 IP_rc.update(opts_def)
472 if rcfiledata:
474 if rcfiledata:
473 # now we can update
475 # now we can update
474 IP_rc.update(rcfiledata)
476 IP_rc.update(rcfiledata)
475 IP_rc.update(opts)
477 IP_rc.update(opts)
476 IP_rc.update(rc_override)
478 IP_rc.update(rc_override)
477
479
478 # Store the original cmd line for reference:
480 # Store the original cmd line for reference:
479 IP_rc.opts = opts
481 IP_rc.opts = opts
480 IP_rc.args = args
482 IP_rc.args = args
481
483
482 # create a *runtime* Struct like rc for holding parameters which may be
484 # create a *runtime* Struct like rc for holding parameters which may be
483 # created and/or modified by runtime user extensions.
485 # created and/or modified by runtime user extensions.
484 IP.runtime_rc = Struct()
486 IP.runtime_rc = Struct()
485
487
486 # from this point on, all config should be handled through IP_rc,
488 # from this point on, all config should be handled through IP_rc,
487 # opts* shouldn't be used anymore.
489 # opts* shouldn't be used anymore.
488
490
489
491
490 # update IP_rc with some special things that need manual
492 # update IP_rc with some special things that need manual
491 # tweaks. Basically options which affect other options. I guess this
493 # tweaks. Basically options which affect other options. I guess this
492 # should just be written so that options are fully orthogonal and we
494 # should just be written so that options are fully orthogonal and we
493 # wouldn't worry about this stuff!
495 # wouldn't worry about this stuff!
494
496
495 if IP_rc.classic:
497 if IP_rc.classic:
496 IP_rc.quick = 1
498 IP_rc.quick = 1
497 IP_rc.cache_size = 0
499 IP_rc.cache_size = 0
498 IP_rc.pprint = 0
500 IP_rc.pprint = 0
499 IP_rc.prompt_in1 = '>>> '
501 IP_rc.prompt_in1 = '>>> '
500 IP_rc.prompt_in2 = '... '
502 IP_rc.prompt_in2 = '... '
501 IP_rc.prompt_out = ''
503 IP_rc.prompt_out = ''
502 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
504 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
503 IP_rc.colors = 'NoColor'
505 IP_rc.colors = 'NoColor'
504 IP_rc.xmode = 'Plain'
506 IP_rc.xmode = 'Plain'
505
507
506 IP.pre_config_initialization()
508 IP.pre_config_initialization()
507 # configure readline
509 # configure readline
508 # Define the history file for saving commands in between sessions
510 # Define the history file for saving commands in between sessions
509 if IP_rc.profile:
511 if IP_rc.profile:
510 histfname = 'history-%s' % IP_rc.profile
512 histfname = 'history-%s' % IP_rc.profile
511 else:
513 else:
512 histfname = 'history'
514 histfname = 'history'
513 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
515 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
514
516
515 # update exception handlers with rc file status
517 # update exception handlers with rc file status
516 otrap.trap_out() # I don't want these messages ever.
518 otrap.trap_out() # I don't want these messages ever.
517 IP.magic_xmode(IP_rc.xmode)
519 IP.magic_xmode(IP_rc.xmode)
518 otrap.release_out()
520 otrap.release_out()
519
521
520 # activate logging if requested and not reloading a log
522 # activate logging if requested and not reloading a log
521 if IP_rc.logplay:
523 if IP_rc.logplay:
522 IP.magic_logstart(IP_rc.logplay + ' append')
524 IP.magic_logstart(IP_rc.logplay + ' append')
523 elif IP_rc.logfile:
525 elif IP_rc.logfile:
524 IP.magic_logstart(IP_rc.logfile)
526 IP.magic_logstart(IP_rc.logfile)
525 elif IP_rc.log:
527 elif IP_rc.log:
526 IP.magic_logstart()
528 IP.magic_logstart()
527
529
528 # find user editor so that it we don't have to look it up constantly
530 # find user editor so that it we don't have to look it up constantly
529 if IP_rc.editor.strip()=='0':
531 if IP_rc.editor.strip()=='0':
530 try:
532 try:
531 ed = os.environ['EDITOR']
533 ed = os.environ['EDITOR']
532 except KeyError:
534 except KeyError:
533 if os.name == 'posix':
535 if os.name == 'posix':
534 ed = 'vi' # the only one guaranteed to be there!
536 ed = 'vi' # the only one guaranteed to be there!
535 else:
537 else:
536 ed = 'notepad' # same in Windows!
538 ed = 'notepad' # same in Windows!
537 IP_rc.editor = ed
539 IP_rc.editor = ed
538
540
539 # Keep track of whether this is an embedded instance or not (useful for
541 # Keep track of whether this is an embedded instance or not (useful for
540 # post-mortems).
542 # post-mortems).
541 IP_rc.embedded = IP.embedded
543 IP_rc.embedded = IP.embedded
542
544
543 # Recursive reload
545 # Recursive reload
544 try:
546 try:
545 from IPython import deep_reload
547 from IPython import deep_reload
546 if IP_rc.deep_reload:
548 if IP_rc.deep_reload:
547 __builtin__.reload = deep_reload.reload
549 __builtin__.reload = deep_reload.reload
548 else:
550 else:
549 __builtin__.dreload = deep_reload.reload
551 __builtin__.dreload = deep_reload.reload
550 del deep_reload
552 del deep_reload
551 except ImportError:
553 except ImportError:
552 pass
554 pass
553
555
554 # Save the current state of our namespace so that the interactive shell
556 # Save the current state of our namespace so that the interactive shell
555 # can later know which variables have been created by us from config files
557 # can later know which variables have been created by us from config files
556 # and loading. This way, loading a file (in any way) is treated just like
558 # and loading. This way, loading a file (in any way) is treated just like
557 # defining things on the command line, and %who works as expected.
559 # defining things on the command line, and %who works as expected.
558
560
559 # DON'T do anything that affects the namespace beyond this point!
561 # DON'T do anything that affects the namespace beyond this point!
560 IP.internal_ns.update(__main__.__dict__)
562 IP.internal_ns.update(__main__.__dict__)
561
563
562 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
564 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
563
565
564 # Now run through the different sections of the users's config
566 # Now run through the different sections of the users's config
565 if IP_rc.debug:
567 if IP_rc.debug:
566 print 'Trying to execute the following configuration structure:'
568 print 'Trying to execute the following configuration structure:'
567 print '(Things listed first are deeper in the inclusion tree and get'
569 print '(Things listed first are deeper in the inclusion tree and get'
568 print 'loaded first).\n'
570 print 'loaded first).\n'
569 pprint(IP_rc.__dict__)
571 pprint(IP_rc.__dict__)
570
572
571 for mod in IP_rc.import_mod:
573 for mod in IP_rc.import_mod:
572 try:
574 try:
573 exec 'import '+mod in IP.user_ns
575 exec 'import '+mod in IP.user_ns
574 except :
576 except :
575 IP.InteractiveTB()
577 IP.InteractiveTB()
576 import_fail_info(mod)
578 import_fail_info(mod)
577
579
578 for mod_fn in IP_rc.import_some:
580 for mod_fn in IP_rc.import_some:
579 if mod_fn == []: break
581 if mod_fn == []: break
580 mod,fn = mod_fn[0],','.join(mod_fn[1:])
582 mod,fn = mod_fn[0],','.join(mod_fn[1:])
581 try:
583 try:
582 exec 'from '+mod+' import '+fn in IP.user_ns
584 exec 'from '+mod+' import '+fn in IP.user_ns
583 except :
585 except :
584 IP.InteractiveTB()
586 IP.InteractiveTB()
585 import_fail_info(mod,fn)
587 import_fail_info(mod,fn)
586
588
587 for mod in IP_rc.import_all:
589 for mod in IP_rc.import_all:
588 try:
590 try:
589 exec 'from '+mod+' import *' in IP.user_ns
591 exec 'from '+mod+' import *' in IP.user_ns
590 except :
592 except :
591 IP.InteractiveTB()
593 IP.InteractiveTB()
592 import_fail_info(mod)
594 import_fail_info(mod)
593
595
594 for code in IP_rc.execute:
596 for code in IP_rc.execute:
595 try:
597 try:
596 exec code in IP.user_ns
598 exec code in IP.user_ns
597 except:
599 except:
598 IP.InteractiveTB()
600 IP.InteractiveTB()
599 warn('Failure executing code: ' + `code`)
601 warn('Failure executing code: ' + `code`)
600
602
601 # Execute the files the user wants in ipythonrc
603 # Execute the files the user wants in ipythonrc
602 for file in IP_rc.execfile:
604 for file in IP_rc.execfile:
603 try:
605 try:
604 file = filefind(file,sys.path+[IPython_dir])
606 file = filefind(file,sys.path+[IPython_dir])
605 except IOError:
607 except IOError:
606 warn(itpl('File $file not found. Skipping it.'))
608 warn(itpl('File $file not found. Skipping it.'))
607 else:
609 else:
608 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
610 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
609
611
610 # finally, try importing ipy_*_conf for final configuration
612 # finally, try importing ipy_*_conf for final configuration
611 try:
613 try:
612 import ipy_system_conf
614 import ipy_system_conf
613 except ImportError:
615 except ImportError:
614 if opts_all.debug: IP.InteractiveTB()
616 if opts_all.debug: IP.InteractiveTB()
615 warn("Could not import 'ipy_system_conf'")
617 warn("Could not import 'ipy_system_conf'")
616 except:
618 except:
617 IP.InteractiveTB()
619 IP.InteractiveTB()
618 import_fail_info('ipy_system_conf')
620 import_fail_info('ipy_system_conf')
619
621
620 if opts_all.profile:
622 if opts_all.profile:
621 profmodname = 'ipy_profile_' + opts_all.profile
623 profmodname = 'ipy_profile_' + opts_all.profile
622 try:
624 try:
623 __import__(profmodname)
625 __import__(profmodname)
624 except ImportError:
626 except ImportError:
625 # only warn if ipythonrc-PROFNAME didn't exist
627 # only warn if ipythonrc-PROFNAME didn't exist
626 if opts.profile =='':
628 if opts.profile =='':
627 warn("Could not start with profile '%s'!\n ('%s/%s.py' does not exist? run '%%upgrade')" % (
629 warn("Could not start with profile '%s'!\n ('%s/%s.py' does not exist? run '%%upgrade')" % (
628 opts_all.profile, ipythondir, profmodname)
630 opts_all.profile, ipythondir, profmodname)
629
631
630 )
632 )
631 except:
633 except:
632 print "Error importing",profmodname
634 print "Error importing",profmodname
633 IP.InteractiveTB()
635 IP.InteractiveTB()
634 import_fail_info(profmodname)
636 import_fail_info(profmodname)
635
637
636 try:
638 try:
637 import ipy_user_conf
639 import ipy_user_conf
638 except ImportError:
640 except ImportError:
639 if opts_all.debug: IP.InteractiveTB()
641 if opts_all.debug: IP.InteractiveTB()
640 warn("Could not import user config!\n ('%s/ipy_user_conf.py' does not exist? Please run '%%upgrade')\n" %
642 warn("Could not import user config!\n ('%s/ipy_user_conf.py' does not exist? Please run '%%upgrade')\n" %
641 ipythondir)
643 ipythondir)
642 except:
644 except:
643 print "Error importing ipy_user_conf"
645 print "Error importing ipy_user_conf"
644 IP.InteractiveTB()
646 IP.InteractiveTB()
645 import_fail_info("ipy_user_conf")
647 import_fail_info("ipy_user_conf")
646
648
647
649
648 # release stdout and stderr and save config log into a global summary
650 # release stdout and stderr and save config log into a global summary
649 msg.config.release_all()
651 msg.config.release_all()
650 if IP_rc.messages:
652 if IP_rc.messages:
651 msg.summary += msg.config.summary_all()
653 msg.summary += msg.config.summary_all()
652
654
653 #------------------------------------------------------------------------
655 #------------------------------------------------------------------------
654 # Setup interactive session
656 # Setup interactive session
655
657
656 # Now we should be fully configured. We can then execute files or load
658 # Now we should be fully configured. We can then execute files or load
657 # things only needed for interactive use. Then we'll open the shell.
659 # things only needed for interactive use. Then we'll open the shell.
658
660
659 # Take a snapshot of the user namespace before opening the shell. That way
661 # Take a snapshot of the user namespace before opening the shell. That way
660 # we'll be able to identify which things were interactively defined and
662 # we'll be able to identify which things were interactively defined and
661 # which were defined through config files.
663 # which were defined through config files.
662 IP.user_config_ns = IP.user_ns.copy()
664 IP.user_config_ns = IP.user_ns.copy()
663
665
664 # Force reading a file as if it were a session log. Slower but safer.
666 # Force reading a file as if it were a session log. Slower but safer.
665 if load_logplay:
667 if load_logplay:
666 print 'Replaying log...'
668 print 'Replaying log...'
667 try:
669 try:
668 if IP_rc.debug:
670 if IP_rc.debug:
669 logplay_quiet = 0
671 logplay_quiet = 0
670 else:
672 else:
671 logplay_quiet = 1
673 logplay_quiet = 1
672
674
673 msg.logplay.trap_all()
675 msg.logplay.trap_all()
674 IP.safe_execfile(load_logplay,IP.user_ns,
676 IP.safe_execfile(load_logplay,IP.user_ns,
675 islog = 1, quiet = logplay_quiet)
677 islog = 1, quiet = logplay_quiet)
676 msg.logplay.release_all()
678 msg.logplay.release_all()
677 if IP_rc.messages:
679 if IP_rc.messages:
678 msg.summary += msg.logplay.summary_all()
680 msg.summary += msg.logplay.summary_all()
679 except:
681 except:
680 warn('Problems replaying logfile %s.' % load_logplay)
682 warn('Problems replaying logfile %s.' % load_logplay)
681 IP.InteractiveTB()
683 IP.InteractiveTB()
682
684
683 # Load remaining files in command line
685 # Load remaining files in command line
684 msg.user_exec.trap_all()
686 msg.user_exec.trap_all()
685
687
686 # Do NOT execute files named in the command line as scripts to be loaded
688 # Do NOT execute files named in the command line as scripts to be loaded
687 # by embedded instances. Doing so has the potential for an infinite
689 # by embedded instances. Doing so has the potential for an infinite
688 # recursion if there are exceptions thrown in the process.
690 # recursion if there are exceptions thrown in the process.
689
691
690 # XXX FIXME: the execution of user files should be moved out to after
692 # XXX FIXME: the execution of user files should be moved out to after
691 # ipython is fully initialized, just as if they were run via %run at the
693 # ipython is fully initialized, just as if they were run via %run at the
692 # ipython prompt. This would also give them the benefit of ipython's
694 # ipython prompt. This would also give them the benefit of ipython's
693 # nice tracebacks.
695 # nice tracebacks.
694
696
695 if (not embedded and IP_rc.args and
697 if (not embedded and IP_rc.args and
696 not IP_rc.args[0].lower().endswith('.ipy')):
698 not IP_rc.args[0].lower().endswith('.ipy')):
697 name_save = IP.user_ns['__name__']
699 name_save = IP.user_ns['__name__']
698 IP.user_ns['__name__'] = '__main__'
700 IP.user_ns['__name__'] = '__main__'
699 # Set our own excepthook in case the user code tries to call it
701 # Set our own excepthook in case the user code tries to call it
700 # directly. This prevents triggering the IPython crash handler.
702 # directly. This prevents triggering the IPython crash handler.
701 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
703 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
702
704
703 save_argv = sys.argv[:] # save it for later restoring
705 save_argv = sys.argv[:] # save it for later restoring
704
706
705 sys.argv = args
707 sys.argv = args
706
708
707 try:
709 try:
708 IP.safe_execfile(args[0], IP.user_ns)
710 IP.safe_execfile(args[0], IP.user_ns)
709 finally:
711 finally:
710 # Reset our crash handler in place
712 # Reset our crash handler in place
711 sys.excepthook = old_excepthook
713 sys.excepthook = old_excepthook
712 sys.argv = save_argv
714 sys.argv = save_argv
713 IP.user_ns['__name__'] = name_save
715 IP.user_ns['__name__'] = name_save
714
716
715 msg.user_exec.release_all()
717 msg.user_exec.release_all()
716 if IP_rc.messages:
718 if IP_rc.messages:
717 msg.summary += msg.user_exec.summary_all()
719 msg.summary += msg.user_exec.summary_all()
718
720
719 # since we can't specify a null string on the cmd line, 0 is the equivalent:
721 # since we can't specify a null string on the cmd line, 0 is the equivalent:
720 if IP_rc.nosep:
722 if IP_rc.nosep:
721 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
723 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
722 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
724 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
723 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
725 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
724 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
726 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
725 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
727 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
726 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
728 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
727 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
729 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
728
730
729 # Determine how many lines at the bottom of the screen are needed for
731 # Determine how many lines at the bottom of the screen are needed for
730 # showing prompts, so we can know wheter long strings are to be printed or
732 # showing prompts, so we can know wheter long strings are to be printed or
731 # paged:
733 # paged:
732 num_lines_bot = IP_rc.separate_in.count('\n')+1
734 num_lines_bot = IP_rc.separate_in.count('\n')+1
733 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
735 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
734
736
735 # configure startup banner
737 # configure startup banner
736 if IP_rc.c: # regular python doesn't print the banner with -c
738 if IP_rc.c: # regular python doesn't print the banner with -c
737 IP_rc.banner = 0
739 IP_rc.banner = 0
738 if IP_rc.banner:
740 if IP_rc.banner:
739 BANN_P = IP.BANNER_PARTS
741 BANN_P = IP.BANNER_PARTS
740 else:
742 else:
741 BANN_P = []
743 BANN_P = []
742
744
743 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
745 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
744
746
745 # add message log (possibly empty)
747 # add message log (possibly empty)
746 if msg.summary: BANN_P.append(msg.summary)
748 if msg.summary: BANN_P.append(msg.summary)
747 # Final banner is a string
749 # Final banner is a string
748 IP.BANNER = '\n'.join(BANN_P)
750 IP.BANNER = '\n'.join(BANN_P)
749
751
750 # Finalize the IPython instance. This assumes the rc structure is fully
752 # Finalize the IPython instance. This assumes the rc structure is fully
751 # in place.
753 # in place.
752 IP.post_config_initialization()
754 IP.post_config_initialization()
753
755
754 return IP
756 return IP
755 #************************ end of file <ipmaker.py> **************************
757 #************************ end of file <ipmaker.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