##// END OF EJS Templates
Merge from branches/0.7.1 into trunk, revs 1052-1057
vivainio -
Show More
@@ -1,461 +1,475 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 1016 2006-01-14 00:54:23Z vivainio $
9 $Id: OInspect.py 1058 2006-01-22 14:30:01Z vivainio $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
13 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #*****************************************************************************
17 #*****************************************************************************
18
18
19 from IPython import Release
19 from IPython import Release
20 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 __license__ = Release.license
21 __license__ = Release.license
22
22
23 __all__ = ['Inspector','InspectColors']
23 __all__ = ['Inspector','InspectColors']
24
24
25 # stdlib modules
25 # stdlib modules
26 import __builtin__
26 import __builtin__
27 import inspect
27 import inspect
28 import linecache
28 import linecache
29 import string
29 import string
30 import StringIO
30 import StringIO
31 import types
31 import types
32
32
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 self.color_table = color_table
111 self.color_table = color_table
112 self.parser = PyColorize.Parser(code_color_table,out='str')
112 self.parser = PyColorize.Parser(code_color_table,out='str')
113 self.format = self.parser.format
113 self.format = self.parser.format
114 self.set_active_scheme(scheme)
114 self.set_active_scheme(scheme)
115
115
116 def __getargspec(self,obj):
116 def __getargspec(self,obj):
117 """Get the names and default values of a function's arguments.
117 """Get the names and default values of a function's arguments.
118
118
119 A tuple of four things is returned: (args, varargs, varkw, defaults).
119 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).
120 '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.
121 '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.
122 'defaults' is an n-tuple of the default values of the last n arguments.
123
123
124 Modified version of inspect.getargspec from the Python Standard
124 Modified version of inspect.getargspec from the Python Standard
125 Library."""
125 Library."""
126
126
127 if inspect.isfunction(obj):
127 if inspect.isfunction(obj):
128 func_obj = obj
128 func_obj = obj
129 elif inspect.ismethod(obj):
129 elif inspect.ismethod(obj):
130 func_obj = obj.im_func
130 func_obj = obj.im_func
131 else:
131 else:
132 raise TypeError, 'arg is not a Python function'
132 raise TypeError, 'arg is not a Python function'
133 args, varargs, varkw = inspect.getargs(func_obj.func_code)
133 args, varargs, varkw = inspect.getargs(func_obj.func_code)
134 return args, varargs, varkw, func_obj.func_defaults
134 return args, varargs, varkw, func_obj.func_defaults
135
135
136 def __getdef(self,obj,oname=''):
136 def __getdef(self,obj,oname=''):
137 """Return the definition header for any callable object.
137 """Return the definition header for any callable object.
138
138
139 If any exception is generated, None is returned instead and the
139 If any exception is generated, None is returned instead and the
140 exception is suppressed."""
140 exception is suppressed."""
141
141
142 try:
142 try:
143 return oname + inspect.formatargspec(*self.__getargspec(obj))
143 return oname + inspect.formatargspec(*self.__getargspec(obj))
144 except:
144 except:
145 return None
145 return None
146
146
147 def __head(self,h):
147 def __head(self,h):
148 """Return a header string with proper colors."""
148 """Return a header string with proper colors."""
149 return '%s%s%s' % (self.color_table.active_colors.header,h,
149 return '%s%s%s' % (self.color_table.active_colors.header,h,
150 self.color_table.active_colors.normal)
150 self.color_table.active_colors.normal)
151
151
152 def set_active_scheme(self,scheme):
152 def set_active_scheme(self,scheme):
153 self.color_table.set_active_scheme(scheme)
153 self.color_table.set_active_scheme(scheme)
154 self.parser.color_table.set_active_scheme(scheme)
154 self.parser.color_table.set_active_scheme(scheme)
155
155
156 def noinfo(self,msg,oname):
156 def noinfo(self,msg,oname):
157 """Generic message when no information is found."""
157 """Generic message when no information is found."""
158 print 'No %s found' % msg,
158 print 'No %s found' % msg,
159 if oname:
159 if oname:
160 print 'for %s' % oname
160 print 'for %s' % oname
161 else:
161 else:
162 print
162 print
163
163
164 def pdef(self,obj,oname=''):
164 def pdef(self,obj,oname=''):
165 """Print the definition header for any callable object.
165 """Print the definition header for any callable object.
166
166
167 If the object is a class, print the constructor information."""
167 If the object is a class, print the constructor information."""
168
168
169 if not callable(obj):
169 if not callable(obj):
170 print 'Object is not callable.'
170 print 'Object is not callable.'
171 return
171 return
172
172
173 header = ''
173 header = ''
174 if type(obj) is types.ClassType:
174 if type(obj) is types.ClassType:
175 header = self.__head('Class constructor information:\n')
175 header = self.__head('Class constructor information:\n')
176 obj = obj.__init__
176 obj = obj.__init__
177 elif type(obj) is types.InstanceType:
177 elif type(obj) is types.InstanceType:
178 obj = obj.__call__
178 obj = obj.__call__
179
179
180 output = self.__getdef(obj,oname)
180 output = self.__getdef(obj,oname)
181 if output is None:
181 if output is None:
182 self.noinfo('definition header',oname)
182 self.noinfo('definition header',oname)
183 else:
183 else:
184 print >>Term.cout, header,self.format(output),
184 print >>Term.cout, header,self.format(output),
185
185
186 def pdoc(self,obj,oname='',formatter = None):
186 def pdoc(self,obj,oname='',formatter = None):
187 """Print the docstring for any object.
187 """Print the docstring for any object.
188
188
189 Optional:
189 Optional:
190 -formatter: a function to run the docstring through for specially
190 -formatter: a function to run the docstring through for specially
191 formatted docstrings."""
191 formatted docstrings."""
192
192
193 head = self.__head # so that itpl can find it even if private
193 head = self.__head # so that itpl can find it even if private
194 ds = getdoc(obj)
194 ds = getdoc(obj)
195 if formatter:
195 if formatter:
196 ds = formatter(ds)
196 ds = formatter(ds)
197 if type(obj) is types.ClassType:
197 if type(obj) is types.ClassType:
198 init_ds = getdoc(obj.__init__)
198 init_ds = getdoc(obj.__init__)
199 output = itpl('$head("Class Docstring:")\n'
199 output = itpl('$head("Class Docstring:")\n'
200 '$indent(ds)\n'
200 '$indent(ds)\n'
201 '$head("Constructor Docstring"):\n'
201 '$head("Constructor Docstring"):\n'
202 '$indent(init_ds)')
202 '$indent(init_ds)')
203 elif type(obj) is types.InstanceType and hasattr(obj,'__call__'):
203 elif type(obj) is types.InstanceType and hasattr(obj,'__call__'):
204 call_ds = getdoc(obj.__call__)
204 call_ds = getdoc(obj.__call__)
205 if call_ds:
205 if call_ds:
206 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
206 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
207 '$head("Calling Docstring:")\n$indent(call_ds)')
207 '$head("Calling Docstring:")\n$indent(call_ds)')
208 else:
208 else:
209 output = ds
209 output = ds
210 else:
210 else:
211 output = ds
211 output = ds
212 if output is None:
212 if output is None:
213 self.noinfo('documentation',oname)
213 self.noinfo('documentation',oname)
214 return
214 return
215 page(output)
215 page(output)
216
216
217 def psource(self,obj,oname=''):
217 def psource(self,obj,oname=''):
218 """Print the source code for an object."""
218 """Print the source code for an object."""
219
219
220 # Flush the source cache because inspect can return out-of-date source
220 # Flush the source cache because inspect can return out-of-date source
221 linecache.checkcache()
221 linecache.checkcache()
222 try:
222 try:
223 src = inspect.getsource(obj)
223 src = inspect.getsource(obj)
224 except:
224 except:
225 self.noinfo('source',oname)
225 self.noinfo('source',oname)
226 else:
226 else:
227 page(self.format(src))
227 page(self.format(src))
228
228
229 def pfile(self,obj,oname=''):
229 def pfile(self,obj,oname=''):
230 """Show the whole file where an object was defined."""
230 """Show the whole file where an object was defined."""
231 try:
231 try:
232 sourcelines,lineno = inspect.getsourcelines(obj)
232 sourcelines,lineno = inspect.getsourcelines(obj)
233 except:
233 except:
234 self.noinfo('file',oname)
234 self.noinfo('file',oname)
235 else:
235 else:
236 # run contents of file through pager starting at line
236 # run contents of file through pager starting at line
237 # where the object is defined
237 # where the object is defined
238 page(self.format(open(inspect.getabsfile(obj)).read()),lineno)
238 ofile = inspect.getabsfile(obj)
239
240 if (ofile.endswith('.so') or ofile.endswith('.dll')):
241 print 'File %r is binary, not printing.' % ofile
242 else:
243 # Print only text files, not extension binaries.
244 page(self.format(open(ofile).read()),lineno)
245 #page(self.format(open(inspect.getabsfile(obj)).read()),lineno)
239
246
240 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
247 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
241 """Show detailed information about an object.
248 """Show detailed information about an object.
242
249
243 Optional arguments:
250 Optional arguments:
244
251
245 - oname: name of the variable pointing to the object.
252 - oname: name of the variable pointing to the object.
246
253
247 - formatter: special formatter for docstrings (see pdoc)
254 - formatter: special formatter for docstrings (see pdoc)
248
255
249 - info: a structure with some information fields which may have been
256 - info: a structure with some information fields which may have been
250 precomputed already.
257 precomputed already.
251
258
252 - detail_level: if set to 1, more information is given.
259 - detail_level: if set to 1, more information is given.
253 """
260 """
254
261
255 obj_type = type(obj)
262 obj_type = type(obj)
256
263
257 header = self.__head
264 header = self.__head
258 if info is None:
265 if info is None:
259 ismagic = 0
266 ismagic = 0
260 isalias = 0
267 isalias = 0
261 ospace = ''
268 ospace = ''
262 else:
269 else:
263 ismagic = info.ismagic
270 ismagic = info.ismagic
264 isalias = info.isalias
271 isalias = info.isalias
265 ospace = info.namespace
272 ospace = info.namespace
266 # Get docstring, special-casing aliases:
273 # Get docstring, special-casing aliases:
267 if isalias:
274 if isalias:
268 ds = "Alias to the system command:\n %s" % obj[1]
275 ds = "Alias to the system command:\n %s" % obj[1]
269 else:
276 else:
270 ds = getdoc(obj)
277 ds = getdoc(obj)
271 if ds is None:
278 if ds is None:
272 ds = '<no docstring>'
279 ds = '<no docstring>'
273 if formatter is not None:
280 if formatter is not None:
274 ds = formatter(ds)
281 ds = formatter(ds)
275
282
276 # store output in a list which gets joined with \n at the end.
283 # store output in a list which gets joined with \n at the end.
277 out = myStringIO()
284 out = myStringIO()
278
285
279 string_max = 200 # max size of strings to show (snipped if longer)
286 string_max = 200 # max size of strings to show (snipped if longer)
280 shalf = int((string_max -5)/2)
287 shalf = int((string_max -5)/2)
281
288
282 if ismagic:
289 if ismagic:
283 obj_type_name = 'Magic function'
290 obj_type_name = 'Magic function'
284 elif isalias:
291 elif isalias:
285 obj_type_name = 'System alias'
292 obj_type_name = 'System alias'
286 else:
293 else:
287 obj_type_name = obj_type.__name__
294 obj_type_name = obj_type.__name__
288 out.writeln(header('Type:\t\t')+obj_type_name)
295 out.writeln(header('Type:\t\t')+obj_type_name)
289
296
290 try:
297 try:
291 bclass = obj.__class__
298 bclass = obj.__class__
292 out.writeln(header('Base Class:\t')+str(bclass))
299 out.writeln(header('Base Class:\t')+str(bclass))
293 except: pass
300 except: pass
294
301
295 # String form, but snip if too long in ? form (full in ??)
302 # String form, but snip if too long in ? form (full in ??)
296 try:
303 try:
297 ostr = str(obj)
304 ostr = str(obj)
298 str_head = 'String Form:'
305 str_head = 'String Form:'
299 if not detail_level and len(ostr)>string_max:
306 if not detail_level and len(ostr)>string_max:
300 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
307 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
301 ostr = ("\n" + " " * len(str_head.expandtabs())).\
308 ostr = ("\n" + " " * len(str_head.expandtabs())).\
302 join(map(string.strip,ostr.split("\n")))
309 join(map(string.strip,ostr.split("\n")))
303 if ostr.find('\n') > -1:
310 if ostr.find('\n') > -1:
304 # Print multi-line strings starting at the next line.
311 # Print multi-line strings starting at the next line.
305 str_sep = '\n'
312 str_sep = '\n'
306 else:
313 else:
307 str_sep = '\t'
314 str_sep = '\t'
308 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
315 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
309 except:
316 except:
310 pass
317 pass
311
318
312 if ospace:
319 if ospace:
313 out.writeln(header('Namespace:\t')+ospace)
320 out.writeln(header('Namespace:\t')+ospace)
314
321
315 # Length (for strings and lists)
322 # Length (for strings and lists)
316 try:
323 try:
317 length = str(len(obj))
324 length = str(len(obj))
318 out.writeln(header('Length:\t\t')+length)
325 out.writeln(header('Length:\t\t')+length)
319 except: pass
326 except: pass
320
327
321 # Filename where object was defined
328 # Filename where object was defined
329 binary_file = False
322 try:
330 try:
323 file = inspect.getabsfile(obj)
331 fname = inspect.getabsfile(obj)
324 if file.endswith('<string>'):
332 if fname.endswith('<string>'):
325 file = 'Dynamically generated function. No source code available.'
333 fname = 'Dynamically generated function. No source code available.'
326 out.writeln(header('File:\t\t')+file)
334 if fname.endswith('.so') or fname.endswith('.dll'):
327 except: pass
335 binary_file = True
336 out.writeln(header('File:\t\t')+fname)
337 except:
338 # if anything goes wrong, we don't want to show source, so it's as
339 # if the file was binary
340 binary_file = True
328
341
329 # reconstruct the function definition and print it:
342 # reconstruct the function definition and print it:
330 defln = self.__getdef(obj,oname)
343 defln = self.__getdef(obj,oname)
331 if defln:
344 if defln:
332 out.write(header('Definition:\t')+self.format(defln))
345 out.write(header('Definition:\t')+self.format(defln))
333
346
334 # Docstrings only in detail 0 mode, since source contains them (we
347 # Docstrings only in detail 0 mode, since source contains them (we
335 # avoid repetitions). If source fails, we add them back, see below.
348 # avoid repetitions). If source fails, we add them back, see below.
336 if ds and detail_level == 0:
349 if ds and detail_level == 0:
337 out.writeln(header('Docstring:\n') + indent(ds))
350 out.writeln(header('Docstring:\n') + indent(ds))
338
351
339 # Original source code for any callable
352 # Original source code for any callable
340 if detail_level:
353 if detail_level:
341 # Flush the source cache because inspect can return out-of-date source
354 # Flush the source cache because inspect can return out-of-date source
342 linecache.checkcache()
355 linecache.checkcache()
343 try:
356 try:
357 if not binary_file:
344 source = self.format(inspect.getsource(obj))
358 source = self.format(inspect.getsource(obj))
345 out.write(header('Source:\n')+source.rstrip())
359 out.write(header('Source:\n')+source.rstrip())
346 except:
360 except:
347 if ds:
361 if ds:
348 out.writeln(header('Docstring:\n') + indent(ds))
362 out.writeln(header('Docstring:\n') + indent(ds))
349
363
350 # Constructor docstring for classes
364 # Constructor docstring for classes
351 if obj_type is types.ClassType:
365 if obj_type is types.ClassType:
352 # reconstruct the function definition and print it:
366 # reconstruct the function definition and print it:
353 try:
367 try:
354 obj_init = obj.__init__
368 obj_init = obj.__init__
355 except AttributeError:
369 except AttributeError:
356 init_def = init_ds = None
370 init_def = init_ds = None
357 else:
371 else:
358 init_def = self.__getdef(obj_init,oname)
372 init_def = self.__getdef(obj_init,oname)
359 init_ds = getdoc(obj_init)
373 init_ds = getdoc(obj_init)
360
374
361 if init_def or init_ds:
375 if init_def or init_ds:
362 out.writeln(header('\nConstructor information:'))
376 out.writeln(header('\nConstructor information:'))
363 if init_def:
377 if init_def:
364 out.write(header('Definition:\t')+ self.format(init_def))
378 out.write(header('Definition:\t')+ self.format(init_def))
365 if init_ds:
379 if init_ds:
366 out.writeln(header('Docstring:\n') + indent(init_ds))
380 out.writeln(header('Docstring:\n') + indent(init_ds))
367 # and class docstring for instances:
381 # and class docstring for instances:
368 elif obj_type is types.InstanceType:
382 elif obj_type is types.InstanceType:
369
383
370 # First, check whether the instance docstring is identical to the
384 # First, check whether the instance docstring is identical to the
371 # class one, and print it separately if they don't coincide. In
385 # class one, and print it separately if they don't coincide. In
372 # most cases they will, but it's nice to print all the info for
386 # most cases they will, but it's nice to print all the info for
373 # objects which use instance-customized docstrings.
387 # objects which use instance-customized docstrings.
374 if ds:
388 if ds:
375 class_ds = getdoc(obj.__class__)
389 class_ds = getdoc(obj.__class__)
376 if class_ds and ds != class_ds:
390 if class_ds and ds != class_ds:
377 out.writeln(header('Class Docstring:\n') +
391 out.writeln(header('Class Docstring:\n') +
378 indent(class_ds))
392 indent(class_ds))
379
393
380 # Next, try to show constructor docstrings
394 # Next, try to show constructor docstrings
381 try:
395 try:
382 init_ds = getdoc(obj.__init__)
396 init_ds = getdoc(obj.__init__)
383 except AttributeError:
397 except AttributeError:
384 init_ds = None
398 init_ds = None
385 if init_ds:
399 if init_ds:
386 out.writeln(header('Constructor Docstring:\n') +
400 out.writeln(header('Constructor Docstring:\n') +
387 indent(init_ds))
401 indent(init_ds))
388
402
389 # Call form docstring for callable instances
403 # Call form docstring for callable instances
390 if hasattr(obj,'__call__'):
404 if hasattr(obj,'__call__'):
391 out.writeln(header('Callable:\t')+'Yes')
405 out.writeln(header('Callable:\t')+'Yes')
392 call_def = self.__getdef(obj.__call__,oname)
406 call_def = self.__getdef(obj.__call__,oname)
393 if call_def is None:
407 if call_def is None:
394 out.write(header('Call def:\t')+
408 out.write(header('Call def:\t')+
395 'Calling definition not available.')
409 'Calling definition not available.')
396 else:
410 else:
397 out.write(header('Call def:\t')+self.format(call_def))
411 out.write(header('Call def:\t')+self.format(call_def))
398 call_ds = getdoc(obj.__call__)
412 call_ds = getdoc(obj.__call__)
399 if call_ds:
413 if call_ds:
400 out.writeln(header('Call docstring:\n') + indent(call_ds))
414 out.writeln(header('Call docstring:\n') + indent(call_ds))
401
415
402 # Finally send to printer/pager
416 # Finally send to printer/pager
403 output = out.getvalue()
417 output = out.getvalue()
404 if output:
418 if output:
405 page(output)
419 page(output)
406 # end pinfo
420 # end pinfo
407
421
408 def psearch(self,pattern,ns_table,ns_search=[],
422 def psearch(self,pattern,ns_table,ns_search=[],
409 ignore_case=False,show_all=False):
423 ignore_case=False,show_all=False):
410 """Search namespaces with wildcards for objects.
424 """Search namespaces with wildcards for objects.
411
425
412 Arguments:
426 Arguments:
413
427
414 - pattern: string containing shell-like wildcards to use in namespace
428 - pattern: string containing shell-like wildcards to use in namespace
415 searches and optionally a type specification to narrow the search to
429 searches and optionally a type specification to narrow the search to
416 objects of that type.
430 objects of that type.
417
431
418 - ns_table: dict of name->namespaces for search.
432 - ns_table: dict of name->namespaces for search.
419
433
420 Optional arguments:
434 Optional arguments:
421
435
422 - ns_search: list of namespace names to include in search.
436 - ns_search: list of namespace names to include in search.
423
437
424 - ignore_case(False): make the search case-insensitive.
438 - ignore_case(False): make the search case-insensitive.
425
439
426 - show_all(False): show all names, including those starting with
440 - show_all(False): show all names, including those starting with
427 underscores.
441 underscores.
428 """
442 """
429 # defaults
443 # defaults
430 type_pattern = 'all'
444 type_pattern = 'all'
431 filter = ''
445 filter = ''
432
446
433 cmds = pattern.split()
447 cmds = pattern.split()
434 len_cmds = len(cmds)
448 len_cmds = len(cmds)
435 if len_cmds == 1:
449 if len_cmds == 1:
436 # Only filter pattern given
450 # Only filter pattern given
437 filter = cmds[0]
451 filter = cmds[0]
438 elif len_cmds == 2:
452 elif len_cmds == 2:
439 # Both filter and type specified
453 # Both filter and type specified
440 filter,type_pattern = cmds
454 filter,type_pattern = cmds
441 else:
455 else:
442 raise ValueError('invalid argument string for psearch: <%s>' %
456 raise ValueError('invalid argument string for psearch: <%s>' %
443 pattern)
457 pattern)
444
458
445 # filter search namespaces
459 # filter search namespaces
446 for name in ns_search:
460 for name in ns_search:
447 if name not in ns_table:
461 if name not in ns_table:
448 raise ValueError('invalid namespace <%s>. Valid names: %s' %
462 raise ValueError('invalid namespace <%s>. Valid names: %s' %
449 (name,ns_table.keys()))
463 (name,ns_table.keys()))
450
464
451 #print 'type_pattern:',type_pattern # dbg
465 #print 'type_pattern:',type_pattern # dbg
452 search_result = []
466 search_result = []
453 for ns_name in ns_search:
467 for ns_name in ns_search:
454 ns = ns_table[ns_name]
468 ns = ns_table[ns_name]
455 tmp_res = list(list_namespace(ns,type_pattern,filter,
469 tmp_res = list(list_namespace(ns,type_pattern,filter,
456 ignore_case=ignore_case,
470 ignore_case=ignore_case,
457 show_all=show_all))
471 show_all=show_all))
458 search_result.extend(tmp_res)
472 search_result.extend(tmp_res)
459 search_result.sort()
473 search_result.sort()
460
474
461 page('\n'.join(search_result))
475 page('\n'.join(search_result))
@@ -1,77 +1,77 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Release data for the IPython project.
2 """Release data for the IPython project.
3
3
4 $Id: Release.py 1014 2006-01-13 19:16:41Z vivainio $"""
4 $Id: Release.py 1058 2006-01-22 14:30:01Z vivainio $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 #
8 #
9 # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
9 # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
10 # <n8gray@caltech.edu>
10 # <n8gray@caltech.edu>
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
14 #*****************************************************************************
15
15
16 # Name of the package for release purposes. This is the name which labels
16 # Name of the package for release purposes. This is the name which labels
17 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
17 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
18 name = 'ipython'
18 name = 'ipython'
19
19
20 # For versions with substrings (like 0.6.16.svn), use an extra . to separate
20 # For versions with substrings (like 0.6.16.svn), use an extra . to separate
21 # the new substring. We have to avoid using either dashes or underscores,
21 # the new substring. We have to avoid using either dashes or underscores,
22 # because bdist_rpm does not accept dashes (an RPM) convention, and
22 # because bdist_rpm does not accept dashes (an RPM) convention, and
23 # bdist_deb does not accept underscores (a Debian convention).
23 # bdist_deb does not accept underscores (a Debian convention).
24
24
25 version = '0.7.1.svn'
25 version = '0.7.2.svn'
26
26
27 revision = '$Revision: 1014 $'
27 revision = '$Revision: 1058 $'
28
28
29 description = "An enhanced interactive Python shell."
29 description = "An enhanced interactive Python shell."
30
30
31 long_description = \
31 long_description = \
32 """
32 """
33 IPython provides a replacement for the interactive Python interpreter with
33 IPython provides a replacement for the interactive Python interpreter with
34 extra functionality.
34 extra functionality.
35
35
36 Main features:
36 Main features:
37
37
38 * Comprehensive object introspection.
38 * Comprehensive object introspection.
39
39
40 * Input history, persistent across sessions.
40 * Input history, persistent across sessions.
41
41
42 * Caching of output results during a session with automatically generated
42 * Caching of output results during a session with automatically generated
43 references.
43 references.
44
44
45 * Readline based name completion.
45 * Readline based name completion.
46
46
47 * Extensible system of 'magic' commands for controlling the environment and
47 * Extensible system of 'magic' commands for controlling the environment and
48 performing many tasks related either to IPython or the operating system.
48 performing many tasks related either to IPython or the operating system.
49
49
50 * Configuration system with easy switching between different setups (simpler
50 * Configuration system with easy switching between different setups (simpler
51 than changing $PYTHONSTARTUP environment variables every time).
51 than changing $PYTHONSTARTUP environment variables every time).
52
52
53 * Session logging and reloading.
53 * Session logging and reloading.
54
54
55 * Extensible syntax processing for special purpose situations.
55 * Extensible syntax processing for special purpose situations.
56
56
57 * Access to the system shell with user-extensible alias system.
57 * Access to the system shell with user-extensible alias system.
58
58
59 * Easily embeddable in other Python programs.
59 * Easily embeddable in other Python programs.
60
60
61 * Integrated access to the pdb debugger and the Python profiler. """
61 * Integrated access to the pdb debugger and the Python profiler. """
62
62
63 license = 'BSD'
63 license = 'BSD'
64
64
65 authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
65 authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
66 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
66 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
67 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
67 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
68 'Ville' : ('Ville Vainio','vivainio@gmail.com')
68 'Ville' : ('Ville Vainio','vivainio@gmail.com')
69 }
69 }
70
70
71 url = 'http://ipython.scipy.org'
71 url = 'http://ipython.scipy.org'
72
72
73 download_url = 'http://ipython.scipy.org/dist'
73 download_url = 'http://ipython.scipy.org/dist'
74
74
75 platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
75 platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
76
76
77 keywords = ['Interactive','Interpreter','Shell']
77 keywords = ['Interactive','Interpreter','Shell']
@@ -1,939 +1,955 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """IPython Shell classes.
2 """IPython Shell classes.
3
3
4 All the matplotlib support code was co-developed with John Hunter,
4 All the matplotlib support code was co-developed with John Hunter,
5 matplotlib's author.
5 matplotlib's author.
6
6
7 $Id: Shell.py 1005 2006-01-12 08:39:26Z fperez $"""
7 $Id: Shell.py 1058 2006-01-22 14:30:01Z vivainio $"""
8
8
9 #*****************************************************************************
9 #*****************************************************************************
10 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
10 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
14 #*****************************************************************************
15
15
16 from IPython import Release
16 from IPython import Release
17 __author__ = '%s <%s>' % Release.authors['Fernando']
17 __author__ = '%s <%s>' % Release.authors['Fernando']
18 __license__ = Release.license
18 __license__ = Release.license
19
19
20 # Code begins
20 # Code begins
21 import __main__
22 import __builtin__
21 import __builtin__
22 import __main__
23 import Queue
23 import os
24 import os
24 import sys
25 import signal
25 import signal
26 import time
26 import sys
27 import threading
27 import threading
28 import time
28
29
29 import IPython
30 import IPython
30 from IPython import ultraTB
31 from IPython import ultraTB
31 from IPython.genutils import Term,warn,error,flag_calls
32 from IPython.genutils import Term,warn,error,flag_calls
32 from IPython.iplib import InteractiveShell
33 from IPython.iplib import InteractiveShell
33 from IPython.ipmaker import make_IPython
34 from IPython.ipmaker import make_IPython
34 from IPython.Magic import Magic
35 from IPython.Magic import Magic
35 from IPython.ipstruct import Struct
36 from IPython.ipstruct import Struct
36
37
37 # global flag to pass around information about Ctrl-C without exceptions
38 # global flag to pass around information about Ctrl-C without exceptions
38 KBINT = False
39 KBINT = False
39
40
40 # global flag to turn on/off Tk support.
41 # global flag to turn on/off Tk support.
41 USE_TK = False
42 USE_TK = False
42
43
43 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
44 # This class is trivial now, but I want to have it in to publish a clean
45 # This class is trivial now, but I want to have it in to publish a clean
45 # interface. Later when the internals are reorganized, code that uses this
46 # interface. Later when the internals are reorganized, code that uses this
46 # shouldn't have to change.
47 # shouldn't have to change.
47
48
48 class IPShell:
49 class IPShell:
49 """Create an IPython instance."""
50 """Create an IPython instance."""
50
51
51 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
52 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
52 debug=1,shell_class=InteractiveShell):
53 debug=1,shell_class=InteractiveShell):
53 self.IP = make_IPython(argv,user_ns=user_ns,user_global_ns=user_global_ns,
54 self.IP = make_IPython(argv,user_ns=user_ns,user_global_ns=user_global_ns,
54 debug=debug,shell_class=shell_class)
55 debug=debug,shell_class=shell_class)
55
56
56 def mainloop(self,sys_exit=0,banner=None):
57 def mainloop(self,sys_exit=0,banner=None):
57 self.IP.mainloop(banner)
58 self.IP.mainloop(banner)
58 if sys_exit:
59 if sys_exit:
59 sys.exit()
60 sys.exit()
60
61
61 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
62 class IPShellEmbed:
63 class IPShellEmbed:
63 """Allow embedding an IPython shell into a running program.
64 """Allow embedding an IPython shell into a running program.
64
65
65 Instances of this class are callable, with the __call__ method being an
66 Instances of this class are callable, with the __call__ method being an
66 alias to the embed() method of an InteractiveShell instance.
67 alias to the embed() method of an InteractiveShell instance.
67
68
68 Usage (see also the example-embed.py file for a running example):
69 Usage (see also the example-embed.py file for a running example):
69
70
70 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
71 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
71
72
72 - argv: list containing valid command-line options for IPython, as they
73 - argv: list containing valid command-line options for IPython, as they
73 would appear in sys.argv[1:].
74 would appear in sys.argv[1:].
74
75
75 For example, the following command-line options:
76 For example, the following command-line options:
76
77
77 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
78 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
78
79
79 would be passed in the argv list as:
80 would be passed in the argv list as:
80
81
81 ['-prompt_in1','Input <\\#>','-colors','LightBG']
82 ['-prompt_in1','Input <\\#>','-colors','LightBG']
82
83
83 - banner: string which gets printed every time the interpreter starts.
84 - banner: string which gets printed every time the interpreter starts.
84
85
85 - exit_msg: string which gets printed every time the interpreter exits.
86 - exit_msg: string which gets printed every time the interpreter exits.
86
87
87 - rc_override: a dict or Struct of configuration options such as those
88 - rc_override: a dict or Struct of configuration options such as those
88 used by IPython. These options are read from your ~/.ipython/ipythonrc
89 used by IPython. These options are read from your ~/.ipython/ipythonrc
89 file when the Shell object is created. Passing an explicit rc_override
90 file when the Shell object is created. Passing an explicit rc_override
90 dict with any options you want allows you to override those values at
91 dict with any options you want allows you to override those values at
91 creation time without having to modify the file. This way you can create
92 creation time without having to modify the file. This way you can create
92 embeddable instances configured in any way you want without editing any
93 embeddable instances configured in any way you want without editing any
93 global files (thus keeping your interactive IPython configuration
94 global files (thus keeping your interactive IPython configuration
94 unchanged).
95 unchanged).
95
96
96 Then the ipshell instance can be called anywhere inside your code:
97 Then the ipshell instance can be called anywhere inside your code:
97
98
98 ipshell(header='') -> Opens up an IPython shell.
99 ipshell(header='') -> Opens up an IPython shell.
99
100
100 - header: string printed by the IPython shell upon startup. This can let
101 - header: string printed by the IPython shell upon startup. This can let
101 you know where in your code you are when dropping into the shell. Note
102 you know where in your code you are when dropping into the shell. Note
102 that 'banner' gets prepended to all calls, so header is used for
103 that 'banner' gets prepended to all calls, so header is used for
103 location-specific information.
104 location-specific information.
104
105
105 For more details, see the __call__ method below.
106 For more details, see the __call__ method below.
106
107
107 When the IPython shell is exited with Ctrl-D, normal program execution
108 When the IPython shell is exited with Ctrl-D, normal program execution
108 resumes.
109 resumes.
109
110
110 This functionality was inspired by a posting on comp.lang.python by cmkl
111 This functionality was inspired by a posting on comp.lang.python by cmkl
111 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
112 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
112 by the IDL stop/continue commands."""
113 by the IDL stop/continue commands."""
113
114
114 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
115 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
115 """Note that argv here is a string, NOT a list."""
116 """Note that argv here is a string, NOT a list."""
116 self.set_banner(banner)
117 self.set_banner(banner)
117 self.set_exit_msg(exit_msg)
118 self.set_exit_msg(exit_msg)
118 self.set_dummy_mode(0)
119 self.set_dummy_mode(0)
119
120
120 # sys.displayhook is a global, we need to save the user's original
121 # sys.displayhook is a global, we need to save the user's original
121 # Don't rely on __displayhook__, as the user may have changed that.
122 # Don't rely on __displayhook__, as the user may have changed that.
122 self.sys_displayhook_ori = sys.displayhook
123 self.sys_displayhook_ori = sys.displayhook
123
124
124 # save readline completer status
125 # save readline completer status
125 try:
126 try:
126 #print 'Save completer',sys.ipcompleter # dbg
127 #print 'Save completer',sys.ipcompleter # dbg
127 self.sys_ipcompleter_ori = sys.ipcompleter
128 self.sys_ipcompleter_ori = sys.ipcompleter
128 except:
129 except:
129 pass # not nested with IPython
130 pass # not nested with IPython
130
131
131 # FIXME. Passing user_ns breaks namespace handling.
132 # FIXME. Passing user_ns breaks namespace handling.
132 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
133 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
133 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
134 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
134
135
135 # copy our own displayhook also
136 # copy our own displayhook also
136 self.sys_displayhook_embed = sys.displayhook
137 self.sys_displayhook_embed = sys.displayhook
137 # and leave the system's display hook clean
138 # and leave the system's display hook clean
138 sys.displayhook = self.sys_displayhook_ori
139 sys.displayhook = self.sys_displayhook_ori
139 # don't use the ipython crash handler so that user exceptions aren't
140 # don't use the ipython crash handler so that user exceptions aren't
140 # trapped
141 # trapped
141 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
142 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
142 mode = self.IP.rc.xmode,
143 mode = self.IP.rc.xmode,
143 call_pdb = self.IP.rc.pdb)
144 call_pdb = self.IP.rc.pdb)
144 self.restore_system_completer()
145 self.restore_system_completer()
145
146
146 def restore_system_completer(self):
147 def restore_system_completer(self):
147 """Restores the readline completer which was in place.
148 """Restores the readline completer which was in place.
148
149
149 This allows embedded IPython within IPython not to disrupt the
150 This allows embedded IPython within IPython not to disrupt the
150 parent's completion.
151 parent's completion.
151 """
152 """
152
153
153 try:
154 try:
154 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
155 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
155 sys.ipcompleter = self.sys_ipcompleter_ori
156 sys.ipcompleter = self.sys_ipcompleter_ori
156 except:
157 except:
157 pass
158 pass
158
159
159 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
160 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
160 """Activate the interactive interpreter.
161 """Activate the interactive interpreter.
161
162
162 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
163 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
163 the interpreter shell with the given local and global namespaces, and
164 the interpreter shell with the given local and global namespaces, and
164 optionally print a header string at startup.
165 optionally print a header string at startup.
165
166
166 The shell can be globally activated/deactivated using the
167 The shell can be globally activated/deactivated using the
167 set/get_dummy_mode methods. This allows you to turn off a shell used
168 set/get_dummy_mode methods. This allows you to turn off a shell used
168 for debugging globally.
169 for debugging globally.
169
170
170 However, *each* time you call the shell you can override the current
171 However, *each* time you call the shell you can override the current
171 state of dummy_mode with the optional keyword parameter 'dummy'. For
172 state of dummy_mode with the optional keyword parameter 'dummy'. For
172 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
173 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
173 can still have a specific call work by making it as IPShell(dummy=0).
174 can still have a specific call work by making it as IPShell(dummy=0).
174
175
175 The optional keyword parameter dummy controls whether the call
176 The optional keyword parameter dummy controls whether the call
176 actually does anything. """
177 actually does anything. """
177
178
178 # Allow the dummy parameter to override the global __dummy_mode
179 # Allow the dummy parameter to override the global __dummy_mode
179 if dummy or (dummy != 0 and self.__dummy_mode):
180 if dummy or (dummy != 0 and self.__dummy_mode):
180 return
181 return
181
182
182 # Set global subsystems (display,completions) to our values
183 # Set global subsystems (display,completions) to our values
183 sys.displayhook = self.sys_displayhook_embed
184 sys.displayhook = self.sys_displayhook_embed
184 if self.IP.has_readline:
185 if self.IP.has_readline:
185 self.IP.readline.set_completer(self.IP.Completer.complete)
186 self.IP.readline.set_completer(self.IP.Completer.complete)
186
187
187 if self.banner and header:
188 if self.banner and header:
188 format = '%s\n%s\n'
189 format = '%s\n%s\n'
189 else:
190 else:
190 format = '%s%s\n'
191 format = '%s%s\n'
191 banner = format % (self.banner,header)
192 banner = format % (self.banner,header)
192
193
193 # Call the embedding code with a stack depth of 1 so it can skip over
194 # Call the embedding code with a stack depth of 1 so it can skip over
194 # our call and get the original caller's namespaces.
195 # our call and get the original caller's namespaces.
195 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
196 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
196
197
197 if self.exit_msg:
198 if self.exit_msg:
198 print self.exit_msg
199 print self.exit_msg
199
200
200 # Restore global systems (display, completion)
201 # Restore global systems (display, completion)
201 sys.displayhook = self.sys_displayhook_ori
202 sys.displayhook = self.sys_displayhook_ori
202 self.restore_system_completer()
203 self.restore_system_completer()
203
204
204 def set_dummy_mode(self,dummy):
205 def set_dummy_mode(self,dummy):
205 """Sets the embeddable shell's dummy mode parameter.
206 """Sets the embeddable shell's dummy mode parameter.
206
207
207 set_dummy_mode(dummy): dummy = 0 or 1.
208 set_dummy_mode(dummy): dummy = 0 or 1.
208
209
209 This parameter is persistent and makes calls to the embeddable shell
210 This parameter is persistent and makes calls to the embeddable shell
210 silently return without performing any action. This allows you to
211 silently return without performing any action. This allows you to
211 globally activate or deactivate a shell you're using with a single call.
212 globally activate or deactivate a shell you're using with a single call.
212
213
213 If you need to manually"""
214 If you need to manually"""
214
215
215 if dummy not in [0,1,False,True]:
216 if dummy not in [0,1,False,True]:
216 raise ValueError,'dummy parameter must be boolean'
217 raise ValueError,'dummy parameter must be boolean'
217 self.__dummy_mode = dummy
218 self.__dummy_mode = dummy
218
219
219 def get_dummy_mode(self):
220 def get_dummy_mode(self):
220 """Return the current value of the dummy mode parameter.
221 """Return the current value of the dummy mode parameter.
221 """
222 """
222 return self.__dummy_mode
223 return self.__dummy_mode
223
224
224 def set_banner(self,banner):
225 def set_banner(self,banner):
225 """Sets the global banner.
226 """Sets the global banner.
226
227
227 This banner gets prepended to every header printed when the shell
228 This banner gets prepended to every header printed when the shell
228 instance is called."""
229 instance is called."""
229
230
230 self.banner = banner
231 self.banner = banner
231
232
232 def set_exit_msg(self,exit_msg):
233 def set_exit_msg(self,exit_msg):
233 """Sets the global exit_msg.
234 """Sets the global exit_msg.
234
235
235 This exit message gets printed upon exiting every time the embedded
236 This exit message gets printed upon exiting every time the embedded
236 shell is called. It is None by default. """
237 shell is called. It is None by default. """
237
238
238 self.exit_msg = exit_msg
239 self.exit_msg = exit_msg
239
240
240 #-----------------------------------------------------------------------------
241 #-----------------------------------------------------------------------------
241 def sigint_handler (signum,stack_frame):
242 def sigint_handler (signum,stack_frame):
242 """Sigint handler for threaded apps.
243 """Sigint handler for threaded apps.
243
244
244 This is a horrible hack to pass information about SIGINT _without_ using
245 This is a horrible hack to pass information about SIGINT _without_ using
245 exceptions, since I haven't been able to properly manage cross-thread
246 exceptions, since I haven't been able to properly manage cross-thread
246 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
247 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
247 that's my understanding from a c.l.py thread where this was discussed)."""
248 that's my understanding from a c.l.py thread where this was discussed)."""
248
249
249 global KBINT
250 global KBINT
250
251
251 print '\nKeyboardInterrupt - Press <Enter> to continue.',
252 print '\nKeyboardInterrupt - Press <Enter> to continue.',
252 Term.cout.flush()
253 Term.cout.flush()
253 # Set global flag so that runsource can know that Ctrl-C was hit
254 # Set global flag so that runsource can know that Ctrl-C was hit
254 KBINT = True
255 KBINT = True
255
256
256 class MTInteractiveShell(InteractiveShell):
257 class MTInteractiveShell(InteractiveShell):
257 """Simple multi-threaded shell."""
258 """Simple multi-threaded shell."""
258
259
259 # Threading strategy taken from:
260 # Threading strategy taken from:
260 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
261 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
261 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
262 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
262 # from the pygtk mailing list, to avoid lockups with system calls.
263 # from the pygtk mailing list, to avoid lockups with system calls.
263
264
264 # class attribute to indicate whether the class supports threads or not.
265 # class attribute to indicate whether the class supports threads or not.
265 # Subclasses with thread support should override this as needed.
266 # Subclasses with thread support should override this as needed.
266 isthreaded = True
267 isthreaded = True
267
268
268 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
269 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
269 user_ns=None,user_global_ns=None,banner2='',**kw):
270 user_ns=None,user_global_ns=None,banner2='',**kw):
270 """Similar to the normal InteractiveShell, but with threading control"""
271 """Similar to the normal InteractiveShell, but with threading control"""
271
272
272 InteractiveShell.__init__(self,name,usage,rc,user_ns,
273 InteractiveShell.__init__(self,name,usage,rc,user_ns,
273 user_global_ns,banner2)
274 user_global_ns,banner2)
274
275
275 # Locking control variable
276 # Locking control variable. We need to use a norma lock, not an RLock
276 self.thread_ready = threading.Condition()
277 # here. I'm not exactly sure why, it seems to me like it should be
278 # the opposite, but we deadlock with an RLock. Puzzled...
279 self.thread_ready = threading.Condition(threading.Lock())
280
281 # A queue to hold the code to be executed. A scalar variable is NOT
282 # enough, because uses like macros cause reentrancy.
283 self.code_queue = Queue.Queue()
277
284
278 # Stuff to do at closing time
285 # Stuff to do at closing time
279 self._kill = False
286 self._kill = False
280 on_kill = kw.get('on_kill')
287 on_kill = kw.get('on_kill')
281 if on_kill is None:
288 if on_kill is None:
282 on_kill = []
289 on_kill = []
283 # Check that all things to kill are callable:
290 # Check that all things to kill are callable:
284 for t in on_kill:
291 for t in on_kill:
285 if not callable(t):
292 if not callable(t):
286 raise TypeError,'on_kill must be a list of callables'
293 raise TypeError,'on_kill must be a list of callables'
287 self.on_kill = on_kill
294 self.on_kill = on_kill
288
295
289 def runsource(self, source, filename="<input>", symbol="single"):
296 def runsource(self, source, filename="<input>", symbol="single"):
290 """Compile and run some source in the interpreter.
297 """Compile and run some source in the interpreter.
291
298
292 Modified version of code.py's runsource(), to handle threading issues.
299 Modified version of code.py's runsource(), to handle threading issues.
293 See the original for full docstring details."""
300 See the original for full docstring details."""
294
301
295 global KBINT
302 global KBINT
296
303
297 # If Ctrl-C was typed, we reset the flag and return right away
304 # If Ctrl-C was typed, we reset the flag and return right away
298 if KBINT:
305 if KBINT:
299 KBINT = False
306 KBINT = False
300 return False
307 return False
301
308
302 try:
309 try:
303 code = self.compile(source, filename, symbol)
310 code = self.compile(source, filename, symbol)
304 except (OverflowError, SyntaxError, ValueError):
311 except (OverflowError, SyntaxError, ValueError):
305 # Case 1
312 # Case 1
306 self.showsyntaxerror(filename)
313 self.showsyntaxerror(filename)
307 return False
314 return False
308
315
309 if code is None:
316 if code is None:
310 # Case 2
317 # Case 2
311 return True
318 return True
312
319
313 # Case 3
320 # Case 3
314 # Store code in self, so the execution thread can handle it
321 # Store code in queue, so the execution thread can handle it.
315 self.thread_ready.acquire()
322
316 self.code_to_run = code
323 # Note that with macros and other applications, we MAY re-enter this
324 # section, so we have to acquire the lock with non-blocking semantics,
325 # else we deadlock.
326 got_lock = self.thread_ready.acquire(False)
327 self.code_queue.put(code)
328 if got_lock:
317 self.thread_ready.wait() # Wait until processed in timeout interval
329 self.thread_ready.wait() # Wait until processed in timeout interval
318 self.thread_ready.release()
330 self.thread_ready.release()
319
331
320 return False
332 return False
321
333
322 def runcode(self):
334 def runcode(self):
323 """Execute a code object.
335 """Execute a code object.
324
336
325 Multithreaded wrapper around IPython's runcode()."""
337 Multithreaded wrapper around IPython's runcode()."""
326
338
327 # lock thread-protected stuff
339 # lock thread-protected stuff
328 self.thread_ready.acquire()
340 self.thread_ready.acquire(False)
329
341
330 # Install sigint handler
342 # Install sigint handler
331 try:
343 try:
332 signal.signal(signal.SIGINT, sigint_handler)
344 signal.signal(signal.SIGINT, sigint_handler)
333 except SystemError:
345 except SystemError:
334 # This happens under Windows, which seems to have all sorts
346 # This happens under Windows, which seems to have all sorts
335 # of problems with signal handling. Oh well...
347 # of problems with signal handling. Oh well...
336 pass
348 pass
337
349
338 if self._kill:
350 if self._kill:
339 print >>Term.cout, 'Closing threads...',
351 print >>Term.cout, 'Closing threads...',
340 Term.cout.flush()
352 Term.cout.flush()
341 for tokill in self.on_kill:
353 for tokill in self.on_kill:
342 tokill()
354 tokill()
343 print >>Term.cout, 'Done.'
355 print >>Term.cout, 'Done.'
344
356
345 # Run pending code by calling parent class
357 # Flush queue of pending code by calling the run methood of the parent
346 if self.code_to_run is not None:
358 # class with all items which may be in the queue.
359 while 1:
360 try:
361 code_to_run = self.code_queue.get_nowait()
362 except Queue.Empty:
363 break
347 self.thread_ready.notify()
364 self.thread_ready.notify()
348 InteractiveShell.runcode(self,self.code_to_run)
365 InteractiveShell.runcode(self,code_to_run)
349
366
350 # We're done with thread-protected variables
367 # We're done with thread-protected variables
351 self.thread_ready.release()
368 self.thread_ready.release()
352 # This MUST return true for gtk threading to work
369 # This MUST return true for gtk threading to work
353 return True
370 return True
354
371
355 def kill (self):
372 def kill (self):
356 """Kill the thread, returning when it has been shut down."""
373 """Kill the thread, returning when it has been shut down."""
357 self.thread_ready.acquire()
374 self.thread_ready.acquire(False)
358 self._kill = True
375 self._kill = True
359 self.thread_ready.release()
376 self.thread_ready.release()
360
377
361 class MatplotlibShellBase:
378 class MatplotlibShellBase:
362 """Mixin class to provide the necessary modifications to regular IPython
379 """Mixin class to provide the necessary modifications to regular IPython
363 shell classes for matplotlib support.
380 shell classes for matplotlib support.
364
381
365 Given Python's MRO, this should be used as the FIRST class in the
382 Given Python's MRO, this should be used as the FIRST class in the
366 inheritance hierarchy, so that it overrides the relevant methods."""
383 inheritance hierarchy, so that it overrides the relevant methods."""
367
384
368 def _matplotlib_config(self,name):
385 def _matplotlib_config(self,name):
369 """Return various items needed to setup the user's shell with matplotlib"""
386 """Return items needed to setup the user's shell with matplotlib"""
370
387
371 # Initialize matplotlib to interactive mode always
388 # Initialize matplotlib to interactive mode always
372 import matplotlib
389 import matplotlib
373 from matplotlib import backends
390 from matplotlib import backends
374 matplotlib.interactive(True)
391 matplotlib.interactive(True)
375
392
376 def use(arg):
393 def use(arg):
377 """IPython wrapper for matplotlib's backend switcher.
394 """IPython wrapper for matplotlib's backend switcher.
378
395
379 In interactive use, we can not allow switching to a different
396 In interactive use, we can not allow switching to a different
380 interactive backend, since thread conflicts will most likely crash
397 interactive backend, since thread conflicts will most likely crash
381 the python interpreter. This routine does a safety check first,
398 the python interpreter. This routine does a safety check first,
382 and refuses to perform a dangerous switch. It still allows
399 and refuses to perform a dangerous switch. It still allows
383 switching to non-interactive backends."""
400 switching to non-interactive backends."""
384
401
385 if arg in backends.interactive_bk and arg != self.mpl_backend:
402 if arg in backends.interactive_bk and arg != self.mpl_backend:
386 m=('invalid matplotlib backend switch.\n'
403 m=('invalid matplotlib backend switch.\n'
387 'This script attempted to switch to the interactive '
404 'This script attempted to switch to the interactive '
388 'backend: `%s`\n'
405 'backend: `%s`\n'
389 'Your current choice of interactive backend is: `%s`\n\n'
406 'Your current choice of interactive backend is: `%s`\n\n'
390 'Switching interactive matplotlib backends at runtime\n'
407 'Switching interactive matplotlib backends at runtime\n'
391 'would crash the python interpreter, '
408 'would crash the python interpreter, '
392 'and IPython has blocked it.\n\n'
409 'and IPython has blocked it.\n\n'
393 'You need to either change your choice of matplotlib backend\n'
410 'You need to either change your choice of matplotlib backend\n'
394 'by editing your .matplotlibrc file, or run this script as a \n'
411 'by editing your .matplotlibrc file, or run this script as a \n'
395 'standalone file from the command line, not using IPython.\n' %
412 'standalone file from the command line, not using IPython.\n' %
396 (arg,self.mpl_backend) )
413 (arg,self.mpl_backend) )
397 raise RuntimeError, m
414 raise RuntimeError, m
398 else:
415 else:
399 self.mpl_use(arg)
416 self.mpl_use(arg)
400 self.mpl_use._called = True
417 self.mpl_use._called = True
401
418
402 self.matplotlib = matplotlib
419 self.matplotlib = matplotlib
403 self.mpl_backend = matplotlib.rcParams['backend']
420 self.mpl_backend = matplotlib.rcParams['backend']
404
421
405 # we also need to block switching of interactive backends by use()
422 # we also need to block switching of interactive backends by use()
406 self.mpl_use = matplotlib.use
423 self.mpl_use = matplotlib.use
407 self.mpl_use._called = False
424 self.mpl_use._called = False
408 # overwrite the original matplotlib.use with our wrapper
425 # overwrite the original matplotlib.use with our wrapper
409 matplotlib.use = use
426 matplotlib.use = use
410
427
411
412 # This must be imported last in the matplotlib series, after
428 # This must be imported last in the matplotlib series, after
413 # backend/interactivity choices have been made
429 # backend/interactivity choices have been made
414 try:
430 try:
415 import matplotlib.pylab as pylab
431 import matplotlib.pylab as pylab
416 self.pylab = pylab
432 self.pylab = pylab
417 self.pylab_name = 'pylab'
433 self.pylab_name = 'pylab'
418 except ImportError:
434 except ImportError:
419 import matplotlib.matlab as matlab
435 import matplotlib.matlab as matlab
420 self.pylab = matlab
436 self.pylab = matlab
421 self.pylab_name = 'matlab'
437 self.pylab_name = 'matlab'
422
438
423 self.pylab.show._needmain = False
439 self.pylab.show._needmain = False
424 # We need to detect at runtime whether show() is called by the user.
440 # We need to detect at runtime whether show() is called by the user.
425 # For this, we wrap it into a decorator which adds a 'called' flag.
441 # For this, we wrap it into a decorator which adds a 'called' flag.
426 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
442 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
427
443
428 # Build a user namespace initialized with matplotlib/matlab features.
444 # Build a user namespace initialized with matplotlib/matlab features.
429 user_ns = {'__name__':'__main__',
445 user_ns = {'__name__':'__main__',
430 '__builtins__' : __builtin__ }
446 '__builtins__' : __builtin__ }
431
447
432 # Be careful not to remove the final \n in the code string below, or
448 # Be careful not to remove the final \n in the code string below, or
433 # things will break badly with py22 (I think it's a python bug, 2.3 is
449 # things will break badly with py22 (I think it's a python bug, 2.3 is
434 # OK).
450 # OK).
435 pname = self.pylab_name # Python can't interpolate dotted var names
451 pname = self.pylab_name # Python can't interpolate dotted var names
436 exec ("import matplotlib\n"
452 exec ("import matplotlib\n"
437 "import matplotlib.%(pname)s as %(pname)s\n"
453 "import matplotlib.%(pname)s as %(pname)s\n"
438 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
454 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
439
455
440 # Build matplotlib info banner
456 # Build matplotlib info banner
441 b="""
457 b="""
442 Welcome to pylab, a matplotlib-based Python environment.
458 Welcome to pylab, a matplotlib-based Python environment.
443 For more information, type 'help(pylab)'.
459 For more information, type 'help(pylab)'.
444 """
460 """
445 return user_ns,b
461 return user_ns,b
446
462
447 def mplot_exec(self,fname,*where,**kw):
463 def mplot_exec(self,fname,*where,**kw):
448 """Execute a matplotlib script.
464 """Execute a matplotlib script.
449
465
450 This is a call to execfile(), but wrapped in safeties to properly
466 This is a call to execfile(), but wrapped in safeties to properly
451 handle interactive rendering and backend switching."""
467 handle interactive rendering and backend switching."""
452
468
453 #print '*** Matplotlib runner ***' # dbg
469 #print '*** Matplotlib runner ***' # dbg
454 # turn off rendering until end of script
470 # turn off rendering until end of script
455 isInteractive = self.matplotlib.rcParams['interactive']
471 isInteractive = self.matplotlib.rcParams['interactive']
456 self.matplotlib.interactive(False)
472 self.matplotlib.interactive(False)
457 self.safe_execfile(fname,*where,**kw)
473 self.safe_execfile(fname,*where,**kw)
458 self.matplotlib.interactive(isInteractive)
474 self.matplotlib.interactive(isInteractive)
459 # make rendering call now, if the user tried to do it
475 # make rendering call now, if the user tried to do it
460 if self.pylab.draw_if_interactive.called:
476 if self.pylab.draw_if_interactive.called:
461 self.pylab.draw()
477 self.pylab.draw()
462 self.pylab.draw_if_interactive.called = False
478 self.pylab.draw_if_interactive.called = False
463
479
464 # if a backend switch was performed, reverse it now
480 # if a backend switch was performed, reverse it now
465 if self.mpl_use._called:
481 if self.mpl_use._called:
466 self.matplotlib.rcParams['backend'] = self.mpl_backend
482 self.matplotlib.rcParams['backend'] = self.mpl_backend
467
483
468 def magic_run(self,parameter_s=''):
484 def magic_run(self,parameter_s=''):
469 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
485 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
470
486
471 # Fix the docstring so users see the original as well
487 # Fix the docstring so users see the original as well
472 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
488 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
473 "\n *** Modified %run for Matplotlib,"
489 "\n *** Modified %run for Matplotlib,"
474 " with proper interactive handling ***")
490 " with proper interactive handling ***")
475
491
476 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
492 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
477 # and multithreaded. Note that these are meant for internal use, the IPShell*
493 # and multithreaded. Note that these are meant for internal use, the IPShell*
478 # classes below are the ones meant for public consumption.
494 # classes below are the ones meant for public consumption.
479
495
480 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
496 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
481 """Single-threaded shell with matplotlib support."""
497 """Single-threaded shell with matplotlib support."""
482
498
483 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
499 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
484 user_ns=None,user_global_ns=None,**kw):
500 user_ns=None,user_global_ns=None,**kw):
485 user_ns,b2 = self._matplotlib_config(name)
501 user_ns,b2 = self._matplotlib_config(name)
486 InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
502 InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
487 banner2=b2,**kw)
503 banner2=b2,**kw)
488
504
489 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
505 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
490 """Multi-threaded shell with matplotlib support."""
506 """Multi-threaded shell with matplotlib support."""
491
507
492 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
508 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
493 user_ns=None,user_global_ns=None, **kw):
509 user_ns=None,user_global_ns=None, **kw):
494 user_ns,b2 = self._matplotlib_config(name)
510 user_ns,b2 = self._matplotlib_config(name)
495 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
511 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
496 banner2=b2,**kw)
512 banner2=b2,**kw)
497
513
498 #-----------------------------------------------------------------------------
514 #-----------------------------------------------------------------------------
499 # Utility functions for the different GUI enabled IPShell* classes.
515 # Utility functions for the different GUI enabled IPShell* classes.
500
516
501 def get_tk():
517 def get_tk():
502 """Tries to import Tkinter and returns a withdrawn Tkinter root
518 """Tries to import Tkinter and returns a withdrawn Tkinter root
503 window. If Tkinter is already imported or not available, this
519 window. If Tkinter is already imported or not available, this
504 returns None. This function calls `hijack_tk` underneath.
520 returns None. This function calls `hijack_tk` underneath.
505 """
521 """
506 if not USE_TK or sys.modules.has_key('Tkinter'):
522 if not USE_TK or sys.modules.has_key('Tkinter'):
507 return None
523 return None
508 else:
524 else:
509 try:
525 try:
510 import Tkinter
526 import Tkinter
511 except ImportError:
527 except ImportError:
512 return None
528 return None
513 else:
529 else:
514 hijack_tk()
530 hijack_tk()
515 r = Tkinter.Tk()
531 r = Tkinter.Tk()
516 r.withdraw()
532 r.withdraw()
517 return r
533 return r
518
534
519 def hijack_tk():
535 def hijack_tk():
520 """Modifies Tkinter's mainloop with a dummy so when a module calls
536 """Modifies Tkinter's mainloop with a dummy so when a module calls
521 mainloop, it does not block.
537 mainloop, it does not block.
522
538
523 """
539 """
524 def misc_mainloop(self, n=0):
540 def misc_mainloop(self, n=0):
525 pass
541 pass
526 def tkinter_mainloop(n=0):
542 def tkinter_mainloop(n=0):
527 pass
543 pass
528
544
529 import Tkinter
545 import Tkinter
530 Tkinter.Misc.mainloop = misc_mainloop
546 Tkinter.Misc.mainloop = misc_mainloop
531 Tkinter.mainloop = tkinter_mainloop
547 Tkinter.mainloop = tkinter_mainloop
532
548
533 def update_tk(tk):
549 def update_tk(tk):
534 """Updates the Tkinter event loop. This is typically called from
550 """Updates the Tkinter event loop. This is typically called from
535 the respective WX or GTK mainloops.
551 the respective WX or GTK mainloops.
536 """
552 """
537 if tk:
553 if tk:
538 tk.update()
554 tk.update()
539
555
540 def hijack_wx():
556 def hijack_wx():
541 """Modifies wxPython's MainLoop with a dummy so user code does not
557 """Modifies wxPython's MainLoop with a dummy so user code does not
542 block IPython. The hijacked mainloop function is returned.
558 block IPython. The hijacked mainloop function is returned.
543 """
559 """
544 def dummy_mainloop(*args, **kw):
560 def dummy_mainloop(*args, **kw):
545 pass
561 pass
546 import wxPython
562 import wxPython
547 ver = wxPython.__version__
563 ver = wxPython.__version__
548 orig_mainloop = None
564 orig_mainloop = None
549 if ver[:3] >= '2.5':
565 if ver[:3] >= '2.5':
550 import wx
566 import wx
551 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
567 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
552 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
568 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
553 else: raise AttributeError('Could not find wx core module')
569 else: raise AttributeError('Could not find wx core module')
554 orig_mainloop = core.PyApp_MainLoop
570 orig_mainloop = core.PyApp_MainLoop
555 core.PyApp_MainLoop = dummy_mainloop
571 core.PyApp_MainLoop = dummy_mainloop
556 elif ver[:3] == '2.4':
572 elif ver[:3] == '2.4':
557 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
573 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
558 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
574 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
559 else:
575 else:
560 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
576 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
561 return orig_mainloop
577 return orig_mainloop
562
578
563 def hijack_gtk():
579 def hijack_gtk():
564 """Modifies pyGTK's mainloop with a dummy so user code does not
580 """Modifies pyGTK's mainloop with a dummy so user code does not
565 block IPython. This function returns the original `gtk.mainloop`
581 block IPython. This function returns the original `gtk.mainloop`
566 function that has been hijacked.
582 function that has been hijacked.
567 """
583 """
568 def dummy_mainloop(*args, **kw):
584 def dummy_mainloop(*args, **kw):
569 pass
585 pass
570 import gtk
586 import gtk
571 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
587 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
572 else: orig_mainloop = gtk.mainloop
588 else: orig_mainloop = gtk.mainloop
573 gtk.mainloop = dummy_mainloop
589 gtk.mainloop = dummy_mainloop
574 gtk.main = dummy_mainloop
590 gtk.main = dummy_mainloop
575 return orig_mainloop
591 return orig_mainloop
576
592
577 #-----------------------------------------------------------------------------
593 #-----------------------------------------------------------------------------
578 # The IPShell* classes below are the ones meant to be run by external code as
594 # The IPShell* classes below are the ones meant to be run by external code as
579 # IPython instances. Note that unless a specific threading strategy is
595 # IPython instances. Note that unless a specific threading strategy is
580 # desired, the factory function start() below should be used instead (it
596 # desired, the factory function start() below should be used instead (it
581 # selects the proper threaded class).
597 # selects the proper threaded class).
582
598
583 class IPShellGTK(threading.Thread):
599 class IPShellGTK(threading.Thread):
584 """Run a gtk mainloop() in a separate thread.
600 """Run a gtk mainloop() in a separate thread.
585
601
586 Python commands can be passed to the thread where they will be executed.
602 Python commands can be passed to the thread where they will be executed.
587 This is implemented by periodically checking for passed code using a
603 This is implemented by periodically checking for passed code using a
588 GTK timeout callback."""
604 GTK timeout callback."""
589
605
590 TIMEOUT = 100 # Millisecond interval between timeouts.
606 TIMEOUT = 100 # Millisecond interval between timeouts.
591
607
592 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
608 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
593 debug=1,shell_class=MTInteractiveShell):
609 debug=1,shell_class=MTInteractiveShell):
594
610
595 import gtk
611 import gtk
596
612
597 self.gtk = gtk
613 self.gtk = gtk
598 self.gtk_mainloop = hijack_gtk()
614 self.gtk_mainloop = hijack_gtk()
599
615
600 # Allows us to use both Tk and GTK.
616 # Allows us to use both Tk and GTK.
601 self.tk = get_tk()
617 self.tk = get_tk()
602
618
603 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
619 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
604 else: mainquit = self.gtk.mainquit
620 else: mainquit = self.gtk.mainquit
605
621
606 self.IP = make_IPython(argv,user_ns=user_ns,
622 self.IP = make_IPython(argv,user_ns=user_ns,
607 user_global_ns=user_global_ns,
623 user_global_ns=user_global_ns,
608 debug=debug,
624 debug=debug,
609 shell_class=shell_class,
625 shell_class=shell_class,
610 on_kill=[mainquit])
626 on_kill=[mainquit])
611
627
612 # HACK: slot for banner in self; it will be passed to the mainloop
628 # HACK: slot for banner in self; it will be passed to the mainloop
613 # method only and .run() needs it. The actual value will be set by
629 # method only and .run() needs it. The actual value will be set by
614 # .mainloop().
630 # .mainloop().
615 self._banner = None
631 self._banner = None
616
632
617 threading.Thread.__init__(self)
633 threading.Thread.__init__(self)
618
634
619 def run(self):
635 def run(self):
620 self.IP.mainloop(self._banner)
636 self.IP.mainloop(self._banner)
621 self.IP.kill()
637 self.IP.kill()
622
638
623 def mainloop(self,sys_exit=0,banner=None):
639 def mainloop(self,sys_exit=0,banner=None):
624
640
625 self._banner = banner
641 self._banner = banner
626
642
627 if self.gtk.pygtk_version >= (2,4,0):
643 if self.gtk.pygtk_version >= (2,4,0):
628 import gobject
644 import gobject
629 gobject.idle_add(self.on_timer)
645 gobject.idle_add(self.on_timer)
630 else:
646 else:
631 self.gtk.idle_add(self.on_timer)
647 self.gtk.idle_add(self.on_timer)
632
648
633 if sys.platform != 'win32':
649 if sys.platform != 'win32':
634 try:
650 try:
635 if self.gtk.gtk_version[0] >= 2:
651 if self.gtk.gtk_version[0] >= 2:
636 self.gtk.threads_init()
652 self.gtk.threads_init()
637 except AttributeError:
653 except AttributeError:
638 pass
654 pass
639 except RuntimeError:
655 except RuntimeError:
640 error('Your pyGTK likely has not been compiled with '
656 error('Your pyGTK likely has not been compiled with '
641 'threading support.\n'
657 'threading support.\n'
642 'The exception printout is below.\n'
658 'The exception printout is below.\n'
643 'You can either rebuild pyGTK with threads, or '
659 'You can either rebuild pyGTK with threads, or '
644 'try using \n'
660 'try using \n'
645 'matplotlib with a different backend (like Tk or WX).\n'
661 'matplotlib with a different backend (like Tk or WX).\n'
646 'Note that matplotlib will most likely not work in its '
662 'Note that matplotlib will most likely not work in its '
647 'current state!')
663 'current state!')
648 self.IP.InteractiveTB()
664 self.IP.InteractiveTB()
649 self.start()
665 self.start()
650 self.gtk.threads_enter()
666 self.gtk.threads_enter()
651 self.gtk_mainloop()
667 self.gtk_mainloop()
652 self.gtk.threads_leave()
668 self.gtk.threads_leave()
653 self.join()
669 self.join()
654
670
655 def on_timer(self):
671 def on_timer(self):
656 """Called when GTK is idle.
672 """Called when GTK is idle.
657
673
658 Must return True always, otherwise GTK stops calling it"""
674 Must return True always, otherwise GTK stops calling it"""
659
675
660 update_tk(self.tk)
676 update_tk(self.tk)
661 self.IP.runcode()
677 self.IP.runcode()
662 time.sleep(0.01)
678 time.sleep(0.01)
663 return True
679 return True
664
680
665 class IPShellWX(threading.Thread):
681 class IPShellWX(threading.Thread):
666 """Run a wx mainloop() in a separate thread.
682 """Run a wx mainloop() in a separate thread.
667
683
668 Python commands can be passed to the thread where they will be executed.
684 Python commands can be passed to the thread where they will be executed.
669 This is implemented by periodically checking for passed code using a
685 This is implemented by periodically checking for passed code using a
670 GTK timeout callback."""
686 GTK timeout callback."""
671
687
672 TIMEOUT = 100 # Millisecond interval between timeouts.
688 TIMEOUT = 100 # Millisecond interval between timeouts.
673
689
674 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
690 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
675 debug=1,shell_class=MTInteractiveShell):
691 debug=1,shell_class=MTInteractiveShell):
676
692
677 self.IP = make_IPython(argv,user_ns=user_ns,
693 self.IP = make_IPython(argv,user_ns=user_ns,
678 user_global_ns=user_global_ns,
694 user_global_ns=user_global_ns,
679 debug=debug,
695 debug=debug,
680 shell_class=shell_class,
696 shell_class=shell_class,
681 on_kill=[self.wxexit])
697 on_kill=[self.wxexit])
682
698
683 wantedwxversion=self.IP.rc.wxversion
699 wantedwxversion=self.IP.rc.wxversion
684 if wantedwxversion!="0":
700 if wantedwxversion!="0":
685 try:
701 try:
686 import wxversion
702 import wxversion
687 except ImportError:
703 except ImportError:
688 error('The wxversion module is needed for WX version selection')
704 error('The wxversion module is needed for WX version selection')
689 else:
705 else:
690 try:
706 try:
691 wxversion.select(wantedwxversion)
707 wxversion.select(wantedwxversion)
692 except:
708 except:
693 self.IP.InteractiveTB()
709 self.IP.InteractiveTB()
694 error('Requested wxPython version %s could not be loaded' %
710 error('Requested wxPython version %s could not be loaded' %
695 wantedwxversion)
711 wantedwxversion)
696
712
697 import wxPython.wx as wx
713 import wxPython.wx as wx
698
714
699 threading.Thread.__init__(self)
715 threading.Thread.__init__(self)
700 self.wx = wx
716 self.wx = wx
701 self.wx_mainloop = hijack_wx()
717 self.wx_mainloop = hijack_wx()
702
718
703 # Allows us to use both Tk and GTK.
719 # Allows us to use both Tk and GTK.
704 self.tk = get_tk()
720 self.tk = get_tk()
705
721
706
722
707 # HACK: slot for banner in self; it will be passed to the mainloop
723 # HACK: slot for banner in self; it will be passed to the mainloop
708 # method only and .run() needs it. The actual value will be set by
724 # method only and .run() needs it. The actual value will be set by
709 # .mainloop().
725 # .mainloop().
710 self._banner = None
726 self._banner = None
711
727
712 self.app = None
728 self.app = None
713
729
714 def wxexit(self, *args):
730 def wxexit(self, *args):
715 if self.app is not None:
731 if self.app is not None:
716 self.app.agent.timer.Stop()
732 self.app.agent.timer.Stop()
717 self.app.ExitMainLoop()
733 self.app.ExitMainLoop()
718
734
719 def run(self):
735 def run(self):
720 self.IP.mainloop(self._banner)
736 self.IP.mainloop(self._banner)
721 self.IP.kill()
737 self.IP.kill()
722
738
723 def mainloop(self,sys_exit=0,banner=None):
739 def mainloop(self,sys_exit=0,banner=None):
724
740
725 self._banner = banner
741 self._banner = banner
726
742
727 self.start()
743 self.start()
728
744
729 class TimerAgent(self.wx.wxMiniFrame):
745 class TimerAgent(self.wx.wxMiniFrame):
730 wx = self.wx
746 wx = self.wx
731 IP = self.IP
747 IP = self.IP
732 tk = self.tk
748 tk = self.tk
733 def __init__(self, parent, interval):
749 def __init__(self, parent, interval):
734 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
750 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
735 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
751 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
736 size=(100, 100),style=style)
752 size=(100, 100),style=style)
737 self.Show(False)
753 self.Show(False)
738 self.interval = interval
754 self.interval = interval
739 self.timerId = self.wx.wxNewId()
755 self.timerId = self.wx.wxNewId()
740
756
741 def StartWork(self):
757 def StartWork(self):
742 self.timer = self.wx.wxTimer(self, self.timerId)
758 self.timer = self.wx.wxTimer(self, self.timerId)
743 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
759 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
744 self.timer.Start(self.interval)
760 self.timer.Start(self.interval)
745
761
746 def OnTimer(self, event):
762 def OnTimer(self, event):
747 update_tk(self.tk)
763 update_tk(self.tk)
748 self.IP.runcode()
764 self.IP.runcode()
749
765
750 class App(self.wx.wxApp):
766 class App(self.wx.wxApp):
751 wx = self.wx
767 wx = self.wx
752 TIMEOUT = self.TIMEOUT
768 TIMEOUT = self.TIMEOUT
753 def OnInit(self):
769 def OnInit(self):
754 'Create the main window and insert the custom frame'
770 'Create the main window and insert the custom frame'
755 self.agent = TimerAgent(None, self.TIMEOUT)
771 self.agent = TimerAgent(None, self.TIMEOUT)
756 self.agent.Show(self.wx.false)
772 self.agent.Show(self.wx.false)
757 self.agent.StartWork()
773 self.agent.StartWork()
758 return self.wx.true
774 return self.wx.true
759
775
760 self.app = App(redirect=False)
776 self.app = App(redirect=False)
761 self.wx_mainloop(self.app)
777 self.wx_mainloop(self.app)
762 self.join()
778 self.join()
763
779
764
780
765 class IPShellQt(threading.Thread):
781 class IPShellQt(threading.Thread):
766 """Run a Qt event loop in a separate thread.
782 """Run a Qt event loop in a separate thread.
767
783
768 Python commands can be passed to the thread where they will be executed.
784 Python commands can be passed to the thread where they will be executed.
769 This is implemented by periodically checking for passed code using a
785 This is implemented by periodically checking for passed code using a
770 Qt timer / slot."""
786 Qt timer / slot."""
771
787
772 TIMEOUT = 100 # Millisecond interval between timeouts.
788 TIMEOUT = 100 # Millisecond interval between timeouts.
773
789
774 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
790 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
775 debug=0,shell_class=MTInteractiveShell):
791 debug=0,shell_class=MTInteractiveShell):
776
792
777 import qt
793 import qt
778
794
779 class newQApplication:
795 class newQApplication:
780 def __init__( self ):
796 def __init__( self ):
781 self.QApplication = qt.QApplication
797 self.QApplication = qt.QApplication
782
798
783 def __call__( *args, **kwargs ):
799 def __call__( *args, **kwargs ):
784 return qt.qApp
800 return qt.qApp
785
801
786 def exec_loop( *args, **kwargs ):
802 def exec_loop( *args, **kwargs ):
787 pass
803 pass
788
804
789 def __getattr__( self, name ):
805 def __getattr__( self, name ):
790 return getattr( self.QApplication, name )
806 return getattr( self.QApplication, name )
791
807
792 qt.QApplication = newQApplication()
808 qt.QApplication = newQApplication()
793
809
794 # Allows us to use both Tk and QT.
810 # Allows us to use both Tk and QT.
795 self.tk = get_tk()
811 self.tk = get_tk()
796
812
797 self.IP = make_IPython(argv,user_ns=user_ns,
813 self.IP = make_IPython(argv,user_ns=user_ns,
798 user_global_ns=user_global_ns,
814 user_global_ns=user_global_ns,
799 debug=debug,
815 debug=debug,
800 shell_class=shell_class,
816 shell_class=shell_class,
801 on_kill=[qt.qApp.exit])
817 on_kill=[qt.qApp.exit])
802
818
803 # HACK: slot for banner in self; it will be passed to the mainloop
819 # HACK: slot for banner in self; it will be passed to the mainloop
804 # method only and .run() needs it. The actual value will be set by
820 # method only and .run() needs it. The actual value will be set by
805 # .mainloop().
821 # .mainloop().
806 self._banner = None
822 self._banner = None
807
823
808 threading.Thread.__init__(self)
824 threading.Thread.__init__(self)
809
825
810 def run(self):
826 def run(self):
811 self.IP.mainloop(self._banner)
827 self.IP.mainloop(self._banner)
812 self.IP.kill()
828 self.IP.kill()
813
829
814 def mainloop(self,sys_exit=0,banner=None):
830 def mainloop(self,sys_exit=0,banner=None):
815
831
816 import qt
832 import qt
817
833
818 self._banner = banner
834 self._banner = banner
819
835
820 if qt.QApplication.startingUp():
836 if qt.QApplication.startingUp():
821 a = qt.QApplication.QApplication(sys.argv)
837 a = qt.QApplication.QApplication(sys.argv)
822 self.timer = qt.QTimer()
838 self.timer = qt.QTimer()
823 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
839 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
824
840
825 self.start()
841 self.start()
826 self.timer.start( self.TIMEOUT, True )
842 self.timer.start( self.TIMEOUT, True )
827 while True:
843 while True:
828 if self.IP._kill: break
844 if self.IP._kill: break
829 qt.qApp.exec_loop()
845 qt.qApp.exec_loop()
830 self.join()
846 self.join()
831
847
832 def on_timer(self):
848 def on_timer(self):
833 update_tk(self.tk)
849 update_tk(self.tk)
834 result = self.IP.runcode()
850 result = self.IP.runcode()
835 self.timer.start( self.TIMEOUT, True )
851 self.timer.start( self.TIMEOUT, True )
836 return result
852 return result
837
853
838 # A set of matplotlib public IPython shell classes, for single-threaded
854 # A set of matplotlib public IPython shell classes, for single-threaded
839 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
855 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
840 class IPShellMatplotlib(IPShell):
856 class IPShellMatplotlib(IPShell):
841 """Subclass IPShell with MatplotlibShell as the internal shell.
857 """Subclass IPShell with MatplotlibShell as the internal shell.
842
858
843 Single-threaded class, meant for the Tk* and FLTK* backends.
859 Single-threaded class, meant for the Tk* and FLTK* backends.
844
860
845 Having this on a separate class simplifies the external driver code."""
861 Having this on a separate class simplifies the external driver code."""
846
862
847 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
863 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
848 IPShell.__init__(self,argv,user_ns,user_global_ns,debug,
864 IPShell.__init__(self,argv,user_ns,user_global_ns,debug,
849 shell_class=MatplotlibShell)
865 shell_class=MatplotlibShell)
850
866
851 class IPShellMatplotlibGTK(IPShellGTK):
867 class IPShellMatplotlibGTK(IPShellGTK):
852 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
868 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
853
869
854 Multi-threaded class, meant for the GTK* backends."""
870 Multi-threaded class, meant for the GTK* backends."""
855
871
856 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
872 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
857 IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug,
873 IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug,
858 shell_class=MatplotlibMTShell)
874 shell_class=MatplotlibMTShell)
859
875
860 class IPShellMatplotlibWX(IPShellWX):
876 class IPShellMatplotlibWX(IPShellWX):
861 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
877 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
862
878
863 Multi-threaded class, meant for the WX* backends."""
879 Multi-threaded class, meant for the WX* backends."""
864
880
865 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
881 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
866 IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug,
882 IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug,
867 shell_class=MatplotlibMTShell)
883 shell_class=MatplotlibMTShell)
868
884
869 class IPShellMatplotlibQt(IPShellQt):
885 class IPShellMatplotlibQt(IPShellQt):
870 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
886 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
871
887
872 Multi-threaded class, meant for the Qt* backends."""
888 Multi-threaded class, meant for the Qt* backends."""
873
889
874 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
890 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
875 IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug,
891 IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug,
876 shell_class=MatplotlibMTShell)
892 shell_class=MatplotlibMTShell)
877
893
878 #-----------------------------------------------------------------------------
894 #-----------------------------------------------------------------------------
879 # Factory functions to actually start the proper thread-aware shell
895 # Factory functions to actually start the proper thread-aware shell
880
896
881 def _matplotlib_shell_class():
897 def _matplotlib_shell_class():
882 """Factory function to handle shell class selection for matplotlib.
898 """Factory function to handle shell class selection for matplotlib.
883
899
884 The proper shell class to use depends on the matplotlib backend, since
900 The proper shell class to use depends on the matplotlib backend, since
885 each backend requires a different threading strategy."""
901 each backend requires a different threading strategy."""
886
902
887 try:
903 try:
888 import matplotlib
904 import matplotlib
889 except ImportError:
905 except ImportError:
890 error('matplotlib could NOT be imported! Starting normal IPython.')
906 error('matplotlib could NOT be imported! Starting normal IPython.')
891 sh_class = IPShell
907 sh_class = IPShell
892 else:
908 else:
893 backend = matplotlib.rcParams['backend']
909 backend = matplotlib.rcParams['backend']
894 if backend.startswith('GTK'):
910 if backend.startswith('GTK'):
895 sh_class = IPShellMatplotlibGTK
911 sh_class = IPShellMatplotlibGTK
896 elif backend.startswith('WX'):
912 elif backend.startswith('WX'):
897 sh_class = IPShellMatplotlibWX
913 sh_class = IPShellMatplotlibWX
898 elif backend.startswith('Qt'):
914 elif backend.startswith('Qt'):
899 sh_class = IPShellMatplotlibQt
915 sh_class = IPShellMatplotlibQt
900 else:
916 else:
901 sh_class = IPShellMatplotlib
917 sh_class = IPShellMatplotlib
902 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
918 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
903 return sh_class
919 return sh_class
904
920
905 # This is the one which should be called by external code.
921 # This is the one which should be called by external code.
906 def start():
922 def start():
907 """Return a running shell instance, dealing with threading options.
923 """Return a running shell instance, dealing with threading options.
908
924
909 This is a factory function which will instantiate the proper IPython shell
925 This is a factory function which will instantiate the proper IPython shell
910 based on the user's threading choice. Such a selector is needed because
926 based on the user's threading choice. Such a selector is needed because
911 different GUI toolkits require different thread handling details."""
927 different GUI toolkits require different thread handling details."""
912
928
913 global USE_TK
929 global USE_TK
914 # Crude sys.argv hack to extract the threading options.
930 # Crude sys.argv hack to extract the threading options.
915 argv = sys.argv
931 argv = sys.argv
916 if len(argv) > 1:
932 if len(argv) > 1:
917 if len(argv) > 2:
933 if len(argv) > 2:
918 arg2 = argv[2]
934 arg2 = argv[2]
919 if arg2.endswith('-tk'):
935 if arg2.endswith('-tk'):
920 USE_TK = True
936 USE_TK = True
921 arg1 = argv[1]
937 arg1 = argv[1]
922 if arg1.endswith('-gthread'):
938 if arg1.endswith('-gthread'):
923 shell = IPShellGTK
939 shell = IPShellGTK
924 elif arg1.endswith( '-qthread' ):
940 elif arg1.endswith( '-qthread' ):
925 shell = IPShellQt
941 shell = IPShellQt
926 elif arg1.endswith('-wthread'):
942 elif arg1.endswith('-wthread'):
927 shell = IPShellWX
943 shell = IPShellWX
928 elif arg1.endswith('-pylab'):
944 elif arg1.endswith('-pylab'):
929 shell = _matplotlib_shell_class()
945 shell = _matplotlib_shell_class()
930 else:
946 else:
931 shell = IPShell
947 shell = IPShell
932 else:
948 else:
933 shell = IPShell
949 shell = IPShell
934 return shell()
950 return shell()
935
951
936 # Some aliases for backwards compatibility
952 # Some aliases for backwards compatibility
937 IPythonShell = IPShell
953 IPythonShell = IPShell
938 IPythonShellEmbed = IPShellEmbed
954 IPythonShellEmbed = IPShellEmbed
939 #************************ End of file <Shell.py> ***************************
955 #************************ End of file <Shell.py> ***************************
@@ -1,1768 +1,1772 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 General purpose utilities.
3 General purpose utilities.
4
4
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 these things are also convenient when working at the command line.
6 these things are also convenient when working at the command line.
7
7
8 $Id: genutils.py 1032 2006-01-20 09:03:57Z fperez $"""
8 $Id: genutils.py 1058 2006-01-22 14:30:01Z vivainio $"""
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 from __future__ import generators # 2.2 compatibility
17 from __future__ import generators # 2.2 compatibility
18
18
19 from IPython import Release
19 from IPython import Release
20 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 __license__ = Release.license
21 __license__ = Release.license
22
22
23 #****************************************************************************
23 #****************************************************************************
24 # required modules from the Python standard library
24 # required modules from the Python standard library
25 import __main__
25 import __main__
26 import commands
26 import commands
27 import os
27 import os
28 import re
28 import re
29 import shlex
29 import shlex
30 import shutil
30 import shutil
31 import sys
31 import sys
32 import tempfile
32 import tempfile
33 import time
33 import time
34 import types
34 import types
35
35
36 # Other IPython utilities
36 # Other IPython utilities
37 from IPython.Itpl import Itpl,itpl,printpl
37 from IPython.Itpl import Itpl,itpl,printpl
38 from IPython import DPyGetOpt
38 from IPython import DPyGetOpt
39 from IPython.path import path
39 from IPython.path import path
40 if os.name == "nt":
40 if os.name == "nt":
41 from IPython.winconsole import get_console_size
41 from IPython.winconsole import get_console_size
42
42
43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
44 # 2.2-friendly
44 # 2.2-friendly
45 try:
45 try:
46 basestring
46 basestring
47 except NameError:
47 except NameError:
48 import types
48 import types
49 basestring = (types.StringType, types.UnicodeType)
49 basestring = (types.StringType, types.UnicodeType)
50 True = 1==1
50 True = 1==1
51 False = 1==0
51 False = 1==0
52
52
53 def enumerate(obj):
53 def enumerate(obj):
54 i = -1
54 i = -1
55 for item in obj:
55 for item in obj:
56 i += 1
56 i += 1
57 yield i, item
57 yield i, item
58
58
59 # add these to the builtin namespace, so that all modules find them
59 # add these to the builtin namespace, so that all modules find them
60 import __builtin__
60 import __builtin__
61 __builtin__.basestring = basestring
61 __builtin__.basestring = basestring
62 __builtin__.True = True
62 __builtin__.True = True
63 __builtin__.False = False
63 __builtin__.False = False
64 __builtin__.enumerate = enumerate
64 __builtin__.enumerate = enumerate
65
65
66 # Try to use shlex.split for converting an input string into a sys.argv-type
66 # Try to use shlex.split for converting an input string into a sys.argv-type
67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
68 try:
68 try:
69 shlex_split = shlex.split
69 shlex_split = shlex.split
70 except AttributeError:
70 except AttributeError:
71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
75 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
75 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
76 % os.sep)
76 % os.sep)
77
77
78 def shlex_split(s):
78 def shlex_split(s):
79 """Simplified backport to Python 2.2 of shlex.split().
79 """Simplified backport to Python 2.2 of shlex.split().
80
80
81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
82 several of the features needed to really match the functionality of
82 several of the features needed to really match the functionality of
83 shlex.split() in 2.3."""
83 shlex.split() in 2.3."""
84
84
85 lex = shlex.shlex(StringIO(s))
85 lex = shlex.shlex(StringIO(s))
86 # Try to get options, extensions and path separators as characters
86 # Try to get options, extensions and path separators as characters
87 lex.wordchars = _wordchars
87 lex.wordchars = _wordchars
88 lex.commenters = ''
88 lex.commenters = ''
89 # Make a list out of the lexer by hand, since in 2.2 it's not an
89 # Make a list out of the lexer by hand, since in 2.2 it's not an
90 # iterator.
90 # iterator.
91 lout = []
91 lout = []
92 while 1:
92 while 1:
93 token = lex.get_token()
93 token = lex.get_token()
94 if token == '':
94 if token == '':
95 break
95 break
96 # Try to handle quoted tokens correctly
96 # Try to handle quoted tokens correctly
97 quotes = _quotesre.match(token)
97 quotes = _quotesre.match(token)
98 if quotes:
98 if quotes:
99 token = quotes.group(1)
99 token = quotes.group(1)
100 lout.append(token)
100 lout.append(token)
101 return lout
101 return lout
102
102
103 #****************************************************************************
103 #****************************************************************************
104 # Exceptions
104 # Exceptions
105 class Error(Exception):
105 class Error(Exception):
106 """Base class for exceptions in this module."""
106 """Base class for exceptions in this module."""
107 pass
107 pass
108
108
109 #----------------------------------------------------------------------------
109 #----------------------------------------------------------------------------
110 class IOStream:
110 class IOStream:
111 def __init__(self,stream,fallback):
111 def __init__(self,stream,fallback):
112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
113 stream = fallback
113 stream = fallback
114 self.stream = stream
114 self.stream = stream
115 self._swrite = stream.write
115 self._swrite = stream.write
116 self.flush = stream.flush
116 self.flush = stream.flush
117
117
118 def write(self,data):
118 def write(self,data):
119 try:
119 try:
120 self._swrite(data)
120 self._swrite(data)
121 except:
121 except:
122 try:
122 try:
123 # print handles some unicode issues which may trip a plain
123 # print handles some unicode issues which may trip a plain
124 # write() call. Attempt to emulate write() by using a
124 # write() call. Attempt to emulate write() by using a
125 # trailing comma
125 # trailing comma
126 print >> self.stream, data,
126 print >> self.stream, data,
127 except:
127 except:
128 # if we get here, something is seriously broken.
128 # if we get here, something is seriously broken.
129 print >> sys.stderr, \
129 print >> sys.stderr, \
130 'ERROR - failed to write data to stream:', stream
130 'ERROR - failed to write data to stream:', stream
131
131
132 class IOTerm:
132 class IOTerm:
133 """ Term holds the file or file-like objects for handling I/O operations.
133 """ Term holds the file or file-like objects for handling I/O operations.
134
134
135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
136 Windows they can can replaced to allow editing the strings before they are
136 Windows they can can replaced to allow editing the strings before they are
137 displayed."""
137 displayed."""
138
138
139 # In the future, having IPython channel all its I/O operations through
139 # In the future, having IPython channel all its I/O operations through
140 # this class will make it easier to embed it into other environments which
140 # this class will make it easier to embed it into other environments which
141 # are not a normal terminal (such as a GUI-based shell)
141 # are not a normal terminal (such as a GUI-based shell)
142 def __init__(self,cin=None,cout=None,cerr=None):
142 def __init__(self,cin=None,cout=None,cerr=None):
143 self.cin = IOStream(cin,sys.stdin)
143 self.cin = IOStream(cin,sys.stdin)
144 self.cout = IOStream(cout,sys.stdout)
144 self.cout = IOStream(cout,sys.stdout)
145 self.cerr = IOStream(cerr,sys.stderr)
145 self.cerr = IOStream(cerr,sys.stderr)
146
146
147 # Global variable to be used for all I/O
147 # Global variable to be used for all I/O
148 Term = IOTerm()
148 Term = IOTerm()
149
149
150 # Windows-specific code to load Gary Bishop's readline and configure it
150 # Windows-specific code to load Gary Bishop's readline and configure it
151 # automatically for the users
151 # automatically for the users
152 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
152 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
153 # windows. Cygwin returns 'cygwin' for sys.platform.
153 # windows. Cygwin returns 'cygwin' for sys.platform.
154 if os.name == 'nt':
154 if os.name == 'nt':
155 try:
155 try:
156 import readline
156 import readline
157 except ImportError:
157 except ImportError:
158 pass
158 pass
159 else:
159 else:
160 try:
160 try:
161 _out = readline.GetOutputFile()
161 _out = readline.GetOutputFile()
162 except AttributeError:
162 except AttributeError:
163 pass
163 pass
164 else:
164 else:
165 # Remake Term to use the readline i/o facilities
165 # Remake Term to use the readline i/o facilities
166 Term = IOTerm(cout=_out,cerr=_out)
166 Term = IOTerm(cout=_out,cerr=_out)
167 del _out
167 del _out
168
168
169 #****************************************************************************
169 #****************************************************************************
170 # Generic warning/error printer, used by everything else
170 # Generic warning/error printer, used by everything else
171 def warn(msg,level=2,exit_val=1):
171 def warn(msg,level=2,exit_val=1):
172 """Standard warning printer. Gives formatting consistency.
172 """Standard warning printer. Gives formatting consistency.
173
173
174 Output is sent to Term.cerr (sys.stderr by default).
174 Output is sent to Term.cerr (sys.stderr by default).
175
175
176 Options:
176 Options:
177
177
178 -level(2): allows finer control:
178 -level(2): allows finer control:
179 0 -> Do nothing, dummy function.
179 0 -> Do nothing, dummy function.
180 1 -> Print message.
180 1 -> Print message.
181 2 -> Print 'WARNING:' + message. (Default level).
181 2 -> Print 'WARNING:' + message. (Default level).
182 3 -> Print 'ERROR:' + message.
182 3 -> Print 'ERROR:' + message.
183 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
183 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
184
184
185 -exit_val (1): exit value returned by sys.exit() for a level 4
185 -exit_val (1): exit value returned by sys.exit() for a level 4
186 warning. Ignored for all other levels."""
186 warning. Ignored for all other levels."""
187
187
188 if level>0:
188 if level>0:
189 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
189 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
190 print >> Term.cerr, '%s%s' % (header[level],msg)
190 print >> Term.cerr, '%s%s' % (header[level],msg)
191 if level == 4:
191 if level == 4:
192 print >> Term.cerr,'Exiting.\n'
192 print >> Term.cerr,'Exiting.\n'
193 sys.exit(exit_val)
193 sys.exit(exit_val)
194
194
195 def info(msg):
195 def info(msg):
196 """Equivalent to warn(msg,level=1)."""
196 """Equivalent to warn(msg,level=1)."""
197
197
198 warn(msg,level=1)
198 warn(msg,level=1)
199
199
200 def error(msg):
200 def error(msg):
201 """Equivalent to warn(msg,level=3)."""
201 """Equivalent to warn(msg,level=3)."""
202
202
203 warn(msg,level=3)
203 warn(msg,level=3)
204
204
205 def fatal(msg,exit_val=1):
205 def fatal(msg,exit_val=1):
206 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
206 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
207
207
208 warn(msg,exit_val=exit_val,level=4)
208 warn(msg,exit_val=exit_val,level=4)
209
209
210
210
211 # useful for debugging
211 # useful for debugging
212 def debugp(expr,pre_msg=''):
212 def debugp(expr,pre_msg=''):
213 """Print the value of an expression from the caller's frame.
213 """Print the value of an expression from the caller's frame.
214
214
215 Takes an expression, evaluates it in the caller's frame and prints both
215 Takes an expression, evaluates it in the caller's frame and prints both
216 the given expression and the resulting value. The input must be of a form
216 the given expression and the resulting value (as well as a debug mark
217 suitable for eval()."""
217 indicating the name of the calling function. The input must be of a form
218 suitable for eval().
219
220 An optional message can be passed, which will be prepended to the printed
221 expr->value pair."""
218
222
219 cf = sys._getframe(1)
223 cf = sys._getframe(1)
220 print '[DBG] %s %s -> %r' % (pre_msg,expr,
224 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
221 eval(expr,cf.f_globals,cf.f_locals))
225 eval(expr,cf.f_globals,cf.f_locals))
222
226
223 # deactivate it from here:
227 # deactivate it by uncommenting the following line, which makes it a no-op
224 def debugp(expr,pre_msg=''): pass
228 def debugp(expr,pre_msg=''): pass
225
229
226 #----------------------------------------------------------------------------
230 #----------------------------------------------------------------------------
227 StringTypes = types.StringTypes
231 StringTypes = types.StringTypes
228
232
229 # Basic timing functionality
233 # Basic timing functionality
230
234
231 # If possible (Unix), use the resource module instead of time.clock()
235 # If possible (Unix), use the resource module instead of time.clock()
232 try:
236 try:
233 import resource
237 import resource
234 def clock():
238 def clock():
235 """clock() -> floating point number
239 """clock() -> floating point number
236
240
237 Return the CPU time in seconds (user time only, system time is
241 Return the CPU time in seconds (user time only, system time is
238 ignored) since the start of the process. This is done via a call to
242 ignored) since the start of the process. This is done via a call to
239 resource.getrusage, so it avoids the wraparound problems in
243 resource.getrusage, so it avoids the wraparound problems in
240 time.clock()."""
244 time.clock()."""
241
245
242 return resource.getrusage(resource.RUSAGE_SELF)[0]
246 return resource.getrusage(resource.RUSAGE_SELF)[0]
243
247
244 def clock2():
248 def clock2():
245 """clock2() -> (t_user,t_system)
249 """clock2() -> (t_user,t_system)
246
250
247 Similar to clock(), but return a tuple of user/system times."""
251 Similar to clock(), but return a tuple of user/system times."""
248 return resource.getrusage(resource.RUSAGE_SELF)[:2]
252 return resource.getrusage(resource.RUSAGE_SELF)[:2]
249
253
250 except ImportError:
254 except ImportError:
251 clock = time.clock
255 clock = time.clock
252 def clock2():
256 def clock2():
253 """Under windows, system CPU time can't be measured.
257 """Under windows, system CPU time can't be measured.
254
258
255 This just returns clock() and zero."""
259 This just returns clock() and zero."""
256 return time.clock(),0.0
260 return time.clock(),0.0
257
261
258 def timings_out(reps,func,*args,**kw):
262 def timings_out(reps,func,*args,**kw):
259 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
263 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
260
264
261 Execute a function reps times, return a tuple with the elapsed total
265 Execute a function reps times, return a tuple with the elapsed total
262 CPU time in seconds, the time per call and the function's output.
266 CPU time in seconds, the time per call and the function's output.
263
267
264 Under Unix, the return value is the sum of user+system time consumed by
268 Under Unix, the return value is the sum of user+system time consumed by
265 the process, computed via the resource module. This prevents problems
269 the process, computed via the resource module. This prevents problems
266 related to the wraparound effect which the time.clock() function has.
270 related to the wraparound effect which the time.clock() function has.
267
271
268 Under Windows the return value is in wall clock seconds. See the
272 Under Windows the return value is in wall clock seconds. See the
269 documentation for the time module for more details."""
273 documentation for the time module for more details."""
270
274
271 reps = int(reps)
275 reps = int(reps)
272 assert reps >=1, 'reps must be >= 1'
276 assert reps >=1, 'reps must be >= 1'
273 if reps==1:
277 if reps==1:
274 start = clock()
278 start = clock()
275 out = func(*args,**kw)
279 out = func(*args,**kw)
276 tot_time = clock()-start
280 tot_time = clock()-start
277 else:
281 else:
278 rng = xrange(reps-1) # the last time is executed separately to store output
282 rng = xrange(reps-1) # the last time is executed separately to store output
279 start = clock()
283 start = clock()
280 for dummy in rng: func(*args,**kw)
284 for dummy in rng: func(*args,**kw)
281 out = func(*args,**kw) # one last time
285 out = func(*args,**kw) # one last time
282 tot_time = clock()-start
286 tot_time = clock()-start
283 av_time = tot_time / reps
287 av_time = tot_time / reps
284 return tot_time,av_time,out
288 return tot_time,av_time,out
285
289
286 def timings(reps,func,*args,**kw):
290 def timings(reps,func,*args,**kw):
287 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
291 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
288
292
289 Execute a function reps times, return a tuple with the elapsed total CPU
293 Execute a function reps times, return a tuple with the elapsed total CPU
290 time in seconds and the time per call. These are just the first two values
294 time in seconds and the time per call. These are just the first two values
291 in timings_out()."""
295 in timings_out()."""
292
296
293 return timings_out(reps,func,*args,**kw)[0:2]
297 return timings_out(reps,func,*args,**kw)[0:2]
294
298
295 def timing(func,*args,**kw):
299 def timing(func,*args,**kw):
296 """timing(func,*args,**kw) -> t_total
300 """timing(func,*args,**kw) -> t_total
297
301
298 Execute a function once, return the elapsed total CPU time in
302 Execute a function once, return the elapsed total CPU time in
299 seconds. This is just the first value in timings_out()."""
303 seconds. This is just the first value in timings_out()."""
300
304
301 return timings_out(1,func,*args,**kw)[0]
305 return timings_out(1,func,*args,**kw)[0]
302
306
303 #****************************************************************************
307 #****************************************************************************
304 # file and system
308 # file and system
305
309
306 def system(cmd,verbose=0,debug=0,header=''):
310 def system(cmd,verbose=0,debug=0,header=''):
307 """Execute a system command, return its exit status.
311 """Execute a system command, return its exit status.
308
312
309 Options:
313 Options:
310
314
311 - verbose (0): print the command to be executed.
315 - verbose (0): print the command to be executed.
312
316
313 - debug (0): only print, do not actually execute.
317 - debug (0): only print, do not actually execute.
314
318
315 - header (''): Header to print on screen prior to the executed command (it
319 - header (''): Header to print on screen prior to the executed command (it
316 is only prepended to the command, no newlines are added).
320 is only prepended to the command, no newlines are added).
317
321
318 Note: a stateful version of this function is available through the
322 Note: a stateful version of this function is available through the
319 SystemExec class."""
323 SystemExec class."""
320
324
321 stat = 0
325 stat = 0
322 if verbose or debug: print header+cmd
326 if verbose or debug: print header+cmd
323 sys.stdout.flush()
327 sys.stdout.flush()
324 if not debug: stat = os.system(cmd)
328 if not debug: stat = os.system(cmd)
325 return stat
329 return stat
326
330
327 # This function is used by ipython in a lot of places to make system calls.
331 # This function is used by ipython in a lot of places to make system calls.
328 # We need it to be slightly different under win32, due to the vagaries of
332 # We need it to be slightly different under win32, due to the vagaries of
329 # 'network shares'. A win32 override is below.
333 # 'network shares'. A win32 override is below.
330
334
331 def shell(cmd,verbose=0,debug=0,header=''):
335 def shell(cmd,verbose=0,debug=0,header=''):
332 """Execute a command in the system shell, always return None.
336 """Execute a command in the system shell, always return None.
333
337
334 Options:
338 Options:
335
339
336 - verbose (0): print the command to be executed.
340 - verbose (0): print the command to be executed.
337
341
338 - debug (0): only print, do not actually execute.
342 - debug (0): only print, do not actually execute.
339
343
340 - header (''): Header to print on screen prior to the executed command (it
344 - header (''): Header to print on screen prior to the executed command (it
341 is only prepended to the command, no newlines are added).
345 is only prepended to the command, no newlines are added).
342
346
343 Note: this is similar to genutils.system(), but it returns None so it can
347 Note: this is similar to genutils.system(), but it returns None so it can
344 be conveniently used in interactive loops without getting the return value
348 be conveniently used in interactive loops without getting the return value
345 (typically 0) printed many times."""
349 (typically 0) printed many times."""
346
350
347 stat = 0
351 stat = 0
348 if verbose or debug: print header+cmd
352 if verbose or debug: print header+cmd
349 # flush stdout so we don't mangle python's buffering
353 # flush stdout so we don't mangle python's buffering
350 sys.stdout.flush()
354 sys.stdout.flush()
351 if not debug:
355 if not debug:
352 os.system(cmd)
356 os.system(cmd)
353
357
354 # override shell() for win32 to deal with network shares
358 # override shell() for win32 to deal with network shares
355 if os.name in ('nt','dos'):
359 if os.name in ('nt','dos'):
356
360
357 shell_ori = shell
361 shell_ori = shell
358
362
359 def shell(cmd,verbose=0,debug=0,header=''):
363 def shell(cmd,verbose=0,debug=0,header=''):
360 if os.getcwd().startswith(r"\\"):
364 if os.getcwd().startswith(r"\\"):
361 path = os.getcwd()
365 path = os.getcwd()
362 # change to c drive (cannot be on UNC-share when issuing os.system,
366 # change to c drive (cannot be on UNC-share when issuing os.system,
363 # as cmd.exe cannot handle UNC addresses)
367 # as cmd.exe cannot handle UNC addresses)
364 os.chdir("c:")
368 os.chdir("c:")
365 # issue pushd to the UNC-share and then run the command
369 # issue pushd to the UNC-share and then run the command
366 try:
370 try:
367 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
371 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
368 finally:
372 finally:
369 os.chdir(path)
373 os.chdir(path)
370 else:
374 else:
371 shell_ori(cmd,verbose,debug,header)
375 shell_ori(cmd,verbose,debug,header)
372
376
373 shell.__doc__ = shell_ori.__doc__
377 shell.__doc__ = shell_ori.__doc__
374
378
375 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
379 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
376 """Dummy substitute for perl's backquotes.
380 """Dummy substitute for perl's backquotes.
377
381
378 Executes a command and returns the output.
382 Executes a command and returns the output.
379
383
380 Accepts the same arguments as system(), plus:
384 Accepts the same arguments as system(), plus:
381
385
382 - split(0): if true, the output is returned as a list split on newlines.
386 - split(0): if true, the output is returned as a list split on newlines.
383
387
384 Note: a stateful version of this function is available through the
388 Note: a stateful version of this function is available through the
385 SystemExec class."""
389 SystemExec class."""
386
390
387 if verbose or debug: print header+cmd
391 if verbose or debug: print header+cmd
388 if not debug:
392 if not debug:
389 output = commands.getoutput(cmd)
393 output = commands.getoutput(cmd)
390 if split:
394 if split:
391 return output.split('\n')
395 return output.split('\n')
392 else:
396 else:
393 return output
397 return output
394
398
395 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
399 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
396 """Return (standard output,standard error) of executing cmd in a shell.
400 """Return (standard output,standard error) of executing cmd in a shell.
397
401
398 Accepts the same arguments as system(), plus:
402 Accepts the same arguments as system(), plus:
399
403
400 - split(0): if true, each of stdout/err is returned as a list split on
404 - split(0): if true, each of stdout/err is returned as a list split on
401 newlines.
405 newlines.
402
406
403 Note: a stateful version of this function is available through the
407 Note: a stateful version of this function is available through the
404 SystemExec class."""
408 SystemExec class."""
405
409
406 if verbose or debug: print header+cmd
410 if verbose or debug: print header+cmd
407 if not cmd:
411 if not cmd:
408 if split:
412 if split:
409 return [],[]
413 return [],[]
410 else:
414 else:
411 return '',''
415 return '',''
412 if not debug:
416 if not debug:
413 pin,pout,perr = os.popen3(cmd)
417 pin,pout,perr = os.popen3(cmd)
414 tout = pout.read().rstrip()
418 tout = pout.read().rstrip()
415 terr = perr.read().rstrip()
419 terr = perr.read().rstrip()
416 pin.close()
420 pin.close()
417 pout.close()
421 pout.close()
418 perr.close()
422 perr.close()
419 if split:
423 if split:
420 return tout.split('\n'),terr.split('\n')
424 return tout.split('\n'),terr.split('\n')
421 else:
425 else:
422 return tout,terr
426 return tout,terr
423
427
424 # for compatibility with older naming conventions
428 # for compatibility with older naming conventions
425 xsys = system
429 xsys = system
426 bq = getoutput
430 bq = getoutput
427
431
428 class SystemExec:
432 class SystemExec:
429 """Access the system and getoutput functions through a stateful interface.
433 """Access the system and getoutput functions through a stateful interface.
430
434
431 Note: here we refer to the system and getoutput functions from this
435 Note: here we refer to the system and getoutput functions from this
432 library, not the ones from the standard python library.
436 library, not the ones from the standard python library.
433
437
434 This class offers the system and getoutput functions as methods, but the
438 This class offers the system and getoutput functions as methods, but the
435 verbose, debug and header parameters can be set for the instance (at
439 verbose, debug and header parameters can be set for the instance (at
436 creation time or later) so that they don't need to be specified on each
440 creation time or later) so that they don't need to be specified on each
437 call.
441 call.
438
442
439 For efficiency reasons, there's no way to override the parameters on a
443 For efficiency reasons, there's no way to override the parameters on a
440 per-call basis other than by setting instance attributes. If you need
444 per-call basis other than by setting instance attributes. If you need
441 local overrides, it's best to directly call system() or getoutput().
445 local overrides, it's best to directly call system() or getoutput().
442
446
443 The following names are provided as alternate options:
447 The following names are provided as alternate options:
444 - xsys: alias to system
448 - xsys: alias to system
445 - bq: alias to getoutput
449 - bq: alias to getoutput
446
450
447 An instance can then be created as:
451 An instance can then be created as:
448 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
452 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
449
453
450 And used as:
454 And used as:
451 >>> sysexec.xsys('pwd')
455 >>> sysexec.xsys('pwd')
452 >>> dirlist = sysexec.bq('ls -l')
456 >>> dirlist = sysexec.bq('ls -l')
453 """
457 """
454
458
455 def __init__(self,verbose=0,debug=0,header='',split=0):
459 def __init__(self,verbose=0,debug=0,header='',split=0):
456 """Specify the instance's values for verbose, debug and header."""
460 """Specify the instance's values for verbose, debug and header."""
457 setattr_list(self,'verbose debug header split')
461 setattr_list(self,'verbose debug header split')
458
462
459 def system(self,cmd):
463 def system(self,cmd):
460 """Stateful interface to system(), with the same keyword parameters."""
464 """Stateful interface to system(), with the same keyword parameters."""
461
465
462 system(cmd,self.verbose,self.debug,self.header)
466 system(cmd,self.verbose,self.debug,self.header)
463
467
464 def shell(self,cmd):
468 def shell(self,cmd):
465 """Stateful interface to shell(), with the same keyword parameters."""
469 """Stateful interface to shell(), with the same keyword parameters."""
466
470
467 shell(cmd,self.verbose,self.debug,self.header)
471 shell(cmd,self.verbose,self.debug,self.header)
468
472
469 xsys = system # alias
473 xsys = system # alias
470
474
471 def getoutput(self,cmd):
475 def getoutput(self,cmd):
472 """Stateful interface to getoutput()."""
476 """Stateful interface to getoutput()."""
473
477
474 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
478 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
475
479
476 def getoutputerror(self,cmd):
480 def getoutputerror(self,cmd):
477 """Stateful interface to getoutputerror()."""
481 """Stateful interface to getoutputerror()."""
478
482
479 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
483 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
480
484
481 bq = getoutput # alias
485 bq = getoutput # alias
482
486
483 #-----------------------------------------------------------------------------
487 #-----------------------------------------------------------------------------
484 def mutex_opts(dict,ex_op):
488 def mutex_opts(dict,ex_op):
485 """Check for presence of mutually exclusive keys in a dict.
489 """Check for presence of mutually exclusive keys in a dict.
486
490
487 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
491 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
488 for op1,op2 in ex_op:
492 for op1,op2 in ex_op:
489 if op1 in dict and op2 in dict:
493 if op1 in dict and op2 in dict:
490 raise ValueError,'\n*** ERROR in Arguments *** '\
494 raise ValueError,'\n*** ERROR in Arguments *** '\
491 'Options '+op1+' and '+op2+' are mutually exclusive.'
495 'Options '+op1+' and '+op2+' are mutually exclusive.'
492
496
493 #-----------------------------------------------------------------------------
497 #-----------------------------------------------------------------------------
494 def get_py_filename(name):
498 def get_py_filename(name):
495 """Return a valid python filename in the current directory.
499 """Return a valid python filename in the current directory.
496
500
497 If the given name is not a file, it adds '.py' and searches again.
501 If the given name is not a file, it adds '.py' and searches again.
498 Raises IOError with an informative message if the file isn't found."""
502 Raises IOError with an informative message if the file isn't found."""
499
503
500 name = os.path.expanduser(name)
504 name = os.path.expanduser(name)
501 if not os.path.isfile(name) and not name.endswith('.py'):
505 if not os.path.isfile(name) and not name.endswith('.py'):
502 name += '.py'
506 name += '.py'
503 if os.path.isfile(name):
507 if os.path.isfile(name):
504 return name
508 return name
505 else:
509 else:
506 raise IOError,'File `%s` not found.' % name
510 raise IOError,'File `%s` not found.' % name
507
511
508 #-----------------------------------------------------------------------------
512 #-----------------------------------------------------------------------------
509 def filefind(fname,alt_dirs = None):
513 def filefind(fname,alt_dirs = None):
510 """Return the given filename either in the current directory, if it
514 """Return the given filename either in the current directory, if it
511 exists, or in a specified list of directories.
515 exists, or in a specified list of directories.
512
516
513 ~ expansion is done on all file and directory names.
517 ~ expansion is done on all file and directory names.
514
518
515 Upon an unsuccessful search, raise an IOError exception."""
519 Upon an unsuccessful search, raise an IOError exception."""
516
520
517 if alt_dirs is None:
521 if alt_dirs is None:
518 try:
522 try:
519 alt_dirs = get_home_dir()
523 alt_dirs = get_home_dir()
520 except HomeDirError:
524 except HomeDirError:
521 alt_dirs = os.getcwd()
525 alt_dirs = os.getcwd()
522 search = [fname] + list_strings(alt_dirs)
526 search = [fname] + list_strings(alt_dirs)
523 search = map(os.path.expanduser,search)
527 search = map(os.path.expanduser,search)
524 #print 'search list for',fname,'list:',search # dbg
528 #print 'search list for',fname,'list:',search # dbg
525 fname = search[0]
529 fname = search[0]
526 if os.path.isfile(fname):
530 if os.path.isfile(fname):
527 return fname
531 return fname
528 for direc in search[1:]:
532 for direc in search[1:]:
529 testname = os.path.join(direc,fname)
533 testname = os.path.join(direc,fname)
530 #print 'testname',testname # dbg
534 #print 'testname',testname # dbg
531 if os.path.isfile(testname):
535 if os.path.isfile(testname):
532 return testname
536 return testname
533 raise IOError,'File' + `fname` + \
537 raise IOError,'File' + `fname` + \
534 ' not found in current or supplied directories:' + `alt_dirs`
538 ' not found in current or supplied directories:' + `alt_dirs`
535
539
536 #----------------------------------------------------------------------------
540 #----------------------------------------------------------------------------
537 def file_read(filename):
541 def file_read(filename):
538 """Read a file and close it. Returns the file source."""
542 """Read a file and close it. Returns the file source."""
539 fobj=open(filename,'r');
543 fobj=open(filename,'r');
540 source = fobj.read();
544 source = fobj.read();
541 fobj.close()
545 fobj.close()
542 return source
546 return source
543
547
544 #----------------------------------------------------------------------------
548 #----------------------------------------------------------------------------
545 def target_outdated(target,deps):
549 def target_outdated(target,deps):
546 """Determine whether a target is out of date.
550 """Determine whether a target is out of date.
547
551
548 target_outdated(target,deps) -> 1/0
552 target_outdated(target,deps) -> 1/0
549
553
550 deps: list of filenames which MUST exist.
554 deps: list of filenames which MUST exist.
551 target: single filename which may or may not exist.
555 target: single filename which may or may not exist.
552
556
553 If target doesn't exist or is older than any file listed in deps, return
557 If target doesn't exist or is older than any file listed in deps, return
554 true, otherwise return false.
558 true, otherwise return false.
555 """
559 """
556 try:
560 try:
557 target_time = os.path.getmtime(target)
561 target_time = os.path.getmtime(target)
558 except os.error:
562 except os.error:
559 return 1
563 return 1
560 for dep in deps:
564 for dep in deps:
561 dep_time = os.path.getmtime(dep)
565 dep_time = os.path.getmtime(dep)
562 if dep_time > target_time:
566 if dep_time > target_time:
563 #print "For target",target,"Dep failed:",dep # dbg
567 #print "For target",target,"Dep failed:",dep # dbg
564 #print "times (dep,tar):",dep_time,target_time # dbg
568 #print "times (dep,tar):",dep_time,target_time # dbg
565 return 1
569 return 1
566 return 0
570 return 0
567
571
568 #-----------------------------------------------------------------------------
572 #-----------------------------------------------------------------------------
569 def target_update(target,deps,cmd):
573 def target_update(target,deps,cmd):
570 """Update a target with a given command given a list of dependencies.
574 """Update a target with a given command given a list of dependencies.
571
575
572 target_update(target,deps,cmd) -> runs cmd if target is outdated.
576 target_update(target,deps,cmd) -> runs cmd if target is outdated.
573
577
574 This is just a wrapper around target_outdated() which calls the given
578 This is just a wrapper around target_outdated() which calls the given
575 command if target is outdated."""
579 command if target is outdated."""
576
580
577 if target_outdated(target,deps):
581 if target_outdated(target,deps):
578 xsys(cmd)
582 xsys(cmd)
579
583
580 #----------------------------------------------------------------------------
584 #----------------------------------------------------------------------------
581 def unquote_ends(istr):
585 def unquote_ends(istr):
582 """Remove a single pair of quotes from the endpoints of a string."""
586 """Remove a single pair of quotes from the endpoints of a string."""
583
587
584 if not istr:
588 if not istr:
585 return istr
589 return istr
586 if (istr[0]=="'" and istr[-1]=="'") or \
590 if (istr[0]=="'" and istr[-1]=="'") or \
587 (istr[0]=='"' and istr[-1]=='"'):
591 (istr[0]=='"' and istr[-1]=='"'):
588 return istr[1:-1]
592 return istr[1:-1]
589 else:
593 else:
590 return istr
594 return istr
591
595
592 #----------------------------------------------------------------------------
596 #----------------------------------------------------------------------------
593 def process_cmdline(argv,names=[],defaults={},usage=''):
597 def process_cmdline(argv,names=[],defaults={},usage=''):
594 """ Process command-line options and arguments.
598 """ Process command-line options and arguments.
595
599
596 Arguments:
600 Arguments:
597
601
598 - argv: list of arguments, typically sys.argv.
602 - argv: list of arguments, typically sys.argv.
599
603
600 - names: list of option names. See DPyGetOpt docs for details on options
604 - names: list of option names. See DPyGetOpt docs for details on options
601 syntax.
605 syntax.
602
606
603 - defaults: dict of default values.
607 - defaults: dict of default values.
604
608
605 - usage: optional usage notice to print if a wrong argument is passed.
609 - usage: optional usage notice to print if a wrong argument is passed.
606
610
607 Return a dict of options and a list of free arguments."""
611 Return a dict of options and a list of free arguments."""
608
612
609 getopt = DPyGetOpt.DPyGetOpt()
613 getopt = DPyGetOpt.DPyGetOpt()
610 getopt.setIgnoreCase(0)
614 getopt.setIgnoreCase(0)
611 getopt.parseConfiguration(names)
615 getopt.parseConfiguration(names)
612
616
613 try:
617 try:
614 getopt.processArguments(argv)
618 getopt.processArguments(argv)
615 except:
619 except:
616 print usage
620 print usage
617 warn(`sys.exc_value`,level=4)
621 warn(`sys.exc_value`,level=4)
618
622
619 defaults.update(getopt.optionValues)
623 defaults.update(getopt.optionValues)
620 args = getopt.freeValues
624 args = getopt.freeValues
621
625
622 return defaults,args
626 return defaults,args
623
627
624 #----------------------------------------------------------------------------
628 #----------------------------------------------------------------------------
625 def optstr2types(ostr):
629 def optstr2types(ostr):
626 """Convert a string of option names to a dict of type mappings.
630 """Convert a string of option names to a dict of type mappings.
627
631
628 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
632 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
629
633
630 This is used to get the types of all the options in a string formatted
634 This is used to get the types of all the options in a string formatted
631 with the conventions of DPyGetOpt. The 'type' None is used for options
635 with the conventions of DPyGetOpt. The 'type' None is used for options
632 which are strings (they need no further conversion). This function's main
636 which are strings (they need no further conversion). This function's main
633 use is to get a typemap for use with read_dict().
637 use is to get a typemap for use with read_dict().
634 """
638 """
635
639
636 typeconv = {None:'',int:'',float:''}
640 typeconv = {None:'',int:'',float:''}
637 typemap = {'s':None,'i':int,'f':float}
641 typemap = {'s':None,'i':int,'f':float}
638 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
642 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
639
643
640 for w in ostr.split():
644 for w in ostr.split():
641 oname,alias,otype = opt_re.match(w).groups()
645 oname,alias,otype = opt_re.match(w).groups()
642 if otype == '' or alias == '!': # simple switches are integers too
646 if otype == '' or alias == '!': # simple switches are integers too
643 otype = 'i'
647 otype = 'i'
644 typeconv[typemap[otype]] += oname + ' '
648 typeconv[typemap[otype]] += oname + ' '
645 return typeconv
649 return typeconv
646
650
647 #----------------------------------------------------------------------------
651 #----------------------------------------------------------------------------
648 def read_dict(filename,type_conv=None,**opt):
652 def read_dict(filename,type_conv=None,**opt):
649
653
650 """Read a dictionary of key=value pairs from an input file, optionally
654 """Read a dictionary of key=value pairs from an input file, optionally
651 performing conversions on the resulting values.
655 performing conversions on the resulting values.
652
656
653 read_dict(filename,type_conv,**opt) -> dict
657 read_dict(filename,type_conv,**opt) -> dict
654
658
655 Only one value per line is accepted, the format should be
659 Only one value per line is accepted, the format should be
656 # optional comments are ignored
660 # optional comments are ignored
657 key value\n
661 key value\n
658
662
659 Args:
663 Args:
660
664
661 - type_conv: A dictionary specifying which keys need to be converted to
665 - type_conv: A dictionary specifying which keys need to be converted to
662 which types. By default all keys are read as strings. This dictionary
666 which types. By default all keys are read as strings. This dictionary
663 should have as its keys valid conversion functions for strings
667 should have as its keys valid conversion functions for strings
664 (int,long,float,complex, or your own). The value for each key
668 (int,long,float,complex, or your own). The value for each key
665 (converter) should be a whitespace separated string containing the names
669 (converter) should be a whitespace separated string containing the names
666 of all the entries in the file to be converted using that function. For
670 of all the entries in the file to be converted using that function. For
667 keys to be left alone, use None as the conversion function (only needed
671 keys to be left alone, use None as the conversion function (only needed
668 with purge=1, see below).
672 with purge=1, see below).
669
673
670 - opt: dictionary with extra options as below (default in parens)
674 - opt: dictionary with extra options as below (default in parens)
671
675
672 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
676 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
673 of the dictionary to be returned. If purge is going to be used, the
677 of the dictionary to be returned. If purge is going to be used, the
674 set of keys to be left as strings also has to be explicitly specified
678 set of keys to be left as strings also has to be explicitly specified
675 using the (non-existent) conversion function None.
679 using the (non-existent) conversion function None.
676
680
677 fs(None): field separator. This is the key/value separator to be used
681 fs(None): field separator. This is the key/value separator to be used
678 when parsing the file. The None default means any whitespace [behavior
682 when parsing the file. The None default means any whitespace [behavior
679 of string.split()].
683 of string.split()].
680
684
681 strip(0): if 1, strip string values of leading/trailinig whitespace.
685 strip(0): if 1, strip string values of leading/trailinig whitespace.
682
686
683 warn(1): warning level if requested keys are not found in file.
687 warn(1): warning level if requested keys are not found in file.
684 - 0: silently ignore.
688 - 0: silently ignore.
685 - 1: inform but proceed.
689 - 1: inform but proceed.
686 - 2: raise KeyError exception.
690 - 2: raise KeyError exception.
687
691
688 no_empty(0): if 1, remove keys with whitespace strings as a value.
692 no_empty(0): if 1, remove keys with whitespace strings as a value.
689
693
690 unique([]): list of keys (or space separated string) which can't be
694 unique([]): list of keys (or space separated string) which can't be
691 repeated. If one such key is found in the file, each new instance
695 repeated. If one such key is found in the file, each new instance
692 overwrites the previous one. For keys not listed here, the behavior is
696 overwrites the previous one. For keys not listed here, the behavior is
693 to make a list of all appearances.
697 to make a list of all appearances.
694
698
695 Example:
699 Example:
696 If the input file test.ini has:
700 If the input file test.ini has:
697 i 3
701 i 3
698 x 4.5
702 x 4.5
699 y 5.5
703 y 5.5
700 s hi ho
704 s hi ho
701 Then:
705 Then:
702
706
703 >>> type_conv={int:'i',float:'x',None:'s'}
707 >>> type_conv={int:'i',float:'x',None:'s'}
704 >>> read_dict('test.ini')
708 >>> read_dict('test.ini')
705 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
709 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
706 >>> read_dict('test.ini',type_conv)
710 >>> read_dict('test.ini',type_conv)
707 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
711 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
708 >>> read_dict('test.ini',type_conv,purge=1)
712 >>> read_dict('test.ini',type_conv,purge=1)
709 {'i': 3, 's': 'hi ho', 'x': 4.5}
713 {'i': 3, 's': 'hi ho', 'x': 4.5}
710 """
714 """
711
715
712 # starting config
716 # starting config
713 opt.setdefault('purge',0)
717 opt.setdefault('purge',0)
714 opt.setdefault('fs',None) # field sep defaults to any whitespace
718 opt.setdefault('fs',None) # field sep defaults to any whitespace
715 opt.setdefault('strip',0)
719 opt.setdefault('strip',0)
716 opt.setdefault('warn',1)
720 opt.setdefault('warn',1)
717 opt.setdefault('no_empty',0)
721 opt.setdefault('no_empty',0)
718 opt.setdefault('unique','')
722 opt.setdefault('unique','')
719 if type(opt['unique']) in StringTypes:
723 if type(opt['unique']) in StringTypes:
720 unique_keys = qw(opt['unique'])
724 unique_keys = qw(opt['unique'])
721 elif type(opt['unique']) in (types.TupleType,types.ListType):
725 elif type(opt['unique']) in (types.TupleType,types.ListType):
722 unique_keys = opt['unique']
726 unique_keys = opt['unique']
723 else:
727 else:
724 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
728 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
725
729
726 dict = {}
730 dict = {}
727 # first read in table of values as strings
731 # first read in table of values as strings
728 file = open(filename,'r')
732 file = open(filename,'r')
729 for line in file.readlines():
733 for line in file.readlines():
730 line = line.strip()
734 line = line.strip()
731 if len(line) and line[0]=='#': continue
735 if len(line) and line[0]=='#': continue
732 if len(line)>0:
736 if len(line)>0:
733 lsplit = line.split(opt['fs'],1)
737 lsplit = line.split(opt['fs'],1)
734 try:
738 try:
735 key,val = lsplit
739 key,val = lsplit
736 except ValueError:
740 except ValueError:
737 key,val = lsplit[0],''
741 key,val = lsplit[0],''
738 key = key.strip()
742 key = key.strip()
739 if opt['strip']: val = val.strip()
743 if opt['strip']: val = val.strip()
740 if val == "''" or val == '""': val = ''
744 if val == "''" or val == '""': val = ''
741 if opt['no_empty'] and (val=='' or val.isspace()):
745 if opt['no_empty'] and (val=='' or val.isspace()):
742 continue
746 continue
743 # if a key is found more than once in the file, build a list
747 # if a key is found more than once in the file, build a list
744 # unless it's in the 'unique' list. In that case, last found in file
748 # unless it's in the 'unique' list. In that case, last found in file
745 # takes precedence. User beware.
749 # takes precedence. User beware.
746 try:
750 try:
747 if dict[key] and key in unique_keys:
751 if dict[key] and key in unique_keys:
748 dict[key] = val
752 dict[key] = val
749 elif type(dict[key]) is types.ListType:
753 elif type(dict[key]) is types.ListType:
750 dict[key].append(val)
754 dict[key].append(val)
751 else:
755 else:
752 dict[key] = [dict[key],val]
756 dict[key] = [dict[key],val]
753 except KeyError:
757 except KeyError:
754 dict[key] = val
758 dict[key] = val
755 # purge if requested
759 # purge if requested
756 if opt['purge']:
760 if opt['purge']:
757 accepted_keys = qwflat(type_conv.values())
761 accepted_keys = qwflat(type_conv.values())
758 for key in dict.keys():
762 for key in dict.keys():
759 if key in accepted_keys: continue
763 if key in accepted_keys: continue
760 del(dict[key])
764 del(dict[key])
761 # now convert if requested
765 # now convert if requested
762 if type_conv==None: return dict
766 if type_conv==None: return dict
763 conversions = type_conv.keys()
767 conversions = type_conv.keys()
764 try: conversions.remove(None)
768 try: conversions.remove(None)
765 except: pass
769 except: pass
766 for convert in conversions:
770 for convert in conversions:
767 for val in qw(type_conv[convert]):
771 for val in qw(type_conv[convert]):
768 try:
772 try:
769 dict[val] = convert(dict[val])
773 dict[val] = convert(dict[val])
770 except KeyError,e:
774 except KeyError,e:
771 if opt['warn'] == 0:
775 if opt['warn'] == 0:
772 pass
776 pass
773 elif opt['warn'] == 1:
777 elif opt['warn'] == 1:
774 print >>sys.stderr, 'Warning: key',val,\
778 print >>sys.stderr, 'Warning: key',val,\
775 'not found in file',filename
779 'not found in file',filename
776 elif opt['warn'] == 2:
780 elif opt['warn'] == 2:
777 raise KeyError,e
781 raise KeyError,e
778 else:
782 else:
779 raise ValueError,'Warning level must be 0,1 or 2'
783 raise ValueError,'Warning level must be 0,1 or 2'
780
784
781 return dict
785 return dict
782
786
783 #----------------------------------------------------------------------------
787 #----------------------------------------------------------------------------
784 def flag_calls(func):
788 def flag_calls(func):
785 """Wrap a function to detect and flag when it gets called.
789 """Wrap a function to detect and flag when it gets called.
786
790
787 This is a decorator which takes a function and wraps it in a function with
791 This is a decorator which takes a function and wraps it in a function with
788 a 'called' attribute. wrapper.called is initialized to False.
792 a 'called' attribute. wrapper.called is initialized to False.
789
793
790 The wrapper.called attribute is set to False right before each call to the
794 The wrapper.called attribute is set to False right before each call to the
791 wrapped function, so if the call fails it remains False. After the call
795 wrapped function, so if the call fails it remains False. After the call
792 completes, wrapper.called is set to True and the output is returned.
796 completes, wrapper.called is set to True and the output is returned.
793
797
794 Testing for truth in wrapper.called allows you to determine if a call to
798 Testing for truth in wrapper.called allows you to determine if a call to
795 func() was attempted and succeeded."""
799 func() was attempted and succeeded."""
796
800
797 def wrapper(*args,**kw):
801 def wrapper(*args,**kw):
798 wrapper.called = False
802 wrapper.called = False
799 out = func(*args,**kw)
803 out = func(*args,**kw)
800 wrapper.called = True
804 wrapper.called = True
801 return out
805 return out
802
806
803 wrapper.called = False
807 wrapper.called = False
804 wrapper.__doc__ = func.__doc__
808 wrapper.__doc__ = func.__doc__
805 return wrapper
809 return wrapper
806
810
807 #----------------------------------------------------------------------------
811 #----------------------------------------------------------------------------
808 class HomeDirError(Error):
812 class HomeDirError(Error):
809 pass
813 pass
810
814
811 def get_home_dir():
815 def get_home_dir():
812 """Return the closest possible equivalent to a 'home' directory.
816 """Return the closest possible equivalent to a 'home' directory.
813
817
814 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
818 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
815
819
816 Currently only Posix and NT are implemented, a HomeDirError exception is
820 Currently only Posix and NT are implemented, a HomeDirError exception is
817 raised for all other OSes. """
821 raised for all other OSes. """
818
822
819 isdir = os.path.isdir
823 isdir = os.path.isdir
820 env = os.environ
824 env = os.environ
821 try:
825 try:
822 homedir = env['HOME']
826 homedir = env['HOME']
823 if not isdir(homedir):
827 if not isdir(homedir):
824 # in case a user stuck some string which does NOT resolve to a
828 # in case a user stuck some string which does NOT resolve to a
825 # valid path, it's as good as if we hadn't foud it
829 # valid path, it's as good as if we hadn't foud it
826 raise KeyError
830 raise KeyError
827 return homedir
831 return homedir
828 except KeyError:
832 except KeyError:
829 if os.name == 'posix':
833 if os.name == 'posix':
830 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
834 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
831 elif os.name == 'nt':
835 elif os.name == 'nt':
832 # For some strange reason, win9x returns 'nt' for os.name.
836 # For some strange reason, win9x returns 'nt' for os.name.
833 try:
837 try:
834 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
838 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
835 if not isdir(homedir):
839 if not isdir(homedir):
836 homedir = os.path.join(env['USERPROFILE'])
840 homedir = os.path.join(env['USERPROFILE'])
837 if not isdir(homedir):
841 if not isdir(homedir):
838 raise HomeDirError
842 raise HomeDirError
839 return homedir
843 return homedir
840 except:
844 except:
841 try:
845 try:
842 # Use the registry to get the 'My Documents' folder.
846 # Use the registry to get the 'My Documents' folder.
843 import _winreg as wreg
847 import _winreg as wreg
844 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
848 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
845 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
849 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
846 homedir = wreg.QueryValueEx(key,'Personal')[0]
850 homedir = wreg.QueryValueEx(key,'Personal')[0]
847 key.Close()
851 key.Close()
848 if not isdir(homedir):
852 if not isdir(homedir):
849 e = ('Invalid "Personal" folder registry key '
853 e = ('Invalid "Personal" folder registry key '
850 'typically "My Documents".\n'
854 'typically "My Documents".\n'
851 'Value: %s\n'
855 'Value: %s\n'
852 'This is not a valid directory on your system.' %
856 'This is not a valid directory on your system.' %
853 homedir)
857 homedir)
854 raise HomeDirError(e)
858 raise HomeDirError(e)
855 return homedir
859 return homedir
856 except HomeDirError:
860 except HomeDirError:
857 raise
861 raise
858 except:
862 except:
859 return 'C:\\'
863 return 'C:\\'
860 elif os.name == 'dos':
864 elif os.name == 'dos':
861 # Desperate, may do absurd things in classic MacOS. May work under DOS.
865 # Desperate, may do absurd things in classic MacOS. May work under DOS.
862 return 'C:\\'
866 return 'C:\\'
863 else:
867 else:
864 raise HomeDirError,'support for your operating system not implemented.'
868 raise HomeDirError,'support for your operating system not implemented.'
865
869
866 #****************************************************************************
870 #****************************************************************************
867 # strings and text
871 # strings and text
868
872
869 class LSString(str):
873 class LSString(str):
870 """String derivative with a special access attributes.
874 """String derivative with a special access attributes.
871
875
872 These are normal strings, but with the special attributes:
876 These are normal strings, but with the special attributes:
873
877
874 .l (or .list) : value as list (split on newlines).
878 .l (or .list) : value as list (split on newlines).
875 .n (or .nlstr): original value (the string itself).
879 .n (or .nlstr): original value (the string itself).
876 .s (or .spstr): value as whitespace-separated string.
880 .s (or .spstr): value as whitespace-separated string.
877
881
878 Any values which require transformations are computed only once and
882 Any values which require transformations are computed only once and
879 cached.
883 cached.
880
884
881 Such strings are very useful to efficiently interact with the shell, which
885 Such strings are very useful to efficiently interact with the shell, which
882 typically only understands whitespace-separated options for commands."""
886 typically only understands whitespace-separated options for commands."""
883
887
884 def get_list(self):
888 def get_list(self):
885 try:
889 try:
886 return self.__list
890 return self.__list
887 except AttributeError:
891 except AttributeError:
888 self.__list = self.split('\n')
892 self.__list = self.split('\n')
889 return self.__list
893 return self.__list
890
894
891 l = list = property(get_list)
895 l = list = property(get_list)
892
896
893 def get_spstr(self):
897 def get_spstr(self):
894 try:
898 try:
895 return self.__spstr
899 return self.__spstr
896 except AttributeError:
900 except AttributeError:
897 self.__spstr = self.replace('\n',' ')
901 self.__spstr = self.replace('\n',' ')
898 return self.__spstr
902 return self.__spstr
899
903
900 s = spstr = property(get_spstr)
904 s = spstr = property(get_spstr)
901
905
902 def get_nlstr(self):
906 def get_nlstr(self):
903 return self
907 return self
904
908
905 n = nlstr = property(get_nlstr)
909 n = nlstr = property(get_nlstr)
906
910
907 def get_paths(self):
911 def get_paths(self):
908 try:
912 try:
909 return self.__paths
913 return self.__paths
910 except AttributeError:
914 except AttributeError:
911 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
915 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
912 return self.__paths
916 return self.__paths
913
917
914 p = paths = property(get_paths)
918 p = paths = property(get_paths)
915
919
916
920
917 #----------------------------------------------------------------------------
921 #----------------------------------------------------------------------------
918 class SList(list):
922 class SList(list):
919 """List derivative with a special access attributes.
923 """List derivative with a special access attributes.
920
924
921 These are normal lists, but with the special attributes:
925 These are normal lists, but with the special attributes:
922
926
923 .l (or .list) : value as list (the list itself).
927 .l (or .list) : value as list (the list itself).
924 .n (or .nlstr): value as a string, joined on newlines.
928 .n (or .nlstr): value as a string, joined on newlines.
925 .s (or .spstr): value as a string, joined on spaces.
929 .s (or .spstr): value as a string, joined on spaces.
926
930
927 Any values which require transformations are computed only once and
931 Any values which require transformations are computed only once and
928 cached."""
932 cached."""
929
933
930 def get_list(self):
934 def get_list(self):
931 return self
935 return self
932
936
933 l = list = property(get_list)
937 l = list = property(get_list)
934
938
935 def get_spstr(self):
939 def get_spstr(self):
936 try:
940 try:
937 return self.__spstr
941 return self.__spstr
938 except AttributeError:
942 except AttributeError:
939 self.__spstr = ' '.join(self)
943 self.__spstr = ' '.join(self)
940 return self.__spstr
944 return self.__spstr
941
945
942 s = spstr = property(get_spstr)
946 s = spstr = property(get_spstr)
943
947
944 def get_nlstr(self):
948 def get_nlstr(self):
945 try:
949 try:
946 return self.__nlstr
950 return self.__nlstr
947 except AttributeError:
951 except AttributeError:
948 self.__nlstr = '\n'.join(self)
952 self.__nlstr = '\n'.join(self)
949 return self.__nlstr
953 return self.__nlstr
950
954
951 n = nlstr = property(get_nlstr)
955 n = nlstr = property(get_nlstr)
952
956
953 def get_paths(self):
957 def get_paths(self):
954 try:
958 try:
955 return self.__paths
959 return self.__paths
956 except AttributeError:
960 except AttributeError:
957 self.__paths = [path(p) for p in self if os.path.exists(p)]
961 self.__paths = [path(p) for p in self if os.path.exists(p)]
958 return self.__paths
962 return self.__paths
959
963
960 p = paths = property(get_paths)
964 p = paths = property(get_paths)
961
965
962 #----------------------------------------------------------------------------
966 #----------------------------------------------------------------------------
963 def esc_quotes(strng):
967 def esc_quotes(strng):
964 """Return the input string with single and double quotes escaped out"""
968 """Return the input string with single and double quotes escaped out"""
965
969
966 return strng.replace('"','\\"').replace("'","\\'")
970 return strng.replace('"','\\"').replace("'","\\'")
967
971
968 #----------------------------------------------------------------------------
972 #----------------------------------------------------------------------------
969 def make_quoted_expr(s):
973 def make_quoted_expr(s):
970 """Return string s in appropriate quotes, using raw string if possible.
974 """Return string s in appropriate quotes, using raw string if possible.
971
975
972 Effectively this turns string: cd \ao\ao\
976 Effectively this turns string: cd \ao\ao\
973 to: r"cd \ao\ao\_"[:-1]
977 to: r"cd \ao\ao\_"[:-1]
974
978
975 Note the use of raw string and padding at the end to allow trailing backslash.
979 Note the use of raw string and padding at the end to allow trailing backslash.
976
980
977 """
981 """
978
982
979 tail = ''
983 tail = ''
980 tailpadding = ''
984 tailpadding = ''
981 raw = ''
985 raw = ''
982 if "\\" in s:
986 if "\\" in s:
983 raw = 'r'
987 raw = 'r'
984 if s.endswith('\\'):
988 if s.endswith('\\'):
985 tail = '[:-1]'
989 tail = '[:-1]'
986 tailpadding = '_'
990 tailpadding = '_'
987 if '"' not in s:
991 if '"' not in s:
988 quote = '"'
992 quote = '"'
989 elif "'" not in s:
993 elif "'" not in s:
990 quote = "'"
994 quote = "'"
991 elif '"""' not in s and not s.endswith('"'):
995 elif '"""' not in s and not s.endswith('"'):
992 quote = '"""'
996 quote = '"""'
993 elif "'''" not in s and not s.endswith("'"):
997 elif "'''" not in s and not s.endswith("'"):
994 quote = "'''"
998 quote = "'''"
995 else:
999 else:
996 # give up, backslash-escaped string will do
1000 # give up, backslash-escaped string will do
997 return '"%s"' % esc_quotes(s)
1001 return '"%s"' % esc_quotes(s)
998 res = itpl("$raw$quote$s$tailpadding$quote$tail")
1002 res = itpl("$raw$quote$s$tailpadding$quote$tail")
999 return res
1003 return res
1000
1004
1001
1005
1002 #----------------------------------------------------------------------------
1006 #----------------------------------------------------------------------------
1003 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
1007 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
1004 """Take multiple lines of input.
1008 """Take multiple lines of input.
1005
1009
1006 A list with each line of input as a separate element is returned when a
1010 A list with each line of input as a separate element is returned when a
1007 termination string is entered (defaults to a single '.'). Input can also
1011 termination string is entered (defaults to a single '.'). Input can also
1008 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1012 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1009
1013
1010 Lines of input which end in \\ are joined into single entries (and a
1014 Lines of input which end in \\ are joined into single entries (and a
1011 secondary continuation prompt is issued as long as the user terminates
1015 secondary continuation prompt is issued as long as the user terminates
1012 lines with \\). This allows entering very long strings which are still
1016 lines with \\). This allows entering very long strings which are still
1013 meant to be treated as single entities.
1017 meant to be treated as single entities.
1014 """
1018 """
1015
1019
1016 try:
1020 try:
1017 if header:
1021 if header:
1018 header += '\n'
1022 header += '\n'
1019 lines = [raw_input(header + ps1)]
1023 lines = [raw_input(header + ps1)]
1020 except EOFError:
1024 except EOFError:
1021 return []
1025 return []
1022 terminate = [terminate_str]
1026 terminate = [terminate_str]
1023 try:
1027 try:
1024 while lines[-1:] != terminate:
1028 while lines[-1:] != terminate:
1025 new_line = raw_input(ps1)
1029 new_line = raw_input(ps1)
1026 while new_line.endswith('\\'):
1030 while new_line.endswith('\\'):
1027 new_line = new_line[:-1] + raw_input(ps2)
1031 new_line = new_line[:-1] + raw_input(ps2)
1028 lines.append(new_line)
1032 lines.append(new_line)
1029
1033
1030 return lines[:-1] # don't return the termination command
1034 return lines[:-1] # don't return the termination command
1031 except EOFError:
1035 except EOFError:
1032 print
1036 print
1033 return lines
1037 return lines
1034
1038
1035 #----------------------------------------------------------------------------
1039 #----------------------------------------------------------------------------
1036 def raw_input_ext(prompt='', ps2='... '):
1040 def raw_input_ext(prompt='', ps2='... '):
1037 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1041 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1038
1042
1039 line = raw_input(prompt)
1043 line = raw_input(prompt)
1040 while line.endswith('\\'):
1044 while line.endswith('\\'):
1041 line = line[:-1] + raw_input(ps2)
1045 line = line[:-1] + raw_input(ps2)
1042 return line
1046 return line
1043
1047
1044 #----------------------------------------------------------------------------
1048 #----------------------------------------------------------------------------
1045 def ask_yes_no(prompt,default=None):
1049 def ask_yes_no(prompt,default=None):
1046 """Asks a question and returns an integer 1/0 (y/n) answer.
1050 """Asks a question and returns an integer 1/0 (y/n) answer.
1047
1051
1048 If default is given (one of 'y','n'), it is used if the user input is
1052 If default is given (one of 'y','n'), it is used if the user input is
1049 empty. Otherwise the question is repeated until an answer is given.
1053 empty. Otherwise the question is repeated until an answer is given.
1050 If EOF occurs 20 times consecutively, the default answer is assumed,
1054 If EOF occurs 20 times consecutively, the default answer is assumed,
1051 or if there is no default, an exception is raised to prevent infinite
1055 or if there is no default, an exception is raised to prevent infinite
1052 loops.
1056 loops.
1053
1057
1054 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1058 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1055
1059
1056 answers = {'y':True,'n':False,'yes':True,'no':False}
1060 answers = {'y':True,'n':False,'yes':True,'no':False}
1057 ans = None
1061 ans = None
1058 eofs, max_eofs = 0, 20
1062 eofs, max_eofs = 0, 20
1059 while ans not in answers.keys():
1063 while ans not in answers.keys():
1060 try:
1064 try:
1061 ans = raw_input(prompt+' ').lower()
1065 ans = raw_input(prompt+' ').lower()
1062 if not ans: # response was an empty string
1066 if not ans: # response was an empty string
1063 ans = default
1067 ans = default
1064 eofs = 0
1068 eofs = 0
1065 except (EOFError,KeyboardInterrupt):
1069 except (EOFError,KeyboardInterrupt):
1066 eofs = eofs + 1
1070 eofs = eofs + 1
1067 if eofs >= max_eofs:
1071 if eofs >= max_eofs:
1068 if default in answers.keys():
1072 if default in answers.keys():
1069 ans = default
1073 ans = default
1070 else:
1074 else:
1071 raise
1075 raise
1072
1076
1073 return answers[ans]
1077 return answers[ans]
1074
1078
1075 #----------------------------------------------------------------------------
1079 #----------------------------------------------------------------------------
1076 def marquee(txt='',width=78,mark='*'):
1080 def marquee(txt='',width=78,mark='*'):
1077 """Return the input string centered in a 'marquee'."""
1081 """Return the input string centered in a 'marquee'."""
1078 if not txt:
1082 if not txt:
1079 return (mark*width)[:width]
1083 return (mark*width)[:width]
1080 nmark = (width-len(txt)-2)/len(mark)/2
1084 nmark = (width-len(txt)-2)/len(mark)/2
1081 if nmark < 0: nmark =0
1085 if nmark < 0: nmark =0
1082 marks = mark*nmark
1086 marks = mark*nmark
1083 return '%s %s %s' % (marks,txt,marks)
1087 return '%s %s %s' % (marks,txt,marks)
1084
1088
1085 #----------------------------------------------------------------------------
1089 #----------------------------------------------------------------------------
1086 class EvalDict:
1090 class EvalDict:
1087 """
1091 """
1088 Emulate a dict which evaluates its contents in the caller's frame.
1092 Emulate a dict which evaluates its contents in the caller's frame.
1089
1093
1090 Usage:
1094 Usage:
1091 >>>number = 19
1095 >>>number = 19
1092 >>>text = "python"
1096 >>>text = "python"
1093 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1097 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1094 """
1098 """
1095
1099
1096 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1100 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1097 # modified (shorter) version of:
1101 # modified (shorter) version of:
1098 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1102 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1099 # Skip Montanaro (skip@pobox.com).
1103 # Skip Montanaro (skip@pobox.com).
1100
1104
1101 def __getitem__(self, name):
1105 def __getitem__(self, name):
1102 frame = sys._getframe(1)
1106 frame = sys._getframe(1)
1103 return eval(name, frame.f_globals, frame.f_locals)
1107 return eval(name, frame.f_globals, frame.f_locals)
1104
1108
1105 EvalString = EvalDict # for backwards compatibility
1109 EvalString = EvalDict # for backwards compatibility
1106 #----------------------------------------------------------------------------
1110 #----------------------------------------------------------------------------
1107 def qw(words,flat=0,sep=None,maxsplit=-1):
1111 def qw(words,flat=0,sep=None,maxsplit=-1):
1108 """Similar to Perl's qw() operator, but with some more options.
1112 """Similar to Perl's qw() operator, but with some more options.
1109
1113
1110 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1114 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1111
1115
1112 words can also be a list itself, and with flat=1, the output will be
1116 words can also be a list itself, and with flat=1, the output will be
1113 recursively flattened. Examples:
1117 recursively flattened. Examples:
1114
1118
1115 >>> qw('1 2')
1119 >>> qw('1 2')
1116 ['1', '2']
1120 ['1', '2']
1117 >>> qw(['a b','1 2',['m n','p q']])
1121 >>> qw(['a b','1 2',['m n','p q']])
1118 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1122 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1119 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1123 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1120 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1124 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1121
1125
1122 if type(words) in StringTypes:
1126 if type(words) in StringTypes:
1123 return [word.strip() for word in words.split(sep,maxsplit)
1127 return [word.strip() for word in words.split(sep,maxsplit)
1124 if word and not word.isspace() ]
1128 if word and not word.isspace() ]
1125 if flat:
1129 if flat:
1126 return flatten(map(qw,words,[1]*len(words)))
1130 return flatten(map(qw,words,[1]*len(words)))
1127 return map(qw,words)
1131 return map(qw,words)
1128
1132
1129 #----------------------------------------------------------------------------
1133 #----------------------------------------------------------------------------
1130 def qwflat(words,sep=None,maxsplit=-1):
1134 def qwflat(words,sep=None,maxsplit=-1):
1131 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1135 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1132 return qw(words,1,sep,maxsplit)
1136 return qw(words,1,sep,maxsplit)
1133
1137
1134 #----------------------------------------------------------------------------
1138 #----------------------------------------------------------------------------
1135 def qw_lol(indata):
1139 def qw_lol(indata):
1136 """qw_lol('a b') -> [['a','b']],
1140 """qw_lol('a b') -> [['a','b']],
1137 otherwise it's just a call to qw().
1141 otherwise it's just a call to qw().
1138
1142
1139 We need this to make sure the modules_some keys *always* end up as a
1143 We need this to make sure the modules_some keys *always* end up as a
1140 list of lists."""
1144 list of lists."""
1141
1145
1142 if type(indata) in StringTypes:
1146 if type(indata) in StringTypes:
1143 return [qw(indata)]
1147 return [qw(indata)]
1144 else:
1148 else:
1145 return qw(indata)
1149 return qw(indata)
1146
1150
1147 #-----------------------------------------------------------------------------
1151 #-----------------------------------------------------------------------------
1148 def list_strings(arg):
1152 def list_strings(arg):
1149 """Always return a list of strings, given a string or list of strings
1153 """Always return a list of strings, given a string or list of strings
1150 as input."""
1154 as input."""
1151
1155
1152 if type(arg) in StringTypes: return [arg]
1156 if type(arg) in StringTypes: return [arg]
1153 else: return arg
1157 else: return arg
1154
1158
1155 #----------------------------------------------------------------------------
1159 #----------------------------------------------------------------------------
1156 def grep(pat,list,case=1):
1160 def grep(pat,list,case=1):
1157 """Simple minded grep-like function.
1161 """Simple minded grep-like function.
1158 grep(pat,list) returns occurrences of pat in list, None on failure.
1162 grep(pat,list) returns occurrences of pat in list, None on failure.
1159
1163
1160 It only does simple string matching, with no support for regexps. Use the
1164 It only does simple string matching, with no support for regexps. Use the
1161 option case=0 for case-insensitive matching."""
1165 option case=0 for case-insensitive matching."""
1162
1166
1163 # This is pretty crude. At least it should implement copying only references
1167 # This is pretty crude. At least it should implement copying only references
1164 # to the original data in case it's big. Now it copies the data for output.
1168 # to the original data in case it's big. Now it copies the data for output.
1165 out=[]
1169 out=[]
1166 if case:
1170 if case:
1167 for term in list:
1171 for term in list:
1168 if term.find(pat)>-1: out.append(term)
1172 if term.find(pat)>-1: out.append(term)
1169 else:
1173 else:
1170 lpat=pat.lower()
1174 lpat=pat.lower()
1171 for term in list:
1175 for term in list:
1172 if term.lower().find(lpat)>-1: out.append(term)
1176 if term.lower().find(lpat)>-1: out.append(term)
1173
1177
1174 if len(out): return out
1178 if len(out): return out
1175 else: return None
1179 else: return None
1176
1180
1177 #----------------------------------------------------------------------------
1181 #----------------------------------------------------------------------------
1178 def dgrep(pat,*opts):
1182 def dgrep(pat,*opts):
1179 """Return grep() on dir()+dir(__builtins__).
1183 """Return grep() on dir()+dir(__builtins__).
1180
1184
1181 A very common use of grep() when working interactively."""
1185 A very common use of grep() when working interactively."""
1182
1186
1183 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1187 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1184
1188
1185 #----------------------------------------------------------------------------
1189 #----------------------------------------------------------------------------
1186 def idgrep(pat):
1190 def idgrep(pat):
1187 """Case-insensitive dgrep()"""
1191 """Case-insensitive dgrep()"""
1188
1192
1189 return dgrep(pat,0)
1193 return dgrep(pat,0)
1190
1194
1191 #----------------------------------------------------------------------------
1195 #----------------------------------------------------------------------------
1192 def igrep(pat,list):
1196 def igrep(pat,list):
1193 """Synonym for case-insensitive grep."""
1197 """Synonym for case-insensitive grep."""
1194
1198
1195 return grep(pat,list,case=0)
1199 return grep(pat,list,case=0)
1196
1200
1197 #----------------------------------------------------------------------------
1201 #----------------------------------------------------------------------------
1198 def indent(str,nspaces=4,ntabs=0):
1202 def indent(str,nspaces=4,ntabs=0):
1199 """Indent a string a given number of spaces or tabstops.
1203 """Indent a string a given number of spaces or tabstops.
1200
1204
1201 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1205 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1202 """
1206 """
1203 if str is None:
1207 if str is None:
1204 return
1208 return
1205 ind = '\t'*ntabs+' '*nspaces
1209 ind = '\t'*ntabs+' '*nspaces
1206 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1210 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1207 if outstr.endswith(os.linesep+ind):
1211 if outstr.endswith(os.linesep+ind):
1208 return outstr[:-len(ind)]
1212 return outstr[:-len(ind)]
1209 else:
1213 else:
1210 return outstr
1214 return outstr
1211
1215
1212 #-----------------------------------------------------------------------------
1216 #-----------------------------------------------------------------------------
1213 def native_line_ends(filename,backup=1):
1217 def native_line_ends(filename,backup=1):
1214 """Convert (in-place) a file to line-ends native to the current OS.
1218 """Convert (in-place) a file to line-ends native to the current OS.
1215
1219
1216 If the optional backup argument is given as false, no backup of the
1220 If the optional backup argument is given as false, no backup of the
1217 original file is left. """
1221 original file is left. """
1218
1222
1219 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1223 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1220
1224
1221 bak_filename = filename + backup_suffixes[os.name]
1225 bak_filename = filename + backup_suffixes[os.name]
1222
1226
1223 original = open(filename).read()
1227 original = open(filename).read()
1224 shutil.copy2(filename,bak_filename)
1228 shutil.copy2(filename,bak_filename)
1225 try:
1229 try:
1226 new = open(filename,'wb')
1230 new = open(filename,'wb')
1227 new.write(os.linesep.join(original.splitlines()))
1231 new.write(os.linesep.join(original.splitlines()))
1228 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1232 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1229 new.close()
1233 new.close()
1230 except:
1234 except:
1231 os.rename(bak_filename,filename)
1235 os.rename(bak_filename,filename)
1232 if not backup:
1236 if not backup:
1233 try:
1237 try:
1234 os.remove(bak_filename)
1238 os.remove(bak_filename)
1235 except:
1239 except:
1236 pass
1240 pass
1237
1241
1238 #----------------------------------------------------------------------------
1242 #----------------------------------------------------------------------------
1239 def get_pager_cmd(pager_cmd = None):
1243 def get_pager_cmd(pager_cmd = None):
1240 """Return a pager command.
1244 """Return a pager command.
1241
1245
1242 Makes some attempts at finding an OS-correct one."""
1246 Makes some attempts at finding an OS-correct one."""
1243
1247
1244 if os.name == 'posix':
1248 if os.name == 'posix':
1245 default_pager_cmd = 'less -r' # -r for color control sequences
1249 default_pager_cmd = 'less -r' # -r for color control sequences
1246 elif os.name in ['nt','dos']:
1250 elif os.name in ['nt','dos']:
1247 default_pager_cmd = 'type'
1251 default_pager_cmd = 'type'
1248
1252
1249 if pager_cmd is None:
1253 if pager_cmd is None:
1250 try:
1254 try:
1251 pager_cmd = os.environ['PAGER']
1255 pager_cmd = os.environ['PAGER']
1252 except:
1256 except:
1253 pager_cmd = default_pager_cmd
1257 pager_cmd = default_pager_cmd
1254 return pager_cmd
1258 return pager_cmd
1255
1259
1256 #-----------------------------------------------------------------------------
1260 #-----------------------------------------------------------------------------
1257 def get_pager_start(pager,start):
1261 def get_pager_start(pager,start):
1258 """Return the string for paging files with an offset.
1262 """Return the string for paging files with an offset.
1259
1263
1260 This is the '+N' argument which less and more (under Unix) accept.
1264 This is the '+N' argument which less and more (under Unix) accept.
1261 """
1265 """
1262
1266
1263 if pager in ['less','more']:
1267 if pager in ['less','more']:
1264 if start:
1268 if start:
1265 start_string = '+' + str(start)
1269 start_string = '+' + str(start)
1266 else:
1270 else:
1267 start_string = ''
1271 start_string = ''
1268 else:
1272 else:
1269 start_string = ''
1273 start_string = ''
1270 return start_string
1274 return start_string
1271
1275
1272 #----------------------------------------------------------------------------
1276 #----------------------------------------------------------------------------
1273 if os.name == "nt":
1277 if os.name == "nt":
1274 import msvcrt
1278 import msvcrt
1275 def page_more():
1279 def page_more():
1276 """ Smart pausing between pages
1280 """ Smart pausing between pages
1277
1281
1278 @return: True if need print more lines, False if quit
1282 @return: True if need print more lines, False if quit
1279 """
1283 """
1280 Term.cout.write('---Return to continue, q to quit--- ')
1284 Term.cout.write('---Return to continue, q to quit--- ')
1281 ans = msvcrt.getch()
1285 ans = msvcrt.getch()
1282 if ans in ("q", "Q"):
1286 if ans in ("q", "Q"):
1283 result = False
1287 result = False
1284 else:
1288 else:
1285 result = True
1289 result = True
1286 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1290 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1287 return result
1291 return result
1288 else:
1292 else:
1289 def page_more():
1293 def page_more():
1290 ans = raw_input('---Return to continue, q to quit--- ')
1294 ans = raw_input('---Return to continue, q to quit--- ')
1291 if ans.lower().startswith('q'):
1295 if ans.lower().startswith('q'):
1292 return False
1296 return False
1293 else:
1297 else:
1294 return True
1298 return True
1295
1299
1296 esc_re = re.compile(r"(\x1b[^m]+m)")
1300 esc_re = re.compile(r"(\x1b[^m]+m)")
1297
1301
1298 def page_dumb(strng,start=0,screen_lines=25):
1302 def page_dumb(strng,start=0,screen_lines=25):
1299 """Very dumb 'pager' in Python, for when nothing else works.
1303 """Very dumb 'pager' in Python, for when nothing else works.
1300
1304
1301 Only moves forward, same interface as page(), except for pager_cmd and
1305 Only moves forward, same interface as page(), except for pager_cmd and
1302 mode."""
1306 mode."""
1303
1307
1304 out_ln = strng.splitlines()[start:]
1308 out_ln = strng.splitlines()[start:]
1305 screens = chop(out_ln,screen_lines-1)
1309 screens = chop(out_ln,screen_lines-1)
1306 if len(screens) == 1:
1310 if len(screens) == 1:
1307 print >>Term.cout, os.linesep.join(screens[0])
1311 print >>Term.cout, os.linesep.join(screens[0])
1308 else:
1312 else:
1309 last_escape = ""
1313 last_escape = ""
1310 for scr in screens[0:-1]:
1314 for scr in screens[0:-1]:
1311 hunk = os.linesep.join(scr)
1315 hunk = os.linesep.join(scr)
1312 print >>Term.cout, last_escape + hunk
1316 print >>Term.cout, last_escape + hunk
1313 if not page_more():
1317 if not page_more():
1314 return
1318 return
1315 esc_list = esc_re.findall(hunk)
1319 esc_list = esc_re.findall(hunk)
1316 if len(esc_list) > 0:
1320 if len(esc_list) > 0:
1317 last_escape = esc_list[-1]
1321 last_escape = esc_list[-1]
1318 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1322 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1319
1323
1320 #----------------------------------------------------------------------------
1324 #----------------------------------------------------------------------------
1321 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1325 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1322 """Print a string, piping through a pager after a certain length.
1326 """Print a string, piping through a pager after a certain length.
1323
1327
1324 The screen_lines parameter specifies the number of *usable* lines of your
1328 The screen_lines parameter specifies the number of *usable* lines of your
1325 terminal screen (total lines minus lines you need to reserve to show other
1329 terminal screen (total lines minus lines you need to reserve to show other
1326 information).
1330 information).
1327
1331
1328 If you set screen_lines to a number <=0, page() will try to auto-determine
1332 If you set screen_lines to a number <=0, page() will try to auto-determine
1329 your screen size and will only use up to (screen_size+screen_lines) for
1333 your screen size and will only use up to (screen_size+screen_lines) for
1330 printing, paging after that. That is, if you want auto-detection but need
1334 printing, paging after that. That is, if you want auto-detection but need
1331 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1335 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1332 auto-detection without any lines reserved simply use screen_lines = 0.
1336 auto-detection without any lines reserved simply use screen_lines = 0.
1333
1337
1334 If a string won't fit in the allowed lines, it is sent through the
1338 If a string won't fit in the allowed lines, it is sent through the
1335 specified pager command. If none given, look for PAGER in the environment,
1339 specified pager command. If none given, look for PAGER in the environment,
1336 and ultimately default to less.
1340 and ultimately default to less.
1337
1341
1338 If no system pager works, the string is sent through a 'dumb pager'
1342 If no system pager works, the string is sent through a 'dumb pager'
1339 written in python, very simplistic.
1343 written in python, very simplistic.
1340 """
1344 """
1341
1345
1342 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1346 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1343 TERM = os.environ.get('TERM','dumb')
1347 TERM = os.environ.get('TERM','dumb')
1344 if TERM in ['dumb','emacs'] and os.name != 'nt':
1348 if TERM in ['dumb','emacs'] and os.name != 'nt':
1345 print strng
1349 print strng
1346 return
1350 return
1347 # chop off the topmost part of the string we don't want to see
1351 # chop off the topmost part of the string we don't want to see
1348 str_lines = strng.split(os.linesep)[start:]
1352 str_lines = strng.split(os.linesep)[start:]
1349 str_toprint = os.linesep.join(str_lines)
1353 str_toprint = os.linesep.join(str_lines)
1350 num_newlines = len(str_lines)
1354 num_newlines = len(str_lines)
1351 len_str = len(str_toprint)
1355 len_str = len(str_toprint)
1352
1356
1353 # Dumb heuristics to guesstimate number of on-screen lines the string
1357 # Dumb heuristics to guesstimate number of on-screen lines the string
1354 # takes. Very basic, but good enough for docstrings in reasonable
1358 # takes. Very basic, but good enough for docstrings in reasonable
1355 # terminals. If someone later feels like refining it, it's not hard.
1359 # terminals. If someone later feels like refining it, it's not hard.
1356 numlines = max(num_newlines,int(len_str/80)+1)
1360 numlines = max(num_newlines,int(len_str/80)+1)
1357
1361
1358 if os.name == "nt":
1362 if os.name == "nt":
1359 screen_lines_def = get_console_size(defaulty=25)[1]
1363 screen_lines_def = get_console_size(defaulty=25)[1]
1360 else:
1364 else:
1361 screen_lines_def = 25 # default value if we can't auto-determine
1365 screen_lines_def = 25 # default value if we can't auto-determine
1362
1366
1363 # auto-determine screen size
1367 # auto-determine screen size
1364 if screen_lines <= 0:
1368 if screen_lines <= 0:
1365 if TERM=='xterm':
1369 if TERM=='xterm':
1366 try:
1370 try:
1367 import curses
1371 import curses
1368 if hasattr(curses,'initscr'):
1372 if hasattr(curses,'initscr'):
1369 use_curses = 1
1373 use_curses = 1
1370 else:
1374 else:
1371 use_curses = 0
1375 use_curses = 0
1372 except ImportError:
1376 except ImportError:
1373 use_curses = 0
1377 use_curses = 0
1374 else:
1378 else:
1375 # curses causes problems on many terminals other than xterm.
1379 # curses causes problems on many terminals other than xterm.
1376 use_curses = 0
1380 use_curses = 0
1377 if use_curses:
1381 if use_curses:
1378 scr = curses.initscr()
1382 scr = curses.initscr()
1379 screen_lines_real,screen_cols = scr.getmaxyx()
1383 screen_lines_real,screen_cols = scr.getmaxyx()
1380 curses.endwin()
1384 curses.endwin()
1381 screen_lines += screen_lines_real
1385 screen_lines += screen_lines_real
1382 #print '***Screen size:',screen_lines_real,'lines x',\
1386 #print '***Screen size:',screen_lines_real,'lines x',\
1383 #screen_cols,'columns.' # dbg
1387 #screen_cols,'columns.' # dbg
1384 else:
1388 else:
1385 screen_lines += screen_lines_def
1389 screen_lines += screen_lines_def
1386
1390
1387 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1391 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1388 if numlines <= screen_lines :
1392 if numlines <= screen_lines :
1389 #print '*** normal print' # dbg
1393 #print '*** normal print' # dbg
1390 print >>Term.cout, str_toprint
1394 print >>Term.cout, str_toprint
1391 else:
1395 else:
1392 # Try to open pager and default to internal one if that fails.
1396 # Try to open pager and default to internal one if that fails.
1393 # All failure modes are tagged as 'retval=1', to match the return
1397 # All failure modes are tagged as 'retval=1', to match the return
1394 # value of a failed system command. If any intermediate attempt
1398 # value of a failed system command. If any intermediate attempt
1395 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1399 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1396 pager_cmd = get_pager_cmd(pager_cmd)
1400 pager_cmd = get_pager_cmd(pager_cmd)
1397 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1401 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1398 if os.name == 'nt':
1402 if os.name == 'nt':
1399 if pager_cmd.startswith('type'):
1403 if pager_cmd.startswith('type'):
1400 # The default WinXP 'type' command is failing on complex strings.
1404 # The default WinXP 'type' command is failing on complex strings.
1401 retval = 1
1405 retval = 1
1402 else:
1406 else:
1403 tmpname = tempfile.mktemp('.txt')
1407 tmpname = tempfile.mktemp('.txt')
1404 tmpfile = file(tmpname,'wt')
1408 tmpfile = file(tmpname,'wt')
1405 tmpfile.write(strng)
1409 tmpfile.write(strng)
1406 tmpfile.close()
1410 tmpfile.close()
1407 cmd = "%s < %s" % (pager_cmd,tmpname)
1411 cmd = "%s < %s" % (pager_cmd,tmpname)
1408 if os.system(cmd):
1412 if os.system(cmd):
1409 retval = 1
1413 retval = 1
1410 else:
1414 else:
1411 retval = None
1415 retval = None
1412 os.remove(tmpname)
1416 os.remove(tmpname)
1413 else:
1417 else:
1414 try:
1418 try:
1415 retval = None
1419 retval = None
1416 # if I use popen4, things hang. No idea why.
1420 # if I use popen4, things hang. No idea why.
1417 #pager,shell_out = os.popen4(pager_cmd)
1421 #pager,shell_out = os.popen4(pager_cmd)
1418 pager = os.popen(pager_cmd,'w')
1422 pager = os.popen(pager_cmd,'w')
1419 pager.write(strng)
1423 pager.write(strng)
1420 pager.close()
1424 pager.close()
1421 retval = pager.close() # success returns None
1425 retval = pager.close() # success returns None
1422 except IOError,msg: # broken pipe when user quits
1426 except IOError,msg: # broken pipe when user quits
1423 if msg.args == (32,'Broken pipe'):
1427 if msg.args == (32,'Broken pipe'):
1424 retval = None
1428 retval = None
1425 else:
1429 else:
1426 retval = 1
1430 retval = 1
1427 except OSError:
1431 except OSError:
1428 # Other strange problems, sometimes seen in Win2k/cygwin
1432 # Other strange problems, sometimes seen in Win2k/cygwin
1429 retval = 1
1433 retval = 1
1430 if retval is not None:
1434 if retval is not None:
1431 page_dumb(strng,screen_lines=screen_lines)
1435 page_dumb(strng,screen_lines=screen_lines)
1432
1436
1433 #----------------------------------------------------------------------------
1437 #----------------------------------------------------------------------------
1434 def page_file(fname,start = 0, pager_cmd = None):
1438 def page_file(fname,start = 0, pager_cmd = None):
1435 """Page a file, using an optional pager command and starting line.
1439 """Page a file, using an optional pager command and starting line.
1436 """
1440 """
1437
1441
1438 pager_cmd = get_pager_cmd(pager_cmd)
1442 pager_cmd = get_pager_cmd(pager_cmd)
1439 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1443 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1440
1444
1441 try:
1445 try:
1442 if os.environ['TERM'] in ['emacs','dumb']:
1446 if os.environ['TERM'] in ['emacs','dumb']:
1443 raise EnvironmentError
1447 raise EnvironmentError
1444 xsys(pager_cmd + ' ' + fname)
1448 xsys(pager_cmd + ' ' + fname)
1445 except:
1449 except:
1446 try:
1450 try:
1447 if start > 0:
1451 if start > 0:
1448 start -= 1
1452 start -= 1
1449 page(open(fname).read(),start)
1453 page(open(fname).read(),start)
1450 except:
1454 except:
1451 print 'Unable to show file',`fname`
1455 print 'Unable to show file',`fname`
1452
1456
1453 #----------------------------------------------------------------------------
1457 #----------------------------------------------------------------------------
1454 def snip_print(str,width = 75,print_full = 0,header = ''):
1458 def snip_print(str,width = 75,print_full = 0,header = ''):
1455 """Print a string snipping the midsection to fit in width.
1459 """Print a string snipping the midsection to fit in width.
1456
1460
1457 print_full: mode control:
1461 print_full: mode control:
1458 - 0: only snip long strings
1462 - 0: only snip long strings
1459 - 1: send to page() directly.
1463 - 1: send to page() directly.
1460 - 2: snip long strings and ask for full length viewing with page()
1464 - 2: snip long strings and ask for full length viewing with page()
1461 Return 1 if snipping was necessary, 0 otherwise."""
1465 Return 1 if snipping was necessary, 0 otherwise."""
1462
1466
1463 if print_full == 1:
1467 if print_full == 1:
1464 page(header+str)
1468 page(header+str)
1465 return 0
1469 return 0
1466
1470
1467 print header,
1471 print header,
1468 if len(str) < width:
1472 if len(str) < width:
1469 print str
1473 print str
1470 snip = 0
1474 snip = 0
1471 else:
1475 else:
1472 whalf = int((width -5)/2)
1476 whalf = int((width -5)/2)
1473 print str[:whalf] + ' <...> ' + str[-whalf:]
1477 print str[:whalf] + ' <...> ' + str[-whalf:]
1474 snip = 1
1478 snip = 1
1475 if snip and print_full == 2:
1479 if snip and print_full == 2:
1476 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1480 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1477 page(str)
1481 page(str)
1478 return snip
1482 return snip
1479
1483
1480 #****************************************************************************
1484 #****************************************************************************
1481 # lists, dicts and structures
1485 # lists, dicts and structures
1482
1486
1483 def belong(candidates,checklist):
1487 def belong(candidates,checklist):
1484 """Check whether a list of items appear in a given list of options.
1488 """Check whether a list of items appear in a given list of options.
1485
1489
1486 Returns a list of 1 and 0, one for each candidate given."""
1490 Returns a list of 1 and 0, one for each candidate given."""
1487
1491
1488 return [x in checklist for x in candidates]
1492 return [x in checklist for x in candidates]
1489
1493
1490 #----------------------------------------------------------------------------
1494 #----------------------------------------------------------------------------
1491 def uniq_stable(elems):
1495 def uniq_stable(elems):
1492 """uniq_stable(elems) -> list
1496 """uniq_stable(elems) -> list
1493
1497
1494 Return from an iterable, a list of all the unique elements in the input,
1498 Return from an iterable, a list of all the unique elements in the input,
1495 but maintaining the order in which they first appear.
1499 but maintaining the order in which they first appear.
1496
1500
1497 A naive solution to this problem which just makes a dictionary with the
1501 A naive solution to this problem which just makes a dictionary with the
1498 elements as keys fails to respect the stability condition, since
1502 elements as keys fails to respect the stability condition, since
1499 dictionaries are unsorted by nature.
1503 dictionaries are unsorted by nature.
1500
1504
1501 Note: All elements in the input must be valid dictionary keys for this
1505 Note: All elements in the input must be valid dictionary keys for this
1502 routine to work, as it internally uses a dictionary for efficiency
1506 routine to work, as it internally uses a dictionary for efficiency
1503 reasons."""
1507 reasons."""
1504
1508
1505 unique = []
1509 unique = []
1506 unique_dict = {}
1510 unique_dict = {}
1507 for nn in elems:
1511 for nn in elems:
1508 if nn not in unique_dict:
1512 if nn not in unique_dict:
1509 unique.append(nn)
1513 unique.append(nn)
1510 unique_dict[nn] = None
1514 unique_dict[nn] = None
1511 return unique
1515 return unique
1512
1516
1513 #----------------------------------------------------------------------------
1517 #----------------------------------------------------------------------------
1514 class NLprinter:
1518 class NLprinter:
1515 """Print an arbitrarily nested list, indicating index numbers.
1519 """Print an arbitrarily nested list, indicating index numbers.
1516
1520
1517 An instance of this class called nlprint is available and callable as a
1521 An instance of this class called nlprint is available and callable as a
1518 function.
1522 function.
1519
1523
1520 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1524 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1521 and using 'sep' to separate the index from the value. """
1525 and using 'sep' to separate the index from the value. """
1522
1526
1523 def __init__(self):
1527 def __init__(self):
1524 self.depth = 0
1528 self.depth = 0
1525
1529
1526 def __call__(self,lst,pos='',**kw):
1530 def __call__(self,lst,pos='',**kw):
1527 """Prints the nested list numbering levels."""
1531 """Prints the nested list numbering levels."""
1528 kw.setdefault('indent',' ')
1532 kw.setdefault('indent',' ')
1529 kw.setdefault('sep',': ')
1533 kw.setdefault('sep',': ')
1530 kw.setdefault('start',0)
1534 kw.setdefault('start',0)
1531 kw.setdefault('stop',len(lst))
1535 kw.setdefault('stop',len(lst))
1532 # we need to remove start and stop from kw so they don't propagate
1536 # we need to remove start and stop from kw so they don't propagate
1533 # into a recursive call for a nested list.
1537 # into a recursive call for a nested list.
1534 start = kw['start']; del kw['start']
1538 start = kw['start']; del kw['start']
1535 stop = kw['stop']; del kw['stop']
1539 stop = kw['stop']; del kw['stop']
1536 if self.depth == 0 and 'header' in kw.keys():
1540 if self.depth == 0 and 'header' in kw.keys():
1537 print kw['header']
1541 print kw['header']
1538
1542
1539 for idx in range(start,stop):
1543 for idx in range(start,stop):
1540 elem = lst[idx]
1544 elem = lst[idx]
1541 if type(elem)==type([]):
1545 if type(elem)==type([]):
1542 self.depth += 1
1546 self.depth += 1
1543 self.__call__(elem,itpl('$pos$idx,'),**kw)
1547 self.__call__(elem,itpl('$pos$idx,'),**kw)
1544 self.depth -= 1
1548 self.depth -= 1
1545 else:
1549 else:
1546 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1550 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1547
1551
1548 nlprint = NLprinter()
1552 nlprint = NLprinter()
1549 #----------------------------------------------------------------------------
1553 #----------------------------------------------------------------------------
1550 def all_belong(candidates,checklist):
1554 def all_belong(candidates,checklist):
1551 """Check whether a list of items ALL appear in a given list of options.
1555 """Check whether a list of items ALL appear in a given list of options.
1552
1556
1553 Returns a single 1 or 0 value."""
1557 Returns a single 1 or 0 value."""
1554
1558
1555 return 1-(0 in [x in checklist for x in candidates])
1559 return 1-(0 in [x in checklist for x in candidates])
1556
1560
1557 #----------------------------------------------------------------------------
1561 #----------------------------------------------------------------------------
1558 def sort_compare(lst1,lst2,inplace = 1):
1562 def sort_compare(lst1,lst2,inplace = 1):
1559 """Sort and compare two lists.
1563 """Sort and compare two lists.
1560
1564
1561 By default it does it in place, thus modifying the lists. Use inplace = 0
1565 By default it does it in place, thus modifying the lists. Use inplace = 0
1562 to avoid that (at the cost of temporary copy creation)."""
1566 to avoid that (at the cost of temporary copy creation)."""
1563 if not inplace:
1567 if not inplace:
1564 lst1 = lst1[:]
1568 lst1 = lst1[:]
1565 lst2 = lst2[:]
1569 lst2 = lst2[:]
1566 lst1.sort(); lst2.sort()
1570 lst1.sort(); lst2.sort()
1567 return lst1 == lst2
1571 return lst1 == lst2
1568
1572
1569 #----------------------------------------------------------------------------
1573 #----------------------------------------------------------------------------
1570 def mkdict(**kwargs):
1574 def mkdict(**kwargs):
1571 """Return a dict from a keyword list.
1575 """Return a dict from a keyword list.
1572
1576
1573 It's just syntactic sugar for making ditcionary creation more convenient:
1577 It's just syntactic sugar for making ditcionary creation more convenient:
1574 # the standard way
1578 # the standard way
1575 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1579 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1576 # a cleaner way
1580 # a cleaner way
1577 >>>data = dict(red=1, green=2, blue=3)
1581 >>>data = dict(red=1, green=2, blue=3)
1578
1582
1579 If you need more than this, look at the Struct() class."""
1583 If you need more than this, look at the Struct() class."""
1580
1584
1581 return kwargs
1585 return kwargs
1582
1586
1583 #----------------------------------------------------------------------------
1587 #----------------------------------------------------------------------------
1584 def list2dict(lst):
1588 def list2dict(lst):
1585 """Takes a list of (key,value) pairs and turns it into a dict."""
1589 """Takes a list of (key,value) pairs and turns it into a dict."""
1586
1590
1587 dic = {}
1591 dic = {}
1588 for k,v in lst: dic[k] = v
1592 for k,v in lst: dic[k] = v
1589 return dic
1593 return dic
1590
1594
1591 #----------------------------------------------------------------------------
1595 #----------------------------------------------------------------------------
1592 def list2dict2(lst,default=''):
1596 def list2dict2(lst,default=''):
1593 """Takes a list and turns it into a dict.
1597 """Takes a list and turns it into a dict.
1594 Much slower than list2dict, but more versatile. This version can take
1598 Much slower than list2dict, but more versatile. This version can take
1595 lists with sublists of arbitrary length (including sclars)."""
1599 lists with sublists of arbitrary length (including sclars)."""
1596
1600
1597 dic = {}
1601 dic = {}
1598 for elem in lst:
1602 for elem in lst:
1599 if type(elem) in (types.ListType,types.TupleType):
1603 if type(elem) in (types.ListType,types.TupleType):
1600 size = len(elem)
1604 size = len(elem)
1601 if size == 0:
1605 if size == 0:
1602 pass
1606 pass
1603 elif size == 1:
1607 elif size == 1:
1604 dic[elem] = default
1608 dic[elem] = default
1605 else:
1609 else:
1606 k,v = elem[0], elem[1:]
1610 k,v = elem[0], elem[1:]
1607 if len(v) == 1: v = v[0]
1611 if len(v) == 1: v = v[0]
1608 dic[k] = v
1612 dic[k] = v
1609 else:
1613 else:
1610 dic[elem] = default
1614 dic[elem] = default
1611 return dic
1615 return dic
1612
1616
1613 #----------------------------------------------------------------------------
1617 #----------------------------------------------------------------------------
1614 def flatten(seq):
1618 def flatten(seq):
1615 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1619 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1616
1620
1617 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1621 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1618
1622
1619 # if the x=0 isn't made, a *global* variable x is left over after calling
1623 # if the x=0 isn't made, a *global* variable x is left over after calling
1620 # this function, with the value of the last element in the return
1624 # this function, with the value of the last element in the return
1621 # list. This does seem like a bug big time to me.
1625 # list. This does seem like a bug big time to me.
1622
1626
1623 # the problem is fixed with the x=0, which seems to force the creation of
1627 # the problem is fixed with the x=0, which seems to force the creation of
1624 # a local name
1628 # a local name
1625
1629
1626 x = 0
1630 x = 0
1627 return [x for subseq in seq for x in subseq]
1631 return [x for subseq in seq for x in subseq]
1628
1632
1629 #----------------------------------------------------------------------------
1633 #----------------------------------------------------------------------------
1630 def get_slice(seq,start=0,stop=None,step=1):
1634 def get_slice(seq,start=0,stop=None,step=1):
1631 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1635 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1632 if stop == None:
1636 if stop == None:
1633 stop = len(seq)
1637 stop = len(seq)
1634 item = lambda i: seq[i]
1638 item = lambda i: seq[i]
1635 return map(item,xrange(start,stop,step))
1639 return map(item,xrange(start,stop,step))
1636
1640
1637 #----------------------------------------------------------------------------
1641 #----------------------------------------------------------------------------
1638 def chop(seq,size):
1642 def chop(seq,size):
1639 """Chop a sequence into chunks of the given size."""
1643 """Chop a sequence into chunks of the given size."""
1640 chunk = lambda i: seq[i:i+size]
1644 chunk = lambda i: seq[i:i+size]
1641 return map(chunk,xrange(0,len(seq),size))
1645 return map(chunk,xrange(0,len(seq),size))
1642
1646
1643 #----------------------------------------------------------------------------
1647 #----------------------------------------------------------------------------
1644 def with(object, **args):
1648 def with(object, **args):
1645 """Set multiple attributes for an object, similar to Pascal's with.
1649 """Set multiple attributes for an object, similar to Pascal's with.
1646
1650
1647 Example:
1651 Example:
1648 with(jim,
1652 with(jim,
1649 born = 1960,
1653 born = 1960,
1650 haircolour = 'Brown',
1654 haircolour = 'Brown',
1651 eyecolour = 'Green')
1655 eyecolour = 'Green')
1652
1656
1653 Credit: Greg Ewing, in
1657 Credit: Greg Ewing, in
1654 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1658 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1655
1659
1656 object.__dict__.update(args)
1660 object.__dict__.update(args)
1657
1661
1658 #----------------------------------------------------------------------------
1662 #----------------------------------------------------------------------------
1659 def setattr_list(obj,alist,nspace = None):
1663 def setattr_list(obj,alist,nspace = None):
1660 """Set a list of attributes for an object taken from a namespace.
1664 """Set a list of attributes for an object taken from a namespace.
1661
1665
1662 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1666 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1663 alist with their values taken from nspace, which must be a dict (something
1667 alist with their values taken from nspace, which must be a dict (something
1664 like locals() will often do) If nspace isn't given, locals() of the
1668 like locals() will often do) If nspace isn't given, locals() of the
1665 *caller* is used, so in most cases you can omit it.
1669 *caller* is used, so in most cases you can omit it.
1666
1670
1667 Note that alist can be given as a string, which will be automatically
1671 Note that alist can be given as a string, which will be automatically
1668 split into a list on whitespace. If given as a list, it must be a list of
1672 split into a list on whitespace. If given as a list, it must be a list of
1669 *strings* (the variable names themselves), not of variables."""
1673 *strings* (the variable names themselves), not of variables."""
1670
1674
1671 # this grabs the local variables from the *previous* call frame -- that is
1675 # this grabs the local variables from the *previous* call frame -- that is
1672 # the locals from the function that called setattr_list().
1676 # the locals from the function that called setattr_list().
1673 # - snipped from weave.inline()
1677 # - snipped from weave.inline()
1674 if nspace is None:
1678 if nspace is None:
1675 call_frame = sys._getframe().f_back
1679 call_frame = sys._getframe().f_back
1676 nspace = call_frame.f_locals
1680 nspace = call_frame.f_locals
1677
1681
1678 if type(alist) in StringTypes:
1682 if type(alist) in StringTypes:
1679 alist = alist.split()
1683 alist = alist.split()
1680 for attr in alist:
1684 for attr in alist:
1681 val = eval(attr,nspace)
1685 val = eval(attr,nspace)
1682 setattr(obj,attr,val)
1686 setattr(obj,attr,val)
1683
1687
1684 #----------------------------------------------------------------------------
1688 #----------------------------------------------------------------------------
1685 def getattr_list(obj,alist,*args):
1689 def getattr_list(obj,alist,*args):
1686 """getattr_list(obj,alist[, default]) -> attribute list.
1690 """getattr_list(obj,alist[, default]) -> attribute list.
1687
1691
1688 Get a list of named attributes for an object. When a default argument is
1692 Get a list of named attributes for an object. When a default argument is
1689 given, it is returned when the attribute doesn't exist; without it, an
1693 given, it is returned when the attribute doesn't exist; without it, an
1690 exception is raised in that case.
1694 exception is raised in that case.
1691
1695
1692 Note that alist can be given as a string, which will be automatically
1696 Note that alist can be given as a string, which will be automatically
1693 split into a list on whitespace. If given as a list, it must be a list of
1697 split into a list on whitespace. If given as a list, it must be a list of
1694 *strings* (the variable names themselves), not of variables."""
1698 *strings* (the variable names themselves), not of variables."""
1695
1699
1696 if type(alist) in StringTypes:
1700 if type(alist) in StringTypes:
1697 alist = alist.split()
1701 alist = alist.split()
1698 if args:
1702 if args:
1699 if len(args)==1:
1703 if len(args)==1:
1700 default = args[0]
1704 default = args[0]
1701 return map(lambda attr: getattr(obj,attr,default),alist)
1705 return map(lambda attr: getattr(obj,attr,default),alist)
1702 else:
1706 else:
1703 raise ValueError,'getattr_list() takes only one optional argument'
1707 raise ValueError,'getattr_list() takes only one optional argument'
1704 else:
1708 else:
1705 return map(lambda attr: getattr(obj,attr),alist)
1709 return map(lambda attr: getattr(obj,attr),alist)
1706
1710
1707 #----------------------------------------------------------------------------
1711 #----------------------------------------------------------------------------
1708 def map_method(method,object_list,*argseq,**kw):
1712 def map_method(method,object_list,*argseq,**kw):
1709 """map_method(method,object_list,*args,**kw) -> list
1713 """map_method(method,object_list,*args,**kw) -> list
1710
1714
1711 Return a list of the results of applying the methods to the items of the
1715 Return a list of the results of applying the methods to the items of the
1712 argument sequence(s). If more than one sequence is given, the method is
1716 argument sequence(s). If more than one sequence is given, the method is
1713 called with an argument list consisting of the corresponding item of each
1717 called with an argument list consisting of the corresponding item of each
1714 sequence. All sequences must be of the same length.
1718 sequence. All sequences must be of the same length.
1715
1719
1716 Keyword arguments are passed verbatim to all objects called.
1720 Keyword arguments are passed verbatim to all objects called.
1717
1721
1718 This is Python code, so it's not nearly as fast as the builtin map()."""
1722 This is Python code, so it's not nearly as fast as the builtin map()."""
1719
1723
1720 out_list = []
1724 out_list = []
1721 idx = 0
1725 idx = 0
1722 for object in object_list:
1726 for object in object_list:
1723 try:
1727 try:
1724 handler = getattr(object, method)
1728 handler = getattr(object, method)
1725 except AttributeError:
1729 except AttributeError:
1726 out_list.append(None)
1730 out_list.append(None)
1727 else:
1731 else:
1728 if argseq:
1732 if argseq:
1729 args = map(lambda lst:lst[idx],argseq)
1733 args = map(lambda lst:lst[idx],argseq)
1730 #print 'ob',object,'hand',handler,'ar',args # dbg
1734 #print 'ob',object,'hand',handler,'ar',args # dbg
1731 out_list.append(handler(args,**kw))
1735 out_list.append(handler(args,**kw))
1732 else:
1736 else:
1733 out_list.append(handler(**kw))
1737 out_list.append(handler(**kw))
1734 idx += 1
1738 idx += 1
1735 return out_list
1739 return out_list
1736
1740
1737 #----------------------------------------------------------------------------
1741 #----------------------------------------------------------------------------
1738 def import_fail_info(mod_name,fns=None):
1742 def import_fail_info(mod_name,fns=None):
1739 """Inform load failure for a module."""
1743 """Inform load failure for a module."""
1740
1744
1741 if fns == None:
1745 if fns == None:
1742 warn("Loading of %s failed.\n" % (mod_name,))
1746 warn("Loading of %s failed.\n" % (mod_name,))
1743 else:
1747 else:
1744 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1748 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1745
1749
1746 #----------------------------------------------------------------------------
1750 #----------------------------------------------------------------------------
1747 # Proposed popitem() extension, written as a method
1751 # Proposed popitem() extension, written as a method
1748
1752
1749 class NotGiven: pass
1753 class NotGiven: pass
1750
1754
1751 def popkey(dct,key,default=NotGiven):
1755 def popkey(dct,key,default=NotGiven):
1752 """Return dct[key] and delete dct[key].
1756 """Return dct[key] and delete dct[key].
1753
1757
1754 If default is given, return it if dct[key] doesn't exist, otherwise raise
1758 If default is given, return it if dct[key] doesn't exist, otherwise raise
1755 KeyError. """
1759 KeyError. """
1756
1760
1757 try:
1761 try:
1758 val = dct[key]
1762 val = dct[key]
1759 except KeyError:
1763 except KeyError:
1760 if default is NotGiven:
1764 if default is NotGiven:
1761 raise
1765 raise
1762 else:
1766 else:
1763 return default
1767 return default
1764 else:
1768 else:
1765 del dct[key]
1769 del dct[key]
1766 return val
1770 return val
1767 #*************************** end of file <genutils.py> **********************
1771 #*************************** end of file <genutils.py> **********************
1768
1772
@@ -1,2221 +1,2229 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 1038 2006-01-20 23:43:35Z vivainio $
9 $Id: iplib.py 1058 2006-01-22 14:30:01Z vivainio $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from __future__ import generators # for 2.2 backwards-compatibility
31 from __future__ import generators # for 2.2 backwards-compatibility
32
32
33 from IPython import Release
33 from IPython import Release
34 __author__ = '%s <%s>\n%s <%s>' % \
34 __author__ = '%s <%s>\n%s <%s>' % \
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 __license__ = Release.license
36 __license__ = Release.license
37 __version__ = Release.version
37 __version__ = Release.version
38
38
39 # Python standard modules
39 # Python standard modules
40 import __main__
40 import __main__
41 import __builtin__
41 import __builtin__
42 import StringIO
42 import StringIO
43 import bdb
43 import bdb
44 import cPickle as pickle
44 import cPickle as pickle
45 import codeop
45 import codeop
46 import exceptions
46 import exceptions
47 import glob
47 import glob
48 import inspect
48 import inspect
49 import keyword
49 import keyword
50 import new
50 import new
51 import os
51 import os
52 import pdb
52 import pdb
53 import pydoc
53 import pydoc
54 import re
54 import re
55 import shutil
55 import shutil
56 import string
56 import string
57 import sys
57 import sys
58 import tempfile
58 import tempfile
59 import traceback
59 import traceback
60 import types
60 import types
61
61
62 from pprint import pprint, pformat
62 from pprint import pprint, pformat
63
63
64 # IPython's own modules
64 # IPython's own modules
65 import IPython
65 import IPython
66 from IPython import OInspect,PyColorize,ultraTB
66 from IPython import OInspect,PyColorize,ultraTB
67 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
68 from IPython.FakeModule import FakeModule
68 from IPython.FakeModule import FakeModule
69 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
70 from IPython.Logger import Logger
70 from IPython.Logger import Logger
71 from IPython.Magic import Magic
71 from IPython.Magic import Magic
72 from IPython.Prompts import CachedOutput
72 from IPython.Prompts import CachedOutput
73 from IPython.ipstruct import Struct
73 from IPython.ipstruct import Struct
74 from IPython.background_jobs import BackgroundJobManager
74 from IPython.background_jobs import BackgroundJobManager
75 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.usage import cmd_line_usage,interactive_usage
76 from IPython.genutils import *
76 from IPython.genutils import *
77 import IPython.ipapi
77 import IPython.ipapi
78
78
79 # Globals
79 # Globals
80
80
81 # store the builtin raw_input globally, and use this always, in case user code
81 # store the builtin raw_input globally, and use this always, in case user code
82 # overwrites it (like wx.py.PyShell does)
82 # overwrites it (like wx.py.PyShell does)
83 raw_input_original = raw_input
83 raw_input_original = raw_input
84
84
85 # compiled regexps for autoindent management
85 # compiled regexps for autoindent management
86 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87
87
88
88
89 #****************************************************************************
89 #****************************************************************************
90 # Some utility function definitions
90 # Some utility function definitions
91
91
92 ini_spaces_re = re.compile(r'^(\s+)')
92 ini_spaces_re = re.compile(r'^(\s+)')
93
93
94 def num_ini_spaces(strng):
94 def num_ini_spaces(strng):
95 """Return the number of initial spaces in a string"""
95 """Return the number of initial spaces in a string"""
96
96
97 ini_spaces = ini_spaces_re.match(strng)
97 ini_spaces = ini_spaces_re.match(strng)
98 if ini_spaces:
98 if ini_spaces:
99 return ini_spaces.end()
99 return ini_spaces.end()
100 else:
100 else:
101 return 0
101 return 0
102
102
103 def softspace(file, newvalue):
103 def softspace(file, newvalue):
104 """Copied from code.py, to remove the dependency"""
104 """Copied from code.py, to remove the dependency"""
105
105
106 oldvalue = 0
106 oldvalue = 0
107 try:
107 try:
108 oldvalue = file.softspace
108 oldvalue = file.softspace
109 except AttributeError:
109 except AttributeError:
110 pass
110 pass
111 try:
111 try:
112 file.softspace = newvalue
112 file.softspace = newvalue
113 except (AttributeError, TypeError):
113 except (AttributeError, TypeError):
114 # "attribute-less object" or "read-only attributes"
114 # "attribute-less object" or "read-only attributes"
115 pass
115 pass
116 return oldvalue
116 return oldvalue
117
117
118
118
119 #****************************************************************************
119 #****************************************************************************
120 # Local use exceptions
120 # Local use exceptions
121 class SpaceInInput(exceptions.Exception): pass
121 class SpaceInInput(exceptions.Exception): pass
122
122
123
123
124 #****************************************************************************
124 #****************************************************************************
125 # Local use classes
125 # Local use classes
126 class Bunch: pass
126 class Bunch: pass
127
127
128 class Undefined: pass
128 class Undefined: pass
129
129
130 class InputList(list):
130 class InputList(list):
131 """Class to store user input.
131 """Class to store user input.
132
132
133 It's basically a list, but slices return a string instead of a list, thus
133 It's basically a list, but slices return a string instead of a list, thus
134 allowing things like (assuming 'In' is an instance):
134 allowing things like (assuming 'In' is an instance):
135
135
136 exec In[4:7]
136 exec In[4:7]
137
137
138 or
138 or
139
139
140 exec In[5:9] + In[14] + In[21:25]"""
140 exec In[5:9] + In[14] + In[21:25]"""
141
141
142 def __getslice__(self,i,j):
142 def __getslice__(self,i,j):
143 return ''.join(list.__getslice__(self,i,j))
143 return ''.join(list.__getslice__(self,i,j))
144
144
145 class SyntaxTB(ultraTB.ListTB):
145 class SyntaxTB(ultraTB.ListTB):
146 """Extension which holds some state: the last exception value"""
146 """Extension which holds some state: the last exception value"""
147
147
148 def __init__(self,color_scheme = 'NoColor'):
148 def __init__(self,color_scheme = 'NoColor'):
149 ultraTB.ListTB.__init__(self,color_scheme)
149 ultraTB.ListTB.__init__(self,color_scheme)
150 self.last_syntax_error = None
150 self.last_syntax_error = None
151
151
152 def __call__(self, etype, value, elist):
152 def __call__(self, etype, value, elist):
153 self.last_syntax_error = value
153 self.last_syntax_error = value
154 ultraTB.ListTB.__call__(self,etype,value,elist)
154 ultraTB.ListTB.__call__(self,etype,value,elist)
155
155
156 def clear_err_state(self):
156 def clear_err_state(self):
157 """Return the current error state and clear it"""
157 """Return the current error state and clear it"""
158 e = self.last_syntax_error
158 e = self.last_syntax_error
159 self.last_syntax_error = None
159 self.last_syntax_error = None
160 return e
160 return e
161
161
162 #****************************************************************************
162 #****************************************************************************
163 # Main IPython class
163 # Main IPython class
164
164
165 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
165 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
166 # until a full rewrite is made. I've cleaned all cross-class uses of
166 # until a full rewrite is made. I've cleaned all cross-class uses of
167 # attributes and methods, but too much user code out there relies on the
167 # attributes and methods, but too much user code out there relies on the
168 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
168 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
169 #
169 #
170 # But at least now, all the pieces have been separated and we could, in
170 # But at least now, all the pieces have been separated and we could, in
171 # principle, stop using the mixin. This will ease the transition to the
171 # principle, stop using the mixin. This will ease the transition to the
172 # chainsaw branch.
172 # chainsaw branch.
173
173
174 # For reference, the following is the list of 'self.foo' uses in the Magic
174 # For reference, the following is the list of 'self.foo' uses in the Magic
175 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
175 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
176 # class, to prevent clashes.
176 # class, to prevent clashes.
177
177
178 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
178 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
179 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
179 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
180 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
180 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
181 # 'self.value']
181 # 'self.value']
182
182
183 class InteractiveShell(object,Magic):
183 class InteractiveShell(object,Magic):
184 """An enhanced console for Python."""
184 """An enhanced console for Python."""
185
185
186 # class attribute to indicate whether the class supports threads or not.
186 # class attribute to indicate whether the class supports threads or not.
187 # Subclasses with thread support should override this as needed.
187 # Subclasses with thread support should override this as needed.
188 isthreaded = False
188 isthreaded = False
189
189
190 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
190 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
191 user_ns = None,user_global_ns=None,banner2='',
191 user_ns = None,user_global_ns=None,banner2='',
192 custom_exceptions=((),None),embedded=False):
192 custom_exceptions=((),None),embedded=False):
193
193
194 # log system
194 # log system
195 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
195 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
196
196
197 # introduce ourselves to IPython.ipapi which is uncallable
197 # introduce ourselves to IPython.ipapi which is uncallable
198 # before it knows an InteractiveShell object.
198 # before it knows an InteractiveShell object.
199 IPython.ipapi._init_with_shell(self)
199 IPython.ipapi._init_with_shell(self)
200
200
201 # some minimal strict typechecks. For some core data structures, I
201 # some minimal strict typechecks. For some core data structures, I
202 # want actual basic python types, not just anything that looks like
202 # want actual basic python types, not just anything that looks like
203 # one. This is especially true for namespaces.
203 # one. This is especially true for namespaces.
204 for ns in (user_ns,user_global_ns):
204 for ns in (user_ns,user_global_ns):
205 if ns is not None and type(ns) != types.DictType:
205 if ns is not None and type(ns) != types.DictType:
206 raise TypeError,'namespace must be a dictionary'
206 raise TypeError,'namespace must be a dictionary'
207
207
208 # Job manager (for jobs run as background threads)
208 # Job manager (for jobs run as background threads)
209 self.jobs = BackgroundJobManager()
209 self.jobs = BackgroundJobManager()
210
210
211 # track which builtins we add, so we can clean up later
211 # track which builtins we add, so we can clean up later
212 self.builtins_added = {}
212 self.builtins_added = {}
213 # This method will add the necessary builtins for operation, but
213 # This method will add the necessary builtins for operation, but
214 # tracking what it did via the builtins_added dict.
214 # tracking what it did via the builtins_added dict.
215 self.add_builtins()
215 self.add_builtins()
216
216
217 # Do the intuitively correct thing for quit/exit: we remove the
217 # Do the intuitively correct thing for quit/exit: we remove the
218 # builtins if they exist, and our own magics will deal with this
218 # builtins if they exist, and our own magics will deal with this
219 try:
219 try:
220 del __builtin__.exit, __builtin__.quit
220 del __builtin__.exit, __builtin__.quit
221 except AttributeError:
221 except AttributeError:
222 pass
222 pass
223
223
224 # Store the actual shell's name
224 # Store the actual shell's name
225 self.name = name
225 self.name = name
226
226
227 # We need to know whether the instance is meant for embedding, since
227 # We need to know whether the instance is meant for embedding, since
228 # global/local namespaces need to be handled differently in that case
228 # global/local namespaces need to be handled differently in that case
229 self.embedded = embedded
229 self.embedded = embedded
230
230
231 # command compiler
231 # command compiler
232 self.compile = codeop.CommandCompiler()
232 self.compile = codeop.CommandCompiler()
233
233
234 # User input buffer
234 # User input buffer
235 self.buffer = []
235 self.buffer = []
236
236
237 # Default name given in compilation of code
237 # Default name given in compilation of code
238 self.filename = '<ipython console>'
238 self.filename = '<ipython console>'
239
239
240 # Make an empty namespace, which extension writers can rely on both
240 # Make an empty namespace, which extension writers can rely on both
241 # existing and NEVER being used by ipython itself. This gives them a
241 # existing and NEVER being used by ipython itself. This gives them a
242 # convenient location for storing additional information and state
242 # convenient location for storing additional information and state
243 # their extensions may require, without fear of collisions with other
243 # their extensions may require, without fear of collisions with other
244 # ipython names that may develop later.
244 # ipython names that may develop later.
245 self.meta = Bunch()
245 self.meta = Bunch()
246
246
247 # Create the namespace where the user will operate. user_ns is
247 # Create the namespace where the user will operate. user_ns is
248 # normally the only one used, and it is passed to the exec calls as
248 # normally the only one used, and it is passed to the exec calls as
249 # the locals argument. But we do carry a user_global_ns namespace
249 # the locals argument. But we do carry a user_global_ns namespace
250 # given as the exec 'globals' argument, This is useful in embedding
250 # given as the exec 'globals' argument, This is useful in embedding
251 # situations where the ipython shell opens in a context where the
251 # situations where the ipython shell opens in a context where the
252 # distinction between locals and globals is meaningful.
252 # distinction between locals and globals is meaningful.
253
253
254 # FIXME. For some strange reason, __builtins__ is showing up at user
254 # FIXME. For some strange reason, __builtins__ is showing up at user
255 # level as a dict instead of a module. This is a manual fix, but I
255 # level as a dict instead of a module. This is a manual fix, but I
256 # should really track down where the problem is coming from. Alex
256 # should really track down where the problem is coming from. Alex
257 # Schmolck reported this problem first.
257 # Schmolck reported this problem first.
258
258
259 # A useful post by Alex Martelli on this topic:
259 # A useful post by Alex Martelli on this topic:
260 # Re: inconsistent value from __builtins__
260 # Re: inconsistent value from __builtins__
261 # Von: Alex Martelli <aleaxit@yahoo.com>
261 # Von: Alex Martelli <aleaxit@yahoo.com>
262 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
262 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
263 # Gruppen: comp.lang.python
263 # Gruppen: comp.lang.python
264
264
265 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
265 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
266 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
266 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
267 # > <type 'dict'>
267 # > <type 'dict'>
268 # > >>> print type(__builtins__)
268 # > >>> print type(__builtins__)
269 # > <type 'module'>
269 # > <type 'module'>
270 # > Is this difference in return value intentional?
270 # > Is this difference in return value intentional?
271
271
272 # Well, it's documented that '__builtins__' can be either a dictionary
272 # Well, it's documented that '__builtins__' can be either a dictionary
273 # or a module, and it's been that way for a long time. Whether it's
273 # or a module, and it's been that way for a long time. Whether it's
274 # intentional (or sensible), I don't know. In any case, the idea is
274 # intentional (or sensible), I don't know. In any case, the idea is
275 # that if you need to access the built-in namespace directly, you
275 # that if you need to access the built-in namespace directly, you
276 # should start with "import __builtin__" (note, no 's') which will
276 # should start with "import __builtin__" (note, no 's') which will
277 # definitely give you a module. Yeah, it's somewhat confusing:-(.
277 # definitely give you a module. Yeah, it's somewhat confusing:-(.
278
278
279 if user_ns is None:
279 if user_ns is None:
280 # Set __name__ to __main__ to better match the behavior of the
280 # Set __name__ to __main__ to better match the behavior of the
281 # normal interpreter.
281 # normal interpreter.
282 user_ns = {'__name__' :'__main__',
282 user_ns = {'__name__' :'__main__',
283 '__builtins__' : __builtin__,
283 '__builtins__' : __builtin__,
284 }
284 }
285
285
286 if user_global_ns is None:
286 if user_global_ns is None:
287 user_global_ns = {}
287 user_global_ns = {}
288
288
289 # Assign namespaces
289 # Assign namespaces
290 # This is the namespace where all normal user variables live
290 # This is the namespace where all normal user variables live
291 self.user_ns = user_ns
291 self.user_ns = user_ns
292 # Embedded instances require a separate namespace for globals.
292 # Embedded instances require a separate namespace for globals.
293 # Normally this one is unused by non-embedded instances.
293 # Normally this one is unused by non-embedded instances.
294 self.user_global_ns = user_global_ns
294 self.user_global_ns = user_global_ns
295 # A namespace to keep track of internal data structures to prevent
295 # A namespace to keep track of internal data structures to prevent
296 # them from cluttering user-visible stuff. Will be updated later
296 # them from cluttering user-visible stuff. Will be updated later
297 self.internal_ns = {}
297 self.internal_ns = {}
298
298
299 # Namespace of system aliases. Each entry in the alias
299 # Namespace of system aliases. Each entry in the alias
300 # table must be a 2-tuple of the form (N,name), where N is the number
300 # table must be a 2-tuple of the form (N,name), where N is the number
301 # of positional arguments of the alias.
301 # of positional arguments of the alias.
302 self.alias_table = {}
302 self.alias_table = {}
303
303
304 # A table holding all the namespaces IPython deals with, so that
304 # A table holding all the namespaces IPython deals with, so that
305 # introspection facilities can search easily.
305 # introspection facilities can search easily.
306 self.ns_table = {'user':user_ns,
306 self.ns_table = {'user':user_ns,
307 'user_global':user_global_ns,
307 'user_global':user_global_ns,
308 'alias':self.alias_table,
308 'alias':self.alias_table,
309 'internal':self.internal_ns,
309 'internal':self.internal_ns,
310 'builtin':__builtin__.__dict__
310 'builtin':__builtin__.__dict__
311 }
311 }
312
312
313 # The user namespace MUST have a pointer to the shell itself.
313 # The user namespace MUST have a pointer to the shell itself.
314 self.user_ns[name] = self
314 self.user_ns[name] = self
315
315
316 # We need to insert into sys.modules something that looks like a
316 # We need to insert into sys.modules something that looks like a
317 # module but which accesses the IPython namespace, for shelve and
317 # module but which accesses the IPython namespace, for shelve and
318 # pickle to work interactively. Normally they rely on getting
318 # pickle to work interactively. Normally they rely on getting
319 # everything out of __main__, but for embedding purposes each IPython
319 # everything out of __main__, but for embedding purposes each IPython
320 # instance has its own private namespace, so we can't go shoving
320 # instance has its own private namespace, so we can't go shoving
321 # everything into __main__.
321 # everything into __main__.
322
322
323 # note, however, that we should only do this for non-embedded
323 # note, however, that we should only do this for non-embedded
324 # ipythons, which really mimic the __main__.__dict__ with their own
324 # ipythons, which really mimic the __main__.__dict__ with their own
325 # namespace. Embedded instances, on the other hand, should not do
325 # namespace. Embedded instances, on the other hand, should not do
326 # this because they need to manage the user local/global namespaces
326 # this because they need to manage the user local/global namespaces
327 # only, but they live within a 'normal' __main__ (meaning, they
327 # only, but they live within a 'normal' __main__ (meaning, they
328 # shouldn't overtake the execution environment of the script they're
328 # shouldn't overtake the execution environment of the script they're
329 # embedded in).
329 # embedded in).
330
330
331 if not embedded:
331 if not embedded:
332 try:
332 try:
333 main_name = self.user_ns['__name__']
333 main_name = self.user_ns['__name__']
334 except KeyError:
334 except KeyError:
335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
336 else:
336 else:
337 #print "pickle hack in place" # dbg
337 #print "pickle hack in place" # dbg
338 #print 'main_name:',main_name # dbg
338 #print 'main_name:',main_name # dbg
339 sys.modules[main_name] = FakeModule(self.user_ns)
339 sys.modules[main_name] = FakeModule(self.user_ns)
340
340
341 # List of input with multi-line handling.
341 # List of input with multi-line handling.
342 # Fill its zero entry, user counter starts at 1
342 # Fill its zero entry, user counter starts at 1
343 self.input_hist = InputList(['\n'])
343 self.input_hist = InputList(['\n'])
344
344
345 # list of visited directories
345 # list of visited directories
346 try:
346 try:
347 self.dir_hist = [os.getcwd()]
347 self.dir_hist = [os.getcwd()]
348 except IOError, e:
348 except IOError, e:
349 self.dir_hist = []
349 self.dir_hist = []
350
350
351 # dict of output history
351 # dict of output history
352 self.output_hist = {}
352 self.output_hist = {}
353
353
354 # dict of things NOT to alias (keywords, builtins and some magics)
354 # dict of things NOT to alias (keywords, builtins and some magics)
355 no_alias = {}
355 no_alias = {}
356 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
356 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
357 for key in keyword.kwlist + no_alias_magics:
357 for key in keyword.kwlist + no_alias_magics:
358 no_alias[key] = 1
358 no_alias[key] = 1
359 no_alias.update(__builtin__.__dict__)
359 no_alias.update(__builtin__.__dict__)
360 self.no_alias = no_alias
360 self.no_alias = no_alias
361
361
362 # make global variables for user access to these
362 # make global variables for user access to these
363 self.user_ns['_ih'] = self.input_hist
363 self.user_ns['_ih'] = self.input_hist
364 self.user_ns['_oh'] = self.output_hist
364 self.user_ns['_oh'] = self.output_hist
365 self.user_ns['_dh'] = self.dir_hist
365 self.user_ns['_dh'] = self.dir_hist
366
366
367 # user aliases to input and output histories
367 # user aliases to input and output histories
368 self.user_ns['In'] = self.input_hist
368 self.user_ns['In'] = self.input_hist
369 self.user_ns['Out'] = self.output_hist
369 self.user_ns['Out'] = self.output_hist
370
370
371 # Object variable to store code object waiting execution. This is
371 # Object variable to store code object waiting execution. This is
372 # used mainly by the multithreaded shells, but it can come in handy in
372 # used mainly by the multithreaded shells, but it can come in handy in
373 # other situations. No need to use a Queue here, since it's a single
373 # other situations. No need to use a Queue here, since it's a single
374 # item which gets cleared once run.
374 # item which gets cleared once run.
375 self.code_to_run = None
375 self.code_to_run = None
376
376
377 # escapes for automatic behavior on the command line
377 # escapes for automatic behavior on the command line
378 self.ESC_SHELL = '!'
378 self.ESC_SHELL = '!'
379 self.ESC_HELP = '?'
379 self.ESC_HELP = '?'
380 self.ESC_MAGIC = '%'
380 self.ESC_MAGIC = '%'
381 self.ESC_QUOTE = ','
381 self.ESC_QUOTE = ','
382 self.ESC_QUOTE2 = ';'
382 self.ESC_QUOTE2 = ';'
383 self.ESC_PAREN = '/'
383 self.ESC_PAREN = '/'
384
384
385 # And their associated handlers
385 # And their associated handlers
386 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
386 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
387 self.ESC_QUOTE : self.handle_auto,
387 self.ESC_QUOTE : self.handle_auto,
388 self.ESC_QUOTE2 : self.handle_auto,
388 self.ESC_QUOTE2 : self.handle_auto,
389 self.ESC_MAGIC : self.handle_magic,
389 self.ESC_MAGIC : self.handle_magic,
390 self.ESC_HELP : self.handle_help,
390 self.ESC_HELP : self.handle_help,
391 self.ESC_SHELL : self.handle_shell_escape,
391 self.ESC_SHELL : self.handle_shell_escape,
392 }
392 }
393
393
394 # class initializations
394 # class initializations
395 Magic.__init__(self,self)
395 Magic.__init__(self,self)
396
396
397 # Python source parser/formatter for syntax highlighting
397 # Python source parser/formatter for syntax highlighting
398 pyformat = PyColorize.Parser().format
398 pyformat = PyColorize.Parser().format
399 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
399 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
400
400
401 # hooks holds pointers used for user-side customizations
401 # hooks holds pointers used for user-side customizations
402 self.hooks = Struct()
402 self.hooks = Struct()
403
403
404 # Set all default hooks, defined in the IPython.hooks module.
404 # Set all default hooks, defined in the IPython.hooks module.
405 hooks = IPython.hooks
405 hooks = IPython.hooks
406 for hook_name in hooks.__all__:
406 for hook_name in hooks.__all__:
407 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
407 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
408 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
408 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
409
409
410 # Flag to mark unconditional exit
410 # Flag to mark unconditional exit
411 self.exit_now = False
411 self.exit_now = False
412
412
413 self.usage_min = """\
413 self.usage_min = """\
414 An enhanced console for Python.
414 An enhanced console for Python.
415 Some of its features are:
415 Some of its features are:
416 - Readline support if the readline library is present.
416 - Readline support if the readline library is present.
417 - Tab completion in the local namespace.
417 - Tab completion in the local namespace.
418 - Logging of input, see command-line options.
418 - Logging of input, see command-line options.
419 - System shell escape via ! , eg !ls.
419 - System shell escape via ! , eg !ls.
420 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
420 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
421 - Keeps track of locally defined variables via %who, %whos.
421 - Keeps track of locally defined variables via %who, %whos.
422 - Show object information with a ? eg ?x or x? (use ?? for more info).
422 - Show object information with a ? eg ?x or x? (use ?? for more info).
423 """
423 """
424 if usage: self.usage = usage
424 if usage: self.usage = usage
425 else: self.usage = self.usage_min
425 else: self.usage = self.usage_min
426
426
427 # Storage
427 # Storage
428 self.rc = rc # This will hold all configuration information
428 self.rc = rc # This will hold all configuration information
429 self.pager = 'less'
429 self.pager = 'less'
430 # temporary files used for various purposes. Deleted at exit.
430 # temporary files used for various purposes. Deleted at exit.
431 self.tempfiles = []
431 self.tempfiles = []
432
432
433 # Keep track of readline usage (later set by init_readline)
433 # Keep track of readline usage (later set by init_readline)
434 self.has_readline = False
434 self.has_readline = False
435
435
436 # template for logfile headers. It gets resolved at runtime by the
436 # template for logfile headers. It gets resolved at runtime by the
437 # logstart method.
437 # logstart method.
438 self.loghead_tpl = \
438 self.loghead_tpl = \
439 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
439 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
440 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
440 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
441 #log# opts = %s
441 #log# opts = %s
442 #log# args = %s
442 #log# args = %s
443 #log# It is safe to make manual edits below here.
443 #log# It is safe to make manual edits below here.
444 #log#-----------------------------------------------------------------------
444 #log#-----------------------------------------------------------------------
445 """
445 """
446 # for pushd/popd management
446 # for pushd/popd management
447 try:
447 try:
448 self.home_dir = get_home_dir()
448 self.home_dir = get_home_dir()
449 except HomeDirError,msg:
449 except HomeDirError,msg:
450 fatal(msg)
450 fatal(msg)
451
451
452 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
452 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
453
453
454 # Functions to call the underlying shell.
454 # Functions to call the underlying shell.
455
455
456 # utility to expand user variables via Itpl
456 # utility to expand user variables via Itpl
457 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
457 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
458 self.user_ns))
458 self.user_ns))
459 # The first is similar to os.system, but it doesn't return a value,
459 # The first is similar to os.system, but it doesn't return a value,
460 # and it allows interpolation of variables in the user's namespace.
460 # and it allows interpolation of variables in the user's namespace.
461 self.system = lambda cmd: shell(self.var_expand(cmd),
461 self.system = lambda cmd: shell(self.var_expand(cmd),
462 header='IPython system call: ',
462 header='IPython system call: ',
463 verbose=self.rc.system_verbose)
463 verbose=self.rc.system_verbose)
464 # These are for getoutput and getoutputerror:
464 # These are for getoutput and getoutputerror:
465 self.getoutput = lambda cmd: \
465 self.getoutput = lambda cmd: \
466 getoutput(self.var_expand(cmd),
466 getoutput(self.var_expand(cmd),
467 header='IPython system call: ',
467 header='IPython system call: ',
468 verbose=self.rc.system_verbose)
468 verbose=self.rc.system_verbose)
469 self.getoutputerror = lambda cmd: \
469 self.getoutputerror = lambda cmd: \
470 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
470 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
471 self.user_ns)),
471 self.user_ns)),
472 header='IPython system call: ',
472 header='IPython system call: ',
473 verbose=self.rc.system_verbose)
473 verbose=self.rc.system_verbose)
474
474
475 # RegExp for splitting line contents into pre-char//first
475 # RegExp for splitting line contents into pre-char//first
476 # word-method//rest. For clarity, each group in on one line.
476 # word-method//rest. For clarity, each group in on one line.
477
477
478 # WARNING: update the regexp if the above escapes are changed, as they
478 # WARNING: update the regexp if the above escapes are changed, as they
479 # are hardwired in.
479 # are hardwired in.
480
480
481 # Don't get carried away with trying to make the autocalling catch too
481 # Don't get carried away with trying to make the autocalling catch too
482 # much: it's better to be conservative rather than to trigger hidden
482 # much: it's better to be conservative rather than to trigger hidden
483 # evals() somewhere and end up causing side effects.
483 # evals() somewhere and end up causing side effects.
484
484
485 self.line_split = re.compile(r'^([\s*,;/])'
485 self.line_split = re.compile(r'^([\s*,;/])'
486 r'([\?\w\.]+\w*\s*)'
486 r'([\?\w\.]+\w*\s*)'
487 r'(\(?.*$)')
487 r'(\(?.*$)')
488
488
489 # Original re, keep around for a while in case changes break something
489 # Original re, keep around for a while in case changes break something
490 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
490 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
491 # r'(\s*[\?\w\.]+\w*\s*)'
491 # r'(\s*[\?\w\.]+\w*\s*)'
492 # r'(\(?.*$)')
492 # r'(\(?.*$)')
493
493
494 # RegExp to identify potential function names
494 # RegExp to identify potential function names
495 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
495 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
496
496
497 # RegExp to exclude strings with this start from autocalling. In
497 # RegExp to exclude strings with this start from autocalling. In
498 # particular, all binary operators should be excluded, so that if foo
498 # particular, all binary operators should be excluded, so that if foo
499 # is callable, foo OP bar doesn't become foo(OP bar), which is
499 # is callable, foo OP bar doesn't become foo(OP bar), which is
500 # invalid. The characters '!=()' don't need to be checked for, as the
500 # invalid. The characters '!=()' don't need to be checked for, as the
501 # _prefilter routine explicitely does so, to catch direct calls and
501 # _prefilter routine explicitely does so, to catch direct calls and
502 # rebindings of existing names.
502 # rebindings of existing names.
503
503
504 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
504 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
505 # it affects the rest of the group in square brackets.
505 # it affects the rest of the group in square brackets.
506 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
506 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
507 '|^is |^not |^in |^and |^or ')
507 '|^is |^not |^in |^and |^or ')
508
508
509 # try to catch also methods for stuff in lists/tuples/dicts: off
509 # try to catch also methods for stuff in lists/tuples/dicts: off
510 # (experimental). For this to work, the line_split regexp would need
510 # (experimental). For this to work, the line_split regexp would need
511 # to be modified so it wouldn't break things at '['. That line is
511 # to be modified so it wouldn't break things at '['. That line is
512 # nasty enough that I shouldn't change it until I can test it _well_.
512 # nasty enough that I shouldn't change it until I can test it _well_.
513 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
513 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
514
514
515 # keep track of where we started running (mainly for crash post-mortem)
515 # keep track of where we started running (mainly for crash post-mortem)
516 self.starting_dir = os.getcwd()
516 self.starting_dir = os.getcwd()
517
517
518 # Various switches which can be set
518 # Various switches which can be set
519 self.CACHELENGTH = 5000 # this is cheap, it's just text
519 self.CACHELENGTH = 5000 # this is cheap, it's just text
520 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
520 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
521 self.banner2 = banner2
521 self.banner2 = banner2
522
522
523 # TraceBack handlers:
523 # TraceBack handlers:
524
524
525 # Syntax error handler.
525 # Syntax error handler.
526 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
526 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
527
527
528 # The interactive one is initialized with an offset, meaning we always
528 # The interactive one is initialized with an offset, meaning we always
529 # want to remove the topmost item in the traceback, which is our own
529 # want to remove the topmost item in the traceback, which is our own
530 # internal code. Valid modes: ['Plain','Context','Verbose']
530 # internal code. Valid modes: ['Plain','Context','Verbose']
531 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
531 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
532 color_scheme='NoColor',
532 color_scheme='NoColor',
533 tb_offset = 1)
533 tb_offset = 1)
534
534
535 # IPython itself shouldn't crash. This will produce a detailed
535 # IPython itself shouldn't crash. This will produce a detailed
536 # post-mortem if it does. But we only install the crash handler for
536 # post-mortem if it does. But we only install the crash handler for
537 # non-threaded shells, the threaded ones use a normal verbose reporter
537 # non-threaded shells, the threaded ones use a normal verbose reporter
538 # and lose the crash handler. This is because exceptions in the main
538 # and lose the crash handler. This is because exceptions in the main
539 # thread (such as in GUI code) propagate directly to sys.excepthook,
539 # thread (such as in GUI code) propagate directly to sys.excepthook,
540 # and there's no point in printing crash dumps for every user exception.
540 # and there's no point in printing crash dumps for every user exception.
541 if self.isthreaded:
541 if self.isthreaded:
542 sys.excepthook = ultraTB.FormattedTB()
542 sys.excepthook = ultraTB.FormattedTB()
543 else:
543 else:
544 from IPython import CrashHandler
544 from IPython import CrashHandler
545 sys.excepthook = CrashHandler.CrashHandler(self)
545 sys.excepthook = CrashHandler.CrashHandler(self)
546
546
547 # The instance will store a pointer to this, so that runtime code
547 # The instance will store a pointer to this, so that runtime code
548 # (such as magics) can access it. This is because during the
548 # (such as magics) can access it. This is because during the
549 # read-eval loop, it gets temporarily overwritten (to deal with GUI
549 # read-eval loop, it gets temporarily overwritten (to deal with GUI
550 # frameworks).
550 # frameworks).
551 self.sys_excepthook = sys.excepthook
551 self.sys_excepthook = sys.excepthook
552
552
553 # and add any custom exception handlers the user may have specified
553 # and add any custom exception handlers the user may have specified
554 self.set_custom_exc(*custom_exceptions)
554 self.set_custom_exc(*custom_exceptions)
555
555
556 # Object inspector
556 # Object inspector
557 self.inspector = OInspect.Inspector(OInspect.InspectColors,
557 self.inspector = OInspect.Inspector(OInspect.InspectColors,
558 PyColorize.ANSICodeColors,
558 PyColorize.ANSICodeColors,
559 'NoColor')
559 'NoColor')
560 # indentation management
560 # indentation management
561 self.autoindent = False
561 self.autoindent = False
562 self.indent_current_nsp = 0
562 self.indent_current_nsp = 0
563
563
564 # Make some aliases automatically
564 # Make some aliases automatically
565 # Prepare list of shell aliases to auto-define
565 # Prepare list of shell aliases to auto-define
566 if os.name == 'posix':
566 if os.name == 'posix':
567 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
567 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
568 'mv mv -i','rm rm -i','cp cp -i',
568 'mv mv -i','rm rm -i','cp cp -i',
569 'cat cat','less less','clear clear',
569 'cat cat','less less','clear clear',
570 # a better ls
570 # a better ls
571 'ls ls -F',
571 'ls ls -F',
572 # long ls
572 # long ls
573 'll ls -lF',
573 'll ls -lF',
574 # color ls
574 # color ls
575 'lc ls -F -o --color',
575 'lc ls -F -o --color',
576 # ls normal files only
576 # ls normal files only
577 'lf ls -F -o --color %l | grep ^-',
577 'lf ls -F -o --color %l | grep ^-',
578 # ls symbolic links
578 # ls symbolic links
579 'lk ls -F -o --color %l | grep ^l',
579 'lk ls -F -o --color %l | grep ^l',
580 # directories or links to directories,
580 # directories or links to directories,
581 'ldir ls -F -o --color %l | grep /$',
581 'ldir ls -F -o --color %l | grep /$',
582 # things which are executable
582 # things which are executable
583 'lx ls -F -o --color %l | grep ^-..x',
583 'lx ls -F -o --color %l | grep ^-..x',
584 )
584 )
585 elif os.name in ['nt','dos']:
585 elif os.name in ['nt','dos']:
586 auto_alias = ('dir dir /on', 'ls dir /on',
586 auto_alias = ('dir dir /on', 'ls dir /on',
587 'ddir dir /ad /on', 'ldir dir /ad /on',
587 'ddir dir /ad /on', 'ldir dir /ad /on',
588 'mkdir mkdir','rmdir rmdir','echo echo',
588 'mkdir mkdir','rmdir rmdir','echo echo',
589 'ren ren','cls cls','copy copy')
589 'ren ren','cls cls','copy copy')
590 else:
590 else:
591 auto_alias = ()
591 auto_alias = ()
592 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
592 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
593 # Call the actual (public) initializer
593 # Call the actual (public) initializer
594 self.init_auto_alias()
594 self.init_auto_alias()
595 # end __init__
595 # end __init__
596
596
597 def post_config_initialization(self):
597 def post_config_initialization(self):
598 """Post configuration init method
598 """Post configuration init method
599
599
600 This is called after the configuration files have been processed to
600 This is called after the configuration files have been processed to
601 'finalize' the initialization."""
601 'finalize' the initialization."""
602
602
603 rc = self.rc
603 rc = self.rc
604
604
605 # Load readline proper
605 # Load readline proper
606 if rc.readline:
606 if rc.readline:
607 self.init_readline()
607 self.init_readline()
608
608
609 # local shortcut, this is used a LOT
609 # local shortcut, this is used a LOT
610 self.log = self.logger.log
610 self.log = self.logger.log
611
611
612 # Initialize cache, set in/out prompts and printing system
612 # Initialize cache, set in/out prompts and printing system
613 self.outputcache = CachedOutput(self,
613 self.outputcache = CachedOutput(self,
614 rc.cache_size,
614 rc.cache_size,
615 rc.pprint,
615 rc.pprint,
616 input_sep = rc.separate_in,
616 input_sep = rc.separate_in,
617 output_sep = rc.separate_out,
617 output_sep = rc.separate_out,
618 output_sep2 = rc.separate_out2,
618 output_sep2 = rc.separate_out2,
619 ps1 = rc.prompt_in1,
619 ps1 = rc.prompt_in1,
620 ps2 = rc.prompt_in2,
620 ps2 = rc.prompt_in2,
621 ps_out = rc.prompt_out,
621 ps_out = rc.prompt_out,
622 pad_left = rc.prompts_pad_left)
622 pad_left = rc.prompts_pad_left)
623
623
624 # user may have over-ridden the default print hook:
624 # user may have over-ridden the default print hook:
625 try:
625 try:
626 self.outputcache.__class__.display = self.hooks.display
626 self.outputcache.__class__.display = self.hooks.display
627 except AttributeError:
627 except AttributeError:
628 pass
628 pass
629
629
630 # I don't like assigning globally to sys, because it means when embedding
630 # I don't like assigning globally to sys, because it means when embedding
631 # instances, each embedded instance overrides the previous choice. But
631 # instances, each embedded instance overrides the previous choice. But
632 # sys.displayhook seems to be called internally by exec, so I don't see a
632 # sys.displayhook seems to be called internally by exec, so I don't see a
633 # way around it.
633 # way around it.
634 sys.displayhook = self.outputcache
634 sys.displayhook = self.outputcache
635
635
636 # Set user colors (don't do it in the constructor above so that it
636 # Set user colors (don't do it in the constructor above so that it
637 # doesn't crash if colors option is invalid)
637 # doesn't crash if colors option is invalid)
638 self.magic_colors(rc.colors)
638 self.magic_colors(rc.colors)
639
639
640 # Set calling of pdb on exceptions
640 # Set calling of pdb on exceptions
641 self.call_pdb = rc.pdb
641 self.call_pdb = rc.pdb
642
642
643 # Load user aliases
643 # Load user aliases
644 for alias in rc.alias:
644 for alias in rc.alias:
645 self.magic_alias(alias)
645 self.magic_alias(alias)
646
646
647 # dynamic data that survives through sessions
647 # dynamic data that survives through sessions
648 # XXX make the filename a config option?
648 # XXX make the filename a config option?
649 persist_base = 'persist'
649 persist_base = 'persist'
650 if rc.profile:
650 if rc.profile:
651 persist_base += '_%s' % rc.profile
651 persist_base += '_%s' % rc.profile
652 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
652 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
653
653
654 try:
654 try:
655 self.persist = pickle.load(file(self.persist_fname))
655 self.persist = pickle.load(file(self.persist_fname))
656 except:
656 except:
657 self.persist = {}
657 self.persist = {}
658
658
659
659
660 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
660 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
661 try:
661 try:
662 obj = pickle.loads(value)
662 obj = pickle.loads(value)
663 except:
663 except:
664
664
665 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
665 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
666 print "The error was:",sys.exc_info()[0]
666 print "The error was:",sys.exc_info()[0]
667 continue
667 continue
668
668
669
669
670 self.user_ns[key] = obj
670 self.user_ns[key] = obj
671
671
672 def add_builtins(self):
672 def add_builtins(self):
673 """Store ipython references into the builtin namespace.
673 """Store ipython references into the builtin namespace.
674
674
675 Some parts of ipython operate via builtins injected here, which hold a
675 Some parts of ipython operate via builtins injected here, which hold a
676 reference to IPython itself."""
676 reference to IPython itself."""
677
677
678 builtins_new = dict(__IPYTHON__ = self,
678 builtins_new = dict(__IPYTHON__ = self,
679 ip_set_hook = self.set_hook,
679 ip_set_hook = self.set_hook,
680 jobs = self.jobs,
680 jobs = self.jobs,
681 ipmagic = self.ipmagic,
681 ipmagic = self.ipmagic,
682 ipalias = self.ipalias,
682 ipalias = self.ipalias,
683 ipsystem = self.ipsystem,
683 ipsystem = self.ipsystem,
684 )
684 )
685 for biname,bival in builtins_new.items():
685 for biname,bival in builtins_new.items():
686 try:
686 try:
687 # store the orignal value so we can restore it
687 # store the orignal value so we can restore it
688 self.builtins_added[biname] = __builtin__.__dict__[biname]
688 self.builtins_added[biname] = __builtin__.__dict__[biname]
689 except KeyError:
689 except KeyError:
690 # or mark that it wasn't defined, and we'll just delete it at
690 # or mark that it wasn't defined, and we'll just delete it at
691 # cleanup
691 # cleanup
692 self.builtins_added[biname] = Undefined
692 self.builtins_added[biname] = Undefined
693 __builtin__.__dict__[biname] = bival
693 __builtin__.__dict__[biname] = bival
694
694
695 # Keep in the builtins a flag for when IPython is active. We set it
695 # Keep in the builtins a flag for when IPython is active. We set it
696 # with setdefault so that multiple nested IPythons don't clobber one
696 # with setdefault so that multiple nested IPythons don't clobber one
697 # another. Each will increase its value by one upon being activated,
697 # another. Each will increase its value by one upon being activated,
698 # which also gives us a way to determine the nesting level.
698 # which also gives us a way to determine the nesting level.
699 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
699 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
700
700
701 def clean_builtins(self):
701 def clean_builtins(self):
702 """Remove any builtins which might have been added by add_builtins, or
702 """Remove any builtins which might have been added by add_builtins, or
703 restore overwritten ones to their previous values."""
703 restore overwritten ones to their previous values."""
704 for biname,bival in self.builtins_added.items():
704 for biname,bival in self.builtins_added.items():
705 if bival is Undefined:
705 if bival is Undefined:
706 del __builtin__.__dict__[biname]
706 del __builtin__.__dict__[biname]
707 else:
707 else:
708 __builtin__.__dict__[biname] = bival
708 __builtin__.__dict__[biname] = bival
709 self.builtins_added.clear()
709 self.builtins_added.clear()
710
710
711 def set_hook(self,name,hook, priority = 50):
711 def set_hook(self,name,hook, priority = 50):
712 """set_hook(name,hook) -> sets an internal IPython hook.
712 """set_hook(name,hook) -> sets an internal IPython hook.
713
713
714 IPython exposes some of its internal API as user-modifiable hooks. By
714 IPython exposes some of its internal API as user-modifiable hooks. By
715 adding your function to one of these hooks, you can modify IPython's
715 adding your function to one of these hooks, you can modify IPython's
716 behavior to call at runtime your own routines."""
716 behavior to call at runtime your own routines."""
717
717
718 # At some point in the future, this should validate the hook before it
718 # At some point in the future, this should validate the hook before it
719 # accepts it. Probably at least check that the hook takes the number
719 # accepts it. Probably at least check that the hook takes the number
720 # of args it's supposed to.
720 # of args it's supposed to.
721 dp = getattr(self.hooks, name, None)
721 dp = getattr(self.hooks, name, None)
722 if not dp:
722 if not dp:
723 dp = IPython.hooks.CommandChainDispatcher()
723 dp = IPython.hooks.CommandChainDispatcher()
724
724
725 f = new.instancemethod(hook,self,self.__class__)
725 f = new.instancemethod(hook,self,self.__class__)
726 try:
726 try:
727 dp.add(f,priority)
727 dp.add(f,priority)
728 except AttributeError:
728 except AttributeError:
729 # it was not commandchain, plain old func - replace
729 # it was not commandchain, plain old func - replace
730 dp = f
730 dp = f
731
731
732 setattr(self.hooks,name, dp)
732 setattr(self.hooks,name, dp)
733
733
734
734
735 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
735 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
736
736
737 def set_custom_exc(self,exc_tuple,handler):
737 def set_custom_exc(self,exc_tuple,handler):
738 """set_custom_exc(exc_tuple,handler)
738 """set_custom_exc(exc_tuple,handler)
739
739
740 Set a custom exception handler, which will be called if any of the
740 Set a custom exception handler, which will be called if any of the
741 exceptions in exc_tuple occur in the mainloop (specifically, in the
741 exceptions in exc_tuple occur in the mainloop (specifically, in the
742 runcode() method.
742 runcode() method.
743
743
744 Inputs:
744 Inputs:
745
745
746 - exc_tuple: a *tuple* of valid exceptions to call the defined
746 - exc_tuple: a *tuple* of valid exceptions to call the defined
747 handler for. It is very important that you use a tuple, and NOT A
747 handler for. It is very important that you use a tuple, and NOT A
748 LIST here, because of the way Python's except statement works. If
748 LIST here, because of the way Python's except statement works. If
749 you only want to trap a single exception, use a singleton tuple:
749 you only want to trap a single exception, use a singleton tuple:
750
750
751 exc_tuple == (MyCustomException,)
751 exc_tuple == (MyCustomException,)
752
752
753 - handler: this must be defined as a function with the following
753 - handler: this must be defined as a function with the following
754 basic interface: def my_handler(self,etype,value,tb).
754 basic interface: def my_handler(self,etype,value,tb).
755
755
756 This will be made into an instance method (via new.instancemethod)
756 This will be made into an instance method (via new.instancemethod)
757 of IPython itself, and it will be called if any of the exceptions
757 of IPython itself, and it will be called if any of the exceptions
758 listed in the exc_tuple are caught. If the handler is None, an
758 listed in the exc_tuple are caught. If the handler is None, an
759 internal basic one is used, which just prints basic info.
759 internal basic one is used, which just prints basic info.
760
760
761 WARNING: by putting in your own exception handler into IPython's main
761 WARNING: by putting in your own exception handler into IPython's main
762 execution loop, you run a very good chance of nasty crashes. This
762 execution loop, you run a very good chance of nasty crashes. This
763 facility should only be used if you really know what you are doing."""
763 facility should only be used if you really know what you are doing."""
764
764
765 assert type(exc_tuple)==type(()) , \
765 assert type(exc_tuple)==type(()) , \
766 "The custom exceptions must be given AS A TUPLE."
766 "The custom exceptions must be given AS A TUPLE."
767
767
768 def dummy_handler(self,etype,value,tb):
768 def dummy_handler(self,etype,value,tb):
769 print '*** Simple custom exception handler ***'
769 print '*** Simple custom exception handler ***'
770 print 'Exception type :',etype
770 print 'Exception type :',etype
771 print 'Exception value:',value
771 print 'Exception value:',value
772 print 'Traceback :',tb
772 print 'Traceback :',tb
773 print 'Source code :','\n'.join(self.buffer)
773 print 'Source code :','\n'.join(self.buffer)
774
774
775 if handler is None: handler = dummy_handler
775 if handler is None: handler = dummy_handler
776
776
777 self.CustomTB = new.instancemethod(handler,self,self.__class__)
777 self.CustomTB = new.instancemethod(handler,self,self.__class__)
778 self.custom_exceptions = exc_tuple
778 self.custom_exceptions = exc_tuple
779
779
780 def set_custom_completer(self,completer,pos=0):
780 def set_custom_completer(self,completer,pos=0):
781 """set_custom_completer(completer,pos=0)
781 """set_custom_completer(completer,pos=0)
782
782
783 Adds a new custom completer function.
783 Adds a new custom completer function.
784
784
785 The position argument (defaults to 0) is the index in the completers
785 The position argument (defaults to 0) is the index in the completers
786 list where you want the completer to be inserted."""
786 list where you want the completer to be inserted."""
787
787
788 newcomp = new.instancemethod(completer,self.Completer,
788 newcomp = new.instancemethod(completer,self.Completer,
789 self.Completer.__class__)
789 self.Completer.__class__)
790 self.Completer.matchers.insert(pos,newcomp)
790 self.Completer.matchers.insert(pos,newcomp)
791
791
792 def _get_call_pdb(self):
792 def _get_call_pdb(self):
793 return self._call_pdb
793 return self._call_pdb
794
794
795 def _set_call_pdb(self,val):
795 def _set_call_pdb(self,val):
796
796
797 if val not in (0,1,False,True):
797 if val not in (0,1,False,True):
798 raise ValueError,'new call_pdb value must be boolean'
798 raise ValueError,'new call_pdb value must be boolean'
799
799
800 # store value in instance
800 # store value in instance
801 self._call_pdb = val
801 self._call_pdb = val
802
802
803 # notify the actual exception handlers
803 # notify the actual exception handlers
804 self.InteractiveTB.call_pdb = val
804 self.InteractiveTB.call_pdb = val
805 if self.isthreaded:
805 if self.isthreaded:
806 try:
806 try:
807 self.sys_excepthook.call_pdb = val
807 self.sys_excepthook.call_pdb = val
808 except:
808 except:
809 warn('Failed to activate pdb for threaded exception handler')
809 warn('Failed to activate pdb for threaded exception handler')
810
810
811 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
811 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
812 'Control auto-activation of pdb at exceptions')
812 'Control auto-activation of pdb at exceptions')
813
813
814
814
815 # These special functions get installed in the builtin namespace, to
815 # These special functions get installed in the builtin namespace, to
816 # provide programmatic (pure python) access to magics, aliases and system
816 # provide programmatic (pure python) access to magics, aliases and system
817 # calls. This is important for logging, user scripting, and more.
817 # calls. This is important for logging, user scripting, and more.
818
818
819 # We are basically exposing, via normal python functions, the three
819 # We are basically exposing, via normal python functions, the three
820 # mechanisms in which ipython offers special call modes (magics for
820 # mechanisms in which ipython offers special call modes (magics for
821 # internal control, aliases for direct system access via pre-selected
821 # internal control, aliases for direct system access via pre-selected
822 # names, and !cmd for calling arbitrary system commands).
822 # names, and !cmd for calling arbitrary system commands).
823
823
824 def ipmagic(self,arg_s):
824 def ipmagic(self,arg_s):
825 """Call a magic function by name.
825 """Call a magic function by name.
826
826
827 Input: a string containing the name of the magic function to call and any
827 Input: a string containing the name of the magic function to call and any
828 additional arguments to be passed to the magic.
828 additional arguments to be passed to the magic.
829
829
830 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
830 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
831 prompt:
831 prompt:
832
832
833 In[1]: %name -opt foo bar
833 In[1]: %name -opt foo bar
834
834
835 To call a magic without arguments, simply use ipmagic('name').
835 To call a magic without arguments, simply use ipmagic('name').
836
836
837 This provides a proper Python function to call IPython's magics in any
837 This provides a proper Python function to call IPython's magics in any
838 valid Python code you can type at the interpreter, including loops and
838 valid Python code you can type at the interpreter, including loops and
839 compound statements. It is added by IPython to the Python builtin
839 compound statements. It is added by IPython to the Python builtin
840 namespace upon initialization."""
840 namespace upon initialization."""
841
841
842 args = arg_s.split(' ',1)
842 args = arg_s.split(' ',1)
843 magic_name = args[0]
843 magic_name = args[0]
844 magic_name = magic_name.lstrip(self.ESC_MAGIC)
844 magic_name = magic_name.lstrip(self.ESC_MAGIC)
845
845
846 try:
846 try:
847 magic_args = args[1]
847 magic_args = args[1]
848 except IndexError:
848 except IndexError:
849 magic_args = ''
849 magic_args = ''
850 fn = getattr(self,'magic_'+magic_name,None)
850 fn = getattr(self,'magic_'+magic_name,None)
851 if fn is None:
851 if fn is None:
852 error("Magic function `%s` not found." % magic_name)
852 error("Magic function `%s` not found." % magic_name)
853 else:
853 else:
854 magic_args = self.var_expand(magic_args)
854 magic_args = self.var_expand(magic_args)
855 return fn(magic_args)
855 return fn(magic_args)
856
856
857 def ipalias(self,arg_s):
857 def ipalias(self,arg_s):
858 """Call an alias by name.
858 """Call an alias by name.
859
859
860 Input: a string containing the name of the alias to call and any
860 Input: a string containing the name of the alias to call and any
861 additional arguments to be passed to the magic.
861 additional arguments to be passed to the magic.
862
862
863 ipalias('name -opt foo bar') is equivalent to typing at the ipython
863 ipalias('name -opt foo bar') is equivalent to typing at the ipython
864 prompt:
864 prompt:
865
865
866 In[1]: name -opt foo bar
866 In[1]: name -opt foo bar
867
867
868 To call an alias without arguments, simply use ipalias('name').
868 To call an alias without arguments, simply use ipalias('name').
869
869
870 This provides a proper Python function to call IPython's aliases in any
870 This provides a proper Python function to call IPython's aliases in any
871 valid Python code you can type at the interpreter, including loops and
871 valid Python code you can type at the interpreter, including loops and
872 compound statements. It is added by IPython to the Python builtin
872 compound statements. It is added by IPython to the Python builtin
873 namespace upon initialization."""
873 namespace upon initialization."""
874
874
875 args = arg_s.split(' ',1)
875 args = arg_s.split(' ',1)
876 alias_name = args[0]
876 alias_name = args[0]
877 try:
877 try:
878 alias_args = args[1]
878 alias_args = args[1]
879 except IndexError:
879 except IndexError:
880 alias_args = ''
880 alias_args = ''
881 if alias_name in self.alias_table:
881 if alias_name in self.alias_table:
882 self.call_alias(alias_name,alias_args)
882 self.call_alias(alias_name,alias_args)
883 else:
883 else:
884 error("Alias `%s` not found." % alias_name)
884 error("Alias `%s` not found." % alias_name)
885
885
886 def ipsystem(self,arg_s):
886 def ipsystem(self,arg_s):
887 """Make a system call, using IPython."""
887 """Make a system call, using IPython."""
888
888
889 self.system(arg_s)
889 self.system(arg_s)
890
890
891 def complete(self,text):
891 def complete(self,text):
892 """Return a sorted list of all possible completions on text.
892 """Return a sorted list of all possible completions on text.
893
893
894 Inputs:
894 Inputs:
895
895
896 - text: a string of text to be completed on.
896 - text: a string of text to be completed on.
897
897
898 This is a wrapper around the completion mechanism, similar to what
898 This is a wrapper around the completion mechanism, similar to what
899 readline does at the command line when the TAB key is hit. By
899 readline does at the command line when the TAB key is hit. By
900 exposing it as a method, it can be used by other non-readline
900 exposing it as a method, it can be used by other non-readline
901 environments (such as GUIs) for text completion.
901 environments (such as GUIs) for text completion.
902
902
903 Simple usage example:
903 Simple usage example:
904
904
905 In [1]: x = 'hello'
905 In [1]: x = 'hello'
906
906
907 In [2]: __IP.complete('x.l')
907 In [2]: __IP.complete('x.l')
908 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
908 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
909
909
910 complete = self.Completer.complete
910 complete = self.Completer.complete
911 state = 0
911 state = 0
912 # use a dict so we get unique keys, since ipyhton's multiple
912 # use a dict so we get unique keys, since ipyhton's multiple
913 # completers can return duplicates.
913 # completers can return duplicates.
914 comps = {}
914 comps = {}
915 while True:
915 while True:
916 newcomp = complete(text,state)
916 newcomp = complete(text,state)
917 if newcomp is None:
917 if newcomp is None:
918 break
918 break
919 comps[newcomp] = 1
919 comps[newcomp] = 1
920 state += 1
920 state += 1
921 outcomps = comps.keys()
921 outcomps = comps.keys()
922 outcomps.sort()
922 outcomps.sort()
923 return outcomps
923 return outcomps
924
924
925 def set_completer_frame(self, frame=None):
925 def set_completer_frame(self, frame=None):
926 if frame:
926 if frame:
927 self.Completer.namespace = frame.f_locals
927 self.Completer.namespace = frame.f_locals
928 self.Completer.global_namespace = frame.f_globals
928 self.Completer.global_namespace = frame.f_globals
929 else:
929 else:
930 self.Completer.namespace = self.user_ns
930 self.Completer.namespace = self.user_ns
931 self.Completer.global_namespace = self.user_global_ns
931 self.Completer.global_namespace = self.user_global_ns
932
932
933 def init_auto_alias(self):
933 def init_auto_alias(self):
934 """Define some aliases automatically.
934 """Define some aliases automatically.
935
935
936 These are ALL parameter-less aliases"""
936 These are ALL parameter-less aliases"""
937
937
938 for alias,cmd in self.auto_alias:
938 for alias,cmd in self.auto_alias:
939 self.alias_table[alias] = (0,cmd)
939 self.alias_table[alias] = (0,cmd)
940
940
941 def alias_table_validate(self,verbose=0):
941 def alias_table_validate(self,verbose=0):
942 """Update information about the alias table.
942 """Update information about the alias table.
943
943
944 In particular, make sure no Python keywords/builtins are in it."""
944 In particular, make sure no Python keywords/builtins are in it."""
945
945
946 no_alias = self.no_alias
946 no_alias = self.no_alias
947 for k in self.alias_table.keys():
947 for k in self.alias_table.keys():
948 if k in no_alias:
948 if k in no_alias:
949 del self.alias_table[k]
949 del self.alias_table[k]
950 if verbose:
950 if verbose:
951 print ("Deleting alias <%s>, it's a Python "
951 print ("Deleting alias <%s>, it's a Python "
952 "keyword or builtin." % k)
952 "keyword or builtin." % k)
953
953
954 def set_autoindent(self,value=None):
954 def set_autoindent(self,value=None):
955 """Set the autoindent flag, checking for readline support.
955 """Set the autoindent flag, checking for readline support.
956
956
957 If called with no arguments, it acts as a toggle."""
957 If called with no arguments, it acts as a toggle."""
958
958
959 if not self.has_readline:
959 if not self.has_readline:
960 if os.name == 'posix':
960 if os.name == 'posix':
961 warn("The auto-indent feature requires the readline library")
961 warn("The auto-indent feature requires the readline library")
962 self.autoindent = 0
962 self.autoindent = 0
963 return
963 return
964 if value is None:
964 if value is None:
965 self.autoindent = not self.autoindent
965 self.autoindent = not self.autoindent
966 else:
966 else:
967 self.autoindent = value
967 self.autoindent = value
968
968
969 def rc_set_toggle(self,rc_field,value=None):
969 def rc_set_toggle(self,rc_field,value=None):
970 """Set or toggle a field in IPython's rc config. structure.
970 """Set or toggle a field in IPython's rc config. structure.
971
971
972 If called with no arguments, it acts as a toggle.
972 If called with no arguments, it acts as a toggle.
973
973
974 If called with a non-existent field, the resulting AttributeError
974 If called with a non-existent field, the resulting AttributeError
975 exception will propagate out."""
975 exception will propagate out."""
976
976
977 rc_val = getattr(self.rc,rc_field)
977 rc_val = getattr(self.rc,rc_field)
978 if value is None:
978 if value is None:
979 value = not rc_val
979 value = not rc_val
980 setattr(self.rc,rc_field,value)
980 setattr(self.rc,rc_field,value)
981
981
982 def user_setup(self,ipythondir,rc_suffix,mode='install'):
982 def user_setup(self,ipythondir,rc_suffix,mode='install'):
983 """Install the user configuration directory.
983 """Install the user configuration directory.
984
984
985 Can be called when running for the first time or to upgrade the user's
985 Can be called when running for the first time or to upgrade the user's
986 .ipython/ directory with the mode parameter. Valid modes are 'install'
986 .ipython/ directory with the mode parameter. Valid modes are 'install'
987 and 'upgrade'."""
987 and 'upgrade'."""
988
988
989 def wait():
989 def wait():
990 try:
990 try:
991 raw_input("Please press <RETURN> to start IPython.")
991 raw_input("Please press <RETURN> to start IPython.")
992 except EOFError:
992 except EOFError:
993 print >> Term.cout
993 print >> Term.cout
994 print '*'*70
994 print '*'*70
995
995
996 cwd = os.getcwd() # remember where we started
996 cwd = os.getcwd() # remember where we started
997 glb = glob.glob
997 glb = glob.glob
998 print '*'*70
998 print '*'*70
999 if mode == 'install':
999 if mode == 'install':
1000 print \
1000 print \
1001 """Welcome to IPython. I will try to create a personal configuration directory
1001 """Welcome to IPython. I will try to create a personal configuration directory
1002 where you can customize many aspects of IPython's functionality in:\n"""
1002 where you can customize many aspects of IPython's functionality in:\n"""
1003 else:
1003 else:
1004 print 'I am going to upgrade your configuration in:'
1004 print 'I am going to upgrade your configuration in:'
1005
1005
1006 print ipythondir
1006 print ipythondir
1007
1007
1008 rcdirend = os.path.join('IPython','UserConfig')
1008 rcdirend = os.path.join('IPython','UserConfig')
1009 cfg = lambda d: os.path.join(d,rcdirend)
1009 cfg = lambda d: os.path.join(d,rcdirend)
1010 try:
1010 try:
1011 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1011 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1012 except IOError:
1012 except IOError:
1013 warning = """
1013 warning = """
1014 Installation error. IPython's directory was not found.
1014 Installation error. IPython's directory was not found.
1015
1015
1016 Check the following:
1016 Check the following:
1017
1017
1018 The ipython/IPython directory should be in a directory belonging to your
1018 The ipython/IPython directory should be in a directory belonging to your
1019 PYTHONPATH environment variable (that is, it should be in a directory
1019 PYTHONPATH environment variable (that is, it should be in a directory
1020 belonging to sys.path). You can copy it explicitly there or just link to it.
1020 belonging to sys.path). You can copy it explicitly there or just link to it.
1021
1021
1022 IPython will proceed with builtin defaults.
1022 IPython will proceed with builtin defaults.
1023 """
1023 """
1024 warn(warning)
1024 warn(warning)
1025 wait()
1025 wait()
1026 return
1026 return
1027
1027
1028 if mode == 'install':
1028 if mode == 'install':
1029 try:
1029 try:
1030 shutil.copytree(rcdir,ipythondir)
1030 shutil.copytree(rcdir,ipythondir)
1031 os.chdir(ipythondir)
1031 os.chdir(ipythondir)
1032 rc_files = glb("ipythonrc*")
1032 rc_files = glb("ipythonrc*")
1033 for rc_file in rc_files:
1033 for rc_file in rc_files:
1034 os.rename(rc_file,rc_file+rc_suffix)
1034 os.rename(rc_file,rc_file+rc_suffix)
1035 except:
1035 except:
1036 warning = """
1036 warning = """
1037
1037
1038 There was a problem with the installation:
1038 There was a problem with the installation:
1039 %s
1039 %s
1040 Try to correct it or contact the developers if you think it's a bug.
1040 Try to correct it or contact the developers if you think it's a bug.
1041 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1041 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1042 warn(warning)
1042 warn(warning)
1043 wait()
1043 wait()
1044 return
1044 return
1045
1045
1046 elif mode == 'upgrade':
1046 elif mode == 'upgrade':
1047 try:
1047 try:
1048 os.chdir(ipythondir)
1048 os.chdir(ipythondir)
1049 except:
1049 except:
1050 print """
1050 print """
1051 Can not upgrade: changing to directory %s failed. Details:
1051 Can not upgrade: changing to directory %s failed. Details:
1052 %s
1052 %s
1053 """ % (ipythondir,sys.exc_info()[1])
1053 """ % (ipythondir,sys.exc_info()[1])
1054 wait()
1054 wait()
1055 return
1055 return
1056 else:
1056 else:
1057 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1057 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1058 for new_full_path in sources:
1058 for new_full_path in sources:
1059 new_filename = os.path.basename(new_full_path)
1059 new_filename = os.path.basename(new_full_path)
1060 if new_filename.startswith('ipythonrc'):
1060 if new_filename.startswith('ipythonrc'):
1061 new_filename = new_filename + rc_suffix
1061 new_filename = new_filename + rc_suffix
1062 # The config directory should only contain files, skip any
1062 # The config directory should only contain files, skip any
1063 # directories which may be there (like CVS)
1063 # directories which may be there (like CVS)
1064 if os.path.isdir(new_full_path):
1064 if os.path.isdir(new_full_path):
1065 continue
1065 continue
1066 if os.path.exists(new_filename):
1066 if os.path.exists(new_filename):
1067 old_file = new_filename+'.old'
1067 old_file = new_filename+'.old'
1068 if os.path.exists(old_file):
1068 if os.path.exists(old_file):
1069 os.remove(old_file)
1069 os.remove(old_file)
1070 os.rename(new_filename,old_file)
1070 os.rename(new_filename,old_file)
1071 shutil.copy(new_full_path,new_filename)
1071 shutil.copy(new_full_path,new_filename)
1072 else:
1072 else:
1073 raise ValueError,'unrecognized mode for install:',`mode`
1073 raise ValueError,'unrecognized mode for install:',`mode`
1074
1074
1075 # Fix line-endings to those native to each platform in the config
1075 # Fix line-endings to those native to each platform in the config
1076 # directory.
1076 # directory.
1077 try:
1077 try:
1078 os.chdir(ipythondir)
1078 os.chdir(ipythondir)
1079 except:
1079 except:
1080 print """
1080 print """
1081 Problem: changing to directory %s failed.
1081 Problem: changing to directory %s failed.
1082 Details:
1082 Details:
1083 %s
1083 %s
1084
1084
1085 Some configuration files may have incorrect line endings. This should not
1085 Some configuration files may have incorrect line endings. This should not
1086 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1086 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1087 wait()
1087 wait()
1088 else:
1088 else:
1089 for fname in glb('ipythonrc*'):
1089 for fname in glb('ipythonrc*'):
1090 try:
1090 try:
1091 native_line_ends(fname,backup=0)
1091 native_line_ends(fname,backup=0)
1092 except IOError:
1092 except IOError:
1093 pass
1093 pass
1094
1094
1095 if mode == 'install':
1095 if mode == 'install':
1096 print """
1096 print """
1097 Successful installation!
1097 Successful installation!
1098
1098
1099 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1099 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1100 IPython manual (there are both HTML and PDF versions supplied with the
1100 IPython manual (there are both HTML and PDF versions supplied with the
1101 distribution) to make sure that your system environment is properly configured
1101 distribution) to make sure that your system environment is properly configured
1102 to take advantage of IPython's features.
1102 to take advantage of IPython's features.
1103
1103
1104 Important note: the configuration system has changed! The old system is
1104 Important note: the configuration system has changed! The old system is
1105 still in place, but its setting may be partly overridden by the settings in
1105 still in place, but its setting may be partly overridden by the settings in
1106 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1106 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1107 if some of the new settings bother you.
1107 if some of the new settings bother you.
1108
1108
1109 """
1109 """
1110 else:
1110 else:
1111 print """
1111 print """
1112 Successful upgrade!
1112 Successful upgrade!
1113
1113
1114 All files in your directory:
1114 All files in your directory:
1115 %(ipythondir)s
1115 %(ipythondir)s
1116 which would have been overwritten by the upgrade were backed up with a .old
1116 which would have been overwritten by the upgrade were backed up with a .old
1117 extension. If you had made particular customizations in those files you may
1117 extension. If you had made particular customizations in those files you may
1118 want to merge them back into the new files.""" % locals()
1118 want to merge them back into the new files.""" % locals()
1119 wait()
1119 wait()
1120 os.chdir(cwd)
1120 os.chdir(cwd)
1121 # end user_setup()
1121 # end user_setup()
1122
1122
1123 def atexit_operations(self):
1123 def atexit_operations(self):
1124 """This will be executed at the time of exit.
1124 """This will be executed at the time of exit.
1125
1125
1126 Saving of persistent data should be performed here. """
1126 Saving of persistent data should be performed here. """
1127
1127
1128 #print '*** IPython exit cleanup ***' # dbg
1128 #print '*** IPython exit cleanup ***' # dbg
1129 # input history
1129 # input history
1130 self.savehist()
1130 self.savehist()
1131
1131
1132 # Cleanup all tempfiles left around
1132 # Cleanup all tempfiles left around
1133 for tfile in self.tempfiles:
1133 for tfile in self.tempfiles:
1134 try:
1134 try:
1135 os.unlink(tfile)
1135 os.unlink(tfile)
1136 except OSError:
1136 except OSError:
1137 pass
1137 pass
1138
1138
1139 # save the "persistent data" catch-all dictionary
1139 # save the "persistent data" catch-all dictionary
1140 try:
1140 try:
1141 pickle.dump(self.persist, open(self.persist_fname,"w"))
1141 pickle.dump(self.persist, open(self.persist_fname,"w"))
1142 except:
1142 except:
1143 print "*** ERROR *** persistent data saving failed."
1143 print "*** ERROR *** persistent data saving failed."
1144
1144
1145 def savehist(self):
1145 def savehist(self):
1146 """Save input history to a file (via readline library)."""
1146 """Save input history to a file (via readline library)."""
1147 try:
1147 try:
1148 self.readline.write_history_file(self.histfile)
1148 self.readline.write_history_file(self.histfile)
1149 except:
1149 except:
1150 print 'Unable to save IPython command history to file: ' + \
1150 print 'Unable to save IPython command history to file: ' + \
1151 `self.histfile`
1151 `self.histfile`
1152
1152
1153 def pre_readline(self):
1153 def pre_readline(self):
1154 """readline hook to be used at the start of each line.
1154 """readline hook to be used at the start of each line.
1155
1155
1156 Currently it handles auto-indent only."""
1156 Currently it handles auto-indent only."""
1157
1157
1158 #debugp('self.indent_current_nsp','pre_readline:')
1158 #debugp('self.indent_current_nsp','pre_readline:')
1159 self.readline.insert_text(self.indent_current_str())
1159 self.readline.insert_text(self.indent_current_str())
1160
1160
1161 def init_readline(self):
1161 def init_readline(self):
1162 """Command history completion/saving/reloading."""
1162 """Command history completion/saving/reloading."""
1163 try:
1163 try:
1164 import readline
1164 import readline
1165 except ImportError:
1165 except ImportError:
1166 self.has_readline = 0
1166 self.has_readline = 0
1167 self.readline = None
1167 self.readline = None
1168 # no point in bugging windows users with this every time:
1168 # no point in bugging windows users with this every time:
1169 if os.name == 'posix':
1169 if os.name == 'posix':
1170 warn('Readline services not available on this platform.')
1170 warn('Readline services not available on this platform.')
1171 else:
1171 else:
1172 import atexit
1172 import atexit
1173 from IPython.completer import IPCompleter
1173 from IPython.completer import IPCompleter
1174 self.Completer = IPCompleter(self,
1174 self.Completer = IPCompleter(self,
1175 self.user_ns,
1175 self.user_ns,
1176 self.user_global_ns,
1176 self.user_global_ns,
1177 self.rc.readline_omit__names,
1177 self.rc.readline_omit__names,
1178 self.alias_table)
1178 self.alias_table)
1179
1179
1180 # Platform-specific configuration
1180 # Platform-specific configuration
1181 if os.name == 'nt':
1181 if os.name == 'nt':
1182 self.readline_startup_hook = readline.set_pre_input_hook
1182 self.readline_startup_hook = readline.set_pre_input_hook
1183 else:
1183 else:
1184 self.readline_startup_hook = readline.set_startup_hook
1184 self.readline_startup_hook = readline.set_startup_hook
1185
1185
1186 # Load user's initrc file (readline config)
1186 # Load user's initrc file (readline config)
1187 inputrc_name = os.environ.get('INPUTRC')
1187 inputrc_name = os.environ.get('INPUTRC')
1188 if inputrc_name is None:
1188 if inputrc_name is None:
1189 home_dir = get_home_dir()
1189 home_dir = get_home_dir()
1190 if home_dir is not None:
1190 if home_dir is not None:
1191 inputrc_name = os.path.join(home_dir,'.inputrc')
1191 inputrc_name = os.path.join(home_dir,'.inputrc')
1192 if os.path.isfile(inputrc_name):
1192 if os.path.isfile(inputrc_name):
1193 try:
1193 try:
1194 readline.read_init_file(inputrc_name)
1194 readline.read_init_file(inputrc_name)
1195 except:
1195 except:
1196 warn('Problems reading readline initialization file <%s>'
1196 warn('Problems reading readline initialization file <%s>'
1197 % inputrc_name)
1197 % inputrc_name)
1198
1198
1199 self.has_readline = 1
1199 self.has_readline = 1
1200 self.readline = readline
1200 self.readline = readline
1201 # save this in sys so embedded copies can restore it properly
1201 # save this in sys so embedded copies can restore it properly
1202 sys.ipcompleter = self.Completer.complete
1202 sys.ipcompleter = self.Completer.complete
1203 readline.set_completer(self.Completer.complete)
1203 readline.set_completer(self.Completer.complete)
1204
1204
1205 # Configure readline according to user's prefs
1205 # Configure readline according to user's prefs
1206 for rlcommand in self.rc.readline_parse_and_bind:
1206 for rlcommand in self.rc.readline_parse_and_bind:
1207 readline.parse_and_bind(rlcommand)
1207 readline.parse_and_bind(rlcommand)
1208
1208
1209 # remove some chars from the delimiters list
1209 # remove some chars from the delimiters list
1210 delims = readline.get_completer_delims()
1210 delims = readline.get_completer_delims()
1211 delims = delims.translate(string._idmap,
1211 delims = delims.translate(string._idmap,
1212 self.rc.readline_remove_delims)
1212 self.rc.readline_remove_delims)
1213 readline.set_completer_delims(delims)
1213 readline.set_completer_delims(delims)
1214 # otherwise we end up with a monster history after a while:
1214 # otherwise we end up with a monster history after a while:
1215 readline.set_history_length(1000)
1215 readline.set_history_length(1000)
1216 try:
1216 try:
1217 #print '*** Reading readline history' # dbg
1217 #print '*** Reading readline history' # dbg
1218 readline.read_history_file(self.histfile)
1218 readline.read_history_file(self.histfile)
1219 except IOError:
1219 except IOError:
1220 pass # It doesn't exist yet.
1220 pass # It doesn't exist yet.
1221
1221
1222 atexit.register(self.atexit_operations)
1222 atexit.register(self.atexit_operations)
1223 del atexit
1223 del atexit
1224
1224
1225 # Configure auto-indent for all platforms
1225 # Configure auto-indent for all platforms
1226 self.set_autoindent(self.rc.autoindent)
1226 self.set_autoindent(self.rc.autoindent)
1227
1227
1228 def _should_recompile(self,e):
1228 def _should_recompile(self,e):
1229 """Utility routine for edit_syntax_error"""
1229 """Utility routine for edit_syntax_error"""
1230
1230
1231 if e.filename in ('<ipython console>','<input>','<string>',
1231 if e.filename in ('<ipython console>','<input>','<string>',
1232 '<console>',None):
1232 '<console>',None):
1233
1233
1234 return False
1234 return False
1235 try:
1235 try:
1236 if not ask_yes_no('Return to editor to correct syntax error? '
1236 if not ask_yes_no('Return to editor to correct syntax error? '
1237 '[Y/n] ','y'):
1237 '[Y/n] ','y'):
1238 return False
1238 return False
1239 except EOFError:
1239 except EOFError:
1240 return False
1240 return False
1241
1241
1242 def int0(x):
1242 def int0(x):
1243 try:
1243 try:
1244 return int(x)
1244 return int(x)
1245 except TypeError:
1245 except TypeError:
1246 return 0
1246 return 0
1247 # always pass integer line and offset values to editor hook
1247 # always pass integer line and offset values to editor hook
1248 self.hooks.fix_error_editor(e.filename,
1248 self.hooks.fix_error_editor(e.filename,
1249 int0(e.lineno),int0(e.offset),e.msg)
1249 int0(e.lineno),int0(e.offset),e.msg)
1250 return True
1250 return True
1251
1251
1252 def edit_syntax_error(self):
1252 def edit_syntax_error(self):
1253 """The bottom half of the syntax error handler called in the main loop.
1253 """The bottom half of the syntax error handler called in the main loop.
1254
1254
1255 Loop until syntax error is fixed or user cancels.
1255 Loop until syntax error is fixed or user cancels.
1256 """
1256 """
1257
1257
1258 while self.SyntaxTB.last_syntax_error:
1258 while self.SyntaxTB.last_syntax_error:
1259 # copy and clear last_syntax_error
1259 # copy and clear last_syntax_error
1260 err = self.SyntaxTB.clear_err_state()
1260 err = self.SyntaxTB.clear_err_state()
1261 if not self._should_recompile(err):
1261 if not self._should_recompile(err):
1262 return
1262 return
1263 try:
1263 try:
1264 # may set last_syntax_error again if a SyntaxError is raised
1264 # may set last_syntax_error again if a SyntaxError is raised
1265 self.safe_execfile(err.filename,self.shell.user_ns)
1265 self.safe_execfile(err.filename,self.shell.user_ns)
1266 except:
1266 except:
1267 self.showtraceback()
1267 self.showtraceback()
1268 else:
1268 else:
1269 f = file(err.filename)
1269 f = file(err.filename)
1270 try:
1270 try:
1271 sys.displayhook(f.read())
1271 sys.displayhook(f.read())
1272 finally:
1272 finally:
1273 f.close()
1273 f.close()
1274
1274
1275 def showsyntaxerror(self, filename=None):
1275 def showsyntaxerror(self, filename=None):
1276 """Display the syntax error that just occurred.
1276 """Display the syntax error that just occurred.
1277
1277
1278 This doesn't display a stack trace because there isn't one.
1278 This doesn't display a stack trace because there isn't one.
1279
1279
1280 If a filename is given, it is stuffed in the exception instead
1280 If a filename is given, it is stuffed in the exception instead
1281 of what was there before (because Python's parser always uses
1281 of what was there before (because Python's parser always uses
1282 "<string>" when reading from a string).
1282 "<string>" when reading from a string).
1283 """
1283 """
1284 etype, value, last_traceback = sys.exc_info()
1284 etype, value, last_traceback = sys.exc_info()
1285 if filename and etype is SyntaxError:
1285 if filename and etype is SyntaxError:
1286 # Work hard to stuff the correct filename in the exception
1286 # Work hard to stuff the correct filename in the exception
1287 try:
1287 try:
1288 msg, (dummy_filename, lineno, offset, line) = value
1288 msg, (dummy_filename, lineno, offset, line) = value
1289 except:
1289 except:
1290 # Not the format we expect; leave it alone
1290 # Not the format we expect; leave it alone
1291 pass
1291 pass
1292 else:
1292 else:
1293 # Stuff in the right filename
1293 # Stuff in the right filename
1294 try:
1294 try:
1295 # Assume SyntaxError is a class exception
1295 # Assume SyntaxError is a class exception
1296 value = SyntaxError(msg, (filename, lineno, offset, line))
1296 value = SyntaxError(msg, (filename, lineno, offset, line))
1297 except:
1297 except:
1298 # If that failed, assume SyntaxError is a string
1298 # If that failed, assume SyntaxError is a string
1299 value = msg, (filename, lineno, offset, line)
1299 value = msg, (filename, lineno, offset, line)
1300 self.SyntaxTB(etype,value,[])
1300 self.SyntaxTB(etype,value,[])
1301
1301
1302 def debugger(self):
1302 def debugger(self):
1303 """Call the pdb debugger."""
1303 """Call the pdb debugger."""
1304
1304
1305 if not self.rc.pdb:
1305 if not self.rc.pdb:
1306 return
1306 return
1307 pdb.pm()
1307 pdb.pm()
1308
1308
1309 def showtraceback(self,exc_tuple = None,filename=None):
1309 def showtraceback(self,exc_tuple = None,filename=None):
1310 """Display the exception that just occurred."""
1310 """Display the exception that just occurred."""
1311
1311
1312 # Though this won't be called by syntax errors in the input line,
1312 # Though this won't be called by syntax errors in the input line,
1313 # there may be SyntaxError cases whith imported code.
1313 # there may be SyntaxError cases whith imported code.
1314 if exc_tuple is None:
1314 if exc_tuple is None:
1315 type, value, tb = sys.exc_info()
1315 type, value, tb = sys.exc_info()
1316 else:
1316 else:
1317 type, value, tb = exc_tuple
1317 type, value, tb = exc_tuple
1318 if type is SyntaxError:
1318 if type is SyntaxError:
1319 self.showsyntaxerror(filename)
1319 self.showsyntaxerror(filename)
1320 else:
1320 else:
1321 self.InteractiveTB()
1321 self.InteractiveTB()
1322 if self.InteractiveTB.call_pdb and self.has_readline:
1322 if self.InteractiveTB.call_pdb and self.has_readline:
1323 # pdb mucks up readline, fix it back
1323 # pdb mucks up readline, fix it back
1324 self.readline.set_completer(self.Completer.complete)
1324 self.readline.set_completer(self.Completer.complete)
1325
1325
1326 def mainloop(self,banner=None):
1326 def mainloop(self,banner=None):
1327 """Creates the local namespace and starts the mainloop.
1327 """Creates the local namespace and starts the mainloop.
1328
1328
1329 If an optional banner argument is given, it will override the
1329 If an optional banner argument is given, it will override the
1330 internally created default banner."""
1330 internally created default banner."""
1331
1331
1332 if self.rc.c: # Emulate Python's -c option
1332 if self.rc.c: # Emulate Python's -c option
1333 self.exec_init_cmd()
1333 self.exec_init_cmd()
1334 if banner is None:
1334 if banner is None:
1335 if self.rc.banner:
1335 if self.rc.banner:
1336 banner = self.BANNER+self.banner2
1336 banner = self.BANNER+self.banner2
1337 else:
1337 else:
1338 banner = ''
1338 banner = ''
1339 self.interact(banner)
1339 self.interact(banner)
1340
1340
1341 def exec_init_cmd(self):
1341 def exec_init_cmd(self):
1342 """Execute a command given at the command line.
1342 """Execute a command given at the command line.
1343
1343
1344 This emulates Python's -c option."""
1344 This emulates Python's -c option."""
1345
1345
1346 sys.argv = ['-c']
1346 sys.argv = ['-c']
1347 self.push(self.rc.c)
1347 self.push(self.rc.c)
1348
1348
1349 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1349 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1350 """Embeds IPython into a running python program.
1350 """Embeds IPython into a running python program.
1351
1351
1352 Input:
1352 Input:
1353
1353
1354 - header: An optional header message can be specified.
1354 - header: An optional header message can be specified.
1355
1355
1356 - local_ns, global_ns: working namespaces. If given as None, the
1356 - local_ns, global_ns: working namespaces. If given as None, the
1357 IPython-initialized one is updated with __main__.__dict__, so that
1357 IPython-initialized one is updated with __main__.__dict__, so that
1358 program variables become visible but user-specific configuration
1358 program variables become visible but user-specific configuration
1359 remains possible.
1359 remains possible.
1360
1360
1361 - stack_depth: specifies how many levels in the stack to go to
1361 - stack_depth: specifies how many levels in the stack to go to
1362 looking for namespaces (when local_ns and global_ns are None). This
1362 looking for namespaces (when local_ns and global_ns are None). This
1363 allows an intermediate caller to make sure that this function gets
1363 allows an intermediate caller to make sure that this function gets
1364 the namespace from the intended level in the stack. By default (0)
1364 the namespace from the intended level in the stack. By default (0)
1365 it will get its locals and globals from the immediate caller.
1365 it will get its locals and globals from the immediate caller.
1366
1366
1367 Warning: it's possible to use this in a program which is being run by
1367 Warning: it's possible to use this in a program which is being run by
1368 IPython itself (via %run), but some funny things will happen (a few
1368 IPython itself (via %run), but some funny things will happen (a few
1369 globals get overwritten). In the future this will be cleaned up, as
1369 globals get overwritten). In the future this will be cleaned up, as
1370 there is no fundamental reason why it can't work perfectly."""
1370 there is no fundamental reason why it can't work perfectly."""
1371
1371
1372 # Get locals and globals from caller
1372 # Get locals and globals from caller
1373 if local_ns is None or global_ns is None:
1373 if local_ns is None or global_ns is None:
1374 call_frame = sys._getframe(stack_depth).f_back
1374 call_frame = sys._getframe(stack_depth).f_back
1375
1375
1376 if local_ns is None:
1376 if local_ns is None:
1377 local_ns = call_frame.f_locals
1377 local_ns = call_frame.f_locals
1378 if global_ns is None:
1378 if global_ns is None:
1379 global_ns = call_frame.f_globals
1379 global_ns = call_frame.f_globals
1380
1380
1381 # Update namespaces and fire up interpreter
1381 # Update namespaces and fire up interpreter
1382
1382
1383 # The global one is easy, we can just throw it in
1383 # The global one is easy, we can just throw it in
1384 self.user_global_ns = global_ns
1384 self.user_global_ns = global_ns
1385
1385
1386 # but the user/local one is tricky: ipython needs it to store internal
1386 # but the user/local one is tricky: ipython needs it to store internal
1387 # data, but we also need the locals. We'll copy locals in the user
1387 # data, but we also need the locals. We'll copy locals in the user
1388 # one, but will track what got copied so we can delete them at exit.
1388 # one, but will track what got copied so we can delete them at exit.
1389 # This is so that a later embedded call doesn't see locals from a
1389 # This is so that a later embedded call doesn't see locals from a
1390 # previous call (which most likely existed in a separate scope).
1390 # previous call (which most likely existed in a separate scope).
1391 local_varnames = local_ns.keys()
1391 local_varnames = local_ns.keys()
1392 self.user_ns.update(local_ns)
1392 self.user_ns.update(local_ns)
1393
1393
1394 # Patch for global embedding to make sure that things don't overwrite
1394 # Patch for global embedding to make sure that things don't overwrite
1395 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1395 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1396 # FIXME. Test this a bit more carefully (the if.. is new)
1396 # FIXME. Test this a bit more carefully (the if.. is new)
1397 if local_ns is None and global_ns is None:
1397 if local_ns is None and global_ns is None:
1398 self.user_global_ns.update(__main__.__dict__)
1398 self.user_global_ns.update(__main__.__dict__)
1399
1399
1400 # make sure the tab-completer has the correct frame information, so it
1400 # make sure the tab-completer has the correct frame information, so it
1401 # actually completes using the frame's locals/globals
1401 # actually completes using the frame's locals/globals
1402 self.set_completer_frame()
1402 self.set_completer_frame()
1403
1403
1404 # before activating the interactive mode, we need to make sure that
1404 # before activating the interactive mode, we need to make sure that
1405 # all names in the builtin namespace needed by ipython point to
1405 # all names in the builtin namespace needed by ipython point to
1406 # ourselves, and not to other instances.
1406 # ourselves, and not to other instances.
1407 self.add_builtins()
1407 self.add_builtins()
1408
1408
1409 self.interact(header)
1409 self.interact(header)
1410
1410
1411 # now, purge out the user namespace from anything we might have added
1411 # now, purge out the user namespace from anything we might have added
1412 # from the caller's local namespace
1412 # from the caller's local namespace
1413 delvar = self.user_ns.pop
1413 delvar = self.user_ns.pop
1414 for var in local_varnames:
1414 for var in local_varnames:
1415 delvar(var,None)
1415 delvar(var,None)
1416 # and clean builtins we may have overridden
1416 # and clean builtins we may have overridden
1417 self.clean_builtins()
1417 self.clean_builtins()
1418
1418
1419 def interact(self, banner=None):
1419 def interact(self, banner=None):
1420 """Closely emulate the interactive Python console.
1420 """Closely emulate the interactive Python console.
1421
1421
1422 The optional banner argument specify the banner to print
1422 The optional banner argument specify the banner to print
1423 before the first interaction; by default it prints a banner
1423 before the first interaction; by default it prints a banner
1424 similar to the one printed by the real Python interpreter,
1424 similar to the one printed by the real Python interpreter,
1425 followed by the current class name in parentheses (so as not
1425 followed by the current class name in parentheses (so as not
1426 to confuse this with the real interpreter -- since it's so
1426 to confuse this with the real interpreter -- since it's so
1427 close!).
1427 close!).
1428
1428
1429 """
1429 """
1430 cprt = 'Type "copyright", "credits" or "license" for more information.'
1430 cprt = 'Type "copyright", "credits" or "license" for more information.'
1431 if banner is None:
1431 if banner is None:
1432 self.write("Python %s on %s\n%s\n(%s)\n" %
1432 self.write("Python %s on %s\n%s\n(%s)\n" %
1433 (sys.version, sys.platform, cprt,
1433 (sys.version, sys.platform, cprt,
1434 self.__class__.__name__))
1434 self.__class__.__name__))
1435 else:
1435 else:
1436 self.write(banner)
1436 self.write(banner)
1437
1437
1438 more = 0
1438 more = 0
1439
1439
1440 # Mark activity in the builtins
1440 # Mark activity in the builtins
1441 __builtin__.__dict__['__IPYTHON__active'] += 1
1441 __builtin__.__dict__['__IPYTHON__active'] += 1
1442
1442
1443 # exit_now is set by a call to %Exit or %Quit
1443 # exit_now is set by a call to %Exit or %Quit
1444 self.exit_now = False
1444 self.exit_now = False
1445 while not self.exit_now:
1445 while not self.exit_now:
1446
1446
1447 try:
1447 try:
1448 if more:
1448 if more:
1449 prompt = self.outputcache.prompt2
1449 prompt = self.outputcache.prompt2
1450 if self.autoindent:
1450 if self.autoindent:
1451 self.readline_startup_hook(self.pre_readline)
1451 self.readline_startup_hook(self.pre_readline)
1452 else:
1452 else:
1453 prompt = self.outputcache.prompt1
1453 prompt = self.outputcache.prompt1
1454 try:
1454 try:
1455 line = self.raw_input(prompt,more)
1455 line = self.raw_input(prompt,more)
1456 if self.autoindent:
1456 if self.autoindent:
1457 self.readline_startup_hook(None)
1457 self.readline_startup_hook(None)
1458 except EOFError:
1458 except EOFError:
1459 if self.autoindent:
1459 if self.autoindent:
1460 self.readline_startup_hook(None)
1460 self.readline_startup_hook(None)
1461 self.write("\n")
1461 self.write("\n")
1462 self.exit()
1462 self.exit()
1463 except:
1464 # exceptions here are VERY RARE, but they can be triggered
1465 # asynchronously by signal handlers, for example.
1466 self.showtraceback()
1463 else:
1467 else:
1464 more = self.push(line)
1468 more = self.push(line)
1465
1469
1466 if (self.SyntaxTB.last_syntax_error and
1470 if (self.SyntaxTB.last_syntax_error and
1467 self.rc.autoedit_syntax):
1471 self.rc.autoedit_syntax):
1468 self.edit_syntax_error()
1472 self.edit_syntax_error()
1469
1473
1470 except KeyboardInterrupt:
1474 except KeyboardInterrupt:
1471 self.write("\nKeyboardInterrupt\n")
1475 self.write("\nKeyboardInterrupt\n")
1472 self.resetbuffer()
1476 self.resetbuffer()
1473 more = 0
1477 more = 0
1474 # keep cache in sync with the prompt counter:
1478 # keep cache in sync with the prompt counter:
1475 self.outputcache.prompt_count -= 1
1479 self.outputcache.prompt_count -= 1
1476
1480
1477 if self.autoindent:
1481 if self.autoindent:
1478 self.indent_current_nsp = 0
1482 self.indent_current_nsp = 0
1479
1483
1480 except bdb.BdbQuit:
1484 except bdb.BdbQuit:
1481 warn("The Python debugger has exited with a BdbQuit exception.\n"
1485 warn("The Python debugger has exited with a BdbQuit exception.\n"
1482 "Because of how pdb handles the stack, it is impossible\n"
1486 "Because of how pdb handles the stack, it is impossible\n"
1483 "for IPython to properly format this particular exception.\n"
1487 "for IPython to properly format this particular exception.\n"
1484 "IPython will resume normal operation.")
1488 "IPython will resume normal operation.")
1485
1489
1486 # We are off again...
1490 # We are off again...
1487 __builtin__.__dict__['__IPYTHON__active'] -= 1
1491 __builtin__.__dict__['__IPYTHON__active'] -= 1
1488
1492
1489 def excepthook(self, type, value, tb):
1493 def excepthook(self, type, value, tb):
1490 """One more defense for GUI apps that call sys.excepthook.
1494 """One more defense for GUI apps that call sys.excepthook.
1491
1495
1492 GUI frameworks like wxPython trap exceptions and call
1496 GUI frameworks like wxPython trap exceptions and call
1493 sys.excepthook themselves. I guess this is a feature that
1497 sys.excepthook themselves. I guess this is a feature that
1494 enables them to keep running after exceptions that would
1498 enables them to keep running after exceptions that would
1495 otherwise kill their mainloop. This is a bother for IPython
1499 otherwise kill their mainloop. This is a bother for IPython
1496 which excepts to catch all of the program exceptions with a try:
1500 which excepts to catch all of the program exceptions with a try:
1497 except: statement.
1501 except: statement.
1498
1502
1499 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1503 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1500 any app directly invokes sys.excepthook, it will look to the user like
1504 any app directly invokes sys.excepthook, it will look to the user like
1501 IPython crashed. In order to work around this, we can disable the
1505 IPython crashed. In order to work around this, we can disable the
1502 CrashHandler and replace it with this excepthook instead, which prints a
1506 CrashHandler and replace it with this excepthook instead, which prints a
1503 regular traceback using our InteractiveTB. In this fashion, apps which
1507 regular traceback using our InteractiveTB. In this fashion, apps which
1504 call sys.excepthook will generate a regular-looking exception from
1508 call sys.excepthook will generate a regular-looking exception from
1505 IPython, and the CrashHandler will only be triggered by real IPython
1509 IPython, and the CrashHandler will only be triggered by real IPython
1506 crashes.
1510 crashes.
1507
1511
1508 This hook should be used sparingly, only in places which are not likely
1512 This hook should be used sparingly, only in places which are not likely
1509 to be true IPython errors.
1513 to be true IPython errors.
1510 """
1514 """
1511
1515
1512 self.InteractiveTB(type, value, tb, tb_offset=0)
1516 self.InteractiveTB(type, value, tb, tb_offset=0)
1513 if self.InteractiveTB.call_pdb and self.has_readline:
1517 if self.InteractiveTB.call_pdb and self.has_readline:
1514 self.readline.set_completer(self.Completer.complete)
1518 self.readline.set_completer(self.Completer.complete)
1515
1519
1516 def call_alias(self,alias,rest=''):
1520 def call_alias(self,alias,rest=''):
1517 """Call an alias given its name and the rest of the line.
1521 """Call an alias given its name and the rest of the line.
1518
1522
1519 This function MUST be given a proper alias, because it doesn't make
1523 This function MUST be given a proper alias, because it doesn't make
1520 any checks when looking up into the alias table. The caller is
1524 any checks when looking up into the alias table. The caller is
1521 responsible for invoking it only with a valid alias."""
1525 responsible for invoking it only with a valid alias."""
1522
1526
1523 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1527 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1524 nargs,cmd = self.alias_table[alias]
1528 nargs,cmd = self.alias_table[alias]
1525 # Expand the %l special to be the user's input line
1529 # Expand the %l special to be the user's input line
1526 if cmd.find('%l') >= 0:
1530 if cmd.find('%l') >= 0:
1527 cmd = cmd.replace('%l',rest)
1531 cmd = cmd.replace('%l',rest)
1528 rest = ''
1532 rest = ''
1529 if nargs==0:
1533 if nargs==0:
1530 # Simple, argument-less aliases
1534 # Simple, argument-less aliases
1531 cmd = '%s %s' % (cmd,rest)
1535 cmd = '%s %s' % (cmd,rest)
1532 else:
1536 else:
1533 # Handle aliases with positional arguments
1537 # Handle aliases with positional arguments
1534 args = rest.split(None,nargs)
1538 args = rest.split(None,nargs)
1535 if len(args)< nargs:
1539 if len(args)< nargs:
1536 error('Alias <%s> requires %s arguments, %s given.' %
1540 error('Alias <%s> requires %s arguments, %s given.' %
1537 (alias,nargs,len(args)))
1541 (alias,nargs,len(args)))
1538 return
1542 return
1539 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1543 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1540 # Now call the macro, evaluating in the user's namespace
1544 # Now call the macro, evaluating in the user's namespace
1541 try:
1545 try:
1542 self.system(cmd)
1546 self.system(cmd)
1543 except:
1547 except:
1544 self.showtraceback()
1548 self.showtraceback()
1545
1549
1546 def indent_current_str(self):
1550 def indent_current_str(self):
1547 """return the current level of indentation as a string"""
1551 """return the current level of indentation as a string"""
1548 return self.indent_current_nsp * ' '
1552 return self.indent_current_nsp * ' '
1549
1553
1550 def autoindent_update(self,line):
1554 def autoindent_update(self,line):
1551 """Keep track of the indent level."""
1555 """Keep track of the indent level."""
1552
1556
1553 debugp('line','autoindent_update:')
1557 #import traceback; traceback.print_stack() # dbg
1558 debugp('line')
1554 debugp('self.indent_current_nsp')
1559 debugp('self.indent_current_nsp')
1555 if self.autoindent:
1560 if self.autoindent:
1556 if line:
1561 if line:
1557 inisp = num_ini_spaces(line)
1562 inisp = num_ini_spaces(line)
1558 if inisp < self.indent_current_nsp:
1563 if inisp < self.indent_current_nsp:
1559 self.indent_current_nsp = inisp
1564 self.indent_current_nsp = inisp
1560
1565
1561 if line[-1] == ':':
1566 if line[-1] == ':':
1562 self.indent_current_nsp += 4
1567 self.indent_current_nsp += 4
1563 elif dedent_re.match(line):
1568 elif dedent_re.match(line):
1564 self.indent_current_nsp -= 4
1569 self.indent_current_nsp -= 4
1565 else:
1570 else:
1566 self.indent_current_nsp = 0
1571 self.indent_current_nsp = 0
1567
1572
1568 def runlines(self,lines):
1573 def runlines(self,lines):
1569 """Run a string of one or more lines of source.
1574 """Run a string of one or more lines of source.
1570
1575
1571 This method is capable of running a string containing multiple source
1576 This method is capable of running a string containing multiple source
1572 lines, as if they had been entered at the IPython prompt. Since it
1577 lines, as if they had been entered at the IPython prompt. Since it
1573 exposes IPython's processing machinery, the given strings can contain
1578 exposes IPython's processing machinery, the given strings can contain
1574 magic calls (%magic), special shell access (!cmd), etc."""
1579 magic calls (%magic), special shell access (!cmd), etc."""
1575
1580
1576 # We must start with a clean buffer, in case this is run from an
1581 # We must start with a clean buffer, in case this is run from an
1577 # interactive IPython session (via a magic, for example).
1582 # interactive IPython session (via a magic, for example).
1578 self.resetbuffer()
1583 self.resetbuffer()
1579 lines = lines.split('\n')
1584 lines = lines.split('\n')
1580 more = 0
1585 more = 0
1581 for line in lines:
1586 for line in lines:
1582 # skip blank lines so we don't mess up the prompt counter, but do
1587 # skip blank lines so we don't mess up the prompt counter, but do
1583 # NOT skip even a blank line if we are in a code block (more is
1588 # NOT skip even a blank line if we are in a code block (more is
1584 # true)
1589 # true)
1585 if line or more:
1590 if line or more:
1586 more = self.push(self.prefilter(line,more))
1591 more = self.push(self.prefilter(line,more))
1587 # IPython's runsource returns None if there was an error
1592 # IPython's runsource returns None if there was an error
1588 # compiling the code. This allows us to stop processing right
1593 # compiling the code. This allows us to stop processing right
1589 # away, so the user gets the error message at the right place.
1594 # away, so the user gets the error message at the right place.
1590 if more is None:
1595 if more is None:
1591 break
1596 break
1592 # final newline in case the input didn't have it, so that the code
1597 # final newline in case the input didn't have it, so that the code
1593 # actually does get executed
1598 # actually does get executed
1594 if more:
1599 if more:
1595 self.push('\n')
1600 self.push('\n')
1596
1601
1597 def runsource(self, source, filename='<input>', symbol='single'):
1602 def runsource(self, source, filename='<input>', symbol='single'):
1598 """Compile and run some source in the interpreter.
1603 """Compile and run some source in the interpreter.
1599
1604
1600 Arguments are as for compile_command().
1605 Arguments are as for compile_command().
1601
1606
1602 One several things can happen:
1607 One several things can happen:
1603
1608
1604 1) The input is incorrect; compile_command() raised an
1609 1) The input is incorrect; compile_command() raised an
1605 exception (SyntaxError or OverflowError). A syntax traceback
1610 exception (SyntaxError or OverflowError). A syntax traceback
1606 will be printed by calling the showsyntaxerror() method.
1611 will be printed by calling the showsyntaxerror() method.
1607
1612
1608 2) The input is incomplete, and more input is required;
1613 2) The input is incomplete, and more input is required;
1609 compile_command() returned None. Nothing happens.
1614 compile_command() returned None. Nothing happens.
1610
1615
1611 3) The input is complete; compile_command() returned a code
1616 3) The input is complete; compile_command() returned a code
1612 object. The code is executed by calling self.runcode() (which
1617 object. The code is executed by calling self.runcode() (which
1613 also handles run-time exceptions, except for SystemExit).
1618 also handles run-time exceptions, except for SystemExit).
1614
1619
1615 The return value is:
1620 The return value is:
1616
1621
1617 - True in case 2
1622 - True in case 2
1618
1623
1619 - False in the other cases, unless an exception is raised, where
1624 - False in the other cases, unless an exception is raised, where
1620 None is returned instead. This can be used by external callers to
1625 None is returned instead. This can be used by external callers to
1621 know whether to continue feeding input or not.
1626 know whether to continue feeding input or not.
1622
1627
1623 The return value can be used to decide whether to use sys.ps1 or
1628 The return value can be used to decide whether to use sys.ps1 or
1624 sys.ps2 to prompt the next line."""
1629 sys.ps2 to prompt the next line."""
1625
1630
1626 try:
1631 try:
1627 code = self.compile(source,filename,symbol)
1632 code = self.compile(source,filename,symbol)
1628 except (OverflowError, SyntaxError, ValueError):
1633 except (OverflowError, SyntaxError, ValueError):
1629 # Case 1
1634 # Case 1
1630 self.showsyntaxerror(filename)
1635 self.showsyntaxerror(filename)
1631 return None
1636 return None
1632
1637
1633 if code is None:
1638 if code is None:
1634 # Case 2
1639 # Case 2
1635 return True
1640 return True
1636
1641
1637 # Case 3
1642 # Case 3
1638 # We store the code object so that threaded shells and
1643 # We store the code object so that threaded shells and
1639 # custom exception handlers can access all this info if needed.
1644 # custom exception handlers can access all this info if needed.
1640 # The source corresponding to this can be obtained from the
1645 # The source corresponding to this can be obtained from the
1641 # buffer attribute as '\n'.join(self.buffer).
1646 # buffer attribute as '\n'.join(self.buffer).
1642 self.code_to_run = code
1647 self.code_to_run = code
1643 # now actually execute the code object
1648 # now actually execute the code object
1644 if self.runcode(code) == 0:
1649 if self.runcode(code) == 0:
1645 return False
1650 return False
1646 else:
1651 else:
1647 return None
1652 return None
1648
1653
1649 def runcode(self,code_obj):
1654 def runcode(self,code_obj):
1650 """Execute a code object.
1655 """Execute a code object.
1651
1656
1652 When an exception occurs, self.showtraceback() is called to display a
1657 When an exception occurs, self.showtraceback() is called to display a
1653 traceback.
1658 traceback.
1654
1659
1655 Return value: a flag indicating whether the code to be run completed
1660 Return value: a flag indicating whether the code to be run completed
1656 successfully:
1661 successfully:
1657
1662
1658 - 0: successful execution.
1663 - 0: successful execution.
1659 - 1: an error occurred.
1664 - 1: an error occurred.
1660 """
1665 """
1661
1666
1662 # Set our own excepthook in case the user code tries to call it
1667 # Set our own excepthook in case the user code tries to call it
1663 # directly, so that the IPython crash handler doesn't get triggered
1668 # directly, so that the IPython crash handler doesn't get triggered
1664 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1669 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1665
1670
1666 # we save the original sys.excepthook in the instance, in case config
1671 # we save the original sys.excepthook in the instance, in case config
1667 # code (such as magics) needs access to it.
1672 # code (such as magics) needs access to it.
1668 self.sys_excepthook = old_excepthook
1673 self.sys_excepthook = old_excepthook
1669 outflag = 1 # happens in more places, so it's easier as default
1674 outflag = 1 # happens in more places, so it's easier as default
1670 try:
1675 try:
1671 try:
1676 try:
1672 # Embedded instances require separate global/local namespaces
1677 # Embedded instances require separate global/local namespaces
1673 # so they can see both the surrounding (local) namespace and
1678 # so they can see both the surrounding (local) namespace and
1674 # the module-level globals when called inside another function.
1679 # the module-level globals when called inside another function.
1675 if self.embedded:
1680 if self.embedded:
1676 exec code_obj in self.user_global_ns, self.user_ns
1681 exec code_obj in self.user_global_ns, self.user_ns
1677 # Normal (non-embedded) instances should only have a single
1682 # Normal (non-embedded) instances should only have a single
1678 # namespace for user code execution, otherwise functions won't
1683 # namespace for user code execution, otherwise functions won't
1679 # see interactive top-level globals.
1684 # see interactive top-level globals.
1680 else:
1685 else:
1681 exec code_obj in self.user_ns
1686 exec code_obj in self.user_ns
1682 finally:
1687 finally:
1683 # Reset our crash handler in place
1688 # Reset our crash handler in place
1684 sys.excepthook = old_excepthook
1689 sys.excepthook = old_excepthook
1685 except SystemExit:
1690 except SystemExit:
1686 self.resetbuffer()
1691 self.resetbuffer()
1687 self.showtraceback()
1692 self.showtraceback()
1688 warn("Type exit or quit to exit IPython "
1693 warn("Type exit or quit to exit IPython "
1689 "(%Exit or %Quit do so unconditionally).",level=1)
1694 "(%Exit or %Quit do so unconditionally).",level=1)
1690 except self.custom_exceptions:
1695 except self.custom_exceptions:
1691 etype,value,tb = sys.exc_info()
1696 etype,value,tb = sys.exc_info()
1692 self.CustomTB(etype,value,tb)
1697 self.CustomTB(etype,value,tb)
1693 except:
1698 except:
1694 self.showtraceback()
1699 self.showtraceback()
1695 else:
1700 else:
1696 outflag = 0
1701 outflag = 0
1697 if softspace(sys.stdout, 0):
1702 if softspace(sys.stdout, 0):
1698 print
1703 print
1699 # Flush out code object which has been run (and source)
1704 # Flush out code object which has been run (and source)
1700 self.code_to_run = None
1705 self.code_to_run = None
1701 return outflag
1706 return outflag
1702
1707
1703 def push(self, line):
1708 def push(self, line):
1704 """Push a line to the interpreter.
1709 """Push a line to the interpreter.
1705
1710
1706 The line should not have a trailing newline; it may have
1711 The line should not have a trailing newline; it may have
1707 internal newlines. The line is appended to a buffer and the
1712 internal newlines. The line is appended to a buffer and the
1708 interpreter's runsource() method is called with the
1713 interpreter's runsource() method is called with the
1709 concatenated contents of the buffer as source. If this
1714 concatenated contents of the buffer as source. If this
1710 indicates that the command was executed or invalid, the buffer
1715 indicates that the command was executed or invalid, the buffer
1711 is reset; otherwise, the command is incomplete, and the buffer
1716 is reset; otherwise, the command is incomplete, and the buffer
1712 is left as it was after the line was appended. The return
1717 is left as it was after the line was appended. The return
1713 value is 1 if more input is required, 0 if the line was dealt
1718 value is 1 if more input is required, 0 if the line was dealt
1714 with in some way (this is the same as runsource()).
1719 with in some way (this is the same as runsource()).
1715 """
1720 """
1716
1721
1717 # autoindent management should be done here, and not in the
1722 # autoindent management should be done here, and not in the
1718 # interactive loop, since that one is only seen by keyboard input. We
1723 # interactive loop, since that one is only seen by keyboard input. We
1719 # need this done correctly even for code run via runlines (which uses
1724 # need this done correctly even for code run via runlines (which uses
1720 # push).
1725 # push).
1721
1726
1722 #print 'push line: <%s>' % line # dbg
1727 #print 'push line: <%s>' % line # dbg
1723 self.autoindent_update(line)
1728 self.autoindent_update(line)
1724
1729
1725 self.buffer.append(line)
1730 self.buffer.append(line)
1726 more = self.runsource('\n'.join(self.buffer), self.filename)
1731 more = self.runsource('\n'.join(self.buffer), self.filename)
1727 if not more:
1732 if not more:
1728 self.resetbuffer()
1733 self.resetbuffer()
1729 return more
1734 return more
1730
1735
1731 def resetbuffer(self):
1736 def resetbuffer(self):
1732 """Reset the input buffer."""
1737 """Reset the input buffer."""
1733 self.buffer[:] = []
1738 self.buffer[:] = []
1734
1739
1735 def raw_input(self,prompt='',continue_prompt=False):
1740 def raw_input(self,prompt='',continue_prompt=False):
1736 """Write a prompt and read a line.
1741 """Write a prompt and read a line.
1737
1742
1738 The returned line does not include the trailing newline.
1743 The returned line does not include the trailing newline.
1739 When the user enters the EOF key sequence, EOFError is raised.
1744 When the user enters the EOF key sequence, EOFError is raised.
1740
1745
1741 Optional inputs:
1746 Optional inputs:
1742
1747
1743 - prompt(''): a string to be printed to prompt the user.
1748 - prompt(''): a string to be printed to prompt the user.
1744
1749
1745 - continue_prompt(False): whether this line is the first one or a
1750 - continue_prompt(False): whether this line is the first one or a
1746 continuation in a sequence of inputs.
1751 continuation in a sequence of inputs.
1747 """
1752 """
1748
1753
1749 line = raw_input_original(prompt)
1754 line = raw_input_original(prompt)
1750 # Try to be reasonably smart about not re-indenting pasted input more
1755 # Try to be reasonably smart about not re-indenting pasted input more
1751 # than necessary. We do this by trimming out the auto-indent initial
1756 # than necessary. We do this by trimming out the auto-indent initial
1752 # spaces, if the user's actual input started itself with whitespace.
1757 # spaces, if the user's actual input started itself with whitespace.
1753 #debugp('self.buffer[-1]')
1758 #debugp('self.buffer[-1]')
1754
1759
1755 debugp('line')
1760 debugp('line')
1756 debugp('self.indent_current_nsp')
1761 debugp('self.indent_current_nsp')
1757 if self.autoindent:
1762 if self.autoindent:
1758 if num_ini_spaces(line) > self.indent_current_nsp:
1763 if num_ini_spaces(line) > self.indent_current_nsp:
1759 line = line[self.indent_current_nsp:]
1764 line = line[self.indent_current_nsp:]
1760 self.indent_current_nsp = 0
1765 self.indent_current_nsp = 0
1761 debugp('self.indent_current_nsp')
1766 debugp('self.indent_current_nsp')
1762
1767
1763 debugp('line')
1768 debugp('line')
1764 return self.prefilter(line,continue_prompt)
1769 lineout = self.prefilter(line,continue_prompt)
1770 debugp('lineout')
1771 return lineout
1765
1772
1766 def split_user_input(self,line):
1773 def split_user_input(self,line):
1767 """Split user input into pre-char, function part and rest."""
1774 """Split user input into pre-char, function part and rest."""
1768
1775
1769 lsplit = self.line_split.match(line)
1776 lsplit = self.line_split.match(line)
1770 if lsplit is None: # no regexp match returns None
1777 if lsplit is None: # no regexp match returns None
1771 try:
1778 try:
1772 iFun,theRest = line.split(None,1)
1779 iFun,theRest = line.split(None,1)
1773 except ValueError:
1780 except ValueError:
1774 iFun,theRest = line,''
1781 iFun,theRest = line,''
1775 pre = re.match('^(\s*)(.*)',line).groups()[0]
1782 pre = re.match('^(\s*)(.*)',line).groups()[0]
1776 else:
1783 else:
1777 pre,iFun,theRest = lsplit.groups()
1784 pre,iFun,theRest = lsplit.groups()
1778
1785
1779 #print 'line:<%s>' % line # dbg
1786 #print 'line:<%s>' % line # dbg
1780 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1787 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1781 return pre,iFun.strip(),theRest
1788 return pre,iFun.strip(),theRest
1782
1789
1783 def _prefilter(self, line, continue_prompt):
1790 def _prefilter(self, line, continue_prompt):
1784 """Calls different preprocessors, depending on the form of line."""
1791 """Calls different preprocessors, depending on the form of line."""
1785
1792
1786 # All handlers *must* return a value, even if it's blank ('').
1793 # All handlers *must* return a value, even if it's blank ('').
1787
1794
1788 # Lines are NOT logged here. Handlers should process the line as
1795 # Lines are NOT logged here. Handlers should process the line as
1789 # needed, update the cache AND log it (so that the input cache array
1796 # needed, update the cache AND log it (so that the input cache array
1790 # stays synced).
1797 # stays synced).
1791
1798
1792 # This function is _very_ delicate, and since it's also the one which
1799 # This function is _very_ delicate, and since it's also the one which
1793 # determines IPython's response to user input, it must be as efficient
1800 # determines IPython's response to user input, it must be as efficient
1794 # as possible. For this reason it has _many_ returns in it, trying
1801 # as possible. For this reason it has _many_ returns in it, trying
1795 # always to exit as quickly as it can figure out what it needs to do.
1802 # always to exit as quickly as it can figure out what it needs to do.
1796
1803
1797 # This function is the main responsible for maintaining IPython's
1804 # This function is the main responsible for maintaining IPython's
1798 # behavior respectful of Python's semantics. So be _very_ careful if
1805 # behavior respectful of Python's semantics. So be _very_ careful if
1799 # making changes to anything here.
1806 # making changes to anything here.
1800
1807
1801 #.....................................................................
1808 #.....................................................................
1802 # Code begins
1809 # Code begins
1803
1810
1804 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1811 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1805
1812
1806 # save the line away in case we crash, so the post-mortem handler can
1813 # save the line away in case we crash, so the post-mortem handler can
1807 # record it
1814 # record it
1808 self._last_input_line = line
1815 self._last_input_line = line
1809
1816
1810 #print '***line: <%s>' % line # dbg
1817 #print '***line: <%s>' % line # dbg
1811
1818
1812 # the input history needs to track even empty lines
1819 # the input history needs to track even empty lines
1813 if not line.strip():
1820 if not line.strip():
1814 if not continue_prompt:
1821 if not continue_prompt:
1815 self.outputcache.prompt_count -= 1
1822 self.outputcache.prompt_count -= 1
1816 return self.handle_normal(line,continue_prompt)
1823 return self.handle_normal(line,continue_prompt)
1817 #return self.handle_normal('',continue_prompt)
1824 #return self.handle_normal('',continue_prompt)
1818
1825
1819 # print '***cont',continue_prompt # dbg
1826 # print '***cont',continue_prompt # dbg
1820 # special handlers are only allowed for single line statements
1827 # special handlers are only allowed for single line statements
1821 if continue_prompt and not self.rc.multi_line_specials:
1828 if continue_prompt and not self.rc.multi_line_specials:
1822 return self.handle_normal(line,continue_prompt)
1829 return self.handle_normal(line,continue_prompt)
1823
1830
1824 # For the rest, we need the structure of the input
1831 # For the rest, we need the structure of the input
1825 pre,iFun,theRest = self.split_user_input(line)
1832 pre,iFun,theRest = self.split_user_input(line)
1826 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1833 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1827
1834
1828 # First check for explicit escapes in the last/first character
1835 # First check for explicit escapes in the last/first character
1829 handler = None
1836 handler = None
1830 if line[-1] == self.ESC_HELP:
1837 if line[-1] == self.ESC_HELP:
1831 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1838 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1832 if handler is None:
1839 if handler is None:
1833 # look at the first character of iFun, NOT of line, so we skip
1840 # look at the first character of iFun, NOT of line, so we skip
1834 # leading whitespace in multiline input
1841 # leading whitespace in multiline input
1835 handler = self.esc_handlers.get(iFun[0:1])
1842 handler = self.esc_handlers.get(iFun[0:1])
1836 if handler is not None:
1843 if handler is not None:
1837 return handler(line,continue_prompt,pre,iFun,theRest)
1844 return handler(line,continue_prompt,pre,iFun,theRest)
1838 # Emacs ipython-mode tags certain input lines
1845 # Emacs ipython-mode tags certain input lines
1839 if line.endswith('# PYTHON-MODE'):
1846 if line.endswith('# PYTHON-MODE'):
1840 return self.handle_emacs(line,continue_prompt)
1847 return self.handle_emacs(line,continue_prompt)
1841
1848
1842 # Next, check if we can automatically execute this thing
1849 # Next, check if we can automatically execute this thing
1843
1850
1844 # Allow ! in multi-line statements if multi_line_specials is on:
1851 # Allow ! in multi-line statements if multi_line_specials is on:
1845 if continue_prompt and self.rc.multi_line_specials and \
1852 if continue_prompt and self.rc.multi_line_specials and \
1846 iFun.startswith(self.ESC_SHELL):
1853 iFun.startswith(self.ESC_SHELL):
1847 return self.handle_shell_escape(line,continue_prompt,
1854 return self.handle_shell_escape(line,continue_prompt,
1848 pre=pre,iFun=iFun,
1855 pre=pre,iFun=iFun,
1849 theRest=theRest)
1856 theRest=theRest)
1850
1857
1851 # Let's try to find if the input line is a magic fn
1858 # Let's try to find if the input line is a magic fn
1852 oinfo = None
1859 oinfo = None
1853 if hasattr(self,'magic_'+iFun):
1860 if hasattr(self,'magic_'+iFun):
1854 # WARNING: _ofind uses getattr(), so it can consume generators and
1861 # WARNING: _ofind uses getattr(), so it can consume generators and
1855 # cause other side effects.
1862 # cause other side effects.
1856 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1863 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1857 if oinfo['ismagic']:
1864 if oinfo['ismagic']:
1858 # Be careful not to call magics when a variable assignment is
1865 # Be careful not to call magics when a variable assignment is
1859 # being made (ls='hi', for example)
1866 # being made (ls='hi', for example)
1860 if self.rc.automagic and \
1867 if self.rc.automagic and \
1861 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1868 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1862 (self.rc.multi_line_specials or not continue_prompt):
1869 (self.rc.multi_line_specials or not continue_prompt):
1863 return self.handle_magic(line,continue_prompt,
1870 return self.handle_magic(line,continue_prompt,
1864 pre,iFun,theRest)
1871 pre,iFun,theRest)
1865 else:
1872 else:
1866 return self.handle_normal(line,continue_prompt)
1873 return self.handle_normal(line,continue_prompt)
1867
1874
1868 # If the rest of the line begins with an (in)equality, assginment or
1875 # If the rest of the line begins with an (in)equality, assginment or
1869 # function call, we should not call _ofind but simply execute it.
1876 # function call, we should not call _ofind but simply execute it.
1870 # This avoids spurious geattr() accesses on objects upon assignment.
1877 # This avoids spurious geattr() accesses on objects upon assignment.
1871 #
1878 #
1872 # It also allows users to assign to either alias or magic names true
1879 # It also allows users to assign to either alias or magic names true
1873 # python variables (the magic/alias systems always take second seat to
1880 # python variables (the magic/alias systems always take second seat to
1874 # true python code).
1881 # true python code).
1875 if theRest and theRest[0] in '!=()':
1882 if theRest and theRest[0] in '!=()':
1876 return self.handle_normal(line,continue_prompt)
1883 return self.handle_normal(line,continue_prompt)
1877
1884
1878 if oinfo is None:
1885 if oinfo is None:
1879 # let's try to ensure that _oinfo is ONLY called when autocall is
1886 # let's try to ensure that _oinfo is ONLY called when autocall is
1880 # on. Since it has inevitable potential side effects, at least
1887 # on. Since it has inevitable potential side effects, at least
1881 # having autocall off should be a guarantee to the user that no
1888 # having autocall off should be a guarantee to the user that no
1882 # weird things will happen.
1889 # weird things will happen.
1883
1890
1884 if self.rc.autocall:
1891 if self.rc.autocall:
1885 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1892 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1886 else:
1893 else:
1887 # in this case, all that's left is either an alias or
1894 # in this case, all that's left is either an alias or
1888 # processing the line normally.
1895 # processing the line normally.
1889 if iFun in self.alias_table:
1896 if iFun in self.alias_table:
1890 return self.handle_alias(line,continue_prompt,
1897 return self.handle_alias(line,continue_prompt,
1891 pre,iFun,theRest)
1898 pre,iFun,theRest)
1892
1899
1893 else:
1900 else:
1894 return self.handle_normal(line,continue_prompt)
1901 return self.handle_normal(line,continue_prompt)
1895
1902
1896 if not oinfo['found']:
1903 if not oinfo['found']:
1897 return self.handle_normal(line,continue_prompt)
1904 return self.handle_normal(line,continue_prompt)
1898 else:
1905 else:
1899 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1906 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1900 if oinfo['isalias']:
1907 if oinfo['isalias']:
1901 return self.handle_alias(line,continue_prompt,
1908 return self.handle_alias(line,continue_prompt,
1902 pre,iFun,theRest)
1909 pre,iFun,theRest)
1903
1910
1904 if (self.rc.autocall
1911 if (self.rc.autocall
1905 and
1912 and
1906 (
1913 (
1907 #only consider exclusion re if not "," or ";" autoquoting
1914 #only consider exclusion re if not "," or ";" autoquoting
1908 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2) or
1915 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2) or
1909 (not self.re_exclude_auto.match(theRest)))
1916 (not self.re_exclude_auto.match(theRest)))
1910 and
1917 and
1911 self.re_fun_name.match(iFun) and
1918 self.re_fun_name.match(iFun) and
1912 callable(oinfo['obj'])) :
1919 callable(oinfo['obj'])) :
1913 #print 'going auto' # dbg
1920 #print 'going auto' # dbg
1914 return self.handle_auto(line,continue_prompt,
1921 return self.handle_auto(line,continue_prompt,
1915 pre,iFun,theRest,oinfo['obj'])
1922 pre,iFun,theRest,oinfo['obj'])
1916 else:
1923 else:
1917 #print 'was callable?', callable(oinfo['obj']) # dbg
1924 #print 'was callable?', callable(oinfo['obj']) # dbg
1918 return self.handle_normal(line,continue_prompt)
1925 return self.handle_normal(line,continue_prompt)
1919
1926
1920 # If we get here, we have a normal Python line. Log and return.
1927 # If we get here, we have a normal Python line. Log and return.
1921 return self.handle_normal(line,continue_prompt)
1928 return self.handle_normal(line,continue_prompt)
1922
1929
1923 def _prefilter_dumb(self, line, continue_prompt):
1930 def _prefilter_dumb(self, line, continue_prompt):
1924 """simple prefilter function, for debugging"""
1931 """simple prefilter function, for debugging"""
1925 return self.handle_normal(line,continue_prompt)
1932 return self.handle_normal(line,continue_prompt)
1926
1933
1927 # Set the default prefilter() function (this can be user-overridden)
1934 # Set the default prefilter() function (this can be user-overridden)
1928 prefilter = _prefilter
1935 prefilter = _prefilter
1929
1936
1930 def handle_normal(self,line,continue_prompt=None,
1937 def handle_normal(self,line,continue_prompt=None,
1931 pre=None,iFun=None,theRest=None):
1938 pre=None,iFun=None,theRest=None):
1932 """Handle normal input lines. Use as a template for handlers."""
1939 """Handle normal input lines. Use as a template for handlers."""
1933
1940
1934 # With autoindent on, we need some way to exit the input loop, and I
1941 # With autoindent on, we need some way to exit the input loop, and I
1935 # don't want to force the user to have to backspace all the way to
1942 # don't want to force the user to have to backspace all the way to
1936 # clear the line. The rule will be in this case, that either two
1943 # clear the line. The rule will be in this case, that either two
1937 # lines of pure whitespace in a row, or a line of pure whitespace but
1944 # lines of pure whitespace in a row, or a line of pure whitespace but
1938 # of a size different to the indent level, will exit the input loop.
1945 # of a size different to the indent level, will exit the input loop.
1939
1946
1940 if (continue_prompt and self.autoindent and line.isspace() and
1947 if (continue_prompt and self.autoindent and line.isspace() and
1941 (line != self.indent_current_str() or
1948 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
1942 (self.buffer[-1]).isspace() )):
1949 (self.buffer[-1]).isspace() )):
1950 #print 'reset line' # dbg
1943 line = ''
1951 line = ''
1944
1952
1945 self.log(line,continue_prompt)
1953 self.log(line,continue_prompt)
1946 return line
1954 return line
1947
1955
1948 def handle_alias(self,line,continue_prompt=None,
1956 def handle_alias(self,line,continue_prompt=None,
1949 pre=None,iFun=None,theRest=None):
1957 pre=None,iFun=None,theRest=None):
1950 """Handle alias input lines. """
1958 """Handle alias input lines. """
1951
1959
1952 # pre is needed, because it carries the leading whitespace. Otherwise
1960 # pre is needed, because it carries the leading whitespace. Otherwise
1953 # aliases won't work in indented sections.
1961 # aliases won't work in indented sections.
1954 line_out = '%sipalias(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1962 line_out = '%sipalias(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1955 self.log(line_out,continue_prompt)
1963 self.log(line_out,continue_prompt)
1956 return line_out
1964 return line_out
1957
1965
1958 def handle_shell_escape(self, line, continue_prompt=None,
1966 def handle_shell_escape(self, line, continue_prompt=None,
1959 pre=None,iFun=None,theRest=None):
1967 pre=None,iFun=None,theRest=None):
1960 """Execute the line in a shell, empty return value"""
1968 """Execute the line in a shell, empty return value"""
1961
1969
1962 #print 'line in :', `line` # dbg
1970 #print 'line in :', `line` # dbg
1963 # Example of a special handler. Others follow a similar pattern.
1971 # Example of a special handler. Others follow a similar pattern.
1964 if line.lstrip().startswith('!!'):
1972 if line.lstrip().startswith('!!'):
1965 # rewrite iFun/theRest to properly hold the call to %sx and
1973 # rewrite iFun/theRest to properly hold the call to %sx and
1966 # the actual command to be executed, so handle_magic can work
1974 # the actual command to be executed, so handle_magic can work
1967 # correctly
1975 # correctly
1968 theRest = '%s %s' % (iFun[2:],theRest)
1976 theRest = '%s %s' % (iFun[2:],theRest)
1969 iFun = 'sx'
1977 iFun = 'sx'
1970 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
1978 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
1971 line.lstrip()[2:]),
1979 line.lstrip()[2:]),
1972 continue_prompt,pre,iFun,theRest)
1980 continue_prompt,pre,iFun,theRest)
1973 else:
1981 else:
1974 cmd=line.lstrip().lstrip('!')
1982 cmd=line.lstrip().lstrip('!')
1975 line_out = '%sipsystem(%s)' % (pre,make_quoted_expr(cmd))
1983 line_out = '%sipsystem(%s)' % (pre,make_quoted_expr(cmd))
1976 # update cache/log and return
1984 # update cache/log and return
1977 self.log(line_out,continue_prompt)
1985 self.log(line_out,continue_prompt)
1978 return line_out
1986 return line_out
1979
1987
1980 def handle_magic(self, line, continue_prompt=None,
1988 def handle_magic(self, line, continue_prompt=None,
1981 pre=None,iFun=None,theRest=None):
1989 pre=None,iFun=None,theRest=None):
1982 """Execute magic functions."""
1990 """Execute magic functions."""
1983
1991
1984
1992
1985 cmd = '%sipmagic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1993 cmd = '%sipmagic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1986 self.log(cmd,continue_prompt)
1994 self.log(cmd,continue_prompt)
1987 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1995 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1988 return cmd
1996 return cmd
1989
1997
1990 def handle_auto(self, line, continue_prompt=None,
1998 def handle_auto(self, line, continue_prompt=None,
1991 pre=None,iFun=None,theRest=None,obj=None):
1999 pre=None,iFun=None,theRest=None,obj=None):
1992 """Hande lines which can be auto-executed, quoting if requested."""
2000 """Hande lines which can be auto-executed, quoting if requested."""
1993
2001
1994 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2002 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1995
2003
1996 # This should only be active for single-line input!
2004 # This should only be active for single-line input!
1997 if continue_prompt:
2005 if continue_prompt:
1998 self.log(line,continue_prompt)
2006 self.log(line,continue_prompt)
1999 return line
2007 return line
2000
2008
2001 auto_rewrite = True
2009 auto_rewrite = True
2002 if pre == self.ESC_QUOTE:
2010 if pre == self.ESC_QUOTE:
2003 # Auto-quote splitting on whitespace
2011 # Auto-quote splitting on whitespace
2004 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2012 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2005 elif pre == self.ESC_QUOTE2:
2013 elif pre == self.ESC_QUOTE2:
2006 # Auto-quote whole string
2014 # Auto-quote whole string
2007 newcmd = '%s("%s")' % (iFun,theRest)
2015 newcmd = '%s("%s")' % (iFun,theRest)
2008 else:
2016 else:
2009 # Auto-paren.
2017 # Auto-paren.
2010 # We only apply it to argument-less calls if the autocall
2018 # We only apply it to argument-less calls if the autocall
2011 # parameter is set to 2. We only need to check that autocall is <
2019 # parameter is set to 2. We only need to check that autocall is <
2012 # 2, since this function isn't called unless it's at least 1.
2020 # 2, since this function isn't called unless it's at least 1.
2013 if not theRest and (self.rc.autocall < 2):
2021 if not theRest and (self.rc.autocall < 2):
2014 newcmd = '%s %s' % (iFun,theRest)
2022 newcmd = '%s %s' % (iFun,theRest)
2015 auto_rewrite = False
2023 auto_rewrite = False
2016 else:
2024 else:
2017 if theRest.startswith('['):
2025 if theRest.startswith('['):
2018 if hasattr(obj,'__getitem__'):
2026 if hasattr(obj,'__getitem__'):
2019 # Don't autocall in this case: item access for an object
2027 # Don't autocall in this case: item access for an object
2020 # which is BOTH callable and implements __getitem__.
2028 # which is BOTH callable and implements __getitem__.
2021 newcmd = '%s %s' % (iFun,theRest)
2029 newcmd = '%s %s' % (iFun,theRest)
2022 auto_rewrite = False
2030 auto_rewrite = False
2023 else:
2031 else:
2024 # if the object doesn't support [] access, go ahead and
2032 # if the object doesn't support [] access, go ahead and
2025 # autocall
2033 # autocall
2026 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2034 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2027 elif theRest.endswith(';'):
2035 elif theRest.endswith(';'):
2028 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2036 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2029 else:
2037 else:
2030 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2038 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2031
2039
2032 if auto_rewrite:
2040 if auto_rewrite:
2033 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2041 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2034 # log what is now valid Python, not the actual user input (without the
2042 # log what is now valid Python, not the actual user input (without the
2035 # final newline)
2043 # final newline)
2036 self.log(newcmd,continue_prompt)
2044 self.log(newcmd,continue_prompt)
2037 return newcmd
2045 return newcmd
2038
2046
2039 def handle_help(self, line, continue_prompt=None,
2047 def handle_help(self, line, continue_prompt=None,
2040 pre=None,iFun=None,theRest=None):
2048 pre=None,iFun=None,theRest=None):
2041 """Try to get some help for the object.
2049 """Try to get some help for the object.
2042
2050
2043 obj? or ?obj -> basic information.
2051 obj? or ?obj -> basic information.
2044 obj?? or ??obj -> more details.
2052 obj?? or ??obj -> more details.
2045 """
2053 """
2046
2054
2047 # We need to make sure that we don't process lines which would be
2055 # We need to make sure that we don't process lines which would be
2048 # otherwise valid python, such as "x=1 # what?"
2056 # otherwise valid python, such as "x=1 # what?"
2049 try:
2057 try:
2050 codeop.compile_command(line)
2058 codeop.compile_command(line)
2051 except SyntaxError:
2059 except SyntaxError:
2052 # We should only handle as help stuff which is NOT valid syntax
2060 # We should only handle as help stuff which is NOT valid syntax
2053 if line[0]==self.ESC_HELP:
2061 if line[0]==self.ESC_HELP:
2054 line = line[1:]
2062 line = line[1:]
2055 elif line[-1]==self.ESC_HELP:
2063 elif line[-1]==self.ESC_HELP:
2056 line = line[:-1]
2064 line = line[:-1]
2057 self.log('#?'+line)
2065 self.log('#?'+line)
2058 if line:
2066 if line:
2059 self.magic_pinfo(line)
2067 self.magic_pinfo(line)
2060 else:
2068 else:
2061 page(self.usage,screen_lines=self.rc.screen_length)
2069 page(self.usage,screen_lines=self.rc.screen_length)
2062 return '' # Empty string is needed here!
2070 return '' # Empty string is needed here!
2063 except:
2071 except:
2064 # Pass any other exceptions through to the normal handler
2072 # Pass any other exceptions through to the normal handler
2065 return self.handle_normal(line,continue_prompt)
2073 return self.handle_normal(line,continue_prompt)
2066 else:
2074 else:
2067 # If the code compiles ok, we should handle it normally
2075 # If the code compiles ok, we should handle it normally
2068 return self.handle_normal(line,continue_prompt)
2076 return self.handle_normal(line,continue_prompt)
2069
2077
2070 def handle_emacs(self,line,continue_prompt=None,
2078 def handle_emacs(self,line,continue_prompt=None,
2071 pre=None,iFun=None,theRest=None):
2079 pre=None,iFun=None,theRest=None):
2072 """Handle input lines marked by python-mode."""
2080 """Handle input lines marked by python-mode."""
2073
2081
2074 # Currently, nothing is done. Later more functionality can be added
2082 # Currently, nothing is done. Later more functionality can be added
2075 # here if needed.
2083 # here if needed.
2076
2084
2077 # The input cache shouldn't be updated
2085 # The input cache shouldn't be updated
2078
2086
2079 return line
2087 return line
2080
2088
2081 def mktempfile(self,data=None):
2089 def mktempfile(self,data=None):
2082 """Make a new tempfile and return its filename.
2090 """Make a new tempfile and return its filename.
2083
2091
2084 This makes a call to tempfile.mktemp, but it registers the created
2092 This makes a call to tempfile.mktemp, but it registers the created
2085 filename internally so ipython cleans it up at exit time.
2093 filename internally so ipython cleans it up at exit time.
2086
2094
2087 Optional inputs:
2095 Optional inputs:
2088
2096
2089 - data(None): if data is given, it gets written out to the temp file
2097 - data(None): if data is given, it gets written out to the temp file
2090 immediately, and the file is closed again."""
2098 immediately, and the file is closed again."""
2091
2099
2092 filename = tempfile.mktemp('.py','ipython_edit_')
2100 filename = tempfile.mktemp('.py','ipython_edit_')
2093 self.tempfiles.append(filename)
2101 self.tempfiles.append(filename)
2094
2102
2095 if data:
2103 if data:
2096 tmp_file = open(filename,'w')
2104 tmp_file = open(filename,'w')
2097 tmp_file.write(data)
2105 tmp_file.write(data)
2098 tmp_file.close()
2106 tmp_file.close()
2099 return filename
2107 return filename
2100
2108
2101 def write(self,data):
2109 def write(self,data):
2102 """Write a string to the default output"""
2110 """Write a string to the default output"""
2103 Term.cout.write(data)
2111 Term.cout.write(data)
2104
2112
2105 def write_err(self,data):
2113 def write_err(self,data):
2106 """Write a string to the default error output"""
2114 """Write a string to the default error output"""
2107 Term.cerr.write(data)
2115 Term.cerr.write(data)
2108
2116
2109 def exit(self):
2117 def exit(self):
2110 """Handle interactive exit.
2118 """Handle interactive exit.
2111
2119
2112 This method sets the exit_now attribute."""
2120 This method sets the exit_now attribute."""
2113
2121
2114 if self.rc.confirm_exit:
2122 if self.rc.confirm_exit:
2115 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2123 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2116 self.exit_now = True
2124 self.exit_now = True
2117 else:
2125 else:
2118 self.exit_now = True
2126 self.exit_now = True
2119 return self.exit_now
2127 return self.exit_now
2120
2128
2121 def safe_execfile(self,fname,*where,**kw):
2129 def safe_execfile(self,fname,*where,**kw):
2122 fname = os.path.expanduser(fname)
2130 fname = os.path.expanduser(fname)
2123
2131
2124 # find things also in current directory
2132 # find things also in current directory
2125 dname = os.path.dirname(fname)
2133 dname = os.path.dirname(fname)
2126 if not sys.path.count(dname):
2134 if not sys.path.count(dname):
2127 sys.path.append(dname)
2135 sys.path.append(dname)
2128
2136
2129 try:
2137 try:
2130 xfile = open(fname)
2138 xfile = open(fname)
2131 except:
2139 except:
2132 print >> Term.cerr, \
2140 print >> Term.cerr, \
2133 'Could not open file <%s> for safe execution.' % fname
2141 'Could not open file <%s> for safe execution.' % fname
2134 return None
2142 return None
2135
2143
2136 kw.setdefault('islog',0)
2144 kw.setdefault('islog',0)
2137 kw.setdefault('quiet',1)
2145 kw.setdefault('quiet',1)
2138 kw.setdefault('exit_ignore',0)
2146 kw.setdefault('exit_ignore',0)
2139 first = xfile.readline()
2147 first = xfile.readline()
2140 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2148 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2141 xfile.close()
2149 xfile.close()
2142 # line by line execution
2150 # line by line execution
2143 if first.startswith(loghead) or kw['islog']:
2151 if first.startswith(loghead) or kw['islog']:
2144 print 'Loading log file <%s> one line at a time...' % fname
2152 print 'Loading log file <%s> one line at a time...' % fname
2145 if kw['quiet']:
2153 if kw['quiet']:
2146 stdout_save = sys.stdout
2154 stdout_save = sys.stdout
2147 sys.stdout = StringIO.StringIO()
2155 sys.stdout = StringIO.StringIO()
2148 try:
2156 try:
2149 globs,locs = where[0:2]
2157 globs,locs = where[0:2]
2150 except:
2158 except:
2151 try:
2159 try:
2152 globs = locs = where[0]
2160 globs = locs = where[0]
2153 except:
2161 except:
2154 globs = locs = globals()
2162 globs = locs = globals()
2155 badblocks = []
2163 badblocks = []
2156
2164
2157 # we also need to identify indented blocks of code when replaying
2165 # we also need to identify indented blocks of code when replaying
2158 # logs and put them together before passing them to an exec
2166 # logs and put them together before passing them to an exec
2159 # statement. This takes a bit of regexp and look-ahead work in the
2167 # statement. This takes a bit of regexp and look-ahead work in the
2160 # file. It's easiest if we swallow the whole thing in memory
2168 # file. It's easiest if we swallow the whole thing in memory
2161 # first, and manually walk through the lines list moving the
2169 # first, and manually walk through the lines list moving the
2162 # counter ourselves.
2170 # counter ourselves.
2163 indent_re = re.compile('\s+\S')
2171 indent_re = re.compile('\s+\S')
2164 xfile = open(fname)
2172 xfile = open(fname)
2165 filelines = xfile.readlines()
2173 filelines = xfile.readlines()
2166 xfile.close()
2174 xfile.close()
2167 nlines = len(filelines)
2175 nlines = len(filelines)
2168 lnum = 0
2176 lnum = 0
2169 while lnum < nlines:
2177 while lnum < nlines:
2170 line = filelines[lnum]
2178 line = filelines[lnum]
2171 lnum += 1
2179 lnum += 1
2172 # don't re-insert logger status info into cache
2180 # don't re-insert logger status info into cache
2173 if line.startswith('#log#'):
2181 if line.startswith('#log#'):
2174 continue
2182 continue
2175 else:
2183 else:
2176 # build a block of code (maybe a single line) for execution
2184 # build a block of code (maybe a single line) for execution
2177 block = line
2185 block = line
2178 try:
2186 try:
2179 next = filelines[lnum] # lnum has already incremented
2187 next = filelines[lnum] # lnum has already incremented
2180 except:
2188 except:
2181 next = None
2189 next = None
2182 while next and indent_re.match(next):
2190 while next and indent_re.match(next):
2183 block += next
2191 block += next
2184 lnum += 1
2192 lnum += 1
2185 try:
2193 try:
2186 next = filelines[lnum]
2194 next = filelines[lnum]
2187 except:
2195 except:
2188 next = None
2196 next = None
2189 # now execute the block of one or more lines
2197 # now execute the block of one or more lines
2190 try:
2198 try:
2191 exec block in globs,locs
2199 exec block in globs,locs
2192 except SystemExit:
2200 except SystemExit:
2193 pass
2201 pass
2194 except:
2202 except:
2195 badblocks.append(block.rstrip())
2203 badblocks.append(block.rstrip())
2196 if kw['quiet']: # restore stdout
2204 if kw['quiet']: # restore stdout
2197 sys.stdout.close()
2205 sys.stdout.close()
2198 sys.stdout = stdout_save
2206 sys.stdout = stdout_save
2199 print 'Finished replaying log file <%s>' % fname
2207 print 'Finished replaying log file <%s>' % fname
2200 if badblocks:
2208 if badblocks:
2201 print >> sys.stderr, ('\nThe following lines/blocks in file '
2209 print >> sys.stderr, ('\nThe following lines/blocks in file '
2202 '<%s> reported errors:' % fname)
2210 '<%s> reported errors:' % fname)
2203
2211
2204 for badline in badblocks:
2212 for badline in badblocks:
2205 print >> sys.stderr, badline
2213 print >> sys.stderr, badline
2206 else: # regular file execution
2214 else: # regular file execution
2207 try:
2215 try:
2208 execfile(fname,*where)
2216 execfile(fname,*where)
2209 except SyntaxError:
2217 except SyntaxError:
2210 etype,evalue = sys.exc_info()[:2]
2218 etype,evalue = sys.exc_info()[:2]
2211 self.SyntaxTB(etype,evalue,[])
2219 self.SyntaxTB(etype,evalue,[])
2212 warn('Failure executing file: <%s>' % fname)
2220 warn('Failure executing file: <%s>' % fname)
2213 except SystemExit,status:
2221 except SystemExit,status:
2214 if not kw['exit_ignore']:
2222 if not kw['exit_ignore']:
2215 self.InteractiveTB()
2223 self.InteractiveTB()
2216 warn('Failure executing file: <%s>' % fname)
2224 warn('Failure executing file: <%s>' % fname)
2217 except:
2225 except:
2218 self.InteractiveTB()
2226 self.InteractiveTB()
2219 warn('Failure executing file: <%s>' % fname)
2227 warn('Failure executing file: <%s>' % fname)
2220
2228
2221 #************************* end of file <iplib.py> *****************************
2229 #************************* end of file <iplib.py> *****************************
@@ -1,42 +1,50 b''
1 Notes for Windows Users
1 Notes for Windows Users
2 =======================
2 =======================
3
3
4 These are just minimal notes. The manual contains more detailed
4 These are just minimal notes. The manual contains more detailed
5 information.
5 information.
6
6
7 Requirements
7 Requirements
8 ------------
8 ------------
9
9
10 IPython runs under (as far as the Windows family is concerned):
10 IPython runs under (as far as the Windows family is concerned):
11
11
12 - Windows XP (I think WinNT/2000 are ok): works well. It needs:
12 - Windows XP, 2000 (and probably WinNT): works well. It needs:
13
13
14 * PyWin32, the win32 Python extensions from
14 * PyWin32, the win32 Python extensions from
15 http://starship.python.net/crew/mhammond.
15 http://starship.python.net/crew/mhammond.
16
16
17 * Gary Bishop's readline from
17 * Gary Bishop's readline from
18 http://sourceforge.net/projects/uncpythontools.
18 http://sourceforge.net/projects/uncpythontools.
19
19
20 * This in turn requires Tomas Heller's ctypes from
20 * This in turn requires Tomas Heller's ctypes from
21 http://starship.python.net/crew/theller/ctypes.
21 http://starship.python.net/crew/theller/ctypes.
22
22
23 - Windows 95/98/ME: I have no idea. It should work, but I can't test.
23 - Windows 95/98/ME: I have no idea. It should work, but I can't test.
24
24
25 - CygWin environments should work, they are basically Posix.
25 - CygWin environments should work, they are basically Posix.
26
26
27 It needs Python 2.3 or newer.
27 It needs Python 2.3 or newer.
28
28
29
29
30 Installation
30 Installation
31 ------------
31 ------------
32
32
33 Double-click the supplied .exe installer file. If all goes well, that's all
33 Double-click the supplied .exe installer file. If all goes well, that's all
34 you need to do. You should now have an IPython entry in your Start Menu.
34 you need to do. You should now have an IPython entry in your Start Menu.
35
35
36
37 Installation from source distribution
38 -------------------------------------
39
36 In case the automatic installer does not work for some reason, you can
40 In case the automatic installer does not work for some reason, you can
37 download the ipython-XXX.tar.gz file, which contains the full IPython source
41 download the ipython-XXX.tar.gz file, which contains the full IPython source
38 distribution (the popular WinZip can read .tar.gz files). After uncompressing
42 distribution (the popular WinZip can read .tar.gz files).
39 the archive, you can install it at a command terminal just like any other
43
40 Python module, by using python setup.py install'. After this completes, you
44 After uncompressing the archive, you can install it at a command terminal just
41 can run the supplied win32_manual_post_install.py script which will add
45 like any other Python module, by using python setup.py install'. After this
42 the relevant shortcuts to your startup menu.
46 completes, you can run the supplied win32_manual_post_install.py script which
47 will add the relevant shortcuts to your startup menu.
48
49 Optionally, you may skip installation altogether and just launch "ipython.py"
50 from the root folder of the extracted source distribution.
@@ -1,4984 +1,5019 b''
1 2006-01-22 Ville Vainio <vivainio@gmail.com>
2
3 * Merge from branches/0.7.1 into trunk, revs 1052-1057
4
5 2006-01-22 Fernando Perez <Fernando.Perez@colorado.edu>
6
7 * IPython/OInspect.py (Inspector.pinfo): fix bug where foo?? or
8 %pfile foo would print the file for foo even if it was a binary.
9 Now, extensions '.so' and '.dll' are skipped.
10
11 * IPython/Shell.py (MTInteractiveShell.__init__): Fix threading
12 bug, where macros would fail in all threaded modes. I'm not 100%
13 sure, so I'm going to put out an rc instead of making a release
14 today, and wait for feedback for at least a few days.
15
16 * IPython/iplib.py (handle_normal): fix (finally? somehow I doubt
17 it...) the handling of pasting external code with autoindent on.
18 To get out of a multiline input, the rule will appear for most
19 users unchanged: two blank lines or change the indent level
20 proposed by IPython. But there is a twist now: you can
21 add/subtract only *one or two spaces*. If you add/subtract three
22 or more (unless you completely delete the line), IPython will
23 accept that line, and you'll need to enter a second one of pure
24 whitespace. I know it sounds complicated, but I can't find a
25 different solution that covers all the cases, with the right
26 heuristics. Hopefully in actual use, nobody will really notice
27 all these strange rules and things will 'just work'.
28
29 2006-01-21 Fernando Perez <Fernando.Perez@colorado.edu>
30
31 * IPython/iplib.py (interact): catch exceptions which can be
32 triggered asynchronously by signal handlers. Thanks to an
33 automatic crash report, submitted by Colin Kingsley
34 <tercel-AT-gentoo.org>.
35
1 2006-01-20 Ville Vainio <vivainio@gmail.com>
36 2006-01-20 Ville Vainio <vivainio@gmail.com>
2
37
3 * Ipython/Extensions/ext_rehashdir.py: Created a usable example
38 * Ipython/Extensions/ext_rehashdir.py: Created a usable example
4 (%rehashdir, very useful, try it out) of how to extend ipython
39 (%rehashdir, very useful, try it out) of how to extend ipython
5 with new magics. Also added Extensions dir to pythonpath to make
40 with new magics. Also added Extensions dir to pythonpath to make
6 importing extensions easy.
41 importing extensions easy.
7
42
8 * %store now complains when trying to store interactively declared
43 * %store now complains when trying to store interactively declared
9 classes / instances of those classes.
44 classes / instances of those classes.
10
45
11 * Extensions/ipy_system_conf.py, UserConfig/ipy_user_conf.py,
46 * Extensions/ipy_system_conf.py, UserConfig/ipy_user_conf.py,
12 ipmaker.py: Config rehaul. Now ipy_..._conf.py are always imported
47 ipmaker.py: Config rehaul. Now ipy_..._conf.py are always imported
13 if they exist, and ipy_user_conf.py with some defaults is created for
48 if they exist, and ipy_user_conf.py with some defaults is created for
14 the user.
49 the user.
15
50
16 * Startup rehashing done by the config file, not InterpreterExec.
51 * Startup rehashing done by the config file, not InterpreterExec.
17 This means system commands are available even without selecting the
52 This means system commands are available even without selecting the
18 pysh profile. It's the sensible default after all.
53 pysh profile. It's the sensible default after all.
19
54
20 2006-01-20 Fernando Perez <Fernando.Perez@colorado.edu>
55 2006-01-20 Fernando Perez <Fernando.Perez@colorado.edu>
21
56
22 * IPython/iplib.py (raw_input): I _think_ I got the pasting of
57 * IPython/iplib.py (raw_input): I _think_ I got the pasting of
23 multiline code with autoindent on working. But I am really not
58 multiline code with autoindent on working. But I am really not
24 sure, so this needs more testing. Will commit a debug-enabled
59 sure, so this needs more testing. Will commit a debug-enabled
25 version for now, while I test it some more, so that Ville and
60 version for now, while I test it some more, so that Ville and
26 others may also catch any problems. Also made
61 others may also catch any problems. Also made
27 self.indent_current_str() a method, to ensure that there's no
62 self.indent_current_str() a method, to ensure that there's no
28 chance of the indent space count and the corresponding string
63 chance of the indent space count and the corresponding string
29 falling out of sync. All code needing the string should just call
64 falling out of sync. All code needing the string should just call
30 the method.
65 the method.
31
66
32 2006-01-18 Fernando Perez <Fernando.Perez@colorado.edu>
67 2006-01-18 Fernando Perez <Fernando.Perez@colorado.edu>
33
68
34 * IPython/Magic.py (magic_edit): fix check for when users don't
69 * IPython/Magic.py (magic_edit): fix check for when users don't
35 save their output files, the try/except was in the wrong section.
70 save their output files, the try/except was in the wrong section.
36
71
37 2006-01-17 Fernando Perez <Fernando.Perez@colorado.edu>
72 2006-01-17 Fernando Perez <Fernando.Perez@colorado.edu>
38
73
39 * IPython/Magic.py (magic_run): fix __file__ global missing from
74 * IPython/Magic.py (magic_run): fix __file__ global missing from
40 script's namespace when executed via %run. After a report by
75 script's namespace when executed via %run. After a report by
41 Vivian.
76 Vivian.
42
77
43 * IPython/Debugger.py (Pdb.__init__): Fix breakage with '%run -d'
78 * IPython/Debugger.py (Pdb.__init__): Fix breakage with '%run -d'
44 when using python 2.4. The parent constructor changed in 2.4, and
79 when using python 2.4. The parent constructor changed in 2.4, and
45 we need to track it directly (we can't call it, as it messes up
80 we need to track it directly (we can't call it, as it messes up
46 readline and tab-completion inside our pdb would stop working).
81 readline and tab-completion inside our pdb would stop working).
47 After a bug report by R. Bernstein <rocky-AT-panix.com>.
82 After a bug report by R. Bernstein <rocky-AT-panix.com>.
48
83
49 2006-01-16 Ville Vainio <vivainio@gmail.com>
84 2006-01-16 Ville Vainio <vivainio@gmail.com>
50
85
51 * Ipython/magic.py:Reverted back to old %edit functionality
86 * Ipython/magic.py:Reverted back to old %edit functionality
52 that returns file contents on exit.
87 that returns file contents on exit.
53
88
54 * IPython/path.py: Added Jason Orendorff's "path" module to
89 * IPython/path.py: Added Jason Orendorff's "path" module to
55 IPython tree, http://www.jorendorff.com/articles/python/path/.
90 IPython tree, http://www.jorendorff.com/articles/python/path/.
56 You can get path objects conveniently through %sc, and !!, e.g.:
91 You can get path objects conveniently through %sc, and !!, e.g.:
57 sc files=ls
92 sc files=ls
58 for p in files.paths: # or files.p
93 for p in files.paths: # or files.p
59 print p,p.mtime
94 print p,p.mtime
60
95
61 * Ipython/iplib.py:"," and ";" autoquoting-upon-autocall
96 * Ipython/iplib.py:"," and ";" autoquoting-upon-autocall
62 now work again without considering the exclusion regexp -
97 now work again without considering the exclusion regexp -
63 hence, things like ',foo my/path' turn to 'foo("my/path")'
98 hence, things like ',foo my/path' turn to 'foo("my/path")'
64 instead of syntax error.
99 instead of syntax error.
65
100
66
101
67 2006-01-14 Ville Vainio <vivainio@gmail.com>
102 2006-01-14 Ville Vainio <vivainio@gmail.com>
68
103
69 * IPython/ipapi.py (ashook, asmagic, options): Added convenience
104 * IPython/ipapi.py (ashook, asmagic, options): Added convenience
70 ipapi decorators for python 2.4 users, options() provides access to rc
105 ipapi decorators for python 2.4 users, options() provides access to rc
71 data.
106 data.
72
107
73 * IPython/Magic.py (magic_cd): %cd now accepts backslashes
108 * IPython/Magic.py (magic_cd): %cd now accepts backslashes
74 as path separators (even on Linux ;-). Space character after
109 as path separators (even on Linux ;-). Space character after
75 backslash (as yielded by tab completer) is still space;
110 backslash (as yielded by tab completer) is still space;
76 "%cd long\ name" works as expected.
111 "%cd long\ name" works as expected.
77
112
78 * IPython/ipapi.py,hooks.py,iplib.py: Hooks now implemented
113 * IPython/ipapi.py,hooks.py,iplib.py: Hooks now implemented
79 as "chain of command", with priority. API stays the same,
114 as "chain of command", with priority. API stays the same,
80 TryNext exception raised by a hook function signals that
115 TryNext exception raised by a hook function signals that
81 current hook failed and next hook should try handling it, as
116 current hook failed and next hook should try handling it, as
82 suggested by Walter Dörwald <walter@livinglogic.de>. Walter also
117 suggested by Walter Dörwald <walter@livinglogic.de>. Walter also
83 requested configurable display hook, which is now implemented.
118 requested configurable display hook, which is now implemented.
84
119
85 2006-01-13 Ville Vainio <vivainio@gmail.com>
120 2006-01-13 Ville Vainio <vivainio@gmail.com>
86
121
87 * IPython/platutils*.py: platform specific utility functions,
122 * IPython/platutils*.py: platform specific utility functions,
88 so far only set_term_title is implemented (change terminal
123 so far only set_term_title is implemented (change terminal
89 label in windowing systems). %cd now changes the title to
124 label in windowing systems). %cd now changes the title to
90 current dir.
125 current dir.
91
126
92 * IPython/Release.py: Added myself to "authors" list,
127 * IPython/Release.py: Added myself to "authors" list,
93 had to create new files.
128 had to create new files.
94
129
95 * IPython/iplib.py (handle_shell_escape): fixed logical flaw in
130 * IPython/iplib.py (handle_shell_escape): fixed logical flaw in
96 shell escape; not a known bug but had potential to be one in the
131 shell escape; not a known bug but had potential to be one in the
97 future.
132 future.
98
133
99 * IPython/ipapi.py (added),OInspect.py,iplib.py: "Public"
134 * IPython/ipapi.py (added),OInspect.py,iplib.py: "Public"
100 extension API for IPython! See the module for usage example. Fix
135 extension API for IPython! See the module for usage example. Fix
101 OInspect for docstring-less magic functions.
136 OInspect for docstring-less magic functions.
102
137
103
138
104 2006-01-13 Fernando Perez <Fernando.Perez@colorado.edu>
139 2006-01-13 Fernando Perez <Fernando.Perez@colorado.edu>
105
140
106 * IPython/iplib.py (raw_input): temporarily deactivate all
141 * IPython/iplib.py (raw_input): temporarily deactivate all
107 attempts at allowing pasting of code with autoindent on. It
142 attempts at allowing pasting of code with autoindent on. It
108 introduced bugs (reported by Prabhu) and I can't seem to find a
143 introduced bugs (reported by Prabhu) and I can't seem to find a
109 robust combination which works in all cases. Will have to revisit
144 robust combination which works in all cases. Will have to revisit
110 later.
145 later.
111
146
112 * IPython/genutils.py: remove isspace() function. We've dropped
147 * IPython/genutils.py: remove isspace() function. We've dropped
113 2.2 compatibility, so it's OK to use the string method.
148 2.2 compatibility, so it's OK to use the string method.
114
149
115 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
150 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
116
151
117 * IPython/iplib.py (InteractiveShell.__init__): fix regexp
152 * IPython/iplib.py (InteractiveShell.__init__): fix regexp
118 matching what NOT to autocall on, to include all python binary
153 matching what NOT to autocall on, to include all python binary
119 operators (including things like 'and', 'or', 'is' and 'in').
154 operators (including things like 'and', 'or', 'is' and 'in').
120 Prompted by a bug report on 'foo & bar', but I realized we had
155 Prompted by a bug report on 'foo & bar', but I realized we had
121 many more potential bug cases with other operators. The regexp is
156 many more potential bug cases with other operators. The regexp is
122 self.re_exclude_auto, it's fairly commented.
157 self.re_exclude_auto, it's fairly commented.
123
158
124 2006-01-12 Ville Vainio <vivainio@gmail.com>
159 2006-01-12 Ville Vainio <vivainio@gmail.com>
125
160
126 * IPython/iplib.py (make_quoted_expr,handle_shell_escape):
161 * IPython/iplib.py (make_quoted_expr,handle_shell_escape):
127 Prettified and hardened string/backslash quoting with ipsystem(),
162 Prettified and hardened string/backslash quoting with ipsystem(),
128 ipalias() and ipmagic(). Now even \ characters are passed to
163 ipalias() and ipmagic(). Now even \ characters are passed to
129 %magics, !shell escapes and aliases exactly as they are in the
164 %magics, !shell escapes and aliases exactly as they are in the
130 ipython command line. Should improve backslash experience,
165 ipython command line. Should improve backslash experience,
131 particularly in Windows (path delimiter for some commands that
166 particularly in Windows (path delimiter for some commands that
132 won't understand '/'), but Unix benefits as well (regexps). %cd
167 won't understand '/'), but Unix benefits as well (regexps). %cd
133 magic still doesn't support backslash path delimiters, though. Also
168 magic still doesn't support backslash path delimiters, though. Also
134 deleted all pretense of supporting multiline command strings in
169 deleted all pretense of supporting multiline command strings in
135 !system or %magic commands. Thanks to Jerry McRae for suggestions.
170 !system or %magic commands. Thanks to Jerry McRae for suggestions.
136
171
137 * doc/build_doc_instructions.txt added. Documentation on how to
172 * doc/build_doc_instructions.txt added. Documentation on how to
138 use doc/update_manual.py, added yesterday. Both files contributed
173 use doc/update_manual.py, added yesterday. Both files contributed
139 by Jörgen Stenarson <jorgen.stenarson-AT-bostream.nu>. This slates
174 by Jörgen Stenarson <jorgen.stenarson-AT-bostream.nu>. This slates
140 doc/*.sh for deprecation at a later date.
175 doc/*.sh for deprecation at a later date.
141
176
142 * /ipython.py Added ipython.py to root directory for
177 * /ipython.py Added ipython.py to root directory for
143 zero-installation (tar xzvf ipython.tgz; cd ipython; python
178 zero-installation (tar xzvf ipython.tgz; cd ipython; python
144 ipython.py) and development convenience (no need to kee doing
179 ipython.py) and development convenience (no need to kee doing
145 "setup.py install" between changes).
180 "setup.py install" between changes).
146
181
147 * Made ! and !! shell escapes work (again) in multiline expressions:
182 * Made ! and !! shell escapes work (again) in multiline expressions:
148 if 1:
183 if 1:
149 !ls
184 !ls
150 !!ls
185 !!ls
151
186
152 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
187 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
153
188
154 * IPython/ipstruct.py (Struct): Rename IPython.Struct to
189 * IPython/ipstruct.py (Struct): Rename IPython.Struct to
155 IPython.ipstruct, to avoid local shadowing of the stdlib 'struct'
190 IPython.ipstruct, to avoid local shadowing of the stdlib 'struct'
156 module in case-insensitive installation. Was causing crashes
191 module in case-insensitive installation. Was causing crashes
157 under win32. Closes http://www.scipy.net/roundup/ipython/issue49.
192 under win32. Closes http://www.scipy.net/roundup/ipython/issue49.
158
193
159 * IPython/Magic.py (magic_pycat): Fix pycat, patch by Marien Zwart
194 * IPython/Magic.py (magic_pycat): Fix pycat, patch by Marien Zwart
160 <marienz-AT-gentoo.org>, closes
195 <marienz-AT-gentoo.org>, closes
161 http://www.scipy.net/roundup/ipython/issue51.
196 http://www.scipy.net/roundup/ipython/issue51.
162
197
163 2006-01-11 Fernando Perez <Fernando.Perez@colorado.edu>
198 2006-01-11 Fernando Perez <Fernando.Perez@colorado.edu>
164
199
165 * IPython/Shell.py (IPShellGTK.on_timer): Finally fix the the
200 * IPython/Shell.py (IPShellGTK.on_timer): Finally fix the the
166 problem of excessive CPU usage under *nix and keyboard lag under
201 problem of excessive CPU usage under *nix and keyboard lag under
167 win32.
202 win32.
168
203
169 2006-01-10 *** Released version 0.7.0
204 2006-01-10 *** Released version 0.7.0
170
205
171 2006-01-10 Fernando Perez <Fernando.Perez@colorado.edu>
206 2006-01-10 Fernando Perez <Fernando.Perez@colorado.edu>
172
207
173 * IPython/Release.py (revision): tag version number to 0.7.0,
208 * IPython/Release.py (revision): tag version number to 0.7.0,
174 ready for release.
209 ready for release.
175
210
176 * IPython/Magic.py (magic_edit): Add print statement to %edit so
211 * IPython/Magic.py (magic_edit): Add print statement to %edit so
177 it informs the user of the name of the temp. file used. This can
212 it informs the user of the name of the temp. file used. This can
178 help if you decide later to reuse that same file, so you know
213 help if you decide later to reuse that same file, so you know
179 where to copy the info from.
214 where to copy the info from.
180
215
181 2006-01-09 Fernando Perez <Fernando.Perez@colorado.edu>
216 2006-01-09 Fernando Perez <Fernando.Perez@colorado.edu>
182
217
183 * setup_bdist_egg.py: little script to build an egg. Added
218 * setup_bdist_egg.py: little script to build an egg. Added
184 support in the release tools as well.
219 support in the release tools as well.
185
220
186 2006-01-08 Fernando Perez <Fernando.Perez@colorado.edu>
221 2006-01-08 Fernando Perez <Fernando.Perez@colorado.edu>
187
222
188 * IPython/Shell.py (IPShellWX.__init__): add support for WXPython
223 * IPython/Shell.py (IPShellWX.__init__): add support for WXPython
189 version selection (new -wxversion command line and ipythonrc
224 version selection (new -wxversion command line and ipythonrc
190 parameter). Patch contributed by Arnd Baecker
225 parameter). Patch contributed by Arnd Baecker
191 <arnd.baecker-AT-web.de>.
226 <arnd.baecker-AT-web.de>.
192
227
193 * IPython/iplib.py (embed_mainloop): fix tab-completion in
228 * IPython/iplib.py (embed_mainloop): fix tab-completion in
194 embedded instances, for variables defined at the interactive
229 embedded instances, for variables defined at the interactive
195 prompt of the embedded ipython. Reported by Arnd.
230 prompt of the embedded ipython. Reported by Arnd.
196
231
197 * IPython/Magic.py (magic_autocall): Fix %autocall magic. Now
232 * IPython/Magic.py (magic_autocall): Fix %autocall magic. Now
198 it can be used as a (stateful) toggle, or with a direct parameter.
233 it can be used as a (stateful) toggle, or with a direct parameter.
199
234
200 * IPython/ultraTB.py (_fixed_getinnerframes): remove debug assert which
235 * IPython/ultraTB.py (_fixed_getinnerframes): remove debug assert which
201 could be triggered in certain cases and cause the traceback
236 could be triggered in certain cases and cause the traceback
202 printer not to work.
237 printer not to work.
203
238
204 2006-01-07 Fernando Perez <Fernando.Perez@colorado.edu>
239 2006-01-07 Fernando Perez <Fernando.Perez@colorado.edu>
205
240
206 * IPython/iplib.py (_should_recompile): Small fix, closes
241 * IPython/iplib.py (_should_recompile): Small fix, closes
207 http://www.scipy.net/roundup/ipython/issue48. Patch by Scott.
242 http://www.scipy.net/roundup/ipython/issue48. Patch by Scott.
208
243
209 2006-01-04 Fernando Perez <Fernando.Perez@colorado.edu>
244 2006-01-04 Fernando Perez <Fernando.Perez@colorado.edu>
210
245
211 * IPython/Shell.py (IPShellGTK.mainloop): fix bug in the GTK
246 * IPython/Shell.py (IPShellGTK.mainloop): fix bug in the GTK
212 backend for matplotlib (100% cpu utiliziation). Thanks to Charlie
247 backend for matplotlib (100% cpu utiliziation). Thanks to Charlie
213 Moad for help with tracking it down.
248 Moad for help with tracking it down.
214
249
215 * IPython/iplib.py (handle_auto): fix autocall handling for
250 * IPython/iplib.py (handle_auto): fix autocall handling for
216 objects which support BOTH __getitem__ and __call__ (so that f [x]
251 objects which support BOTH __getitem__ and __call__ (so that f [x]
217 is left alone, instead of becoming f([x]) automatically).
252 is left alone, instead of becoming f([x]) automatically).
218
253
219 * IPython/Magic.py (magic_cd): fix crash when cd -b was used.
254 * IPython/Magic.py (magic_cd): fix crash when cd -b was used.
220 Ville's patch.
255 Ville's patch.
221
256
222 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
257 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
223
258
224 * IPython/iplib.py (handle_auto): changed autocall semantics to
259 * IPython/iplib.py (handle_auto): changed autocall semantics to
225 include 'smart' mode, where the autocall transformation is NOT
260 include 'smart' mode, where the autocall transformation is NOT
226 applied if there are no arguments on the line. This allows you to
261 applied if there are no arguments on the line. This allows you to
227 just type 'foo' if foo is a callable to see its internal form,
262 just type 'foo' if foo is a callable to see its internal form,
228 instead of having it called with no arguments (typically a
263 instead of having it called with no arguments (typically a
229 mistake). The old 'full' autocall still exists: for that, you
264 mistake). The old 'full' autocall still exists: for that, you
230 need to set the 'autocall' parameter to 2 in your ipythonrc file.
265 need to set the 'autocall' parameter to 2 in your ipythonrc file.
231
266
232 * IPython/completer.py (Completer.attr_matches): add
267 * IPython/completer.py (Completer.attr_matches): add
233 tab-completion support for Enthoughts' traits. After a report by
268 tab-completion support for Enthoughts' traits. After a report by
234 Arnd and a patch by Prabhu.
269 Arnd and a patch by Prabhu.
235
270
236 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
271 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
237
272
238 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
273 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
239 Schmolck's patch to fix inspect.getinnerframes().
274 Schmolck's patch to fix inspect.getinnerframes().
240
275
241 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
276 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
242 for embedded instances, regarding handling of namespaces and items
277 for embedded instances, regarding handling of namespaces and items
243 added to the __builtin__ one. Multiple embedded instances and
278 added to the __builtin__ one. Multiple embedded instances and
244 recursive embeddings should work better now (though I'm not sure
279 recursive embeddings should work better now (though I'm not sure
245 I've got all the corner cases fixed, that code is a bit of a brain
280 I've got all the corner cases fixed, that code is a bit of a brain
246 twister).
281 twister).
247
282
248 * IPython/Magic.py (magic_edit): added support to edit in-memory
283 * IPython/Magic.py (magic_edit): added support to edit in-memory
249 macros (automatically creates the necessary temp files). %edit
284 macros (automatically creates the necessary temp files). %edit
250 also doesn't return the file contents anymore, it's just noise.
285 also doesn't return the file contents anymore, it's just noise.
251
286
252 * IPython/completer.py (Completer.attr_matches): revert change to
287 * IPython/completer.py (Completer.attr_matches): revert change to
253 complete only on attributes listed in __all__. I realized it
288 complete only on attributes listed in __all__. I realized it
254 cripples the tab-completion system as a tool for exploring the
289 cripples the tab-completion system as a tool for exploring the
255 internals of unknown libraries (it renders any non-__all__
290 internals of unknown libraries (it renders any non-__all__
256 attribute off-limits). I got bit by this when trying to see
291 attribute off-limits). I got bit by this when trying to see
257 something inside the dis module.
292 something inside the dis module.
258
293
259 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
294 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
260
295
261 * IPython/iplib.py (InteractiveShell.__init__): add .meta
296 * IPython/iplib.py (InteractiveShell.__init__): add .meta
262 namespace for users and extension writers to hold data in. This
297 namespace for users and extension writers to hold data in. This
263 follows the discussion in
298 follows the discussion in
264 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
299 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
265
300
266 * IPython/completer.py (IPCompleter.complete): small patch to help
301 * IPython/completer.py (IPCompleter.complete): small patch to help
267 tab-completion under Emacs, after a suggestion by John Barnard
302 tab-completion under Emacs, after a suggestion by John Barnard
268 <barnarj-AT-ccf.org>.
303 <barnarj-AT-ccf.org>.
269
304
270 * IPython/Magic.py (Magic.extract_input_slices): added support for
305 * IPython/Magic.py (Magic.extract_input_slices): added support for
271 the slice notation in magics to use N-M to represent numbers N...M
306 the slice notation in magics to use N-M to represent numbers N...M
272 (closed endpoints). This is used by %macro and %save.
307 (closed endpoints). This is used by %macro and %save.
273
308
274 * IPython/completer.py (Completer.attr_matches): for modules which
309 * IPython/completer.py (Completer.attr_matches): for modules which
275 define __all__, complete only on those. After a patch by Jeffrey
310 define __all__, complete only on those. After a patch by Jeffrey
276 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
311 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
277 speed up this routine.
312 speed up this routine.
278
313
279 * IPython/Logger.py (Logger.log): fix a history handling bug. I
314 * IPython/Logger.py (Logger.log): fix a history handling bug. I
280 don't know if this is the end of it, but the behavior now is
315 don't know if this is the end of it, but the behavior now is
281 certainly much more correct. Note that coupled with macros,
316 certainly much more correct. Note that coupled with macros,
282 slightly surprising (at first) behavior may occur: a macro will in
317 slightly surprising (at first) behavior may occur: a macro will in
283 general expand to multiple lines of input, so upon exiting, the
318 general expand to multiple lines of input, so upon exiting, the
284 in/out counters will both be bumped by the corresponding amount
319 in/out counters will both be bumped by the corresponding amount
285 (as if the macro's contents had been typed interactively). Typing
320 (as if the macro's contents had been typed interactively). Typing
286 %hist will reveal the intermediate (silently processed) lines.
321 %hist will reveal the intermediate (silently processed) lines.
287
322
288 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
323 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
289 pickle to fail (%run was overwriting __main__ and not restoring
324 pickle to fail (%run was overwriting __main__ and not restoring
290 it, but pickle relies on __main__ to operate).
325 it, but pickle relies on __main__ to operate).
291
326
292 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
327 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
293 using properties, but forgot to make the main InteractiveShell
328 using properties, but forgot to make the main InteractiveShell
294 class a new-style class. Properties fail silently, and
329 class a new-style class. Properties fail silently, and
295 misteriously, with old-style class (getters work, but
330 misteriously, with old-style class (getters work, but
296 setters don't do anything).
331 setters don't do anything).
297
332
298 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
333 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
299
334
300 * IPython/Magic.py (magic_history): fix history reporting bug (I
335 * IPython/Magic.py (magic_history): fix history reporting bug (I
301 know some nasties are still there, I just can't seem to find a
336 know some nasties are still there, I just can't seem to find a
302 reproducible test case to track them down; the input history is
337 reproducible test case to track them down; the input history is
303 falling out of sync...)
338 falling out of sync...)
304
339
305 * IPython/iplib.py (handle_shell_escape): fix bug where both
340 * IPython/iplib.py (handle_shell_escape): fix bug where both
306 aliases and system accesses where broken for indented code (such
341 aliases and system accesses where broken for indented code (such
307 as loops).
342 as loops).
308
343
309 * IPython/genutils.py (shell): fix small but critical bug for
344 * IPython/genutils.py (shell): fix small but critical bug for
310 win32 system access.
345 win32 system access.
311
346
312 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
347 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
313
348
314 * IPython/iplib.py (showtraceback): remove use of the
349 * IPython/iplib.py (showtraceback): remove use of the
315 sys.last_{type/value/traceback} structures, which are non
350 sys.last_{type/value/traceback} structures, which are non
316 thread-safe.
351 thread-safe.
317 (_prefilter): change control flow to ensure that we NEVER
352 (_prefilter): change control flow to ensure that we NEVER
318 introspect objects when autocall is off. This will guarantee that
353 introspect objects when autocall is off. This will guarantee that
319 having an input line of the form 'x.y', where access to attribute
354 having an input line of the form 'x.y', where access to attribute
320 'y' has side effects, doesn't trigger the side effect TWICE. It
355 'y' has side effects, doesn't trigger the side effect TWICE. It
321 is important to note that, with autocall on, these side effects
356 is important to note that, with autocall on, these side effects
322 can still happen.
357 can still happen.
323 (ipsystem): new builtin, to complete the ip{magic/alias/system}
358 (ipsystem): new builtin, to complete the ip{magic/alias/system}
324 trio. IPython offers these three kinds of special calls which are
359 trio. IPython offers these three kinds of special calls which are
325 not python code, and it's a good thing to have their call method
360 not python code, and it's a good thing to have their call method
326 be accessible as pure python functions (not just special syntax at
361 be accessible as pure python functions (not just special syntax at
327 the command line). It gives us a better internal implementation
362 the command line). It gives us a better internal implementation
328 structure, as well as exposing these for user scripting more
363 structure, as well as exposing these for user scripting more
329 cleanly.
364 cleanly.
330
365
331 * IPython/macro.py (Macro.__init__): moved macros to a standalone
366 * IPython/macro.py (Macro.__init__): moved macros to a standalone
332 file. Now that they'll be more likely to be used with the
367 file. Now that they'll be more likely to be used with the
333 persistance system (%store), I want to make sure their module path
368 persistance system (%store), I want to make sure their module path
334 doesn't change in the future, so that we don't break things for
369 doesn't change in the future, so that we don't break things for
335 users' persisted data.
370 users' persisted data.
336
371
337 * IPython/iplib.py (autoindent_update): move indentation
372 * IPython/iplib.py (autoindent_update): move indentation
338 management into the _text_ processing loop, not the keyboard
373 management into the _text_ processing loop, not the keyboard
339 interactive one. This is necessary to correctly process non-typed
374 interactive one. This is necessary to correctly process non-typed
340 multiline input (such as macros).
375 multiline input (such as macros).
341
376
342 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
377 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
343 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
378 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
344 which was producing problems in the resulting manual.
379 which was producing problems in the resulting manual.
345 (magic_whos): improve reporting of instances (show their class,
380 (magic_whos): improve reporting of instances (show their class,
346 instead of simply printing 'instance' which isn't terribly
381 instead of simply printing 'instance' which isn't terribly
347 informative).
382 informative).
348
383
349 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
384 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
350 (minor mods) to support network shares under win32.
385 (minor mods) to support network shares under win32.
351
386
352 * IPython/winconsole.py (get_console_size): add new winconsole
387 * IPython/winconsole.py (get_console_size): add new winconsole
353 module and fixes to page_dumb() to improve its behavior under
388 module and fixes to page_dumb() to improve its behavior under
354 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
389 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
355
390
356 * IPython/Magic.py (Macro): simplified Macro class to just
391 * IPython/Magic.py (Macro): simplified Macro class to just
357 subclass list. We've had only 2.2 compatibility for a very long
392 subclass list. We've had only 2.2 compatibility for a very long
358 time, yet I was still avoiding subclassing the builtin types. No
393 time, yet I was still avoiding subclassing the builtin types. No
359 more (I'm also starting to use properties, though I won't shift to
394 more (I'm also starting to use properties, though I won't shift to
360 2.3-specific features quite yet).
395 2.3-specific features quite yet).
361 (magic_store): added Ville's patch for lightweight variable
396 (magic_store): added Ville's patch for lightweight variable
362 persistence, after a request on the user list by Matt Wilkie
397 persistence, after a request on the user list by Matt Wilkie
363 <maphew-AT-gmail.com>. The new %store magic's docstring has full
398 <maphew-AT-gmail.com>. The new %store magic's docstring has full
364 details.
399 details.
365
400
366 * IPython/iplib.py (InteractiveShell.post_config_initialization):
401 * IPython/iplib.py (InteractiveShell.post_config_initialization):
367 changed the default logfile name from 'ipython.log' to
402 changed the default logfile name from 'ipython.log' to
368 'ipython_log.py'. These logs are real python files, and now that
403 'ipython_log.py'. These logs are real python files, and now that
369 we have much better multiline support, people are more likely to
404 we have much better multiline support, people are more likely to
370 want to use them as such. Might as well name them correctly.
405 want to use them as such. Might as well name them correctly.
371
406
372 * IPython/Magic.py: substantial cleanup. While we can't stop
407 * IPython/Magic.py: substantial cleanup. While we can't stop
373 using magics as mixins, due to the existing customizations 'out
408 using magics as mixins, due to the existing customizations 'out
374 there' which rely on the mixin naming conventions, at least I
409 there' which rely on the mixin naming conventions, at least I
375 cleaned out all cross-class name usage. So once we are OK with
410 cleaned out all cross-class name usage. So once we are OK with
376 breaking compatibility, the two systems can be separated.
411 breaking compatibility, the two systems can be separated.
377
412
378 * IPython/Logger.py: major cleanup. This one is NOT a mixin
413 * IPython/Logger.py: major cleanup. This one is NOT a mixin
379 anymore, and the class is a fair bit less hideous as well. New
414 anymore, and the class is a fair bit less hideous as well. New
380 features were also introduced: timestamping of input, and logging
415 features were also introduced: timestamping of input, and logging
381 of output results. These are user-visible with the -t and -o
416 of output results. These are user-visible with the -t and -o
382 options to %logstart. Closes
417 options to %logstart. Closes
383 http://www.scipy.net/roundup/ipython/issue11 and a request by
418 http://www.scipy.net/roundup/ipython/issue11 and a request by
384 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
419 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
385
420
386 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
421 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
387
422
388 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
423 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
389 better hadnle backslashes in paths. See the thread 'More Windows
424 better hadnle backslashes in paths. See the thread 'More Windows
390 questions part 2 - \/ characters revisited' on the iypthon user
425 questions part 2 - \/ characters revisited' on the iypthon user
391 list:
426 list:
392 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
427 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
393
428
394 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
429 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
395
430
396 (InteractiveShell.__init__): change threaded shells to not use the
431 (InteractiveShell.__init__): change threaded shells to not use the
397 ipython crash handler. This was causing more problems than not,
432 ipython crash handler. This was causing more problems than not,
398 as exceptions in the main thread (GUI code, typically) would
433 as exceptions in the main thread (GUI code, typically) would
399 always show up as a 'crash', when they really weren't.
434 always show up as a 'crash', when they really weren't.
400
435
401 The colors and exception mode commands (%colors/%xmode) have been
436 The colors and exception mode commands (%colors/%xmode) have been
402 synchronized to also take this into account, so users can get
437 synchronized to also take this into account, so users can get
403 verbose exceptions for their threaded code as well. I also added
438 verbose exceptions for their threaded code as well. I also added
404 support for activating pdb inside this exception handler as well,
439 support for activating pdb inside this exception handler as well,
405 so now GUI authors can use IPython's enhanced pdb at runtime.
440 so now GUI authors can use IPython's enhanced pdb at runtime.
406
441
407 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
442 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
408 true by default, and add it to the shipped ipythonrc file. Since
443 true by default, and add it to the shipped ipythonrc file. Since
409 this asks the user before proceeding, I think it's OK to make it
444 this asks the user before proceeding, I think it's OK to make it
410 true by default.
445 true by default.
411
446
412 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
447 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
413 of the previous special-casing of input in the eval loop. I think
448 of the previous special-casing of input in the eval loop. I think
414 this is cleaner, as they really are commands and shouldn't have
449 this is cleaner, as they really are commands and shouldn't have
415 a special role in the middle of the core code.
450 a special role in the middle of the core code.
416
451
417 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
452 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
418
453
419 * IPython/iplib.py (edit_syntax_error): added support for
454 * IPython/iplib.py (edit_syntax_error): added support for
420 automatically reopening the editor if the file had a syntax error
455 automatically reopening the editor if the file had a syntax error
421 in it. Thanks to scottt who provided the patch at:
456 in it. Thanks to scottt who provided the patch at:
422 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
457 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
423 version committed).
458 version committed).
424
459
425 * IPython/iplib.py (handle_normal): add suport for multi-line
460 * IPython/iplib.py (handle_normal): add suport for multi-line
426 input with emtpy lines. This fixes
461 input with emtpy lines. This fixes
427 http://www.scipy.net/roundup/ipython/issue43 and a similar
462 http://www.scipy.net/roundup/ipython/issue43 and a similar
428 discussion on the user list.
463 discussion on the user list.
429
464
430 WARNING: a behavior change is necessarily introduced to support
465 WARNING: a behavior change is necessarily introduced to support
431 blank lines: now a single blank line with whitespace does NOT
466 blank lines: now a single blank line with whitespace does NOT
432 break the input loop, which means that when autoindent is on, by
467 break the input loop, which means that when autoindent is on, by
433 default hitting return on the next (indented) line does NOT exit.
468 default hitting return on the next (indented) line does NOT exit.
434
469
435 Instead, to exit a multiline input you can either have:
470 Instead, to exit a multiline input you can either have:
436
471
437 - TWO whitespace lines (just hit return again), or
472 - TWO whitespace lines (just hit return again), or
438 - a single whitespace line of a different length than provided
473 - a single whitespace line of a different length than provided
439 by the autoindent (add or remove a space).
474 by the autoindent (add or remove a space).
440
475
441 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
476 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
442 module to better organize all readline-related functionality.
477 module to better organize all readline-related functionality.
443 I've deleted FlexCompleter and put all completion clases here.
478 I've deleted FlexCompleter and put all completion clases here.
444
479
445 * IPython/iplib.py (raw_input): improve indentation management.
480 * IPython/iplib.py (raw_input): improve indentation management.
446 It is now possible to paste indented code with autoindent on, and
481 It is now possible to paste indented code with autoindent on, and
447 the code is interpreted correctly (though it still looks bad on
482 the code is interpreted correctly (though it still looks bad on
448 screen, due to the line-oriented nature of ipython).
483 screen, due to the line-oriented nature of ipython).
449 (MagicCompleter.complete): change behavior so that a TAB key on an
484 (MagicCompleter.complete): change behavior so that a TAB key on an
450 otherwise empty line actually inserts a tab, instead of completing
485 otherwise empty line actually inserts a tab, instead of completing
451 on the entire global namespace. This makes it easier to use the
486 on the entire global namespace. This makes it easier to use the
452 TAB key for indentation. After a request by Hans Meine
487 TAB key for indentation. After a request by Hans Meine
453 <hans_meine-AT-gmx.net>
488 <hans_meine-AT-gmx.net>
454 (_prefilter): add support so that typing plain 'exit' or 'quit'
489 (_prefilter): add support so that typing plain 'exit' or 'quit'
455 does a sensible thing. Originally I tried to deviate as little as
490 does a sensible thing. Originally I tried to deviate as little as
456 possible from the default python behavior, but even that one may
491 possible from the default python behavior, but even that one may
457 change in this direction (thread on python-dev to that effect).
492 change in this direction (thread on python-dev to that effect).
458 Regardless, ipython should do the right thing even if CPython's
493 Regardless, ipython should do the right thing even if CPython's
459 '>>>' prompt doesn't.
494 '>>>' prompt doesn't.
460 (InteractiveShell): removed subclassing code.InteractiveConsole
495 (InteractiveShell): removed subclassing code.InteractiveConsole
461 class. By now we'd overridden just about all of its methods: I've
496 class. By now we'd overridden just about all of its methods: I've
462 copied the remaining two over, and now ipython is a standalone
497 copied the remaining two over, and now ipython is a standalone
463 class. This will provide a clearer picture for the chainsaw
498 class. This will provide a clearer picture for the chainsaw
464 branch refactoring.
499 branch refactoring.
465
500
466 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
501 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
467
502
468 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
503 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
469 failures for objects which break when dir() is called on them.
504 failures for objects which break when dir() is called on them.
470
505
471 * IPython/FlexCompleter.py (Completer.__init__): Added support for
506 * IPython/FlexCompleter.py (Completer.__init__): Added support for
472 distinct local and global namespaces in the completer API. This
507 distinct local and global namespaces in the completer API. This
473 change allows us top properly handle completion with distinct
508 change allows us top properly handle completion with distinct
474 scopes, including in embedded instances (this had never really
509 scopes, including in embedded instances (this had never really
475 worked correctly).
510 worked correctly).
476
511
477 Note: this introduces a change in the constructor for
512 Note: this introduces a change in the constructor for
478 MagicCompleter, as a new global_namespace parameter is now the
513 MagicCompleter, as a new global_namespace parameter is now the
479 second argument (the others were bumped one position).
514 second argument (the others were bumped one position).
480
515
481 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
516 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
482
517
483 * IPython/iplib.py (embed_mainloop): fix tab-completion in
518 * IPython/iplib.py (embed_mainloop): fix tab-completion in
484 embedded instances (which can be done now thanks to Vivian's
519 embedded instances (which can be done now thanks to Vivian's
485 frame-handling fixes for pdb).
520 frame-handling fixes for pdb).
486 (InteractiveShell.__init__): Fix namespace handling problem in
521 (InteractiveShell.__init__): Fix namespace handling problem in
487 embedded instances. We were overwriting __main__ unconditionally,
522 embedded instances. We were overwriting __main__ unconditionally,
488 and this should only be done for 'full' (non-embedded) IPython;
523 and this should only be done for 'full' (non-embedded) IPython;
489 embedded instances must respect the caller's __main__. Thanks to
524 embedded instances must respect the caller's __main__. Thanks to
490 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
525 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
491
526
492 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
527 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
493
528
494 * setup.py: added download_url to setup(). This registers the
529 * setup.py: added download_url to setup(). This registers the
495 download address at PyPI, which is not only useful to humans
530 download address at PyPI, which is not only useful to humans
496 browsing the site, but is also picked up by setuptools (the Eggs
531 browsing the site, but is also picked up by setuptools (the Eggs
497 machinery). Thanks to Ville and R. Kern for the info/discussion
532 machinery). Thanks to Ville and R. Kern for the info/discussion
498 on this.
533 on this.
499
534
500 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
535 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
501
536
502 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
537 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
503 This brings a lot of nice functionality to the pdb mode, which now
538 This brings a lot of nice functionality to the pdb mode, which now
504 has tab-completion, syntax highlighting, and better stack handling
539 has tab-completion, syntax highlighting, and better stack handling
505 than before. Many thanks to Vivian De Smedt
540 than before. Many thanks to Vivian De Smedt
506 <vivian-AT-vdesmedt.com> for the original patches.
541 <vivian-AT-vdesmedt.com> for the original patches.
507
542
508 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
543 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
509
544
510 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
545 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
511 sequence to consistently accept the banner argument. The
546 sequence to consistently accept the banner argument. The
512 inconsistency was tripping SAGE, thanks to Gary Zablackis
547 inconsistency was tripping SAGE, thanks to Gary Zablackis
513 <gzabl-AT-yahoo.com> for the report.
548 <gzabl-AT-yahoo.com> for the report.
514
549
515 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
550 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
516
551
517 * IPython/iplib.py (InteractiveShell.post_config_initialization):
552 * IPython/iplib.py (InteractiveShell.post_config_initialization):
518 Fix bug where a naked 'alias' call in the ipythonrc file would
553 Fix bug where a naked 'alias' call in the ipythonrc file would
519 cause a crash. Bug reported by Jorgen Stenarson.
554 cause a crash. Bug reported by Jorgen Stenarson.
520
555
521 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
556 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
522
557
523 * IPython/ipmaker.py (make_IPython): cleanups which should improve
558 * IPython/ipmaker.py (make_IPython): cleanups which should improve
524 startup time.
559 startup time.
525
560
526 * IPython/iplib.py (runcode): my globals 'fix' for embedded
561 * IPython/iplib.py (runcode): my globals 'fix' for embedded
527 instances had introduced a bug with globals in normal code. Now
562 instances had introduced a bug with globals in normal code. Now
528 it's working in all cases.
563 it's working in all cases.
529
564
530 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
565 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
531 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
566 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
532 has been introduced to set the default case sensitivity of the
567 has been introduced to set the default case sensitivity of the
533 searches. Users can still select either mode at runtime on a
568 searches. Users can still select either mode at runtime on a
534 per-search basis.
569 per-search basis.
535
570
536 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
571 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
537
572
538 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
573 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
539 attributes in wildcard searches for subclasses. Modified version
574 attributes in wildcard searches for subclasses. Modified version
540 of a patch by Jorgen.
575 of a patch by Jorgen.
541
576
542 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
577 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
543
578
544 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
579 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
545 embedded instances. I added a user_global_ns attribute to the
580 embedded instances. I added a user_global_ns attribute to the
546 InteractiveShell class to handle this.
581 InteractiveShell class to handle this.
547
582
548 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
583 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
549
584
550 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
585 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
551 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
586 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
552 (reported under win32, but may happen also in other platforms).
587 (reported under win32, but may happen also in other platforms).
553 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
588 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
554
589
555 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
590 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
556
591
557 * IPython/Magic.py (magic_psearch): new support for wildcard
592 * IPython/Magic.py (magic_psearch): new support for wildcard
558 patterns. Now, typing ?a*b will list all names which begin with a
593 patterns. Now, typing ?a*b will list all names which begin with a
559 and end in b, for example. The %psearch magic has full
594 and end in b, for example. The %psearch magic has full
560 docstrings. Many thanks to Jörgen Stenarson
595 docstrings. Many thanks to Jörgen Stenarson
561 <jorgen.stenarson-AT-bostream.nu>, author of the patches
596 <jorgen.stenarson-AT-bostream.nu>, author of the patches
562 implementing this functionality.
597 implementing this functionality.
563
598
564 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
599 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
565
600
566 * Manual: fixed long-standing annoyance of double-dashes (as in
601 * Manual: fixed long-standing annoyance of double-dashes (as in
567 --prefix=~, for example) being stripped in the HTML version. This
602 --prefix=~, for example) being stripped in the HTML version. This
568 is a latex2html bug, but a workaround was provided. Many thanks
603 is a latex2html bug, but a workaround was provided. Many thanks
569 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
604 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
570 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
605 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
571 rolling. This seemingly small issue had tripped a number of users
606 rolling. This seemingly small issue had tripped a number of users
572 when first installing, so I'm glad to see it gone.
607 when first installing, so I'm glad to see it gone.
573
608
574 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
609 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
575
610
576 * IPython/Extensions/numeric_formats.py: fix missing import,
611 * IPython/Extensions/numeric_formats.py: fix missing import,
577 reported by Stephen Walton.
612 reported by Stephen Walton.
578
613
579 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
614 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
580
615
581 * IPython/demo.py: finish demo module, fully documented now.
616 * IPython/demo.py: finish demo module, fully documented now.
582
617
583 * IPython/genutils.py (file_read): simple little utility to read a
618 * IPython/genutils.py (file_read): simple little utility to read a
584 file and ensure it's closed afterwards.
619 file and ensure it's closed afterwards.
585
620
586 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
621 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
587
622
588 * IPython/demo.py (Demo.__init__): added support for individually
623 * IPython/demo.py (Demo.__init__): added support for individually
589 tagging blocks for automatic execution.
624 tagging blocks for automatic execution.
590
625
591 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
626 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
592 syntax-highlighted python sources, requested by John.
627 syntax-highlighted python sources, requested by John.
593
628
594 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
629 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
595
630
596 * IPython/demo.py (Demo.again): fix bug where again() blocks after
631 * IPython/demo.py (Demo.again): fix bug where again() blocks after
597 finishing.
632 finishing.
598
633
599 * IPython/genutils.py (shlex_split): moved from Magic to here,
634 * IPython/genutils.py (shlex_split): moved from Magic to here,
600 where all 2.2 compatibility stuff lives. I needed it for demo.py.
635 where all 2.2 compatibility stuff lives. I needed it for demo.py.
601
636
602 * IPython/demo.py (Demo.__init__): added support for silent
637 * IPython/demo.py (Demo.__init__): added support for silent
603 blocks, improved marks as regexps, docstrings written.
638 blocks, improved marks as regexps, docstrings written.
604 (Demo.__init__): better docstring, added support for sys.argv.
639 (Demo.__init__): better docstring, added support for sys.argv.
605
640
606 * IPython/genutils.py (marquee): little utility used by the demo
641 * IPython/genutils.py (marquee): little utility used by the demo
607 code, handy in general.
642 code, handy in general.
608
643
609 * IPython/demo.py (Demo.__init__): new class for interactive
644 * IPython/demo.py (Demo.__init__): new class for interactive
610 demos. Not documented yet, I just wrote it in a hurry for
645 demos. Not documented yet, I just wrote it in a hurry for
611 scipy'05. Will docstring later.
646 scipy'05. Will docstring later.
612
647
613 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
648 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
614
649
615 * IPython/Shell.py (sigint_handler): Drastic simplification which
650 * IPython/Shell.py (sigint_handler): Drastic simplification which
616 also seems to make Ctrl-C work correctly across threads! This is
651 also seems to make Ctrl-C work correctly across threads! This is
617 so simple, that I can't beleive I'd missed it before. Needs more
652 so simple, that I can't beleive I'd missed it before. Needs more
618 testing, though.
653 testing, though.
619 (KBINT): Never mind, revert changes. I'm sure I'd tried something
654 (KBINT): Never mind, revert changes. I'm sure I'd tried something
620 like this before...
655 like this before...
621
656
622 * IPython/genutils.py (get_home_dir): add protection against
657 * IPython/genutils.py (get_home_dir): add protection against
623 non-dirs in win32 registry.
658 non-dirs in win32 registry.
624
659
625 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
660 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
626 bug where dict was mutated while iterating (pysh crash).
661 bug where dict was mutated while iterating (pysh crash).
627
662
628 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
663 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
629
664
630 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
665 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
631 spurious newlines added by this routine. After a report by
666 spurious newlines added by this routine. After a report by
632 F. Mantegazza.
667 F. Mantegazza.
633
668
634 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
669 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
635
670
636 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
671 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
637 calls. These were a leftover from the GTK 1.x days, and can cause
672 calls. These were a leftover from the GTK 1.x days, and can cause
638 problems in certain cases (after a report by John Hunter).
673 problems in certain cases (after a report by John Hunter).
639
674
640 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
675 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
641 os.getcwd() fails at init time. Thanks to patch from David Remahl
676 os.getcwd() fails at init time. Thanks to patch from David Remahl
642 <chmod007-AT-mac.com>.
677 <chmod007-AT-mac.com>.
643 (InteractiveShell.__init__): prevent certain special magics from
678 (InteractiveShell.__init__): prevent certain special magics from
644 being shadowed by aliases. Closes
679 being shadowed by aliases. Closes
645 http://www.scipy.net/roundup/ipython/issue41.
680 http://www.scipy.net/roundup/ipython/issue41.
646
681
647 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
682 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
648
683
649 * IPython/iplib.py (InteractiveShell.complete): Added new
684 * IPython/iplib.py (InteractiveShell.complete): Added new
650 top-level completion method to expose the completion mechanism
685 top-level completion method to expose the completion mechanism
651 beyond readline-based environments.
686 beyond readline-based environments.
652
687
653 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
688 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
654
689
655 * tools/ipsvnc (svnversion): fix svnversion capture.
690 * tools/ipsvnc (svnversion): fix svnversion capture.
656
691
657 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
692 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
658 attribute to self, which was missing. Before, it was set by a
693 attribute to self, which was missing. Before, it was set by a
659 routine which in certain cases wasn't being called, so the
694 routine which in certain cases wasn't being called, so the
660 instance could end up missing the attribute. This caused a crash.
695 instance could end up missing the attribute. This caused a crash.
661 Closes http://www.scipy.net/roundup/ipython/issue40.
696 Closes http://www.scipy.net/roundup/ipython/issue40.
662
697
663 2005-08-16 Fernando Perez <fperez@colorado.edu>
698 2005-08-16 Fernando Perez <fperez@colorado.edu>
664
699
665 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
700 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
666 contains non-string attribute. Closes
701 contains non-string attribute. Closes
667 http://www.scipy.net/roundup/ipython/issue38.
702 http://www.scipy.net/roundup/ipython/issue38.
668
703
669 2005-08-14 Fernando Perez <fperez@colorado.edu>
704 2005-08-14 Fernando Perez <fperez@colorado.edu>
670
705
671 * tools/ipsvnc: Minor improvements, to add changeset info.
706 * tools/ipsvnc: Minor improvements, to add changeset info.
672
707
673 2005-08-12 Fernando Perez <fperez@colorado.edu>
708 2005-08-12 Fernando Perez <fperez@colorado.edu>
674
709
675 * IPython/iplib.py (runsource): remove self.code_to_run_src
710 * IPython/iplib.py (runsource): remove self.code_to_run_src
676 attribute. I realized this is nothing more than
711 attribute. I realized this is nothing more than
677 '\n'.join(self.buffer), and having the same data in two different
712 '\n'.join(self.buffer), and having the same data in two different
678 places is just asking for synchronization bugs. This may impact
713 places is just asking for synchronization bugs. This may impact
679 people who have custom exception handlers, so I need to warn
714 people who have custom exception handlers, so I need to warn
680 ipython-dev about it (F. Mantegazza may use them).
715 ipython-dev about it (F. Mantegazza may use them).
681
716
682 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
717 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
683
718
684 * IPython/genutils.py: fix 2.2 compatibility (generators)
719 * IPython/genutils.py: fix 2.2 compatibility (generators)
685
720
686 2005-07-18 Fernando Perez <fperez@colorado.edu>
721 2005-07-18 Fernando Perez <fperez@colorado.edu>
687
722
688 * IPython/genutils.py (get_home_dir): fix to help users with
723 * IPython/genutils.py (get_home_dir): fix to help users with
689 invalid $HOME under win32.
724 invalid $HOME under win32.
690
725
691 2005-07-17 Fernando Perez <fperez@colorado.edu>
726 2005-07-17 Fernando Perez <fperez@colorado.edu>
692
727
693 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
728 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
694 some old hacks and clean up a bit other routines; code should be
729 some old hacks and clean up a bit other routines; code should be
695 simpler and a bit faster.
730 simpler and a bit faster.
696
731
697 * IPython/iplib.py (interact): removed some last-resort attempts
732 * IPython/iplib.py (interact): removed some last-resort attempts
698 to survive broken stdout/stderr. That code was only making it
733 to survive broken stdout/stderr. That code was only making it
699 harder to abstract out the i/o (necessary for gui integration),
734 harder to abstract out the i/o (necessary for gui integration),
700 and the crashes it could prevent were extremely rare in practice
735 and the crashes it could prevent were extremely rare in practice
701 (besides being fully user-induced in a pretty violent manner).
736 (besides being fully user-induced in a pretty violent manner).
702
737
703 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
738 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
704 Nothing major yet, but the code is simpler to read; this should
739 Nothing major yet, but the code is simpler to read; this should
705 make it easier to do more serious modifications in the future.
740 make it easier to do more serious modifications in the future.
706
741
707 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
742 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
708 which broke in .15 (thanks to a report by Ville).
743 which broke in .15 (thanks to a report by Ville).
709
744
710 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
745 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
711 be quite correct, I know next to nothing about unicode). This
746 be quite correct, I know next to nothing about unicode). This
712 will allow unicode strings to be used in prompts, amongst other
747 will allow unicode strings to be used in prompts, amongst other
713 cases. It also will prevent ipython from crashing when unicode
748 cases. It also will prevent ipython from crashing when unicode
714 shows up unexpectedly in many places. If ascii encoding fails, we
749 shows up unexpectedly in many places. If ascii encoding fails, we
715 assume utf_8. Currently the encoding is not a user-visible
750 assume utf_8. Currently the encoding is not a user-visible
716 setting, though it could be made so if there is demand for it.
751 setting, though it could be made so if there is demand for it.
717
752
718 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
753 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
719
754
720 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
755 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
721
756
722 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
757 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
723
758
724 * IPython/genutils.py: Add 2.2 compatibility here, so all other
759 * IPython/genutils.py: Add 2.2 compatibility here, so all other
725 code can work transparently for 2.2/2.3.
760 code can work transparently for 2.2/2.3.
726
761
727 2005-07-16 Fernando Perez <fperez@colorado.edu>
762 2005-07-16 Fernando Perez <fperez@colorado.edu>
728
763
729 * IPython/ultraTB.py (ExceptionColors): Make a global variable
764 * IPython/ultraTB.py (ExceptionColors): Make a global variable
730 out of the color scheme table used for coloring exception
765 out of the color scheme table used for coloring exception
731 tracebacks. This allows user code to add new schemes at runtime.
766 tracebacks. This allows user code to add new schemes at runtime.
732 This is a minimally modified version of the patch at
767 This is a minimally modified version of the patch at
733 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
768 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
734 for the contribution.
769 for the contribution.
735
770
736 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
771 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
737 slightly modified version of the patch in
772 slightly modified version of the patch in
738 http://www.scipy.net/roundup/ipython/issue34, which also allows me
773 http://www.scipy.net/roundup/ipython/issue34, which also allows me
739 to remove the previous try/except solution (which was costlier).
774 to remove the previous try/except solution (which was costlier).
740 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
775 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
741
776
742 2005-06-08 Fernando Perez <fperez@colorado.edu>
777 2005-06-08 Fernando Perez <fperez@colorado.edu>
743
778
744 * IPython/iplib.py (write/write_err): Add methods to abstract all
779 * IPython/iplib.py (write/write_err): Add methods to abstract all
745 I/O a bit more.
780 I/O a bit more.
746
781
747 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
782 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
748 warning, reported by Aric Hagberg, fix by JD Hunter.
783 warning, reported by Aric Hagberg, fix by JD Hunter.
749
784
750 2005-06-02 *** Released version 0.6.15
785 2005-06-02 *** Released version 0.6.15
751
786
752 2005-06-01 Fernando Perez <fperez@colorado.edu>
787 2005-06-01 Fernando Perez <fperez@colorado.edu>
753
788
754 * IPython/iplib.py (MagicCompleter.file_matches): Fix
789 * IPython/iplib.py (MagicCompleter.file_matches): Fix
755 tab-completion of filenames within open-quoted strings. Note that
790 tab-completion of filenames within open-quoted strings. Note that
756 this requires that in ~/.ipython/ipythonrc, users change the
791 this requires that in ~/.ipython/ipythonrc, users change the
757 readline delimiters configuration to read:
792 readline delimiters configuration to read:
758
793
759 readline_remove_delims -/~
794 readline_remove_delims -/~
760
795
761
796
762 2005-05-31 *** Released version 0.6.14
797 2005-05-31 *** Released version 0.6.14
763
798
764 2005-05-29 Fernando Perez <fperez@colorado.edu>
799 2005-05-29 Fernando Perez <fperez@colorado.edu>
765
800
766 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
801 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
767 with files not on the filesystem. Reported by Eliyahu Sandler
802 with files not on the filesystem. Reported by Eliyahu Sandler
768 <eli@gondolin.net>
803 <eli@gondolin.net>
769
804
770 2005-05-22 Fernando Perez <fperez@colorado.edu>
805 2005-05-22 Fernando Perez <fperez@colorado.edu>
771
806
772 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
807 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
773 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
808 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
774
809
775 2005-05-19 Fernando Perez <fperez@colorado.edu>
810 2005-05-19 Fernando Perez <fperez@colorado.edu>
776
811
777 * IPython/iplib.py (safe_execfile): close a file which could be
812 * IPython/iplib.py (safe_execfile): close a file which could be
778 left open (causing problems in win32, which locks open files).
813 left open (causing problems in win32, which locks open files).
779 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
814 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
780
815
781 2005-05-18 Fernando Perez <fperez@colorado.edu>
816 2005-05-18 Fernando Perez <fperez@colorado.edu>
782
817
783 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
818 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
784 keyword arguments correctly to safe_execfile().
819 keyword arguments correctly to safe_execfile().
785
820
786 2005-05-13 Fernando Perez <fperez@colorado.edu>
821 2005-05-13 Fernando Perez <fperez@colorado.edu>
787
822
788 * ipython.1: Added info about Qt to manpage, and threads warning
823 * ipython.1: Added info about Qt to manpage, and threads warning
789 to usage page (invoked with --help).
824 to usage page (invoked with --help).
790
825
791 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
826 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
792 new matcher (it goes at the end of the priority list) to do
827 new matcher (it goes at the end of the priority list) to do
793 tab-completion on named function arguments. Submitted by George
828 tab-completion on named function arguments. Submitted by George
794 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
829 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
795 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
830 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
796 for more details.
831 for more details.
797
832
798 * IPython/Magic.py (magic_run): Added new -e flag to ignore
833 * IPython/Magic.py (magic_run): Added new -e flag to ignore
799 SystemExit exceptions in the script being run. Thanks to a report
834 SystemExit exceptions in the script being run. Thanks to a report
800 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
835 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
801 producing very annoying behavior when running unit tests.
836 producing very annoying behavior when running unit tests.
802
837
803 2005-05-12 Fernando Perez <fperez@colorado.edu>
838 2005-05-12 Fernando Perez <fperez@colorado.edu>
804
839
805 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
840 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
806 which I'd broken (again) due to a changed regexp. In the process,
841 which I'd broken (again) due to a changed regexp. In the process,
807 added ';' as an escape to auto-quote the whole line without
842 added ';' as an escape to auto-quote the whole line without
808 splitting its arguments. Thanks to a report by Jerry McRae
843 splitting its arguments. Thanks to a report by Jerry McRae
809 <qrs0xyc02-AT-sneakemail.com>.
844 <qrs0xyc02-AT-sneakemail.com>.
810
845
811 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
846 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
812 possible crashes caused by a TokenError. Reported by Ed Schofield
847 possible crashes caused by a TokenError. Reported by Ed Schofield
813 <schofield-AT-ftw.at>.
848 <schofield-AT-ftw.at>.
814
849
815 2005-05-06 Fernando Perez <fperez@colorado.edu>
850 2005-05-06 Fernando Perez <fperez@colorado.edu>
816
851
817 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
852 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
818
853
819 2005-04-29 Fernando Perez <fperez@colorado.edu>
854 2005-04-29 Fernando Perez <fperez@colorado.edu>
820
855
821 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
856 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
822 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
857 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
823 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
858 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
824 which provides support for Qt interactive usage (similar to the
859 which provides support for Qt interactive usage (similar to the
825 existing one for WX and GTK). This had been often requested.
860 existing one for WX and GTK). This had been often requested.
826
861
827 2005-04-14 *** Released version 0.6.13
862 2005-04-14 *** Released version 0.6.13
828
863
829 2005-04-08 Fernando Perez <fperez@colorado.edu>
864 2005-04-08 Fernando Perez <fperez@colorado.edu>
830
865
831 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
866 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
832 from _ofind, which gets called on almost every input line. Now,
867 from _ofind, which gets called on almost every input line. Now,
833 we only try to get docstrings if they are actually going to be
868 we only try to get docstrings if they are actually going to be
834 used (the overhead of fetching unnecessary docstrings can be
869 used (the overhead of fetching unnecessary docstrings can be
835 noticeable for certain objects, such as Pyro proxies).
870 noticeable for certain objects, such as Pyro proxies).
836
871
837 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
872 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
838 for completers. For some reason I had been passing them the state
873 for completers. For some reason I had been passing them the state
839 variable, which completers never actually need, and was in
874 variable, which completers never actually need, and was in
840 conflict with the rlcompleter API. Custom completers ONLY need to
875 conflict with the rlcompleter API. Custom completers ONLY need to
841 take the text parameter.
876 take the text parameter.
842
877
843 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
878 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
844 work correctly in pysh. I've also moved all the logic which used
879 work correctly in pysh. I've also moved all the logic which used
845 to be in pysh.py here, which will prevent problems with future
880 to be in pysh.py here, which will prevent problems with future
846 upgrades. However, this time I must warn users to update their
881 upgrades. However, this time I must warn users to update their
847 pysh profile to include the line
882 pysh profile to include the line
848
883
849 import_all IPython.Extensions.InterpreterExec
884 import_all IPython.Extensions.InterpreterExec
850
885
851 because otherwise things won't work for them. They MUST also
886 because otherwise things won't work for them. They MUST also
852 delete pysh.py and the line
887 delete pysh.py and the line
853
888
854 execfile pysh.py
889 execfile pysh.py
855
890
856 from their ipythonrc-pysh.
891 from their ipythonrc-pysh.
857
892
858 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
893 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
859 robust in the face of objects whose dir() returns non-strings
894 robust in the face of objects whose dir() returns non-strings
860 (which it shouldn't, but some broken libs like ITK do). Thanks to
895 (which it shouldn't, but some broken libs like ITK do). Thanks to
861 a patch by John Hunter (implemented differently, though). Also
896 a patch by John Hunter (implemented differently, though). Also
862 minor improvements by using .extend instead of + on lists.
897 minor improvements by using .extend instead of + on lists.
863
898
864 * pysh.py:
899 * pysh.py:
865
900
866 2005-04-06 Fernando Perez <fperez@colorado.edu>
901 2005-04-06 Fernando Perez <fperez@colorado.edu>
867
902
868 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
903 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
869 by default, so that all users benefit from it. Those who don't
904 by default, so that all users benefit from it. Those who don't
870 want it can still turn it off.
905 want it can still turn it off.
871
906
872 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
907 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
873 config file, I'd forgotten about this, so users were getting it
908 config file, I'd forgotten about this, so users were getting it
874 off by default.
909 off by default.
875
910
876 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
911 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
877 consistency. Now magics can be called in multiline statements,
912 consistency. Now magics can be called in multiline statements,
878 and python variables can be expanded in magic calls via $var.
913 and python variables can be expanded in magic calls via $var.
879 This makes the magic system behave just like aliases or !system
914 This makes the magic system behave just like aliases or !system
880 calls.
915 calls.
881
916
882 2005-03-28 Fernando Perez <fperez@colorado.edu>
917 2005-03-28 Fernando Perez <fperez@colorado.edu>
883
918
884 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
919 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
885 expensive string additions for building command. Add support for
920 expensive string additions for building command. Add support for
886 trailing ';' when autocall is used.
921 trailing ';' when autocall is used.
887
922
888 2005-03-26 Fernando Perez <fperez@colorado.edu>
923 2005-03-26 Fernando Perez <fperez@colorado.edu>
889
924
890 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
925 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
891 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
926 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
892 ipython.el robust against prompts with any number of spaces
927 ipython.el robust against prompts with any number of spaces
893 (including 0) after the ':' character.
928 (including 0) after the ':' character.
894
929
895 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
930 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
896 continuation prompt, which misled users to think the line was
931 continuation prompt, which misled users to think the line was
897 already indented. Closes debian Bug#300847, reported to me by
932 already indented. Closes debian Bug#300847, reported to me by
898 Norbert Tretkowski <tretkowski-AT-inittab.de>.
933 Norbert Tretkowski <tretkowski-AT-inittab.de>.
899
934
900 2005-03-23 Fernando Perez <fperez@colorado.edu>
935 2005-03-23 Fernando Perez <fperez@colorado.edu>
901
936
902 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
937 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
903 properly aligned if they have embedded newlines.
938 properly aligned if they have embedded newlines.
904
939
905 * IPython/iplib.py (runlines): Add a public method to expose
940 * IPython/iplib.py (runlines): Add a public method to expose
906 IPython's code execution machinery, so that users can run strings
941 IPython's code execution machinery, so that users can run strings
907 as if they had been typed at the prompt interactively.
942 as if they had been typed at the prompt interactively.
908 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
943 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
909 methods which can call the system shell, but with python variable
944 methods which can call the system shell, but with python variable
910 expansion. The three such methods are: __IPYTHON__.system,
945 expansion. The three such methods are: __IPYTHON__.system,
911 .getoutput and .getoutputerror. These need to be documented in a
946 .getoutput and .getoutputerror. These need to be documented in a
912 'public API' section (to be written) of the manual.
947 'public API' section (to be written) of the manual.
913
948
914 2005-03-20 Fernando Perez <fperez@colorado.edu>
949 2005-03-20 Fernando Perez <fperez@colorado.edu>
915
950
916 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
951 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
917 for custom exception handling. This is quite powerful, and it
952 for custom exception handling. This is quite powerful, and it
918 allows for user-installable exception handlers which can trap
953 allows for user-installable exception handlers which can trap
919 custom exceptions at runtime and treat them separately from
954 custom exceptions at runtime and treat them separately from
920 IPython's default mechanisms. At the request of Frédéric
955 IPython's default mechanisms. At the request of Frédéric
921 Mantegazza <mantegazza-AT-ill.fr>.
956 Mantegazza <mantegazza-AT-ill.fr>.
922 (InteractiveShell.set_custom_completer): public API function to
957 (InteractiveShell.set_custom_completer): public API function to
923 add new completers at runtime.
958 add new completers at runtime.
924
959
925 2005-03-19 Fernando Perez <fperez@colorado.edu>
960 2005-03-19 Fernando Perez <fperez@colorado.edu>
926
961
927 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
962 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
928 allow objects which provide their docstrings via non-standard
963 allow objects which provide their docstrings via non-standard
929 mechanisms (like Pyro proxies) to still be inspected by ipython's
964 mechanisms (like Pyro proxies) to still be inspected by ipython's
930 ? system.
965 ? system.
931
966
932 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
967 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
933 automatic capture system. I tried quite hard to make it work
968 automatic capture system. I tried quite hard to make it work
934 reliably, and simply failed. I tried many combinations with the
969 reliably, and simply failed. I tried many combinations with the
935 subprocess module, but eventually nothing worked in all needed
970 subprocess module, but eventually nothing worked in all needed
936 cases (not blocking stdin for the child, duplicating stdout
971 cases (not blocking stdin for the child, duplicating stdout
937 without blocking, etc). The new %sc/%sx still do capture to these
972 without blocking, etc). The new %sc/%sx still do capture to these
938 magical list/string objects which make shell use much more
973 magical list/string objects which make shell use much more
939 conveninent, so not all is lost.
974 conveninent, so not all is lost.
940
975
941 XXX - FIX MANUAL for the change above!
976 XXX - FIX MANUAL for the change above!
942
977
943 (runsource): I copied code.py's runsource() into ipython to modify
978 (runsource): I copied code.py's runsource() into ipython to modify
944 it a bit. Now the code object and source to be executed are
979 it a bit. Now the code object and source to be executed are
945 stored in ipython. This makes this info accessible to third-party
980 stored in ipython. This makes this info accessible to third-party
946 tools, like custom exception handlers. After a request by Frédéric
981 tools, like custom exception handlers. After a request by Frédéric
947 Mantegazza <mantegazza-AT-ill.fr>.
982 Mantegazza <mantegazza-AT-ill.fr>.
948
983
949 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
984 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
950 history-search via readline (like C-p/C-n). I'd wanted this for a
985 history-search via readline (like C-p/C-n). I'd wanted this for a
951 long time, but only recently found out how to do it. For users
986 long time, but only recently found out how to do it. For users
952 who already have their ipythonrc files made and want this, just
987 who already have their ipythonrc files made and want this, just
953 add:
988 add:
954
989
955 readline_parse_and_bind "\e[A": history-search-backward
990 readline_parse_and_bind "\e[A": history-search-backward
956 readline_parse_and_bind "\e[B": history-search-forward
991 readline_parse_and_bind "\e[B": history-search-forward
957
992
958 2005-03-18 Fernando Perez <fperez@colorado.edu>
993 2005-03-18 Fernando Perez <fperez@colorado.edu>
959
994
960 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
995 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
961 LSString and SList classes which allow transparent conversions
996 LSString and SList classes which allow transparent conversions
962 between list mode and whitespace-separated string.
997 between list mode and whitespace-separated string.
963 (magic_r): Fix recursion problem in %r.
998 (magic_r): Fix recursion problem in %r.
964
999
965 * IPython/genutils.py (LSString): New class to be used for
1000 * IPython/genutils.py (LSString): New class to be used for
966 automatic storage of the results of all alias/system calls in _o
1001 automatic storage of the results of all alias/system calls in _o
967 and _e (stdout/err). These provide a .l/.list attribute which
1002 and _e (stdout/err). These provide a .l/.list attribute which
968 does automatic splitting on newlines. This means that for most
1003 does automatic splitting on newlines. This means that for most
969 uses, you'll never need to do capturing of output with %sc/%sx
1004 uses, you'll never need to do capturing of output with %sc/%sx
970 anymore, since ipython keeps this always done for you. Note that
1005 anymore, since ipython keeps this always done for you. Note that
971 only the LAST results are stored, the _o/e variables are
1006 only the LAST results are stored, the _o/e variables are
972 overwritten on each call. If you need to save their contents
1007 overwritten on each call. If you need to save their contents
973 further, simply bind them to any other name.
1008 further, simply bind them to any other name.
974
1009
975 2005-03-17 Fernando Perez <fperez@colorado.edu>
1010 2005-03-17 Fernando Perez <fperez@colorado.edu>
976
1011
977 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
1012 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
978 prompt namespace handling.
1013 prompt namespace handling.
979
1014
980 2005-03-16 Fernando Perez <fperez@colorado.edu>
1015 2005-03-16 Fernando Perez <fperez@colorado.edu>
981
1016
982 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
1017 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
983 classic prompts to be '>>> ' (final space was missing, and it
1018 classic prompts to be '>>> ' (final space was missing, and it
984 trips the emacs python mode).
1019 trips the emacs python mode).
985 (BasePrompt.__str__): Added safe support for dynamic prompt
1020 (BasePrompt.__str__): Added safe support for dynamic prompt
986 strings. Now you can set your prompt string to be '$x', and the
1021 strings. Now you can set your prompt string to be '$x', and the
987 value of x will be printed from your interactive namespace. The
1022 value of x will be printed from your interactive namespace. The
988 interpolation syntax includes the full Itpl support, so
1023 interpolation syntax includes the full Itpl support, so
989 ${foo()+x+bar()} is a valid prompt string now, and the function
1024 ${foo()+x+bar()} is a valid prompt string now, and the function
990 calls will be made at runtime.
1025 calls will be made at runtime.
991
1026
992 2005-03-15 Fernando Perez <fperez@colorado.edu>
1027 2005-03-15 Fernando Perez <fperez@colorado.edu>
993
1028
994 * IPython/Magic.py (magic_history): renamed %hist to %history, to
1029 * IPython/Magic.py (magic_history): renamed %hist to %history, to
995 avoid name clashes in pylab. %hist still works, it just forwards
1030 avoid name clashes in pylab. %hist still works, it just forwards
996 the call to %history.
1031 the call to %history.
997
1032
998 2005-03-02 *** Released version 0.6.12
1033 2005-03-02 *** Released version 0.6.12
999
1034
1000 2005-03-02 Fernando Perez <fperez@colorado.edu>
1035 2005-03-02 Fernando Perez <fperez@colorado.edu>
1001
1036
1002 * IPython/iplib.py (handle_magic): log magic calls properly as
1037 * IPython/iplib.py (handle_magic): log magic calls properly as
1003 ipmagic() function calls.
1038 ipmagic() function calls.
1004
1039
1005 * IPython/Magic.py (magic_time): Improved %time to support
1040 * IPython/Magic.py (magic_time): Improved %time to support
1006 statements and provide wall-clock as well as CPU time.
1041 statements and provide wall-clock as well as CPU time.
1007
1042
1008 2005-02-27 Fernando Perez <fperez@colorado.edu>
1043 2005-02-27 Fernando Perez <fperez@colorado.edu>
1009
1044
1010 * IPython/hooks.py: New hooks module, to expose user-modifiable
1045 * IPython/hooks.py: New hooks module, to expose user-modifiable
1011 IPython functionality in a clean manner. For now only the editor
1046 IPython functionality in a clean manner. For now only the editor
1012 hook is actually written, and other thigns which I intend to turn
1047 hook is actually written, and other thigns which I intend to turn
1013 into proper hooks aren't yet there. The display and prefilter
1048 into proper hooks aren't yet there. The display and prefilter
1014 stuff, for example, should be hooks. But at least now the
1049 stuff, for example, should be hooks. But at least now the
1015 framework is in place, and the rest can be moved here with more
1050 framework is in place, and the rest can be moved here with more
1016 time later. IPython had had a .hooks variable for a long time for
1051 time later. IPython had had a .hooks variable for a long time for
1017 this purpose, but I'd never actually used it for anything.
1052 this purpose, but I'd never actually used it for anything.
1018
1053
1019 2005-02-26 Fernando Perez <fperez@colorado.edu>
1054 2005-02-26 Fernando Perez <fperez@colorado.edu>
1020
1055
1021 * IPython/ipmaker.py (make_IPython): make the default ipython
1056 * IPython/ipmaker.py (make_IPython): make the default ipython
1022 directory be called _ipython under win32, to follow more the
1057 directory be called _ipython under win32, to follow more the
1023 naming peculiarities of that platform (where buggy software like
1058 naming peculiarities of that platform (where buggy software like
1024 Visual Sourcesafe breaks with .named directories). Reported by
1059 Visual Sourcesafe breaks with .named directories). Reported by
1025 Ville Vainio.
1060 Ville Vainio.
1026
1061
1027 2005-02-23 Fernando Perez <fperez@colorado.edu>
1062 2005-02-23 Fernando Perez <fperez@colorado.edu>
1028
1063
1029 * IPython/iplib.py (InteractiveShell.__init__): removed a few
1064 * IPython/iplib.py (InteractiveShell.__init__): removed a few
1030 auto_aliases for win32 which were causing problems. Users can
1065 auto_aliases for win32 which were causing problems. Users can
1031 define the ones they personally like.
1066 define the ones they personally like.
1032
1067
1033 2005-02-21 Fernando Perez <fperez@colorado.edu>
1068 2005-02-21 Fernando Perez <fperez@colorado.edu>
1034
1069
1035 * IPython/Magic.py (magic_time): new magic to time execution of
1070 * IPython/Magic.py (magic_time): new magic to time execution of
1036 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
1071 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
1037
1072
1038 2005-02-19 Fernando Perez <fperez@colorado.edu>
1073 2005-02-19 Fernando Perez <fperez@colorado.edu>
1039
1074
1040 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
1075 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
1041 into keys (for prompts, for example).
1076 into keys (for prompts, for example).
1042
1077
1043 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
1078 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
1044 prompts in case users want them. This introduces a small behavior
1079 prompts in case users want them. This introduces a small behavior
1045 change: ipython does not automatically add a space to all prompts
1080 change: ipython does not automatically add a space to all prompts
1046 anymore. To get the old prompts with a space, users should add it
1081 anymore. To get the old prompts with a space, users should add it
1047 manually to their ipythonrc file, so for example prompt_in1 should
1082 manually to their ipythonrc file, so for example prompt_in1 should
1048 now read 'In [\#]: ' instead of 'In [\#]:'.
1083 now read 'In [\#]: ' instead of 'In [\#]:'.
1049 (BasePrompt.__init__): New option prompts_pad_left (only in rc
1084 (BasePrompt.__init__): New option prompts_pad_left (only in rc
1050 file) to control left-padding of secondary prompts.
1085 file) to control left-padding of secondary prompts.
1051
1086
1052 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
1087 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
1053 the profiler can't be imported. Fix for Debian, which removed
1088 the profiler can't be imported. Fix for Debian, which removed
1054 profile.py because of License issues. I applied a slightly
1089 profile.py because of License issues. I applied a slightly
1055 modified version of the original Debian patch at
1090 modified version of the original Debian patch at
1056 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
1091 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
1057
1092
1058 2005-02-17 Fernando Perez <fperez@colorado.edu>
1093 2005-02-17 Fernando Perez <fperez@colorado.edu>
1059
1094
1060 * IPython/genutils.py (native_line_ends): Fix bug which would
1095 * IPython/genutils.py (native_line_ends): Fix bug which would
1061 cause improper line-ends under win32 b/c I was not opening files
1096 cause improper line-ends under win32 b/c I was not opening files
1062 in binary mode. Bug report and fix thanks to Ville.
1097 in binary mode. Bug report and fix thanks to Ville.
1063
1098
1064 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
1099 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
1065 trying to catch spurious foo[1] autocalls. My fix actually broke
1100 trying to catch spurious foo[1] autocalls. My fix actually broke
1066 ',/' autoquote/call with explicit escape (bad regexp).
1101 ',/' autoquote/call with explicit escape (bad regexp).
1067
1102
1068 2005-02-15 *** Released version 0.6.11
1103 2005-02-15 *** Released version 0.6.11
1069
1104
1070 2005-02-14 Fernando Perez <fperez@colorado.edu>
1105 2005-02-14 Fernando Perez <fperez@colorado.edu>
1071
1106
1072 * IPython/background_jobs.py: New background job management
1107 * IPython/background_jobs.py: New background job management
1073 subsystem. This is implemented via a new set of classes, and
1108 subsystem. This is implemented via a new set of classes, and
1074 IPython now provides a builtin 'jobs' object for background job
1109 IPython now provides a builtin 'jobs' object for background job
1075 execution. A convenience %bg magic serves as a lightweight
1110 execution. A convenience %bg magic serves as a lightweight
1076 frontend for starting the more common type of calls. This was
1111 frontend for starting the more common type of calls. This was
1077 inspired by discussions with B. Granger and the BackgroundCommand
1112 inspired by discussions with B. Granger and the BackgroundCommand
1078 class described in the book Python Scripting for Computational
1113 class described in the book Python Scripting for Computational
1079 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
1114 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
1080 (although ultimately no code from this text was used, as IPython's
1115 (although ultimately no code from this text was used, as IPython's
1081 system is a separate implementation).
1116 system is a separate implementation).
1082
1117
1083 * IPython/iplib.py (MagicCompleter.python_matches): add new option
1118 * IPython/iplib.py (MagicCompleter.python_matches): add new option
1084 to control the completion of single/double underscore names
1119 to control the completion of single/double underscore names
1085 separately. As documented in the example ipytonrc file, the
1120 separately. As documented in the example ipytonrc file, the
1086 readline_omit__names variable can now be set to 2, to omit even
1121 readline_omit__names variable can now be set to 2, to omit even
1087 single underscore names. Thanks to a patch by Brian Wong
1122 single underscore names. Thanks to a patch by Brian Wong
1088 <BrianWong-AT-AirgoNetworks.Com>.
1123 <BrianWong-AT-AirgoNetworks.Com>.
1089 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
1124 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
1090 be autocalled as foo([1]) if foo were callable. A problem for
1125 be autocalled as foo([1]) if foo were callable. A problem for
1091 things which are both callable and implement __getitem__.
1126 things which are both callable and implement __getitem__.
1092 (init_readline): Fix autoindentation for win32. Thanks to a patch
1127 (init_readline): Fix autoindentation for win32. Thanks to a patch
1093 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
1128 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
1094
1129
1095 2005-02-12 Fernando Perez <fperez@colorado.edu>
1130 2005-02-12 Fernando Perez <fperez@colorado.edu>
1096
1131
1097 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
1132 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
1098 which I had written long ago to sort out user error messages which
1133 which I had written long ago to sort out user error messages which
1099 may occur during startup. This seemed like a good idea initially,
1134 may occur during startup. This seemed like a good idea initially,
1100 but it has proven a disaster in retrospect. I don't want to
1135 but it has proven a disaster in retrospect. I don't want to
1101 change much code for now, so my fix is to set the internal 'debug'
1136 change much code for now, so my fix is to set the internal 'debug'
1102 flag to true everywhere, whose only job was precisely to control
1137 flag to true everywhere, whose only job was precisely to control
1103 this subsystem. This closes issue 28 (as well as avoiding all
1138 this subsystem. This closes issue 28 (as well as avoiding all
1104 sorts of strange hangups which occur from time to time).
1139 sorts of strange hangups which occur from time to time).
1105
1140
1106 2005-02-07 Fernando Perez <fperez@colorado.edu>
1141 2005-02-07 Fernando Perez <fperez@colorado.edu>
1107
1142
1108 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
1143 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
1109 previous call produced a syntax error.
1144 previous call produced a syntax error.
1110
1145
1111 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1146 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1112 classes without constructor.
1147 classes without constructor.
1113
1148
1114 2005-02-06 Fernando Perez <fperez@colorado.edu>
1149 2005-02-06 Fernando Perez <fperez@colorado.edu>
1115
1150
1116 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
1151 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
1117 completions with the results of each matcher, so we return results
1152 completions with the results of each matcher, so we return results
1118 to the user from all namespaces. This breaks with ipython
1153 to the user from all namespaces. This breaks with ipython
1119 tradition, but I think it's a nicer behavior. Now you get all
1154 tradition, but I think it's a nicer behavior. Now you get all
1120 possible completions listed, from all possible namespaces (python,
1155 possible completions listed, from all possible namespaces (python,
1121 filesystem, magics...) After a request by John Hunter
1156 filesystem, magics...) After a request by John Hunter
1122 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1157 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1123
1158
1124 2005-02-05 Fernando Perez <fperez@colorado.edu>
1159 2005-02-05 Fernando Perez <fperez@colorado.edu>
1125
1160
1126 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
1161 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
1127 the call had quote characters in it (the quotes were stripped).
1162 the call had quote characters in it (the quotes were stripped).
1128
1163
1129 2005-01-31 Fernando Perez <fperez@colorado.edu>
1164 2005-01-31 Fernando Perez <fperez@colorado.edu>
1130
1165
1131 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
1166 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
1132 Itpl.itpl() to make the code more robust against psyco
1167 Itpl.itpl() to make the code more robust against psyco
1133 optimizations.
1168 optimizations.
1134
1169
1135 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
1170 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
1136 of causing an exception. Quicker, cleaner.
1171 of causing an exception. Quicker, cleaner.
1137
1172
1138 2005-01-28 Fernando Perez <fperez@colorado.edu>
1173 2005-01-28 Fernando Perez <fperez@colorado.edu>
1139
1174
1140 * scripts/ipython_win_post_install.py (install): hardcode
1175 * scripts/ipython_win_post_install.py (install): hardcode
1141 sys.prefix+'python.exe' as the executable path. It turns out that
1176 sys.prefix+'python.exe' as the executable path. It turns out that
1142 during the post-installation run, sys.executable resolves to the
1177 during the post-installation run, sys.executable resolves to the
1143 name of the binary installer! I should report this as a distutils
1178 name of the binary installer! I should report this as a distutils
1144 bug, I think. I updated the .10 release with this tiny fix, to
1179 bug, I think. I updated the .10 release with this tiny fix, to
1145 avoid annoying the lists further.
1180 avoid annoying the lists further.
1146
1181
1147 2005-01-27 *** Released version 0.6.10
1182 2005-01-27 *** Released version 0.6.10
1148
1183
1149 2005-01-27 Fernando Perez <fperez@colorado.edu>
1184 2005-01-27 Fernando Perez <fperez@colorado.edu>
1150
1185
1151 * IPython/numutils.py (norm): Added 'inf' as optional name for
1186 * IPython/numutils.py (norm): Added 'inf' as optional name for
1152 L-infinity norm, included references to mathworld.com for vector
1187 L-infinity norm, included references to mathworld.com for vector
1153 norm definitions.
1188 norm definitions.
1154 (amin/amax): added amin/amax for array min/max. Similar to what
1189 (amin/amax): added amin/amax for array min/max. Similar to what
1155 pylab ships with after the recent reorganization of names.
1190 pylab ships with after the recent reorganization of names.
1156 (spike/spike_odd): removed deprecated spike/spike_odd functions.
1191 (spike/spike_odd): removed deprecated spike/spike_odd functions.
1157
1192
1158 * ipython.el: committed Alex's recent fixes and improvements.
1193 * ipython.el: committed Alex's recent fixes and improvements.
1159 Tested with python-mode from CVS, and it looks excellent. Since
1194 Tested with python-mode from CVS, and it looks excellent. Since
1160 python-mode hasn't released anything in a while, I'm temporarily
1195 python-mode hasn't released anything in a while, I'm temporarily
1161 putting a copy of today's CVS (v 4.70) of python-mode in:
1196 putting a copy of today's CVS (v 4.70) of python-mode in:
1162 http://ipython.scipy.org/tmp/python-mode.el
1197 http://ipython.scipy.org/tmp/python-mode.el
1163
1198
1164 * scripts/ipython_win_post_install.py (install): Win32 fix to use
1199 * scripts/ipython_win_post_install.py (install): Win32 fix to use
1165 sys.executable for the executable name, instead of assuming it's
1200 sys.executable for the executable name, instead of assuming it's
1166 called 'python.exe' (the post-installer would have produced broken
1201 called 'python.exe' (the post-installer would have produced broken
1167 setups on systems with a differently named python binary).
1202 setups on systems with a differently named python binary).
1168
1203
1169 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
1204 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
1170 references to os.linesep, to make the code more
1205 references to os.linesep, to make the code more
1171 platform-independent. This is also part of the win32 coloring
1206 platform-independent. This is also part of the win32 coloring
1172 fixes.
1207 fixes.
1173
1208
1174 * IPython/genutils.py (page_dumb): Remove attempts to chop long
1209 * IPython/genutils.py (page_dumb): Remove attempts to chop long
1175 lines, which actually cause coloring bugs because the length of
1210 lines, which actually cause coloring bugs because the length of
1176 the line is very difficult to correctly compute with embedded
1211 the line is very difficult to correctly compute with embedded
1177 escapes. This was the source of all the coloring problems under
1212 escapes. This was the source of all the coloring problems under
1178 Win32. I think that _finally_, Win32 users have a properly
1213 Win32. I think that _finally_, Win32 users have a properly
1179 working ipython in all respects. This would never have happened
1214 working ipython in all respects. This would never have happened
1180 if not for Gary Bishop and Viktor Ransmayr's great help and work.
1215 if not for Gary Bishop and Viktor Ransmayr's great help and work.
1181
1216
1182 2005-01-26 *** Released version 0.6.9
1217 2005-01-26 *** Released version 0.6.9
1183
1218
1184 2005-01-25 Fernando Perez <fperez@colorado.edu>
1219 2005-01-25 Fernando Perez <fperez@colorado.edu>
1185
1220
1186 * setup.py: finally, we have a true Windows installer, thanks to
1221 * setup.py: finally, we have a true Windows installer, thanks to
1187 the excellent work of Viktor Ransmayr
1222 the excellent work of Viktor Ransmayr
1188 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
1223 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
1189 Windows users. The setup routine is quite a bit cleaner thanks to
1224 Windows users. The setup routine is quite a bit cleaner thanks to
1190 this, and the post-install script uses the proper functions to
1225 this, and the post-install script uses the proper functions to
1191 allow a clean de-installation using the standard Windows Control
1226 allow a clean de-installation using the standard Windows Control
1192 Panel.
1227 Panel.
1193
1228
1194 * IPython/genutils.py (get_home_dir): changed to use the $HOME
1229 * IPython/genutils.py (get_home_dir): changed to use the $HOME
1195 environment variable under all OSes (including win32) if
1230 environment variable under all OSes (including win32) if
1196 available. This will give consistency to win32 users who have set
1231 available. This will give consistency to win32 users who have set
1197 this variable for any reason. If os.environ['HOME'] fails, the
1232 this variable for any reason. If os.environ['HOME'] fails, the
1198 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
1233 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
1199
1234
1200 2005-01-24 Fernando Perez <fperez@colorado.edu>
1235 2005-01-24 Fernando Perez <fperez@colorado.edu>
1201
1236
1202 * IPython/numutils.py (empty_like): add empty_like(), similar to
1237 * IPython/numutils.py (empty_like): add empty_like(), similar to
1203 zeros_like() but taking advantage of the new empty() Numeric routine.
1238 zeros_like() but taking advantage of the new empty() Numeric routine.
1204
1239
1205 2005-01-23 *** Released version 0.6.8
1240 2005-01-23 *** Released version 0.6.8
1206
1241
1207 2005-01-22 Fernando Perez <fperez@colorado.edu>
1242 2005-01-22 Fernando Perez <fperez@colorado.edu>
1208
1243
1209 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
1244 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
1210 automatic show() calls. After discussing things with JDH, it
1245 automatic show() calls. After discussing things with JDH, it
1211 turns out there are too many corner cases where this can go wrong.
1246 turns out there are too many corner cases where this can go wrong.
1212 It's best not to try to be 'too smart', and simply have ipython
1247 It's best not to try to be 'too smart', and simply have ipython
1213 reproduce as much as possible the default behavior of a normal
1248 reproduce as much as possible the default behavior of a normal
1214 python shell.
1249 python shell.
1215
1250
1216 * IPython/iplib.py (InteractiveShell.__init__): Modified the
1251 * IPython/iplib.py (InteractiveShell.__init__): Modified the
1217 line-splitting regexp and _prefilter() to avoid calling getattr()
1252 line-splitting regexp and _prefilter() to avoid calling getattr()
1218 on assignments. This closes
1253 on assignments. This closes
1219 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
1254 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
1220 readline uses getattr(), so a simple <TAB> keypress is still
1255 readline uses getattr(), so a simple <TAB> keypress is still
1221 enough to trigger getattr() calls on an object.
1256 enough to trigger getattr() calls on an object.
1222
1257
1223 2005-01-21 Fernando Perez <fperez@colorado.edu>
1258 2005-01-21 Fernando Perez <fperez@colorado.edu>
1224
1259
1225 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
1260 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
1226 docstring under pylab so it doesn't mask the original.
1261 docstring under pylab so it doesn't mask the original.
1227
1262
1228 2005-01-21 *** Released version 0.6.7
1263 2005-01-21 *** Released version 0.6.7
1229
1264
1230 2005-01-21 Fernando Perez <fperez@colorado.edu>
1265 2005-01-21 Fernando Perez <fperez@colorado.edu>
1231
1266
1232 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
1267 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
1233 signal handling for win32 users in multithreaded mode.
1268 signal handling for win32 users in multithreaded mode.
1234
1269
1235 2005-01-17 Fernando Perez <fperez@colorado.edu>
1270 2005-01-17 Fernando Perez <fperez@colorado.edu>
1236
1271
1237 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1272 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1238 instances with no __init__. After a crash report by Norbert Nemec
1273 instances with no __init__. After a crash report by Norbert Nemec
1239 <Norbert-AT-nemec-online.de>.
1274 <Norbert-AT-nemec-online.de>.
1240
1275
1241 2005-01-14 Fernando Perez <fperez@colorado.edu>
1276 2005-01-14 Fernando Perez <fperez@colorado.edu>
1242
1277
1243 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
1278 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
1244 names for verbose exceptions, when multiple dotted names and the
1279 names for verbose exceptions, when multiple dotted names and the
1245 'parent' object were present on the same line.
1280 'parent' object were present on the same line.
1246
1281
1247 2005-01-11 Fernando Perez <fperez@colorado.edu>
1282 2005-01-11 Fernando Perez <fperez@colorado.edu>
1248
1283
1249 * IPython/genutils.py (flag_calls): new utility to trap and flag
1284 * IPython/genutils.py (flag_calls): new utility to trap and flag
1250 calls in functions. I need it to clean up matplotlib support.
1285 calls in functions. I need it to clean up matplotlib support.
1251 Also removed some deprecated code in genutils.
1286 Also removed some deprecated code in genutils.
1252
1287
1253 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
1288 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
1254 that matplotlib scripts called with %run, which don't call show()
1289 that matplotlib scripts called with %run, which don't call show()
1255 themselves, still have their plotting windows open.
1290 themselves, still have their plotting windows open.
1256
1291
1257 2005-01-05 Fernando Perez <fperez@colorado.edu>
1292 2005-01-05 Fernando Perez <fperez@colorado.edu>
1258
1293
1259 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
1294 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
1260 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
1295 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
1261
1296
1262 2004-12-19 Fernando Perez <fperez@colorado.edu>
1297 2004-12-19 Fernando Perez <fperez@colorado.edu>
1263
1298
1264 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
1299 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
1265 parent_runcode, which was an eyesore. The same result can be
1300 parent_runcode, which was an eyesore. The same result can be
1266 obtained with Python's regular superclass mechanisms.
1301 obtained with Python's regular superclass mechanisms.
1267
1302
1268 2004-12-17 Fernando Perez <fperez@colorado.edu>
1303 2004-12-17 Fernando Perez <fperez@colorado.edu>
1269
1304
1270 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
1305 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
1271 reported by Prabhu.
1306 reported by Prabhu.
1272 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
1307 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
1273 sys.stderr) instead of explicitly calling sys.stderr. This helps
1308 sys.stderr) instead of explicitly calling sys.stderr. This helps
1274 maintain our I/O abstractions clean, for future GUI embeddings.
1309 maintain our I/O abstractions clean, for future GUI embeddings.
1275
1310
1276 * IPython/genutils.py (info): added new utility for sys.stderr
1311 * IPython/genutils.py (info): added new utility for sys.stderr
1277 unified info message handling (thin wrapper around warn()).
1312 unified info message handling (thin wrapper around warn()).
1278
1313
1279 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
1314 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
1280 composite (dotted) names on verbose exceptions.
1315 composite (dotted) names on verbose exceptions.
1281 (VerboseTB.nullrepr): harden against another kind of errors which
1316 (VerboseTB.nullrepr): harden against another kind of errors which
1282 Python's inspect module can trigger, and which were crashing
1317 Python's inspect module can trigger, and which were crashing
1283 IPython. Thanks to a report by Marco Lombardi
1318 IPython. Thanks to a report by Marco Lombardi
1284 <mlombard-AT-ma010192.hq.eso.org>.
1319 <mlombard-AT-ma010192.hq.eso.org>.
1285
1320
1286 2004-12-13 *** Released version 0.6.6
1321 2004-12-13 *** Released version 0.6.6
1287
1322
1288 2004-12-12 Fernando Perez <fperez@colorado.edu>
1323 2004-12-12 Fernando Perez <fperez@colorado.edu>
1289
1324
1290 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
1325 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
1291 generated by pygtk upon initialization if it was built without
1326 generated by pygtk upon initialization if it was built without
1292 threads (for matplotlib users). After a crash reported by
1327 threads (for matplotlib users). After a crash reported by
1293 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
1328 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
1294
1329
1295 * IPython/ipmaker.py (make_IPython): fix small bug in the
1330 * IPython/ipmaker.py (make_IPython): fix small bug in the
1296 import_some parameter for multiple imports.
1331 import_some parameter for multiple imports.
1297
1332
1298 * IPython/iplib.py (ipmagic): simplified the interface of
1333 * IPython/iplib.py (ipmagic): simplified the interface of
1299 ipmagic() to take a single string argument, just as it would be
1334 ipmagic() to take a single string argument, just as it would be
1300 typed at the IPython cmd line.
1335 typed at the IPython cmd line.
1301 (ipalias): Added new ipalias() with an interface identical to
1336 (ipalias): Added new ipalias() with an interface identical to
1302 ipmagic(). This completes exposing a pure python interface to the
1337 ipmagic(). This completes exposing a pure python interface to the
1303 alias and magic system, which can be used in loops or more complex
1338 alias and magic system, which can be used in loops or more complex
1304 code where IPython's automatic line mangling is not active.
1339 code where IPython's automatic line mangling is not active.
1305
1340
1306 * IPython/genutils.py (timing): changed interface of timing to
1341 * IPython/genutils.py (timing): changed interface of timing to
1307 simply run code once, which is the most common case. timings()
1342 simply run code once, which is the most common case. timings()
1308 remains unchanged, for the cases where you want multiple runs.
1343 remains unchanged, for the cases where you want multiple runs.
1309
1344
1310 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
1345 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
1311 bug where Python2.2 crashes with exec'ing code which does not end
1346 bug where Python2.2 crashes with exec'ing code which does not end
1312 in a single newline. Python 2.3 is OK, so I hadn't noticed this
1347 in a single newline. Python 2.3 is OK, so I hadn't noticed this
1313 before.
1348 before.
1314
1349
1315 2004-12-10 Fernando Perez <fperez@colorado.edu>
1350 2004-12-10 Fernando Perez <fperez@colorado.edu>
1316
1351
1317 * IPython/Magic.py (Magic.magic_prun): changed name of option from
1352 * IPython/Magic.py (Magic.magic_prun): changed name of option from
1318 -t to -T, to accomodate the new -t flag in %run (the %run and
1353 -t to -T, to accomodate the new -t flag in %run (the %run and
1319 %prun options are kind of intermixed, and it's not easy to change
1354 %prun options are kind of intermixed, and it's not easy to change
1320 this with the limitations of python's getopt).
1355 this with the limitations of python's getopt).
1321
1356
1322 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
1357 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
1323 the execution of scripts. It's not as fine-tuned as timeit.py,
1358 the execution of scripts. It's not as fine-tuned as timeit.py,
1324 but it works from inside ipython (and under 2.2, which lacks
1359 but it works from inside ipython (and under 2.2, which lacks
1325 timeit.py). Optionally a number of runs > 1 can be given for
1360 timeit.py). Optionally a number of runs > 1 can be given for
1326 timing very short-running code.
1361 timing very short-running code.
1327
1362
1328 * IPython/genutils.py (uniq_stable): new routine which returns a
1363 * IPython/genutils.py (uniq_stable): new routine which returns a
1329 list of unique elements in any iterable, but in stable order of
1364 list of unique elements in any iterable, but in stable order of
1330 appearance. I needed this for the ultraTB fixes, and it's a handy
1365 appearance. I needed this for the ultraTB fixes, and it's a handy
1331 utility.
1366 utility.
1332
1367
1333 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
1368 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
1334 dotted names in Verbose exceptions. This had been broken since
1369 dotted names in Verbose exceptions. This had been broken since
1335 the very start, now x.y will properly be printed in a Verbose
1370 the very start, now x.y will properly be printed in a Verbose
1336 traceback, instead of x being shown and y appearing always as an
1371 traceback, instead of x being shown and y appearing always as an
1337 'undefined global'. Getting this to work was a bit tricky,
1372 'undefined global'. Getting this to work was a bit tricky,
1338 because by default python tokenizers are stateless. Saved by
1373 because by default python tokenizers are stateless. Saved by
1339 python's ability to easily add a bit of state to an arbitrary
1374 python's ability to easily add a bit of state to an arbitrary
1340 function (without needing to build a full-blown callable object).
1375 function (without needing to build a full-blown callable object).
1341
1376
1342 Also big cleanup of this code, which had horrendous runtime
1377 Also big cleanup of this code, which had horrendous runtime
1343 lookups of zillions of attributes for colorization. Moved all
1378 lookups of zillions of attributes for colorization. Moved all
1344 this code into a few templates, which make it cleaner and quicker.
1379 this code into a few templates, which make it cleaner and quicker.
1345
1380
1346 Printout quality was also improved for Verbose exceptions: one
1381 Printout quality was also improved for Verbose exceptions: one
1347 variable per line, and memory addresses are printed (this can be
1382 variable per line, and memory addresses are printed (this can be
1348 quite handy in nasty debugging situations, which is what Verbose
1383 quite handy in nasty debugging situations, which is what Verbose
1349 is for).
1384 is for).
1350
1385
1351 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1386 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1352 the command line as scripts to be loaded by embedded instances.
1387 the command line as scripts to be loaded by embedded instances.
1353 Doing so has the potential for an infinite recursion if there are
1388 Doing so has the potential for an infinite recursion if there are
1354 exceptions thrown in the process. This fixes a strange crash
1389 exceptions thrown in the process. This fixes a strange crash
1355 reported by Philippe MULLER <muller-AT-irit.fr>.
1390 reported by Philippe MULLER <muller-AT-irit.fr>.
1356
1391
1357 2004-12-09 Fernando Perez <fperez@colorado.edu>
1392 2004-12-09 Fernando Perez <fperez@colorado.edu>
1358
1393
1359 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1394 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1360 to reflect new names in matplotlib, which now expose the
1395 to reflect new names in matplotlib, which now expose the
1361 matlab-compatible interface via a pylab module instead of the
1396 matlab-compatible interface via a pylab module instead of the
1362 'matlab' name. The new code is backwards compatible, so users of
1397 'matlab' name. The new code is backwards compatible, so users of
1363 all matplotlib versions are OK. Patch by J. Hunter.
1398 all matplotlib versions are OK. Patch by J. Hunter.
1364
1399
1365 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1400 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1366 of __init__ docstrings for instances (class docstrings are already
1401 of __init__ docstrings for instances (class docstrings are already
1367 automatically printed). Instances with customized docstrings
1402 automatically printed). Instances with customized docstrings
1368 (indep. of the class) are also recognized and all 3 separate
1403 (indep. of the class) are also recognized and all 3 separate
1369 docstrings are printed (instance, class, constructor). After some
1404 docstrings are printed (instance, class, constructor). After some
1370 comments/suggestions by J. Hunter.
1405 comments/suggestions by J. Hunter.
1371
1406
1372 2004-12-05 Fernando Perez <fperez@colorado.edu>
1407 2004-12-05 Fernando Perez <fperez@colorado.edu>
1373
1408
1374 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1409 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1375 warnings when tab-completion fails and triggers an exception.
1410 warnings when tab-completion fails and triggers an exception.
1376
1411
1377 2004-12-03 Fernando Perez <fperez@colorado.edu>
1412 2004-12-03 Fernando Perez <fperez@colorado.edu>
1378
1413
1379 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1414 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1380 be triggered when using 'run -p'. An incorrect option flag was
1415 be triggered when using 'run -p'. An incorrect option flag was
1381 being set ('d' instead of 'D').
1416 being set ('d' instead of 'D').
1382 (manpage): fix missing escaped \- sign.
1417 (manpage): fix missing escaped \- sign.
1383
1418
1384 2004-11-30 *** Released version 0.6.5
1419 2004-11-30 *** Released version 0.6.5
1385
1420
1386 2004-11-30 Fernando Perez <fperez@colorado.edu>
1421 2004-11-30 Fernando Perez <fperez@colorado.edu>
1387
1422
1388 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1423 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1389 setting with -d option.
1424 setting with -d option.
1390
1425
1391 * setup.py (docfiles): Fix problem where the doc glob I was using
1426 * setup.py (docfiles): Fix problem where the doc glob I was using
1392 was COMPLETELY BROKEN. It was giving the right files by pure
1427 was COMPLETELY BROKEN. It was giving the right files by pure
1393 accident, but failed once I tried to include ipython.el. Note:
1428 accident, but failed once I tried to include ipython.el. Note:
1394 glob() does NOT allow you to do exclusion on multiple endings!
1429 glob() does NOT allow you to do exclusion on multiple endings!
1395
1430
1396 2004-11-29 Fernando Perez <fperez@colorado.edu>
1431 2004-11-29 Fernando Perez <fperez@colorado.edu>
1397
1432
1398 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1433 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1399 the manpage as the source. Better formatting & consistency.
1434 the manpage as the source. Better formatting & consistency.
1400
1435
1401 * IPython/Magic.py (magic_run): Added new -d option, to run
1436 * IPython/Magic.py (magic_run): Added new -d option, to run
1402 scripts under the control of the python pdb debugger. Note that
1437 scripts under the control of the python pdb debugger. Note that
1403 this required changing the %prun option -d to -D, to avoid a clash
1438 this required changing the %prun option -d to -D, to avoid a clash
1404 (since %run must pass options to %prun, and getopt is too dumb to
1439 (since %run must pass options to %prun, and getopt is too dumb to
1405 handle options with string values with embedded spaces). Thanks
1440 handle options with string values with embedded spaces). Thanks
1406 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1441 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1407 (magic_who_ls): added type matching to %who and %whos, so that one
1442 (magic_who_ls): added type matching to %who and %whos, so that one
1408 can filter their output to only include variables of certain
1443 can filter their output to only include variables of certain
1409 types. Another suggestion by Matthew.
1444 types. Another suggestion by Matthew.
1410 (magic_whos): Added memory summaries in kb and Mb for arrays.
1445 (magic_whos): Added memory summaries in kb and Mb for arrays.
1411 (magic_who): Improve formatting (break lines every 9 vars).
1446 (magic_who): Improve formatting (break lines every 9 vars).
1412
1447
1413 2004-11-28 Fernando Perez <fperez@colorado.edu>
1448 2004-11-28 Fernando Perez <fperez@colorado.edu>
1414
1449
1415 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1450 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1416 cache when empty lines were present.
1451 cache when empty lines were present.
1417
1452
1418 2004-11-24 Fernando Perez <fperez@colorado.edu>
1453 2004-11-24 Fernando Perez <fperez@colorado.edu>
1419
1454
1420 * IPython/usage.py (__doc__): document the re-activated threading
1455 * IPython/usage.py (__doc__): document the re-activated threading
1421 options for WX and GTK.
1456 options for WX and GTK.
1422
1457
1423 2004-11-23 Fernando Perez <fperez@colorado.edu>
1458 2004-11-23 Fernando Perez <fperez@colorado.edu>
1424
1459
1425 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1460 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1426 the -wthread and -gthread options, along with a new -tk one to try
1461 the -wthread and -gthread options, along with a new -tk one to try
1427 and coordinate Tk threading with wx/gtk. The tk support is very
1462 and coordinate Tk threading with wx/gtk. The tk support is very
1428 platform dependent, since it seems to require Tcl and Tk to be
1463 platform dependent, since it seems to require Tcl and Tk to be
1429 built with threads (Fedora1/2 appears NOT to have it, but in
1464 built with threads (Fedora1/2 appears NOT to have it, but in
1430 Prabhu's Debian boxes it works OK). But even with some Tk
1465 Prabhu's Debian boxes it works OK). But even with some Tk
1431 limitations, this is a great improvement.
1466 limitations, this is a great improvement.
1432
1467
1433 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1468 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1434 info in user prompts. Patch by Prabhu.
1469 info in user prompts. Patch by Prabhu.
1435
1470
1436 2004-11-18 Fernando Perez <fperez@colorado.edu>
1471 2004-11-18 Fernando Perez <fperez@colorado.edu>
1437
1472
1438 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1473 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1439 EOFErrors and bail, to avoid infinite loops if a non-terminating
1474 EOFErrors and bail, to avoid infinite loops if a non-terminating
1440 file is fed into ipython. Patch submitted in issue 19 by user,
1475 file is fed into ipython. Patch submitted in issue 19 by user,
1441 many thanks.
1476 many thanks.
1442
1477
1443 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1478 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1444 autoquote/parens in continuation prompts, which can cause lots of
1479 autoquote/parens in continuation prompts, which can cause lots of
1445 problems. Closes roundup issue 20.
1480 problems. Closes roundup issue 20.
1446
1481
1447 2004-11-17 Fernando Perez <fperez@colorado.edu>
1482 2004-11-17 Fernando Perez <fperez@colorado.edu>
1448
1483
1449 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1484 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1450 reported as debian bug #280505. I'm not sure my local changelog
1485 reported as debian bug #280505. I'm not sure my local changelog
1451 entry has the proper debian format (Jack?).
1486 entry has the proper debian format (Jack?).
1452
1487
1453 2004-11-08 *** Released version 0.6.4
1488 2004-11-08 *** Released version 0.6.4
1454
1489
1455 2004-11-08 Fernando Perez <fperez@colorado.edu>
1490 2004-11-08 Fernando Perez <fperez@colorado.edu>
1456
1491
1457 * IPython/iplib.py (init_readline): Fix exit message for Windows
1492 * IPython/iplib.py (init_readline): Fix exit message for Windows
1458 when readline is active. Thanks to a report by Eric Jones
1493 when readline is active. Thanks to a report by Eric Jones
1459 <eric-AT-enthought.com>.
1494 <eric-AT-enthought.com>.
1460
1495
1461 2004-11-07 Fernando Perez <fperez@colorado.edu>
1496 2004-11-07 Fernando Perez <fperez@colorado.edu>
1462
1497
1463 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1498 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1464 sometimes seen by win2k/cygwin users.
1499 sometimes seen by win2k/cygwin users.
1465
1500
1466 2004-11-06 Fernando Perez <fperez@colorado.edu>
1501 2004-11-06 Fernando Perez <fperez@colorado.edu>
1467
1502
1468 * IPython/iplib.py (interact): Change the handling of %Exit from
1503 * IPython/iplib.py (interact): Change the handling of %Exit from
1469 trying to propagate a SystemExit to an internal ipython flag.
1504 trying to propagate a SystemExit to an internal ipython flag.
1470 This is less elegant than using Python's exception mechanism, but
1505 This is less elegant than using Python's exception mechanism, but
1471 I can't get that to work reliably with threads, so under -pylab
1506 I can't get that to work reliably with threads, so under -pylab
1472 %Exit was hanging IPython. Cross-thread exception handling is
1507 %Exit was hanging IPython. Cross-thread exception handling is
1473 really a bitch. Thaks to a bug report by Stephen Walton
1508 really a bitch. Thaks to a bug report by Stephen Walton
1474 <stephen.walton-AT-csun.edu>.
1509 <stephen.walton-AT-csun.edu>.
1475
1510
1476 2004-11-04 Fernando Perez <fperez@colorado.edu>
1511 2004-11-04 Fernando Perez <fperez@colorado.edu>
1477
1512
1478 * IPython/iplib.py (raw_input_original): store a pointer to the
1513 * IPython/iplib.py (raw_input_original): store a pointer to the
1479 true raw_input to harden against code which can modify it
1514 true raw_input to harden against code which can modify it
1480 (wx.py.PyShell does this and would otherwise crash ipython).
1515 (wx.py.PyShell does this and would otherwise crash ipython).
1481 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1516 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1482
1517
1483 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1518 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1484 Ctrl-C problem, which does not mess up the input line.
1519 Ctrl-C problem, which does not mess up the input line.
1485
1520
1486 2004-11-03 Fernando Perez <fperez@colorado.edu>
1521 2004-11-03 Fernando Perez <fperez@colorado.edu>
1487
1522
1488 * IPython/Release.py: Changed licensing to BSD, in all files.
1523 * IPython/Release.py: Changed licensing to BSD, in all files.
1489 (name): lowercase name for tarball/RPM release.
1524 (name): lowercase name for tarball/RPM release.
1490
1525
1491 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1526 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1492 use throughout ipython.
1527 use throughout ipython.
1493
1528
1494 * IPython/Magic.py (Magic._ofind): Switch to using the new
1529 * IPython/Magic.py (Magic._ofind): Switch to using the new
1495 OInspect.getdoc() function.
1530 OInspect.getdoc() function.
1496
1531
1497 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1532 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1498 of the line currently being canceled via Ctrl-C. It's extremely
1533 of the line currently being canceled via Ctrl-C. It's extremely
1499 ugly, but I don't know how to do it better (the problem is one of
1534 ugly, but I don't know how to do it better (the problem is one of
1500 handling cross-thread exceptions).
1535 handling cross-thread exceptions).
1501
1536
1502 2004-10-28 Fernando Perez <fperez@colorado.edu>
1537 2004-10-28 Fernando Perez <fperez@colorado.edu>
1503
1538
1504 * IPython/Shell.py (signal_handler): add signal handlers to trap
1539 * IPython/Shell.py (signal_handler): add signal handlers to trap
1505 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1540 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1506 report by Francesc Alted.
1541 report by Francesc Alted.
1507
1542
1508 2004-10-21 Fernando Perez <fperez@colorado.edu>
1543 2004-10-21 Fernando Perez <fperez@colorado.edu>
1509
1544
1510 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1545 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1511 to % for pysh syntax extensions.
1546 to % for pysh syntax extensions.
1512
1547
1513 2004-10-09 Fernando Perez <fperez@colorado.edu>
1548 2004-10-09 Fernando Perez <fperez@colorado.edu>
1514
1549
1515 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1550 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1516 arrays to print a more useful summary, without calling str(arr).
1551 arrays to print a more useful summary, without calling str(arr).
1517 This avoids the problem of extremely lengthy computations which
1552 This avoids the problem of extremely lengthy computations which
1518 occur if arr is large, and appear to the user as a system lockup
1553 occur if arr is large, and appear to the user as a system lockup
1519 with 100% cpu activity. After a suggestion by Kristian Sandberg
1554 with 100% cpu activity. After a suggestion by Kristian Sandberg
1520 <Kristian.Sandberg@colorado.edu>.
1555 <Kristian.Sandberg@colorado.edu>.
1521 (Magic.__init__): fix bug in global magic escapes not being
1556 (Magic.__init__): fix bug in global magic escapes not being
1522 correctly set.
1557 correctly set.
1523
1558
1524 2004-10-08 Fernando Perez <fperez@colorado.edu>
1559 2004-10-08 Fernando Perez <fperez@colorado.edu>
1525
1560
1526 * IPython/Magic.py (__license__): change to absolute imports of
1561 * IPython/Magic.py (__license__): change to absolute imports of
1527 ipython's own internal packages, to start adapting to the absolute
1562 ipython's own internal packages, to start adapting to the absolute
1528 import requirement of PEP-328.
1563 import requirement of PEP-328.
1529
1564
1530 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1565 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1531 files, and standardize author/license marks through the Release
1566 files, and standardize author/license marks through the Release
1532 module instead of having per/file stuff (except for files with
1567 module instead of having per/file stuff (except for files with
1533 particular licenses, like the MIT/PSF-licensed codes).
1568 particular licenses, like the MIT/PSF-licensed codes).
1534
1569
1535 * IPython/Debugger.py: remove dead code for python 2.1
1570 * IPython/Debugger.py: remove dead code for python 2.1
1536
1571
1537 2004-10-04 Fernando Perez <fperez@colorado.edu>
1572 2004-10-04 Fernando Perez <fperez@colorado.edu>
1538
1573
1539 * IPython/iplib.py (ipmagic): New function for accessing magics
1574 * IPython/iplib.py (ipmagic): New function for accessing magics
1540 via a normal python function call.
1575 via a normal python function call.
1541
1576
1542 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1577 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1543 from '@' to '%', to accomodate the new @decorator syntax of python
1578 from '@' to '%', to accomodate the new @decorator syntax of python
1544 2.4.
1579 2.4.
1545
1580
1546 2004-09-29 Fernando Perez <fperez@colorado.edu>
1581 2004-09-29 Fernando Perez <fperez@colorado.edu>
1547
1582
1548 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1583 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1549 matplotlib.use to prevent running scripts which try to switch
1584 matplotlib.use to prevent running scripts which try to switch
1550 interactive backends from within ipython. This will just crash
1585 interactive backends from within ipython. This will just crash
1551 the python interpreter, so we can't allow it (but a detailed error
1586 the python interpreter, so we can't allow it (but a detailed error
1552 is given to the user).
1587 is given to the user).
1553
1588
1554 2004-09-28 Fernando Perez <fperez@colorado.edu>
1589 2004-09-28 Fernando Perez <fperez@colorado.edu>
1555
1590
1556 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1591 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1557 matplotlib-related fixes so that using @run with non-matplotlib
1592 matplotlib-related fixes so that using @run with non-matplotlib
1558 scripts doesn't pop up spurious plot windows. This requires
1593 scripts doesn't pop up spurious plot windows. This requires
1559 matplotlib >= 0.63, where I had to make some changes as well.
1594 matplotlib >= 0.63, where I had to make some changes as well.
1560
1595
1561 * IPython/ipmaker.py (make_IPython): update version requirement to
1596 * IPython/ipmaker.py (make_IPython): update version requirement to
1562 python 2.2.
1597 python 2.2.
1563
1598
1564 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1599 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1565 banner arg for embedded customization.
1600 banner arg for embedded customization.
1566
1601
1567 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1602 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1568 explicit uses of __IP as the IPython's instance name. Now things
1603 explicit uses of __IP as the IPython's instance name. Now things
1569 are properly handled via the shell.name value. The actual code
1604 are properly handled via the shell.name value. The actual code
1570 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1605 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1571 is much better than before. I'll clean things completely when the
1606 is much better than before. I'll clean things completely when the
1572 magic stuff gets a real overhaul.
1607 magic stuff gets a real overhaul.
1573
1608
1574 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1609 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1575 minor changes to debian dir.
1610 minor changes to debian dir.
1576
1611
1577 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1612 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1578 pointer to the shell itself in the interactive namespace even when
1613 pointer to the shell itself in the interactive namespace even when
1579 a user-supplied dict is provided. This is needed for embedding
1614 a user-supplied dict is provided. This is needed for embedding
1580 purposes (found by tests with Michel Sanner).
1615 purposes (found by tests with Michel Sanner).
1581
1616
1582 2004-09-27 Fernando Perez <fperez@colorado.edu>
1617 2004-09-27 Fernando Perez <fperez@colorado.edu>
1583
1618
1584 * IPython/UserConfig/ipythonrc: remove []{} from
1619 * IPython/UserConfig/ipythonrc: remove []{} from
1585 readline_remove_delims, so that things like [modname.<TAB> do
1620 readline_remove_delims, so that things like [modname.<TAB> do
1586 proper completion. This disables [].TAB, but that's a less common
1621 proper completion. This disables [].TAB, but that's a less common
1587 case than module names in list comprehensions, for example.
1622 case than module names in list comprehensions, for example.
1588 Thanks to a report by Andrea Riciputi.
1623 Thanks to a report by Andrea Riciputi.
1589
1624
1590 2004-09-09 Fernando Perez <fperez@colorado.edu>
1625 2004-09-09 Fernando Perez <fperez@colorado.edu>
1591
1626
1592 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1627 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1593 blocking problems in win32 and osx. Fix by John.
1628 blocking problems in win32 and osx. Fix by John.
1594
1629
1595 2004-09-08 Fernando Perez <fperez@colorado.edu>
1630 2004-09-08 Fernando Perez <fperez@colorado.edu>
1596
1631
1597 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1632 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1598 for Win32 and OSX. Fix by John Hunter.
1633 for Win32 and OSX. Fix by John Hunter.
1599
1634
1600 2004-08-30 *** Released version 0.6.3
1635 2004-08-30 *** Released version 0.6.3
1601
1636
1602 2004-08-30 Fernando Perez <fperez@colorado.edu>
1637 2004-08-30 Fernando Perez <fperez@colorado.edu>
1603
1638
1604 * setup.py (isfile): Add manpages to list of dependent files to be
1639 * setup.py (isfile): Add manpages to list of dependent files to be
1605 updated.
1640 updated.
1606
1641
1607 2004-08-27 Fernando Perez <fperez@colorado.edu>
1642 2004-08-27 Fernando Perez <fperez@colorado.edu>
1608
1643
1609 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1644 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1610 for now. They don't really work with standalone WX/GTK code
1645 for now. They don't really work with standalone WX/GTK code
1611 (though matplotlib IS working fine with both of those backends).
1646 (though matplotlib IS working fine with both of those backends).
1612 This will neeed much more testing. I disabled most things with
1647 This will neeed much more testing. I disabled most things with
1613 comments, so turning it back on later should be pretty easy.
1648 comments, so turning it back on later should be pretty easy.
1614
1649
1615 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1650 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1616 autocalling of expressions like r'foo', by modifying the line
1651 autocalling of expressions like r'foo', by modifying the line
1617 split regexp. Closes
1652 split regexp. Closes
1618 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1653 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1619 Riley <ipythonbugs-AT-sabi.net>.
1654 Riley <ipythonbugs-AT-sabi.net>.
1620 (InteractiveShell.mainloop): honor --nobanner with banner
1655 (InteractiveShell.mainloop): honor --nobanner with banner
1621 extensions.
1656 extensions.
1622
1657
1623 * IPython/Shell.py: Significant refactoring of all classes, so
1658 * IPython/Shell.py: Significant refactoring of all classes, so
1624 that we can really support ALL matplotlib backends and threading
1659 that we can really support ALL matplotlib backends and threading
1625 models (John spotted a bug with Tk which required this). Now we
1660 models (John spotted a bug with Tk which required this). Now we
1626 should support single-threaded, WX-threads and GTK-threads, both
1661 should support single-threaded, WX-threads and GTK-threads, both
1627 for generic code and for matplotlib.
1662 for generic code and for matplotlib.
1628
1663
1629 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1664 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1630 -pylab, to simplify things for users. Will also remove the pylab
1665 -pylab, to simplify things for users. Will also remove the pylab
1631 profile, since now all of matplotlib configuration is directly
1666 profile, since now all of matplotlib configuration is directly
1632 handled here. This also reduces startup time.
1667 handled here. This also reduces startup time.
1633
1668
1634 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1669 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1635 shell wasn't being correctly called. Also in IPShellWX.
1670 shell wasn't being correctly called. Also in IPShellWX.
1636
1671
1637 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1672 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1638 fine-tune banner.
1673 fine-tune banner.
1639
1674
1640 * IPython/numutils.py (spike): Deprecate these spike functions,
1675 * IPython/numutils.py (spike): Deprecate these spike functions,
1641 delete (long deprecated) gnuplot_exec handler.
1676 delete (long deprecated) gnuplot_exec handler.
1642
1677
1643 2004-08-26 Fernando Perez <fperez@colorado.edu>
1678 2004-08-26 Fernando Perez <fperez@colorado.edu>
1644
1679
1645 * ipython.1: Update for threading options, plus some others which
1680 * ipython.1: Update for threading options, plus some others which
1646 were missing.
1681 were missing.
1647
1682
1648 * IPython/ipmaker.py (__call__): Added -wthread option for
1683 * IPython/ipmaker.py (__call__): Added -wthread option for
1649 wxpython thread handling. Make sure threading options are only
1684 wxpython thread handling. Make sure threading options are only
1650 valid at the command line.
1685 valid at the command line.
1651
1686
1652 * scripts/ipython: moved shell selection into a factory function
1687 * scripts/ipython: moved shell selection into a factory function
1653 in Shell.py, to keep the starter script to a minimum.
1688 in Shell.py, to keep the starter script to a minimum.
1654
1689
1655 2004-08-25 Fernando Perez <fperez@colorado.edu>
1690 2004-08-25 Fernando Perez <fperez@colorado.edu>
1656
1691
1657 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1692 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1658 John. Along with some recent changes he made to matplotlib, the
1693 John. Along with some recent changes he made to matplotlib, the
1659 next versions of both systems should work very well together.
1694 next versions of both systems should work very well together.
1660
1695
1661 2004-08-24 Fernando Perez <fperez@colorado.edu>
1696 2004-08-24 Fernando Perez <fperez@colorado.edu>
1662
1697
1663 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1698 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1664 tried to switch the profiling to using hotshot, but I'm getting
1699 tried to switch the profiling to using hotshot, but I'm getting
1665 strange errors from prof.runctx() there. I may be misreading the
1700 strange errors from prof.runctx() there. I may be misreading the
1666 docs, but it looks weird. For now the profiling code will
1701 docs, but it looks weird. For now the profiling code will
1667 continue to use the standard profiler.
1702 continue to use the standard profiler.
1668
1703
1669 2004-08-23 Fernando Perez <fperez@colorado.edu>
1704 2004-08-23 Fernando Perez <fperez@colorado.edu>
1670
1705
1671 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1706 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1672 threaded shell, by John Hunter. It's not quite ready yet, but
1707 threaded shell, by John Hunter. It's not quite ready yet, but
1673 close.
1708 close.
1674
1709
1675 2004-08-22 Fernando Perez <fperez@colorado.edu>
1710 2004-08-22 Fernando Perez <fperez@colorado.edu>
1676
1711
1677 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1712 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1678 in Magic and ultraTB.
1713 in Magic and ultraTB.
1679
1714
1680 * ipython.1: document threading options in manpage.
1715 * ipython.1: document threading options in manpage.
1681
1716
1682 * scripts/ipython: Changed name of -thread option to -gthread,
1717 * scripts/ipython: Changed name of -thread option to -gthread,
1683 since this is GTK specific. I want to leave the door open for a
1718 since this is GTK specific. I want to leave the door open for a
1684 -wthread option for WX, which will most likely be necessary. This
1719 -wthread option for WX, which will most likely be necessary. This
1685 change affects usage and ipmaker as well.
1720 change affects usage and ipmaker as well.
1686
1721
1687 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1722 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1688 handle the matplotlib shell issues. Code by John Hunter
1723 handle the matplotlib shell issues. Code by John Hunter
1689 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1724 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1690 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1725 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1691 broken (and disabled for end users) for now, but it puts the
1726 broken (and disabled for end users) for now, but it puts the
1692 infrastructure in place.
1727 infrastructure in place.
1693
1728
1694 2004-08-21 Fernando Perez <fperez@colorado.edu>
1729 2004-08-21 Fernando Perez <fperez@colorado.edu>
1695
1730
1696 * ipythonrc-pylab: Add matplotlib support.
1731 * ipythonrc-pylab: Add matplotlib support.
1697
1732
1698 * matplotlib_config.py: new files for matplotlib support, part of
1733 * matplotlib_config.py: new files for matplotlib support, part of
1699 the pylab profile.
1734 the pylab profile.
1700
1735
1701 * IPython/usage.py (__doc__): documented the threading options.
1736 * IPython/usage.py (__doc__): documented the threading options.
1702
1737
1703 2004-08-20 Fernando Perez <fperez@colorado.edu>
1738 2004-08-20 Fernando Perez <fperez@colorado.edu>
1704
1739
1705 * ipython: Modified the main calling routine to handle the -thread
1740 * ipython: Modified the main calling routine to handle the -thread
1706 and -mpthread options. This needs to be done as a top-level hack,
1741 and -mpthread options. This needs to be done as a top-level hack,
1707 because it determines which class to instantiate for IPython
1742 because it determines which class to instantiate for IPython
1708 itself.
1743 itself.
1709
1744
1710 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1745 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1711 classes to support multithreaded GTK operation without blocking,
1746 classes to support multithreaded GTK operation without blocking,
1712 and matplotlib with all backends. This is a lot of still very
1747 and matplotlib with all backends. This is a lot of still very
1713 experimental code, and threads are tricky. So it may still have a
1748 experimental code, and threads are tricky. So it may still have a
1714 few rough edges... This code owes a lot to
1749 few rough edges... This code owes a lot to
1715 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1750 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1716 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1751 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1717 to John Hunter for all the matplotlib work.
1752 to John Hunter for all the matplotlib work.
1718
1753
1719 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1754 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1720 options for gtk thread and matplotlib support.
1755 options for gtk thread and matplotlib support.
1721
1756
1722 2004-08-16 Fernando Perez <fperez@colorado.edu>
1757 2004-08-16 Fernando Perez <fperez@colorado.edu>
1723
1758
1724 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1759 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1725 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1760 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1726 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1761 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1727
1762
1728 2004-08-11 Fernando Perez <fperez@colorado.edu>
1763 2004-08-11 Fernando Perez <fperez@colorado.edu>
1729
1764
1730 * setup.py (isfile): Fix build so documentation gets updated for
1765 * setup.py (isfile): Fix build so documentation gets updated for
1731 rpms (it was only done for .tgz builds).
1766 rpms (it was only done for .tgz builds).
1732
1767
1733 2004-08-10 Fernando Perez <fperez@colorado.edu>
1768 2004-08-10 Fernando Perez <fperez@colorado.edu>
1734
1769
1735 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1770 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1736
1771
1737 * iplib.py : Silence syntax error exceptions in tab-completion.
1772 * iplib.py : Silence syntax error exceptions in tab-completion.
1738
1773
1739 2004-08-05 Fernando Perez <fperez@colorado.edu>
1774 2004-08-05 Fernando Perez <fperez@colorado.edu>
1740
1775
1741 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1776 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1742 'color off' mark for continuation prompts. This was causing long
1777 'color off' mark for continuation prompts. This was causing long
1743 continuation lines to mis-wrap.
1778 continuation lines to mis-wrap.
1744
1779
1745 2004-08-01 Fernando Perez <fperez@colorado.edu>
1780 2004-08-01 Fernando Perez <fperez@colorado.edu>
1746
1781
1747 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1782 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1748 for building ipython to be a parameter. All this is necessary
1783 for building ipython to be a parameter. All this is necessary
1749 right now to have a multithreaded version, but this insane
1784 right now to have a multithreaded version, but this insane
1750 non-design will be cleaned up soon. For now, it's a hack that
1785 non-design will be cleaned up soon. For now, it's a hack that
1751 works.
1786 works.
1752
1787
1753 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1788 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1754 args in various places. No bugs so far, but it's a dangerous
1789 args in various places. No bugs so far, but it's a dangerous
1755 practice.
1790 practice.
1756
1791
1757 2004-07-31 Fernando Perez <fperez@colorado.edu>
1792 2004-07-31 Fernando Perez <fperez@colorado.edu>
1758
1793
1759 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1794 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1760 fix completion of files with dots in their names under most
1795 fix completion of files with dots in their names under most
1761 profiles (pysh was OK because the completion order is different).
1796 profiles (pysh was OK because the completion order is different).
1762
1797
1763 2004-07-27 Fernando Perez <fperez@colorado.edu>
1798 2004-07-27 Fernando Perez <fperez@colorado.edu>
1764
1799
1765 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1800 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1766 keywords manually, b/c the one in keyword.py was removed in python
1801 keywords manually, b/c the one in keyword.py was removed in python
1767 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1802 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1768 This is NOT a bug under python 2.3 and earlier.
1803 This is NOT a bug under python 2.3 and earlier.
1769
1804
1770 2004-07-26 Fernando Perez <fperez@colorado.edu>
1805 2004-07-26 Fernando Perez <fperez@colorado.edu>
1771
1806
1772 * IPython/ultraTB.py (VerboseTB.text): Add another
1807 * IPython/ultraTB.py (VerboseTB.text): Add another
1773 linecache.checkcache() call to try to prevent inspect.py from
1808 linecache.checkcache() call to try to prevent inspect.py from
1774 crashing under python 2.3. I think this fixes
1809 crashing under python 2.3. I think this fixes
1775 http://www.scipy.net/roundup/ipython/issue17.
1810 http://www.scipy.net/roundup/ipython/issue17.
1776
1811
1777 2004-07-26 *** Released version 0.6.2
1812 2004-07-26 *** Released version 0.6.2
1778
1813
1779 2004-07-26 Fernando Perez <fperez@colorado.edu>
1814 2004-07-26 Fernando Perez <fperez@colorado.edu>
1780
1815
1781 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1816 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1782 fail for any number.
1817 fail for any number.
1783 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1818 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1784 empty bookmarks.
1819 empty bookmarks.
1785
1820
1786 2004-07-26 *** Released version 0.6.1
1821 2004-07-26 *** Released version 0.6.1
1787
1822
1788 2004-07-26 Fernando Perez <fperez@colorado.edu>
1823 2004-07-26 Fernando Perez <fperez@colorado.edu>
1789
1824
1790 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1825 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1791
1826
1792 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1827 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1793 escaping '()[]{}' in filenames.
1828 escaping '()[]{}' in filenames.
1794
1829
1795 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1830 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1796 Python 2.2 users who lack a proper shlex.split.
1831 Python 2.2 users who lack a proper shlex.split.
1797
1832
1798 2004-07-19 Fernando Perez <fperez@colorado.edu>
1833 2004-07-19 Fernando Perez <fperez@colorado.edu>
1799
1834
1800 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1835 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1801 for reading readline's init file. I follow the normal chain:
1836 for reading readline's init file. I follow the normal chain:
1802 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1837 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1803 report by Mike Heeter. This closes
1838 report by Mike Heeter. This closes
1804 http://www.scipy.net/roundup/ipython/issue16.
1839 http://www.scipy.net/roundup/ipython/issue16.
1805
1840
1806 2004-07-18 Fernando Perez <fperez@colorado.edu>
1841 2004-07-18 Fernando Perez <fperez@colorado.edu>
1807
1842
1808 * IPython/iplib.py (__init__): Add better handling of '\' under
1843 * IPython/iplib.py (__init__): Add better handling of '\' under
1809 Win32 for filenames. After a patch by Ville.
1844 Win32 for filenames. After a patch by Ville.
1810
1845
1811 2004-07-17 Fernando Perez <fperez@colorado.edu>
1846 2004-07-17 Fernando Perez <fperez@colorado.edu>
1812
1847
1813 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1848 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1814 autocalling would be triggered for 'foo is bar' if foo is
1849 autocalling would be triggered for 'foo is bar' if foo is
1815 callable. I also cleaned up the autocall detection code to use a
1850 callable. I also cleaned up the autocall detection code to use a
1816 regexp, which is faster. Bug reported by Alexander Schmolck.
1851 regexp, which is faster. Bug reported by Alexander Schmolck.
1817
1852
1818 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1853 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1819 '?' in them would confuse the help system. Reported by Alex
1854 '?' in them would confuse the help system. Reported by Alex
1820 Schmolck.
1855 Schmolck.
1821
1856
1822 2004-07-16 Fernando Perez <fperez@colorado.edu>
1857 2004-07-16 Fernando Perez <fperez@colorado.edu>
1823
1858
1824 * IPython/GnuplotInteractive.py (__all__): added plot2.
1859 * IPython/GnuplotInteractive.py (__all__): added plot2.
1825
1860
1826 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1861 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1827 plotting dictionaries, lists or tuples of 1d arrays.
1862 plotting dictionaries, lists or tuples of 1d arrays.
1828
1863
1829 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1864 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1830 optimizations.
1865 optimizations.
1831
1866
1832 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1867 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1833 the information which was there from Janko's original IPP code:
1868 the information which was there from Janko's original IPP code:
1834
1869
1835 03.05.99 20:53 porto.ifm.uni-kiel.de
1870 03.05.99 20:53 porto.ifm.uni-kiel.de
1836 --Started changelog.
1871 --Started changelog.
1837 --make clear do what it say it does
1872 --make clear do what it say it does
1838 --added pretty output of lines from inputcache
1873 --added pretty output of lines from inputcache
1839 --Made Logger a mixin class, simplifies handling of switches
1874 --Made Logger a mixin class, simplifies handling of switches
1840 --Added own completer class. .string<TAB> expands to last history
1875 --Added own completer class. .string<TAB> expands to last history
1841 line which starts with string. The new expansion is also present
1876 line which starts with string. The new expansion is also present
1842 with Ctrl-r from the readline library. But this shows, who this
1877 with Ctrl-r from the readline library. But this shows, who this
1843 can be done for other cases.
1878 can be done for other cases.
1844 --Added convention that all shell functions should accept a
1879 --Added convention that all shell functions should accept a
1845 parameter_string This opens the door for different behaviour for
1880 parameter_string This opens the door for different behaviour for
1846 each function. @cd is a good example of this.
1881 each function. @cd is a good example of this.
1847
1882
1848 04.05.99 12:12 porto.ifm.uni-kiel.de
1883 04.05.99 12:12 porto.ifm.uni-kiel.de
1849 --added logfile rotation
1884 --added logfile rotation
1850 --added new mainloop method which freezes first the namespace
1885 --added new mainloop method which freezes first the namespace
1851
1886
1852 07.05.99 21:24 porto.ifm.uni-kiel.de
1887 07.05.99 21:24 porto.ifm.uni-kiel.de
1853 --added the docreader classes. Now there is a help system.
1888 --added the docreader classes. Now there is a help system.
1854 -This is only a first try. Currently it's not easy to put new
1889 -This is only a first try. Currently it's not easy to put new
1855 stuff in the indices. But this is the way to go. Info would be
1890 stuff in the indices. But this is the way to go. Info would be
1856 better, but HTML is every where and not everybody has an info
1891 better, but HTML is every where and not everybody has an info
1857 system installed and it's not so easy to change html-docs to info.
1892 system installed and it's not so easy to change html-docs to info.
1858 --added global logfile option
1893 --added global logfile option
1859 --there is now a hook for object inspection method pinfo needs to
1894 --there is now a hook for object inspection method pinfo needs to
1860 be provided for this. Can be reached by two '??'.
1895 be provided for this. Can be reached by two '??'.
1861
1896
1862 08.05.99 20:51 porto.ifm.uni-kiel.de
1897 08.05.99 20:51 porto.ifm.uni-kiel.de
1863 --added a README
1898 --added a README
1864 --bug in rc file. Something has changed so functions in the rc
1899 --bug in rc file. Something has changed so functions in the rc
1865 file need to reference the shell and not self. Not clear if it's a
1900 file need to reference the shell and not self. Not clear if it's a
1866 bug or feature.
1901 bug or feature.
1867 --changed rc file for new behavior
1902 --changed rc file for new behavior
1868
1903
1869 2004-07-15 Fernando Perez <fperez@colorado.edu>
1904 2004-07-15 Fernando Perez <fperez@colorado.edu>
1870
1905
1871 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1906 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1872 cache was falling out of sync in bizarre manners when multi-line
1907 cache was falling out of sync in bizarre manners when multi-line
1873 input was present. Minor optimizations and cleanup.
1908 input was present. Minor optimizations and cleanup.
1874
1909
1875 (Logger): Remove old Changelog info for cleanup. This is the
1910 (Logger): Remove old Changelog info for cleanup. This is the
1876 information which was there from Janko's original code:
1911 information which was there from Janko's original code:
1877
1912
1878 Changes to Logger: - made the default log filename a parameter
1913 Changes to Logger: - made the default log filename a parameter
1879
1914
1880 - put a check for lines beginning with !@? in log(). Needed
1915 - put a check for lines beginning with !@? in log(). Needed
1881 (even if the handlers properly log their lines) for mid-session
1916 (even if the handlers properly log their lines) for mid-session
1882 logging activation to work properly. Without this, lines logged
1917 logging activation to work properly. Without this, lines logged
1883 in mid session, which get read from the cache, would end up
1918 in mid session, which get read from the cache, would end up
1884 'bare' (with !@? in the open) in the log. Now they are caught
1919 'bare' (with !@? in the open) in the log. Now they are caught
1885 and prepended with a #.
1920 and prepended with a #.
1886
1921
1887 * IPython/iplib.py (InteractiveShell.init_readline): added check
1922 * IPython/iplib.py (InteractiveShell.init_readline): added check
1888 in case MagicCompleter fails to be defined, so we don't crash.
1923 in case MagicCompleter fails to be defined, so we don't crash.
1889
1924
1890 2004-07-13 Fernando Perez <fperez@colorado.edu>
1925 2004-07-13 Fernando Perez <fperez@colorado.edu>
1891
1926
1892 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1927 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1893 of EPS if the requested filename ends in '.eps'.
1928 of EPS if the requested filename ends in '.eps'.
1894
1929
1895 2004-07-04 Fernando Perez <fperez@colorado.edu>
1930 2004-07-04 Fernando Perez <fperez@colorado.edu>
1896
1931
1897 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1932 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1898 escaping of quotes when calling the shell.
1933 escaping of quotes when calling the shell.
1899
1934
1900 2004-07-02 Fernando Perez <fperez@colorado.edu>
1935 2004-07-02 Fernando Perez <fperez@colorado.edu>
1901
1936
1902 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1937 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1903 gettext not working because we were clobbering '_'. Fixes
1938 gettext not working because we were clobbering '_'. Fixes
1904 http://www.scipy.net/roundup/ipython/issue6.
1939 http://www.scipy.net/roundup/ipython/issue6.
1905
1940
1906 2004-07-01 Fernando Perez <fperez@colorado.edu>
1941 2004-07-01 Fernando Perez <fperez@colorado.edu>
1907
1942
1908 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1943 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1909 into @cd. Patch by Ville.
1944 into @cd. Patch by Ville.
1910
1945
1911 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1946 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1912 new function to store things after ipmaker runs. Patch by Ville.
1947 new function to store things after ipmaker runs. Patch by Ville.
1913 Eventually this will go away once ipmaker is removed and the class
1948 Eventually this will go away once ipmaker is removed and the class
1914 gets cleaned up, but for now it's ok. Key functionality here is
1949 gets cleaned up, but for now it's ok. Key functionality here is
1915 the addition of the persistent storage mechanism, a dict for
1950 the addition of the persistent storage mechanism, a dict for
1916 keeping data across sessions (for now just bookmarks, but more can
1951 keeping data across sessions (for now just bookmarks, but more can
1917 be implemented later).
1952 be implemented later).
1918
1953
1919 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1954 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1920 persistent across sections. Patch by Ville, I modified it
1955 persistent across sections. Patch by Ville, I modified it
1921 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1956 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1922 added a '-l' option to list all bookmarks.
1957 added a '-l' option to list all bookmarks.
1923
1958
1924 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1959 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1925 center for cleanup. Registered with atexit.register(). I moved
1960 center for cleanup. Registered with atexit.register(). I moved
1926 here the old exit_cleanup(). After a patch by Ville.
1961 here the old exit_cleanup(). After a patch by Ville.
1927
1962
1928 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1963 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1929 characters in the hacked shlex_split for python 2.2.
1964 characters in the hacked shlex_split for python 2.2.
1930
1965
1931 * IPython/iplib.py (file_matches): more fixes to filenames with
1966 * IPython/iplib.py (file_matches): more fixes to filenames with
1932 whitespace in them. It's not perfect, but limitations in python's
1967 whitespace in them. It's not perfect, but limitations in python's
1933 readline make it impossible to go further.
1968 readline make it impossible to go further.
1934
1969
1935 2004-06-29 Fernando Perez <fperez@colorado.edu>
1970 2004-06-29 Fernando Perez <fperez@colorado.edu>
1936
1971
1937 * IPython/iplib.py (file_matches): escape whitespace correctly in
1972 * IPython/iplib.py (file_matches): escape whitespace correctly in
1938 filename completions. Bug reported by Ville.
1973 filename completions. Bug reported by Ville.
1939
1974
1940 2004-06-28 Fernando Perez <fperez@colorado.edu>
1975 2004-06-28 Fernando Perez <fperez@colorado.edu>
1941
1976
1942 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1977 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1943 the history file will be called 'history-PROFNAME' (or just
1978 the history file will be called 'history-PROFNAME' (or just
1944 'history' if no profile is loaded). I was getting annoyed at
1979 'history' if no profile is loaded). I was getting annoyed at
1945 getting my Numerical work history clobbered by pysh sessions.
1980 getting my Numerical work history clobbered by pysh sessions.
1946
1981
1947 * IPython/iplib.py (InteractiveShell.__init__): Internal
1982 * IPython/iplib.py (InteractiveShell.__init__): Internal
1948 getoutputerror() function so that we can honor the system_verbose
1983 getoutputerror() function so that we can honor the system_verbose
1949 flag for _all_ system calls. I also added escaping of #
1984 flag for _all_ system calls. I also added escaping of #
1950 characters here to avoid confusing Itpl.
1985 characters here to avoid confusing Itpl.
1951
1986
1952 * IPython/Magic.py (shlex_split): removed call to shell in
1987 * IPython/Magic.py (shlex_split): removed call to shell in
1953 parse_options and replaced it with shlex.split(). The annoying
1988 parse_options and replaced it with shlex.split(). The annoying
1954 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1989 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1955 to backport it from 2.3, with several frail hacks (the shlex
1990 to backport it from 2.3, with several frail hacks (the shlex
1956 module is rather limited in 2.2). Thanks to a suggestion by Ville
1991 module is rather limited in 2.2). Thanks to a suggestion by Ville
1957 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1992 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1958 problem.
1993 problem.
1959
1994
1960 (Magic.magic_system_verbose): new toggle to print the actual
1995 (Magic.magic_system_verbose): new toggle to print the actual
1961 system calls made by ipython. Mainly for debugging purposes.
1996 system calls made by ipython. Mainly for debugging purposes.
1962
1997
1963 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1998 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1964 doesn't support persistence. Reported (and fix suggested) by
1999 doesn't support persistence. Reported (and fix suggested) by
1965 Travis Caldwell <travis_caldwell2000@yahoo.com>.
2000 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1966
2001
1967 2004-06-26 Fernando Perez <fperez@colorado.edu>
2002 2004-06-26 Fernando Perez <fperez@colorado.edu>
1968
2003
1969 * IPython/Logger.py (Logger.log): fix to handle correctly empty
2004 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1970 continue prompts.
2005 continue prompts.
1971
2006
1972 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
2007 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1973 function (basically a big docstring) and a few more things here to
2008 function (basically a big docstring) and a few more things here to
1974 speedup startup. pysh.py is now very lightweight. We want because
2009 speedup startup. pysh.py is now very lightweight. We want because
1975 it gets execfile'd, while InterpreterExec gets imported, so
2010 it gets execfile'd, while InterpreterExec gets imported, so
1976 byte-compilation saves time.
2011 byte-compilation saves time.
1977
2012
1978 2004-06-25 Fernando Perez <fperez@colorado.edu>
2013 2004-06-25 Fernando Perez <fperez@colorado.edu>
1979
2014
1980 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
2015 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1981 -NUM', which was recently broken.
2016 -NUM', which was recently broken.
1982
2017
1983 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
2018 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1984 in multi-line input (but not !!, which doesn't make sense there).
2019 in multi-line input (but not !!, which doesn't make sense there).
1985
2020
1986 * IPython/UserConfig/ipythonrc: made autoindent on by default.
2021 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1987 It's just too useful, and people can turn it off in the less
2022 It's just too useful, and people can turn it off in the less
1988 common cases where it's a problem.
2023 common cases where it's a problem.
1989
2024
1990 2004-06-24 Fernando Perez <fperez@colorado.edu>
2025 2004-06-24 Fernando Perez <fperez@colorado.edu>
1991
2026
1992 * IPython/iplib.py (InteractiveShell._prefilter): big change -
2027 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1993 special syntaxes (like alias calling) is now allied in multi-line
2028 special syntaxes (like alias calling) is now allied in multi-line
1994 input. This is still _very_ experimental, but it's necessary for
2029 input. This is still _very_ experimental, but it's necessary for
1995 efficient shell usage combining python looping syntax with system
2030 efficient shell usage combining python looping syntax with system
1996 calls. For now it's restricted to aliases, I don't think it
2031 calls. For now it's restricted to aliases, I don't think it
1997 really even makes sense to have this for magics.
2032 really even makes sense to have this for magics.
1998
2033
1999 2004-06-23 Fernando Perez <fperez@colorado.edu>
2034 2004-06-23 Fernando Perez <fperez@colorado.edu>
2000
2035
2001 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
2036 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
2002 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
2037 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
2003
2038
2004 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
2039 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
2005 extensions under Windows (after code sent by Gary Bishop). The
2040 extensions under Windows (after code sent by Gary Bishop). The
2006 extensions considered 'executable' are stored in IPython's rc
2041 extensions considered 'executable' are stored in IPython's rc
2007 structure as win_exec_ext.
2042 structure as win_exec_ext.
2008
2043
2009 * IPython/genutils.py (shell): new function, like system() but
2044 * IPython/genutils.py (shell): new function, like system() but
2010 without return value. Very useful for interactive shell work.
2045 without return value. Very useful for interactive shell work.
2011
2046
2012 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
2047 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
2013 delete aliases.
2048 delete aliases.
2014
2049
2015 * IPython/iplib.py (InteractiveShell.alias_table_update): make
2050 * IPython/iplib.py (InteractiveShell.alias_table_update): make
2016 sure that the alias table doesn't contain python keywords.
2051 sure that the alias table doesn't contain python keywords.
2017
2052
2018 2004-06-21 Fernando Perez <fperez@colorado.edu>
2053 2004-06-21 Fernando Perez <fperez@colorado.edu>
2019
2054
2020 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
2055 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
2021 non-existent items are found in $PATH. Reported by Thorsten.
2056 non-existent items are found in $PATH. Reported by Thorsten.
2022
2057
2023 2004-06-20 Fernando Perez <fperez@colorado.edu>
2058 2004-06-20 Fernando Perez <fperez@colorado.edu>
2024
2059
2025 * IPython/iplib.py (complete): modified the completer so that the
2060 * IPython/iplib.py (complete): modified the completer so that the
2026 order of priorities can be easily changed at runtime.
2061 order of priorities can be easily changed at runtime.
2027
2062
2028 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
2063 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
2029 Modified to auto-execute all lines beginning with '~', '/' or '.'.
2064 Modified to auto-execute all lines beginning with '~', '/' or '.'.
2030
2065
2031 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
2066 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
2032 expand Python variables prepended with $ in all system calls. The
2067 expand Python variables prepended with $ in all system calls. The
2033 same was done to InteractiveShell.handle_shell_escape. Now all
2068 same was done to InteractiveShell.handle_shell_escape. Now all
2034 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
2069 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
2035 expansion of python variables and expressions according to the
2070 expansion of python variables and expressions according to the
2036 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
2071 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
2037
2072
2038 Though PEP-215 has been rejected, a similar (but simpler) one
2073 Though PEP-215 has been rejected, a similar (but simpler) one
2039 seems like it will go into Python 2.4, PEP-292 -
2074 seems like it will go into Python 2.4, PEP-292 -
2040 http://www.python.org/peps/pep-0292.html.
2075 http://www.python.org/peps/pep-0292.html.
2041
2076
2042 I'll keep the full syntax of PEP-215, since IPython has since the
2077 I'll keep the full syntax of PEP-215, since IPython has since the
2043 start used Ka-Ping Yee's reference implementation discussed there
2078 start used Ka-Ping Yee's reference implementation discussed there
2044 (Itpl), and I actually like the powerful semantics it offers.
2079 (Itpl), and I actually like the powerful semantics it offers.
2045
2080
2046 In order to access normal shell variables, the $ has to be escaped
2081 In order to access normal shell variables, the $ has to be escaped
2047 via an extra $. For example:
2082 via an extra $. For example:
2048
2083
2049 In [7]: PATH='a python variable'
2084 In [7]: PATH='a python variable'
2050
2085
2051 In [8]: !echo $PATH
2086 In [8]: !echo $PATH
2052 a python variable
2087 a python variable
2053
2088
2054 In [9]: !echo $$PATH
2089 In [9]: !echo $$PATH
2055 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2090 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2056
2091
2057 (Magic.parse_options): escape $ so the shell doesn't evaluate
2092 (Magic.parse_options): escape $ so the shell doesn't evaluate
2058 things prematurely.
2093 things prematurely.
2059
2094
2060 * IPython/iplib.py (InteractiveShell.call_alias): added the
2095 * IPython/iplib.py (InteractiveShell.call_alias): added the
2061 ability for aliases to expand python variables via $.
2096 ability for aliases to expand python variables via $.
2062
2097
2063 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
2098 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
2064 system, now there's a @rehash/@rehashx pair of magics. These work
2099 system, now there's a @rehash/@rehashx pair of magics. These work
2065 like the csh rehash command, and can be invoked at any time. They
2100 like the csh rehash command, and can be invoked at any time. They
2066 build a table of aliases to everything in the user's $PATH
2101 build a table of aliases to everything in the user's $PATH
2067 (@rehash uses everything, @rehashx is slower but only adds
2102 (@rehash uses everything, @rehashx is slower but only adds
2068 executable files). With this, the pysh.py-based shell profile can
2103 executable files). With this, the pysh.py-based shell profile can
2069 now simply call rehash upon startup, and full access to all
2104 now simply call rehash upon startup, and full access to all
2070 programs in the user's path is obtained.
2105 programs in the user's path is obtained.
2071
2106
2072 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
2107 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
2073 functionality is now fully in place. I removed the old dynamic
2108 functionality is now fully in place. I removed the old dynamic
2074 code generation based approach, in favor of a much lighter one
2109 code generation based approach, in favor of a much lighter one
2075 based on a simple dict. The advantage is that this allows me to
2110 based on a simple dict. The advantage is that this allows me to
2076 now have thousands of aliases with negligible cost (unthinkable
2111 now have thousands of aliases with negligible cost (unthinkable
2077 with the old system).
2112 with the old system).
2078
2113
2079 2004-06-19 Fernando Perez <fperez@colorado.edu>
2114 2004-06-19 Fernando Perez <fperez@colorado.edu>
2080
2115
2081 * IPython/iplib.py (__init__): extended MagicCompleter class to
2116 * IPython/iplib.py (__init__): extended MagicCompleter class to
2082 also complete (last in priority) on user aliases.
2117 also complete (last in priority) on user aliases.
2083
2118
2084 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
2119 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
2085 call to eval.
2120 call to eval.
2086 (ItplNS.__init__): Added a new class which functions like Itpl,
2121 (ItplNS.__init__): Added a new class which functions like Itpl,
2087 but allows configuring the namespace for the evaluation to occur
2122 but allows configuring the namespace for the evaluation to occur
2088 in.
2123 in.
2089
2124
2090 2004-06-18 Fernando Perez <fperez@colorado.edu>
2125 2004-06-18 Fernando Perez <fperez@colorado.edu>
2091
2126
2092 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
2127 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
2093 better message when 'exit' or 'quit' are typed (a common newbie
2128 better message when 'exit' or 'quit' are typed (a common newbie
2094 confusion).
2129 confusion).
2095
2130
2096 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
2131 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
2097 check for Windows users.
2132 check for Windows users.
2098
2133
2099 * IPython/iplib.py (InteractiveShell.user_setup): removed
2134 * IPython/iplib.py (InteractiveShell.user_setup): removed
2100 disabling of colors for Windows. I'll test at runtime and issue a
2135 disabling of colors for Windows. I'll test at runtime and issue a
2101 warning if Gary's readline isn't found, as to nudge users to
2136 warning if Gary's readline isn't found, as to nudge users to
2102 download it.
2137 download it.
2103
2138
2104 2004-06-16 Fernando Perez <fperez@colorado.edu>
2139 2004-06-16 Fernando Perez <fperez@colorado.edu>
2105
2140
2106 * IPython/genutils.py (Stream.__init__): changed to print errors
2141 * IPython/genutils.py (Stream.__init__): changed to print errors
2107 to sys.stderr. I had a circular dependency here. Now it's
2142 to sys.stderr. I had a circular dependency here. Now it's
2108 possible to run ipython as IDLE's shell (consider this pre-alpha,
2143 possible to run ipython as IDLE's shell (consider this pre-alpha,
2109 since true stdout things end up in the starting terminal instead
2144 since true stdout things end up in the starting terminal instead
2110 of IDLE's out).
2145 of IDLE's out).
2111
2146
2112 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
2147 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
2113 users who haven't # updated their prompt_in2 definitions. Remove
2148 users who haven't # updated their prompt_in2 definitions. Remove
2114 eventually.
2149 eventually.
2115 (multiple_replace): added credit to original ASPN recipe.
2150 (multiple_replace): added credit to original ASPN recipe.
2116
2151
2117 2004-06-15 Fernando Perez <fperez@colorado.edu>
2152 2004-06-15 Fernando Perez <fperez@colorado.edu>
2118
2153
2119 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
2154 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
2120 list of auto-defined aliases.
2155 list of auto-defined aliases.
2121
2156
2122 2004-06-13 Fernando Perez <fperez@colorado.edu>
2157 2004-06-13 Fernando Perez <fperez@colorado.edu>
2123
2158
2124 * setup.py (scriptfiles): Don't trigger win_post_install unless an
2159 * setup.py (scriptfiles): Don't trigger win_post_install unless an
2125 install was really requested (so setup.py can be used for other
2160 install was really requested (so setup.py can be used for other
2126 things under Windows).
2161 things under Windows).
2127
2162
2128 2004-06-10 Fernando Perez <fperez@colorado.edu>
2163 2004-06-10 Fernando Perez <fperez@colorado.edu>
2129
2164
2130 * IPython/Logger.py (Logger.create_log): Manually remove any old
2165 * IPython/Logger.py (Logger.create_log): Manually remove any old
2131 backup, since os.remove may fail under Windows. Fixes bug
2166 backup, since os.remove may fail under Windows. Fixes bug
2132 reported by Thorsten.
2167 reported by Thorsten.
2133
2168
2134 2004-06-09 Fernando Perez <fperez@colorado.edu>
2169 2004-06-09 Fernando Perez <fperez@colorado.edu>
2135
2170
2136 * examples/example-embed.py: fixed all references to %n (replaced
2171 * examples/example-embed.py: fixed all references to %n (replaced
2137 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
2172 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
2138 for all examples and the manual as well.
2173 for all examples and the manual as well.
2139
2174
2140 2004-06-08 Fernando Perez <fperez@colorado.edu>
2175 2004-06-08 Fernando Perez <fperez@colorado.edu>
2141
2176
2142 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
2177 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
2143 alignment and color management. All 3 prompt subsystems now
2178 alignment and color management. All 3 prompt subsystems now
2144 inherit from BasePrompt.
2179 inherit from BasePrompt.
2145
2180
2146 * tools/release: updates for windows installer build and tag rpms
2181 * tools/release: updates for windows installer build and tag rpms
2147 with python version (since paths are fixed).
2182 with python version (since paths are fixed).
2148
2183
2149 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
2184 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
2150 which will become eventually obsolete. Also fixed the default
2185 which will become eventually obsolete. Also fixed the default
2151 prompt_in2 to use \D, so at least new users start with the correct
2186 prompt_in2 to use \D, so at least new users start with the correct
2152 defaults.
2187 defaults.
2153 WARNING: Users with existing ipythonrc files will need to apply
2188 WARNING: Users with existing ipythonrc files will need to apply
2154 this fix manually!
2189 this fix manually!
2155
2190
2156 * setup.py: make windows installer (.exe). This is finally the
2191 * setup.py: make windows installer (.exe). This is finally the
2157 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
2192 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
2158 which I hadn't included because it required Python 2.3 (or recent
2193 which I hadn't included because it required Python 2.3 (or recent
2159 distutils).
2194 distutils).
2160
2195
2161 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
2196 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
2162 usage of new '\D' escape.
2197 usage of new '\D' escape.
2163
2198
2164 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
2199 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
2165 lacks os.getuid())
2200 lacks os.getuid())
2166 (CachedOutput.set_colors): Added the ability to turn coloring
2201 (CachedOutput.set_colors): Added the ability to turn coloring
2167 on/off with @colors even for manually defined prompt colors. It
2202 on/off with @colors even for manually defined prompt colors. It
2168 uses a nasty global, but it works safely and via the generic color
2203 uses a nasty global, but it works safely and via the generic color
2169 handling mechanism.
2204 handling mechanism.
2170 (Prompt2.__init__): Introduced new escape '\D' for continuation
2205 (Prompt2.__init__): Introduced new escape '\D' for continuation
2171 prompts. It represents the counter ('\#') as dots.
2206 prompts. It represents the counter ('\#') as dots.
2172 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
2207 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
2173 need to update their ipythonrc files and replace '%n' with '\D' in
2208 need to update their ipythonrc files and replace '%n' with '\D' in
2174 their prompt_in2 settings everywhere. Sorry, but there's
2209 their prompt_in2 settings everywhere. Sorry, but there's
2175 otherwise no clean way to get all prompts to properly align. The
2210 otherwise no clean way to get all prompts to properly align. The
2176 ipythonrc shipped with IPython has been updated.
2211 ipythonrc shipped with IPython has been updated.
2177
2212
2178 2004-06-07 Fernando Perez <fperez@colorado.edu>
2213 2004-06-07 Fernando Perez <fperez@colorado.edu>
2179
2214
2180 * setup.py (isfile): Pass local_icons option to latex2html, so the
2215 * setup.py (isfile): Pass local_icons option to latex2html, so the
2181 resulting HTML file is self-contained. Thanks to
2216 resulting HTML file is self-contained. Thanks to
2182 dryice-AT-liu.com.cn for the tip.
2217 dryice-AT-liu.com.cn for the tip.
2183
2218
2184 * pysh.py: I created a new profile 'shell', which implements a
2219 * pysh.py: I created a new profile 'shell', which implements a
2185 _rudimentary_ IPython-based shell. This is in NO WAY a realy
2220 _rudimentary_ IPython-based shell. This is in NO WAY a realy
2186 system shell, nor will it become one anytime soon. It's mainly
2221 system shell, nor will it become one anytime soon. It's mainly
2187 meant to illustrate the use of the new flexible bash-like prompts.
2222 meant to illustrate the use of the new flexible bash-like prompts.
2188 I guess it could be used by hardy souls for true shell management,
2223 I guess it could be used by hardy souls for true shell management,
2189 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
2224 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
2190 profile. This uses the InterpreterExec extension provided by
2225 profile. This uses the InterpreterExec extension provided by
2191 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
2226 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
2192
2227
2193 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
2228 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
2194 auto-align itself with the length of the previous input prompt
2229 auto-align itself with the length of the previous input prompt
2195 (taking into account the invisible color escapes).
2230 (taking into account the invisible color escapes).
2196 (CachedOutput.__init__): Large restructuring of this class. Now
2231 (CachedOutput.__init__): Large restructuring of this class. Now
2197 all three prompts (primary1, primary2, output) are proper objects,
2232 all three prompts (primary1, primary2, output) are proper objects,
2198 managed by the 'parent' CachedOutput class. The code is still a
2233 managed by the 'parent' CachedOutput class. The code is still a
2199 bit hackish (all prompts share state via a pointer to the cache),
2234 bit hackish (all prompts share state via a pointer to the cache),
2200 but it's overall far cleaner than before.
2235 but it's overall far cleaner than before.
2201
2236
2202 * IPython/genutils.py (getoutputerror): modified to add verbose,
2237 * IPython/genutils.py (getoutputerror): modified to add verbose,
2203 debug and header options. This makes the interface of all getout*
2238 debug and header options. This makes the interface of all getout*
2204 functions uniform.
2239 functions uniform.
2205 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
2240 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
2206
2241
2207 * IPython/Magic.py (Magic.default_option): added a function to
2242 * IPython/Magic.py (Magic.default_option): added a function to
2208 allow registering default options for any magic command. This
2243 allow registering default options for any magic command. This
2209 makes it easy to have profiles which customize the magics globally
2244 makes it easy to have profiles which customize the magics globally
2210 for a certain use. The values set through this function are
2245 for a certain use. The values set through this function are
2211 picked up by the parse_options() method, which all magics should
2246 picked up by the parse_options() method, which all magics should
2212 use to parse their options.
2247 use to parse their options.
2213
2248
2214 * IPython/genutils.py (warn): modified the warnings framework to
2249 * IPython/genutils.py (warn): modified the warnings framework to
2215 use the Term I/O class. I'm trying to slowly unify all of
2250 use the Term I/O class. I'm trying to slowly unify all of
2216 IPython's I/O operations to pass through Term.
2251 IPython's I/O operations to pass through Term.
2217
2252
2218 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
2253 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
2219 the secondary prompt to correctly match the length of the primary
2254 the secondary prompt to correctly match the length of the primary
2220 one for any prompt. Now multi-line code will properly line up
2255 one for any prompt. Now multi-line code will properly line up
2221 even for path dependent prompts, such as the new ones available
2256 even for path dependent prompts, such as the new ones available
2222 via the prompt_specials.
2257 via the prompt_specials.
2223
2258
2224 2004-06-06 Fernando Perez <fperez@colorado.edu>
2259 2004-06-06 Fernando Perez <fperez@colorado.edu>
2225
2260
2226 * IPython/Prompts.py (prompt_specials): Added the ability to have
2261 * IPython/Prompts.py (prompt_specials): Added the ability to have
2227 bash-like special sequences in the prompts, which get
2262 bash-like special sequences in the prompts, which get
2228 automatically expanded. Things like hostname, current working
2263 automatically expanded. Things like hostname, current working
2229 directory and username are implemented already, but it's easy to
2264 directory and username are implemented already, but it's easy to
2230 add more in the future. Thanks to a patch by W.J. van der Laan
2265 add more in the future. Thanks to a patch by W.J. van der Laan
2231 <gnufnork-AT-hetdigitalegat.nl>
2266 <gnufnork-AT-hetdigitalegat.nl>
2232 (prompt_specials): Added color support for prompt strings, so
2267 (prompt_specials): Added color support for prompt strings, so
2233 users can define arbitrary color setups for their prompts.
2268 users can define arbitrary color setups for their prompts.
2234
2269
2235 2004-06-05 Fernando Perez <fperez@colorado.edu>
2270 2004-06-05 Fernando Perez <fperez@colorado.edu>
2236
2271
2237 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
2272 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
2238 code to load Gary Bishop's readline and configure it
2273 code to load Gary Bishop's readline and configure it
2239 automatically. Thanks to Gary for help on this.
2274 automatically. Thanks to Gary for help on this.
2240
2275
2241 2004-06-01 Fernando Perez <fperez@colorado.edu>
2276 2004-06-01 Fernando Perez <fperez@colorado.edu>
2242
2277
2243 * IPython/Logger.py (Logger.create_log): fix bug for logging
2278 * IPython/Logger.py (Logger.create_log): fix bug for logging
2244 with no filename (previous fix was incomplete).
2279 with no filename (previous fix was incomplete).
2245
2280
2246 2004-05-25 Fernando Perez <fperez@colorado.edu>
2281 2004-05-25 Fernando Perez <fperez@colorado.edu>
2247
2282
2248 * IPython/Magic.py (Magic.parse_options): fix bug where naked
2283 * IPython/Magic.py (Magic.parse_options): fix bug where naked
2249 parens would get passed to the shell.
2284 parens would get passed to the shell.
2250
2285
2251 2004-05-20 Fernando Perez <fperez@colorado.edu>
2286 2004-05-20 Fernando Perez <fperez@colorado.edu>
2252
2287
2253 * IPython/Magic.py (Magic.magic_prun): changed default profile
2288 * IPython/Magic.py (Magic.magic_prun): changed default profile
2254 sort order to 'time' (the more common profiling need).
2289 sort order to 'time' (the more common profiling need).
2255
2290
2256 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
2291 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
2257 so that source code shown is guaranteed in sync with the file on
2292 so that source code shown is guaranteed in sync with the file on
2258 disk (also changed in psource). Similar fix to the one for
2293 disk (also changed in psource). Similar fix to the one for
2259 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
2294 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
2260 <yann.ledu-AT-noos.fr>.
2295 <yann.ledu-AT-noos.fr>.
2261
2296
2262 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
2297 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
2263 with a single option would not be correctly parsed. Closes
2298 with a single option would not be correctly parsed. Closes
2264 http://www.scipy.net/roundup/ipython/issue14. This bug had been
2299 http://www.scipy.net/roundup/ipython/issue14. This bug had been
2265 introduced in 0.6.0 (on 2004-05-06).
2300 introduced in 0.6.0 (on 2004-05-06).
2266
2301
2267 2004-05-13 *** Released version 0.6.0
2302 2004-05-13 *** Released version 0.6.0
2268
2303
2269 2004-05-13 Fernando Perez <fperez@colorado.edu>
2304 2004-05-13 Fernando Perez <fperez@colorado.edu>
2270
2305
2271 * debian/: Added debian/ directory to CVS, so that debian support
2306 * debian/: Added debian/ directory to CVS, so that debian support
2272 is publicly accessible. The debian package is maintained by Jack
2307 is publicly accessible. The debian package is maintained by Jack
2273 Moffit <jack-AT-xiph.org>.
2308 Moffit <jack-AT-xiph.org>.
2274
2309
2275 * Documentation: included the notes about an ipython-based system
2310 * Documentation: included the notes about an ipython-based system
2276 shell (the hypothetical 'pysh') into the new_design.pdf document,
2311 shell (the hypothetical 'pysh') into the new_design.pdf document,
2277 so that these ideas get distributed to users along with the
2312 so that these ideas get distributed to users along with the
2278 official documentation.
2313 official documentation.
2279
2314
2280 2004-05-10 Fernando Perez <fperez@colorado.edu>
2315 2004-05-10 Fernando Perez <fperez@colorado.edu>
2281
2316
2282 * IPython/Logger.py (Logger.create_log): fix recently introduced
2317 * IPython/Logger.py (Logger.create_log): fix recently introduced
2283 bug (misindented line) where logstart would fail when not given an
2318 bug (misindented line) where logstart would fail when not given an
2284 explicit filename.
2319 explicit filename.
2285
2320
2286 2004-05-09 Fernando Perez <fperez@colorado.edu>
2321 2004-05-09 Fernando Perez <fperez@colorado.edu>
2287
2322
2288 * IPython/Magic.py (Magic.parse_options): skip system call when
2323 * IPython/Magic.py (Magic.parse_options): skip system call when
2289 there are no options to look for. Faster, cleaner for the common
2324 there are no options to look for. Faster, cleaner for the common
2290 case.
2325 case.
2291
2326
2292 * Documentation: many updates to the manual: describing Windows
2327 * Documentation: many updates to the manual: describing Windows
2293 support better, Gnuplot updates, credits, misc small stuff. Also
2328 support better, Gnuplot updates, credits, misc small stuff. Also
2294 updated the new_design doc a bit.
2329 updated the new_design doc a bit.
2295
2330
2296 2004-05-06 *** Released version 0.6.0.rc1
2331 2004-05-06 *** Released version 0.6.0.rc1
2297
2332
2298 2004-05-06 Fernando Perez <fperez@colorado.edu>
2333 2004-05-06 Fernando Perez <fperez@colorado.edu>
2299
2334
2300 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
2335 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
2301 operations to use the vastly more efficient list/''.join() method.
2336 operations to use the vastly more efficient list/''.join() method.
2302 (FormattedTB.text): Fix
2337 (FormattedTB.text): Fix
2303 http://www.scipy.net/roundup/ipython/issue12 - exception source
2338 http://www.scipy.net/roundup/ipython/issue12 - exception source
2304 extract not updated after reload. Thanks to Mike Salib
2339 extract not updated after reload. Thanks to Mike Salib
2305 <msalib-AT-mit.edu> for pinning the source of the problem.
2340 <msalib-AT-mit.edu> for pinning the source of the problem.
2306 Fortunately, the solution works inside ipython and doesn't require
2341 Fortunately, the solution works inside ipython and doesn't require
2307 any changes to python proper.
2342 any changes to python proper.
2308
2343
2309 * IPython/Magic.py (Magic.parse_options): Improved to process the
2344 * IPython/Magic.py (Magic.parse_options): Improved to process the
2310 argument list as a true shell would (by actually using the
2345 argument list as a true shell would (by actually using the
2311 underlying system shell). This way, all @magics automatically get
2346 underlying system shell). This way, all @magics automatically get
2312 shell expansion for variables. Thanks to a comment by Alex
2347 shell expansion for variables. Thanks to a comment by Alex
2313 Schmolck.
2348 Schmolck.
2314
2349
2315 2004-04-04 Fernando Perez <fperez@colorado.edu>
2350 2004-04-04 Fernando Perez <fperez@colorado.edu>
2316
2351
2317 * IPython/iplib.py (InteractiveShell.interact): Added a special
2352 * IPython/iplib.py (InteractiveShell.interact): Added a special
2318 trap for a debugger quit exception, which is basically impossible
2353 trap for a debugger quit exception, which is basically impossible
2319 to handle by normal mechanisms, given what pdb does to the stack.
2354 to handle by normal mechanisms, given what pdb does to the stack.
2320 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
2355 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
2321
2356
2322 2004-04-03 Fernando Perez <fperez@colorado.edu>
2357 2004-04-03 Fernando Perez <fperez@colorado.edu>
2323
2358
2324 * IPython/genutils.py (Term): Standardized the names of the Term
2359 * IPython/genutils.py (Term): Standardized the names of the Term
2325 class streams to cin/cout/cerr, following C++ naming conventions
2360 class streams to cin/cout/cerr, following C++ naming conventions
2326 (I can't use in/out/err because 'in' is not a valid attribute
2361 (I can't use in/out/err because 'in' is not a valid attribute
2327 name).
2362 name).
2328
2363
2329 * IPython/iplib.py (InteractiveShell.interact): don't increment
2364 * IPython/iplib.py (InteractiveShell.interact): don't increment
2330 the prompt if there's no user input. By Daniel 'Dang' Griffith
2365 the prompt if there's no user input. By Daniel 'Dang' Griffith
2331 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
2366 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
2332 Francois Pinard.
2367 Francois Pinard.
2333
2368
2334 2004-04-02 Fernando Perez <fperez@colorado.edu>
2369 2004-04-02 Fernando Perez <fperez@colorado.edu>
2335
2370
2336 * IPython/genutils.py (Stream.__init__): Modified to survive at
2371 * IPython/genutils.py (Stream.__init__): Modified to survive at
2337 least importing in contexts where stdin/out/err aren't true file
2372 least importing in contexts where stdin/out/err aren't true file
2338 objects, such as PyCrust (they lack fileno() and mode). However,
2373 objects, such as PyCrust (they lack fileno() and mode). However,
2339 the recovery facilities which rely on these things existing will
2374 the recovery facilities which rely on these things existing will
2340 not work.
2375 not work.
2341
2376
2342 2004-04-01 Fernando Perez <fperez@colorado.edu>
2377 2004-04-01 Fernando Perez <fperez@colorado.edu>
2343
2378
2344 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2379 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2345 use the new getoutputerror() function, so it properly
2380 use the new getoutputerror() function, so it properly
2346 distinguishes stdout/err.
2381 distinguishes stdout/err.
2347
2382
2348 * IPython/genutils.py (getoutputerror): added a function to
2383 * IPython/genutils.py (getoutputerror): added a function to
2349 capture separately the standard output and error of a command.
2384 capture separately the standard output and error of a command.
2350 After a comment from dang on the mailing lists. This code is
2385 After a comment from dang on the mailing lists. This code is
2351 basically a modified version of commands.getstatusoutput(), from
2386 basically a modified version of commands.getstatusoutput(), from
2352 the standard library.
2387 the standard library.
2353
2388
2354 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2389 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2355 '!!' as a special syntax (shorthand) to access @sx.
2390 '!!' as a special syntax (shorthand) to access @sx.
2356
2391
2357 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2392 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2358 command and return its output as a list split on '\n'.
2393 command and return its output as a list split on '\n'.
2359
2394
2360 2004-03-31 Fernando Perez <fperez@colorado.edu>
2395 2004-03-31 Fernando Perez <fperez@colorado.edu>
2361
2396
2362 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2397 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2363 method to dictionaries used as FakeModule instances if they lack
2398 method to dictionaries used as FakeModule instances if they lack
2364 it. At least pydoc in python2.3 breaks for runtime-defined
2399 it. At least pydoc in python2.3 breaks for runtime-defined
2365 functions without this hack. At some point I need to _really_
2400 functions without this hack. At some point I need to _really_
2366 understand what FakeModule is doing, because it's a gross hack.
2401 understand what FakeModule is doing, because it's a gross hack.
2367 But it solves Arnd's problem for now...
2402 But it solves Arnd's problem for now...
2368
2403
2369 2004-02-27 Fernando Perez <fperez@colorado.edu>
2404 2004-02-27 Fernando Perez <fperez@colorado.edu>
2370
2405
2371 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2406 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2372 mode would behave erratically. Also increased the number of
2407 mode would behave erratically. Also increased the number of
2373 possible logs in rotate mod to 999. Thanks to Rod Holland
2408 possible logs in rotate mod to 999. Thanks to Rod Holland
2374 <rhh@StructureLABS.com> for the report and fixes.
2409 <rhh@StructureLABS.com> for the report and fixes.
2375
2410
2376 2004-02-26 Fernando Perez <fperez@colorado.edu>
2411 2004-02-26 Fernando Perez <fperez@colorado.edu>
2377
2412
2378 * IPython/genutils.py (page): Check that the curses module really
2413 * IPython/genutils.py (page): Check that the curses module really
2379 has the initscr attribute before trying to use it. For some
2414 has the initscr attribute before trying to use it. For some
2380 reason, the Solaris curses module is missing this. I think this
2415 reason, the Solaris curses module is missing this. I think this
2381 should be considered a Solaris python bug, but I'm not sure.
2416 should be considered a Solaris python bug, but I'm not sure.
2382
2417
2383 2004-01-17 Fernando Perez <fperez@colorado.edu>
2418 2004-01-17 Fernando Perez <fperez@colorado.edu>
2384
2419
2385 * IPython/genutils.py (Stream.__init__): Changes to try to make
2420 * IPython/genutils.py (Stream.__init__): Changes to try to make
2386 ipython robust against stdin/out/err being closed by the user.
2421 ipython robust against stdin/out/err being closed by the user.
2387 This is 'user error' (and blocks a normal python session, at least
2422 This is 'user error' (and blocks a normal python session, at least
2388 the stdout case). However, Ipython should be able to survive such
2423 the stdout case). However, Ipython should be able to survive such
2389 instances of abuse as gracefully as possible. To simplify the
2424 instances of abuse as gracefully as possible. To simplify the
2390 coding and maintain compatibility with Gary Bishop's Term
2425 coding and maintain compatibility with Gary Bishop's Term
2391 contributions, I've made use of classmethods for this. I think
2426 contributions, I've made use of classmethods for this. I think
2392 this introduces a dependency on python 2.2.
2427 this introduces a dependency on python 2.2.
2393
2428
2394 2004-01-13 Fernando Perez <fperez@colorado.edu>
2429 2004-01-13 Fernando Perez <fperez@colorado.edu>
2395
2430
2396 * IPython/numutils.py (exp_safe): simplified the code a bit and
2431 * IPython/numutils.py (exp_safe): simplified the code a bit and
2397 removed the need for importing the kinds module altogether.
2432 removed the need for importing the kinds module altogether.
2398
2433
2399 2004-01-06 Fernando Perez <fperez@colorado.edu>
2434 2004-01-06 Fernando Perez <fperez@colorado.edu>
2400
2435
2401 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2436 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2402 a magic function instead, after some community feedback. No
2437 a magic function instead, after some community feedback. No
2403 special syntax will exist for it, but its name is deliberately
2438 special syntax will exist for it, but its name is deliberately
2404 very short.
2439 very short.
2405
2440
2406 2003-12-20 Fernando Perez <fperez@colorado.edu>
2441 2003-12-20 Fernando Perez <fperez@colorado.edu>
2407
2442
2408 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2443 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2409 new functionality, to automagically assign the result of a shell
2444 new functionality, to automagically assign the result of a shell
2410 command to a variable. I'll solicit some community feedback on
2445 command to a variable. I'll solicit some community feedback on
2411 this before making it permanent.
2446 this before making it permanent.
2412
2447
2413 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2448 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2414 requested about callables for which inspect couldn't obtain a
2449 requested about callables for which inspect couldn't obtain a
2415 proper argspec. Thanks to a crash report sent by Etienne
2450 proper argspec. Thanks to a crash report sent by Etienne
2416 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2451 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2417
2452
2418 2003-12-09 Fernando Perez <fperez@colorado.edu>
2453 2003-12-09 Fernando Perez <fperez@colorado.edu>
2419
2454
2420 * IPython/genutils.py (page): patch for the pager to work across
2455 * IPython/genutils.py (page): patch for the pager to work across
2421 various versions of Windows. By Gary Bishop.
2456 various versions of Windows. By Gary Bishop.
2422
2457
2423 2003-12-04 Fernando Perez <fperez@colorado.edu>
2458 2003-12-04 Fernando Perez <fperez@colorado.edu>
2424
2459
2425 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2460 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2426 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2461 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2427 While I tested this and it looks ok, there may still be corner
2462 While I tested this and it looks ok, there may still be corner
2428 cases I've missed.
2463 cases I've missed.
2429
2464
2430 2003-12-01 Fernando Perez <fperez@colorado.edu>
2465 2003-12-01 Fernando Perez <fperez@colorado.edu>
2431
2466
2432 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2467 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2433 where a line like 'p,q=1,2' would fail because the automagic
2468 where a line like 'p,q=1,2' would fail because the automagic
2434 system would be triggered for @p.
2469 system would be triggered for @p.
2435
2470
2436 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2471 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2437 cleanups, code unmodified.
2472 cleanups, code unmodified.
2438
2473
2439 * IPython/genutils.py (Term): added a class for IPython to handle
2474 * IPython/genutils.py (Term): added a class for IPython to handle
2440 output. In most cases it will just be a proxy for stdout/err, but
2475 output. In most cases it will just be a proxy for stdout/err, but
2441 having this allows modifications to be made for some platforms,
2476 having this allows modifications to be made for some platforms,
2442 such as handling color escapes under Windows. All of this code
2477 such as handling color escapes under Windows. All of this code
2443 was contributed by Gary Bishop, with minor modifications by me.
2478 was contributed by Gary Bishop, with minor modifications by me.
2444 The actual changes affect many files.
2479 The actual changes affect many files.
2445
2480
2446 2003-11-30 Fernando Perez <fperez@colorado.edu>
2481 2003-11-30 Fernando Perez <fperez@colorado.edu>
2447
2482
2448 * IPython/iplib.py (file_matches): new completion code, courtesy
2483 * IPython/iplib.py (file_matches): new completion code, courtesy
2449 of Jeff Collins. This enables filename completion again under
2484 of Jeff Collins. This enables filename completion again under
2450 python 2.3, which disabled it at the C level.
2485 python 2.3, which disabled it at the C level.
2451
2486
2452 2003-11-11 Fernando Perez <fperez@colorado.edu>
2487 2003-11-11 Fernando Perez <fperez@colorado.edu>
2453
2488
2454 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2489 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2455 for Numeric.array(map(...)), but often convenient.
2490 for Numeric.array(map(...)), but often convenient.
2456
2491
2457 2003-11-05 Fernando Perez <fperez@colorado.edu>
2492 2003-11-05 Fernando Perez <fperez@colorado.edu>
2458
2493
2459 * IPython/numutils.py (frange): Changed a call from int() to
2494 * IPython/numutils.py (frange): Changed a call from int() to
2460 int(round()) to prevent a problem reported with arange() in the
2495 int(round()) to prevent a problem reported with arange() in the
2461 numpy list.
2496 numpy list.
2462
2497
2463 2003-10-06 Fernando Perez <fperez@colorado.edu>
2498 2003-10-06 Fernando Perez <fperez@colorado.edu>
2464
2499
2465 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2500 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2466 prevent crashes if sys lacks an argv attribute (it happens with
2501 prevent crashes if sys lacks an argv attribute (it happens with
2467 embedded interpreters which build a bare-bones sys module).
2502 embedded interpreters which build a bare-bones sys module).
2468 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2503 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2469
2504
2470 2003-09-24 Fernando Perez <fperez@colorado.edu>
2505 2003-09-24 Fernando Perez <fperez@colorado.edu>
2471
2506
2472 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2507 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2473 to protect against poorly written user objects where __getattr__
2508 to protect against poorly written user objects where __getattr__
2474 raises exceptions other than AttributeError. Thanks to a bug
2509 raises exceptions other than AttributeError. Thanks to a bug
2475 report by Oliver Sander <osander-AT-gmx.de>.
2510 report by Oliver Sander <osander-AT-gmx.de>.
2476
2511
2477 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2512 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2478 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2513 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2479
2514
2480 2003-09-09 Fernando Perez <fperez@colorado.edu>
2515 2003-09-09 Fernando Perez <fperez@colorado.edu>
2481
2516
2482 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2517 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2483 unpacking a list whith a callable as first element would
2518 unpacking a list whith a callable as first element would
2484 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2519 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2485 Collins.
2520 Collins.
2486
2521
2487 2003-08-25 *** Released version 0.5.0
2522 2003-08-25 *** Released version 0.5.0
2488
2523
2489 2003-08-22 Fernando Perez <fperez@colorado.edu>
2524 2003-08-22 Fernando Perez <fperez@colorado.edu>
2490
2525
2491 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2526 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2492 improperly defined user exceptions. Thanks to feedback from Mark
2527 improperly defined user exceptions. Thanks to feedback from Mark
2493 Russell <mrussell-AT-verio.net>.
2528 Russell <mrussell-AT-verio.net>.
2494
2529
2495 2003-08-20 Fernando Perez <fperez@colorado.edu>
2530 2003-08-20 Fernando Perez <fperez@colorado.edu>
2496
2531
2497 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2532 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2498 printing so that it would print multi-line string forms starting
2533 printing so that it would print multi-line string forms starting
2499 with a new line. This way the formatting is better respected for
2534 with a new line. This way the formatting is better respected for
2500 objects which work hard to make nice string forms.
2535 objects which work hard to make nice string forms.
2501
2536
2502 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2537 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2503 autocall would overtake data access for objects with both
2538 autocall would overtake data access for objects with both
2504 __getitem__ and __call__.
2539 __getitem__ and __call__.
2505
2540
2506 2003-08-19 *** Released version 0.5.0-rc1
2541 2003-08-19 *** Released version 0.5.0-rc1
2507
2542
2508 2003-08-19 Fernando Perez <fperez@colorado.edu>
2543 2003-08-19 Fernando Perez <fperez@colorado.edu>
2509
2544
2510 * IPython/deep_reload.py (load_tail): single tiny change here
2545 * IPython/deep_reload.py (load_tail): single tiny change here
2511 seems to fix the long-standing bug of dreload() failing to work
2546 seems to fix the long-standing bug of dreload() failing to work
2512 for dotted names. But this module is pretty tricky, so I may have
2547 for dotted names. But this module is pretty tricky, so I may have
2513 missed some subtlety. Needs more testing!.
2548 missed some subtlety. Needs more testing!.
2514
2549
2515 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2550 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2516 exceptions which have badly implemented __str__ methods.
2551 exceptions which have badly implemented __str__ methods.
2517 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2552 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2518 which I've been getting reports about from Python 2.3 users. I
2553 which I've been getting reports about from Python 2.3 users. I
2519 wish I had a simple test case to reproduce the problem, so I could
2554 wish I had a simple test case to reproduce the problem, so I could
2520 either write a cleaner workaround or file a bug report if
2555 either write a cleaner workaround or file a bug report if
2521 necessary.
2556 necessary.
2522
2557
2523 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2558 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2524 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2559 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2525 a bug report by Tjabo Kloppenburg.
2560 a bug report by Tjabo Kloppenburg.
2526
2561
2527 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2562 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2528 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2563 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2529 seems rather unstable. Thanks to a bug report by Tjabo
2564 seems rather unstable. Thanks to a bug report by Tjabo
2530 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2565 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2531
2566
2532 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2567 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2533 this out soon because of the critical fixes in the inner loop for
2568 this out soon because of the critical fixes in the inner loop for
2534 generators.
2569 generators.
2535
2570
2536 * IPython/Magic.py (Magic.getargspec): removed. This (and
2571 * IPython/Magic.py (Magic.getargspec): removed. This (and
2537 _get_def) have been obsoleted by OInspect for a long time, I
2572 _get_def) have been obsoleted by OInspect for a long time, I
2538 hadn't noticed that they were dead code.
2573 hadn't noticed that they were dead code.
2539 (Magic._ofind): restored _ofind functionality for a few literals
2574 (Magic._ofind): restored _ofind functionality for a few literals
2540 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2575 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2541 for things like "hello".capitalize?, since that would require a
2576 for things like "hello".capitalize?, since that would require a
2542 potentially dangerous eval() again.
2577 potentially dangerous eval() again.
2543
2578
2544 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2579 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2545 logic a bit more to clean up the escapes handling and minimize the
2580 logic a bit more to clean up the escapes handling and minimize the
2546 use of _ofind to only necessary cases. The interactive 'feel' of
2581 use of _ofind to only necessary cases. The interactive 'feel' of
2547 IPython should have improved quite a bit with the changes in
2582 IPython should have improved quite a bit with the changes in
2548 _prefilter and _ofind (besides being far safer than before).
2583 _prefilter and _ofind (besides being far safer than before).
2549
2584
2550 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2585 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2551 obscure, never reported). Edit would fail to find the object to
2586 obscure, never reported). Edit would fail to find the object to
2552 edit under some circumstances.
2587 edit under some circumstances.
2553 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2588 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2554 which were causing double-calling of generators. Those eval calls
2589 which were causing double-calling of generators. Those eval calls
2555 were _very_ dangerous, since code with side effects could be
2590 were _very_ dangerous, since code with side effects could be
2556 triggered. As they say, 'eval is evil'... These were the
2591 triggered. As they say, 'eval is evil'... These were the
2557 nastiest evals in IPython. Besides, _ofind is now far simpler,
2592 nastiest evals in IPython. Besides, _ofind is now far simpler,
2558 and it should also be quite a bit faster. Its use of inspect is
2593 and it should also be quite a bit faster. Its use of inspect is
2559 also safer, so perhaps some of the inspect-related crashes I've
2594 also safer, so perhaps some of the inspect-related crashes I've
2560 seen lately with Python 2.3 might be taken care of. That will
2595 seen lately with Python 2.3 might be taken care of. That will
2561 need more testing.
2596 need more testing.
2562
2597
2563 2003-08-17 Fernando Perez <fperez@colorado.edu>
2598 2003-08-17 Fernando Perez <fperez@colorado.edu>
2564
2599
2565 * IPython/iplib.py (InteractiveShell._prefilter): significant
2600 * IPython/iplib.py (InteractiveShell._prefilter): significant
2566 simplifications to the logic for handling user escapes. Faster
2601 simplifications to the logic for handling user escapes. Faster
2567 and simpler code.
2602 and simpler code.
2568
2603
2569 2003-08-14 Fernando Perez <fperez@colorado.edu>
2604 2003-08-14 Fernando Perez <fperez@colorado.edu>
2570
2605
2571 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2606 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2572 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2607 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2573 but it should be quite a bit faster. And the recursive version
2608 but it should be quite a bit faster. And the recursive version
2574 generated O(log N) intermediate storage for all rank>1 arrays,
2609 generated O(log N) intermediate storage for all rank>1 arrays,
2575 even if they were contiguous.
2610 even if they were contiguous.
2576 (l1norm): Added this function.
2611 (l1norm): Added this function.
2577 (norm): Added this function for arbitrary norms (including
2612 (norm): Added this function for arbitrary norms (including
2578 l-infinity). l1 and l2 are still special cases for convenience
2613 l-infinity). l1 and l2 are still special cases for convenience
2579 and speed.
2614 and speed.
2580
2615
2581 2003-08-03 Fernando Perez <fperez@colorado.edu>
2616 2003-08-03 Fernando Perez <fperez@colorado.edu>
2582
2617
2583 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2618 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2584 exceptions, which now raise PendingDeprecationWarnings in Python
2619 exceptions, which now raise PendingDeprecationWarnings in Python
2585 2.3. There were some in Magic and some in Gnuplot2.
2620 2.3. There were some in Magic and some in Gnuplot2.
2586
2621
2587 2003-06-30 Fernando Perez <fperez@colorado.edu>
2622 2003-06-30 Fernando Perez <fperez@colorado.edu>
2588
2623
2589 * IPython/genutils.py (page): modified to call curses only for
2624 * IPython/genutils.py (page): modified to call curses only for
2590 terminals where TERM=='xterm'. After problems under many other
2625 terminals where TERM=='xterm'. After problems under many other
2591 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2626 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2592
2627
2593 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2628 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2594 would be triggered when readline was absent. This was just an old
2629 would be triggered when readline was absent. This was just an old
2595 debugging statement I'd forgotten to take out.
2630 debugging statement I'd forgotten to take out.
2596
2631
2597 2003-06-20 Fernando Perez <fperez@colorado.edu>
2632 2003-06-20 Fernando Perez <fperez@colorado.edu>
2598
2633
2599 * IPython/genutils.py (clock): modified to return only user time
2634 * IPython/genutils.py (clock): modified to return only user time
2600 (not counting system time), after a discussion on scipy. While
2635 (not counting system time), after a discussion on scipy. While
2601 system time may be a useful quantity occasionally, it may much
2636 system time may be a useful quantity occasionally, it may much
2602 more easily be skewed by occasional swapping or other similar
2637 more easily be skewed by occasional swapping or other similar
2603 activity.
2638 activity.
2604
2639
2605 2003-06-05 Fernando Perez <fperez@colorado.edu>
2640 2003-06-05 Fernando Perez <fperez@colorado.edu>
2606
2641
2607 * IPython/numutils.py (identity): new function, for building
2642 * IPython/numutils.py (identity): new function, for building
2608 arbitrary rank Kronecker deltas (mostly backwards compatible with
2643 arbitrary rank Kronecker deltas (mostly backwards compatible with
2609 Numeric.identity)
2644 Numeric.identity)
2610
2645
2611 2003-06-03 Fernando Perez <fperez@colorado.edu>
2646 2003-06-03 Fernando Perez <fperez@colorado.edu>
2612
2647
2613 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2648 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2614 arguments passed to magics with spaces, to allow trailing '\' to
2649 arguments passed to magics with spaces, to allow trailing '\' to
2615 work normally (mainly for Windows users).
2650 work normally (mainly for Windows users).
2616
2651
2617 2003-05-29 Fernando Perez <fperez@colorado.edu>
2652 2003-05-29 Fernando Perez <fperez@colorado.edu>
2618
2653
2619 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2654 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2620 instead of pydoc.help. This fixes a bizarre behavior where
2655 instead of pydoc.help. This fixes a bizarre behavior where
2621 printing '%s' % locals() would trigger the help system. Now
2656 printing '%s' % locals() would trigger the help system. Now
2622 ipython behaves like normal python does.
2657 ipython behaves like normal python does.
2623
2658
2624 Note that if one does 'from pydoc import help', the bizarre
2659 Note that if one does 'from pydoc import help', the bizarre
2625 behavior returns, but this will also happen in normal python, so
2660 behavior returns, but this will also happen in normal python, so
2626 it's not an ipython bug anymore (it has to do with how pydoc.help
2661 it's not an ipython bug anymore (it has to do with how pydoc.help
2627 is implemented).
2662 is implemented).
2628
2663
2629 2003-05-22 Fernando Perez <fperez@colorado.edu>
2664 2003-05-22 Fernando Perez <fperez@colorado.edu>
2630
2665
2631 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2666 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2632 return [] instead of None when nothing matches, also match to end
2667 return [] instead of None when nothing matches, also match to end
2633 of line. Patch by Gary Bishop.
2668 of line. Patch by Gary Bishop.
2634
2669
2635 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2670 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2636 protection as before, for files passed on the command line. This
2671 protection as before, for files passed on the command line. This
2637 prevents the CrashHandler from kicking in if user files call into
2672 prevents the CrashHandler from kicking in if user files call into
2638 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2673 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2639 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2674 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2640
2675
2641 2003-05-20 *** Released version 0.4.0
2676 2003-05-20 *** Released version 0.4.0
2642
2677
2643 2003-05-20 Fernando Perez <fperez@colorado.edu>
2678 2003-05-20 Fernando Perez <fperez@colorado.edu>
2644
2679
2645 * setup.py: added support for manpages. It's a bit hackish b/c of
2680 * setup.py: added support for manpages. It's a bit hackish b/c of
2646 a bug in the way the bdist_rpm distutils target handles gzipped
2681 a bug in the way the bdist_rpm distutils target handles gzipped
2647 manpages, but it works. After a patch by Jack.
2682 manpages, but it works. After a patch by Jack.
2648
2683
2649 2003-05-19 Fernando Perez <fperez@colorado.edu>
2684 2003-05-19 Fernando Perez <fperez@colorado.edu>
2650
2685
2651 * IPython/numutils.py: added a mockup of the kinds module, since
2686 * IPython/numutils.py: added a mockup of the kinds module, since
2652 it was recently removed from Numeric. This way, numutils will
2687 it was recently removed from Numeric. This way, numutils will
2653 work for all users even if they are missing kinds.
2688 work for all users even if they are missing kinds.
2654
2689
2655 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2690 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2656 failure, which can occur with SWIG-wrapped extensions. After a
2691 failure, which can occur with SWIG-wrapped extensions. After a
2657 crash report from Prabhu.
2692 crash report from Prabhu.
2658
2693
2659 2003-05-16 Fernando Perez <fperez@colorado.edu>
2694 2003-05-16 Fernando Perez <fperez@colorado.edu>
2660
2695
2661 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2696 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2662 protect ipython from user code which may call directly
2697 protect ipython from user code which may call directly
2663 sys.excepthook (this looks like an ipython crash to the user, even
2698 sys.excepthook (this looks like an ipython crash to the user, even
2664 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2699 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2665 This is especially important to help users of WxWindows, but may
2700 This is especially important to help users of WxWindows, but may
2666 also be useful in other cases.
2701 also be useful in other cases.
2667
2702
2668 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2703 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2669 an optional tb_offset to be specified, and to preserve exception
2704 an optional tb_offset to be specified, and to preserve exception
2670 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2705 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2671
2706
2672 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2707 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2673
2708
2674 2003-05-15 Fernando Perez <fperez@colorado.edu>
2709 2003-05-15 Fernando Perez <fperez@colorado.edu>
2675
2710
2676 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2711 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2677 installing for a new user under Windows.
2712 installing for a new user under Windows.
2678
2713
2679 2003-05-12 Fernando Perez <fperez@colorado.edu>
2714 2003-05-12 Fernando Perez <fperez@colorado.edu>
2680
2715
2681 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2716 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2682 handler for Emacs comint-based lines. Currently it doesn't do
2717 handler for Emacs comint-based lines. Currently it doesn't do
2683 much (but importantly, it doesn't update the history cache). In
2718 much (but importantly, it doesn't update the history cache). In
2684 the future it may be expanded if Alex needs more functionality
2719 the future it may be expanded if Alex needs more functionality
2685 there.
2720 there.
2686
2721
2687 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2722 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2688 info to crash reports.
2723 info to crash reports.
2689
2724
2690 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2725 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2691 just like Python's -c. Also fixed crash with invalid -color
2726 just like Python's -c. Also fixed crash with invalid -color
2692 option value at startup. Thanks to Will French
2727 option value at startup. Thanks to Will French
2693 <wfrench-AT-bestweb.net> for the bug report.
2728 <wfrench-AT-bestweb.net> for the bug report.
2694
2729
2695 2003-05-09 Fernando Perez <fperez@colorado.edu>
2730 2003-05-09 Fernando Perez <fperez@colorado.edu>
2696
2731
2697 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2732 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2698 to EvalDict (it's a mapping, after all) and simplified its code
2733 to EvalDict (it's a mapping, after all) and simplified its code
2699 quite a bit, after a nice discussion on c.l.py where Gustavo
2734 quite a bit, after a nice discussion on c.l.py where Gustavo
2700 Córdova <gcordova-AT-sismex.com> suggested the new version.
2735 Córdova <gcordova-AT-sismex.com> suggested the new version.
2701
2736
2702 2003-04-30 Fernando Perez <fperez@colorado.edu>
2737 2003-04-30 Fernando Perez <fperez@colorado.edu>
2703
2738
2704 * IPython/genutils.py (timings_out): modified it to reduce its
2739 * IPython/genutils.py (timings_out): modified it to reduce its
2705 overhead in the common reps==1 case.
2740 overhead in the common reps==1 case.
2706
2741
2707 2003-04-29 Fernando Perez <fperez@colorado.edu>
2742 2003-04-29 Fernando Perez <fperez@colorado.edu>
2708
2743
2709 * IPython/genutils.py (timings_out): Modified to use the resource
2744 * IPython/genutils.py (timings_out): Modified to use the resource
2710 module, which avoids the wraparound problems of time.clock().
2745 module, which avoids the wraparound problems of time.clock().
2711
2746
2712 2003-04-17 *** Released version 0.2.15pre4
2747 2003-04-17 *** Released version 0.2.15pre4
2713
2748
2714 2003-04-17 Fernando Perez <fperez@colorado.edu>
2749 2003-04-17 Fernando Perez <fperez@colorado.edu>
2715
2750
2716 * setup.py (scriptfiles): Split windows-specific stuff over to a
2751 * setup.py (scriptfiles): Split windows-specific stuff over to a
2717 separate file, in an attempt to have a Windows GUI installer.
2752 separate file, in an attempt to have a Windows GUI installer.
2718 That didn't work, but part of the groundwork is done.
2753 That didn't work, but part of the groundwork is done.
2719
2754
2720 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2755 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2721 indent/unindent with 4 spaces. Particularly useful in combination
2756 indent/unindent with 4 spaces. Particularly useful in combination
2722 with the new auto-indent option.
2757 with the new auto-indent option.
2723
2758
2724 2003-04-16 Fernando Perez <fperez@colorado.edu>
2759 2003-04-16 Fernando Perez <fperez@colorado.edu>
2725
2760
2726 * IPython/Magic.py: various replacements of self.rc for
2761 * IPython/Magic.py: various replacements of self.rc for
2727 self.shell.rc. A lot more remains to be done to fully disentangle
2762 self.shell.rc. A lot more remains to be done to fully disentangle
2728 this class from the main Shell class.
2763 this class from the main Shell class.
2729
2764
2730 * IPython/GnuplotRuntime.py: added checks for mouse support so
2765 * IPython/GnuplotRuntime.py: added checks for mouse support so
2731 that we don't try to enable it if the current gnuplot doesn't
2766 that we don't try to enable it if the current gnuplot doesn't
2732 really support it. Also added checks so that we don't try to
2767 really support it. Also added checks so that we don't try to
2733 enable persist under Windows (where Gnuplot doesn't recognize the
2768 enable persist under Windows (where Gnuplot doesn't recognize the
2734 option).
2769 option).
2735
2770
2736 * IPython/iplib.py (InteractiveShell.interact): Added optional
2771 * IPython/iplib.py (InteractiveShell.interact): Added optional
2737 auto-indenting code, after a patch by King C. Shu
2772 auto-indenting code, after a patch by King C. Shu
2738 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2773 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2739 get along well with pasting indented code. If I ever figure out
2774 get along well with pasting indented code. If I ever figure out
2740 how to make that part go well, it will become on by default.
2775 how to make that part go well, it will become on by default.
2741
2776
2742 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2777 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2743 crash ipython if there was an unmatched '%' in the user's prompt
2778 crash ipython if there was an unmatched '%' in the user's prompt
2744 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2779 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2745
2780
2746 * IPython/iplib.py (InteractiveShell.interact): removed the
2781 * IPython/iplib.py (InteractiveShell.interact): removed the
2747 ability to ask the user whether he wants to crash or not at the
2782 ability to ask the user whether he wants to crash or not at the
2748 'last line' exception handler. Calling functions at that point
2783 'last line' exception handler. Calling functions at that point
2749 changes the stack, and the error reports would have incorrect
2784 changes the stack, and the error reports would have incorrect
2750 tracebacks.
2785 tracebacks.
2751
2786
2752 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2787 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2753 pass through a peger a pretty-printed form of any object. After a
2788 pass through a peger a pretty-printed form of any object. After a
2754 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2789 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2755
2790
2756 2003-04-14 Fernando Perez <fperez@colorado.edu>
2791 2003-04-14 Fernando Perez <fperez@colorado.edu>
2757
2792
2758 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2793 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2759 all files in ~ would be modified at first install (instead of
2794 all files in ~ would be modified at first install (instead of
2760 ~/.ipython). This could be potentially disastrous, as the
2795 ~/.ipython). This could be potentially disastrous, as the
2761 modification (make line-endings native) could damage binary files.
2796 modification (make line-endings native) could damage binary files.
2762
2797
2763 2003-04-10 Fernando Perez <fperez@colorado.edu>
2798 2003-04-10 Fernando Perez <fperez@colorado.edu>
2764
2799
2765 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2800 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2766 handle only lines which are invalid python. This now means that
2801 handle only lines which are invalid python. This now means that
2767 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2802 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2768 for the bug report.
2803 for the bug report.
2769
2804
2770 2003-04-01 Fernando Perez <fperez@colorado.edu>
2805 2003-04-01 Fernando Perez <fperez@colorado.edu>
2771
2806
2772 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2807 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2773 where failing to set sys.last_traceback would crash pdb.pm().
2808 where failing to set sys.last_traceback would crash pdb.pm().
2774 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2809 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2775 report.
2810 report.
2776
2811
2777 2003-03-25 Fernando Perez <fperez@colorado.edu>
2812 2003-03-25 Fernando Perez <fperez@colorado.edu>
2778
2813
2779 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2814 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2780 before printing it (it had a lot of spurious blank lines at the
2815 before printing it (it had a lot of spurious blank lines at the
2781 end).
2816 end).
2782
2817
2783 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2818 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2784 output would be sent 21 times! Obviously people don't use this
2819 output would be sent 21 times! Obviously people don't use this
2785 too often, or I would have heard about it.
2820 too often, or I would have heard about it.
2786
2821
2787 2003-03-24 Fernando Perez <fperez@colorado.edu>
2822 2003-03-24 Fernando Perez <fperez@colorado.edu>
2788
2823
2789 * setup.py (scriptfiles): renamed the data_files parameter from
2824 * setup.py (scriptfiles): renamed the data_files parameter from
2790 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2825 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2791 for the patch.
2826 for the patch.
2792
2827
2793 2003-03-20 Fernando Perez <fperez@colorado.edu>
2828 2003-03-20 Fernando Perez <fperez@colorado.edu>
2794
2829
2795 * IPython/genutils.py (error): added error() and fatal()
2830 * IPython/genutils.py (error): added error() and fatal()
2796 functions.
2831 functions.
2797
2832
2798 2003-03-18 *** Released version 0.2.15pre3
2833 2003-03-18 *** Released version 0.2.15pre3
2799
2834
2800 2003-03-18 Fernando Perez <fperez@colorado.edu>
2835 2003-03-18 Fernando Perez <fperez@colorado.edu>
2801
2836
2802 * setupext/install_data_ext.py
2837 * setupext/install_data_ext.py
2803 (install_data_ext.initialize_options): Class contributed by Jack
2838 (install_data_ext.initialize_options): Class contributed by Jack
2804 Moffit for fixing the old distutils hack. He is sending this to
2839 Moffit for fixing the old distutils hack. He is sending this to
2805 the distutils folks so in the future we may not need it as a
2840 the distutils folks so in the future we may not need it as a
2806 private fix.
2841 private fix.
2807
2842
2808 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2843 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2809 changes for Debian packaging. See his patch for full details.
2844 changes for Debian packaging. See his patch for full details.
2810 The old distutils hack of making the ipythonrc* files carry a
2845 The old distutils hack of making the ipythonrc* files carry a
2811 bogus .py extension is gone, at last. Examples were moved to a
2846 bogus .py extension is gone, at last. Examples were moved to a
2812 separate subdir under doc/, and the separate executable scripts
2847 separate subdir under doc/, and the separate executable scripts
2813 now live in their own directory. Overall a great cleanup. The
2848 now live in their own directory. Overall a great cleanup. The
2814 manual was updated to use the new files, and setup.py has been
2849 manual was updated to use the new files, and setup.py has been
2815 fixed for this setup.
2850 fixed for this setup.
2816
2851
2817 * IPython/PyColorize.py (Parser.usage): made non-executable and
2852 * IPython/PyColorize.py (Parser.usage): made non-executable and
2818 created a pycolor wrapper around it to be included as a script.
2853 created a pycolor wrapper around it to be included as a script.
2819
2854
2820 2003-03-12 *** Released version 0.2.15pre2
2855 2003-03-12 *** Released version 0.2.15pre2
2821
2856
2822 2003-03-12 Fernando Perez <fperez@colorado.edu>
2857 2003-03-12 Fernando Perez <fperez@colorado.edu>
2823
2858
2824 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2859 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2825 long-standing problem with garbage characters in some terminals.
2860 long-standing problem with garbage characters in some terminals.
2826 The issue was really that the \001 and \002 escapes must _only_ be
2861 The issue was really that the \001 and \002 escapes must _only_ be
2827 passed to input prompts (which call readline), but _never_ to
2862 passed to input prompts (which call readline), but _never_ to
2828 normal text to be printed on screen. I changed ColorANSI to have
2863 normal text to be printed on screen. I changed ColorANSI to have
2829 two classes: TermColors and InputTermColors, each with the
2864 two classes: TermColors and InputTermColors, each with the
2830 appropriate escapes for input prompts or normal text. The code in
2865 appropriate escapes for input prompts or normal text. The code in
2831 Prompts.py got slightly more complicated, but this very old and
2866 Prompts.py got slightly more complicated, but this very old and
2832 annoying bug is finally fixed.
2867 annoying bug is finally fixed.
2833
2868
2834 All the credit for nailing down the real origin of this problem
2869 All the credit for nailing down the real origin of this problem
2835 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2870 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2836 *Many* thanks to him for spending quite a bit of effort on this.
2871 *Many* thanks to him for spending quite a bit of effort on this.
2837
2872
2838 2003-03-05 *** Released version 0.2.15pre1
2873 2003-03-05 *** Released version 0.2.15pre1
2839
2874
2840 2003-03-03 Fernando Perez <fperez@colorado.edu>
2875 2003-03-03 Fernando Perez <fperez@colorado.edu>
2841
2876
2842 * IPython/FakeModule.py: Moved the former _FakeModule to a
2877 * IPython/FakeModule.py: Moved the former _FakeModule to a
2843 separate file, because it's also needed by Magic (to fix a similar
2878 separate file, because it's also needed by Magic (to fix a similar
2844 pickle-related issue in @run).
2879 pickle-related issue in @run).
2845
2880
2846 2003-03-02 Fernando Perez <fperez@colorado.edu>
2881 2003-03-02 Fernando Perez <fperez@colorado.edu>
2847
2882
2848 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2883 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2849 the autocall option at runtime.
2884 the autocall option at runtime.
2850 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2885 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2851 across Magic.py to start separating Magic from InteractiveShell.
2886 across Magic.py to start separating Magic from InteractiveShell.
2852 (Magic._ofind): Fixed to return proper namespace for dotted
2887 (Magic._ofind): Fixed to return proper namespace for dotted
2853 names. Before, a dotted name would always return 'not currently
2888 names. Before, a dotted name would always return 'not currently
2854 defined', because it would find the 'parent'. s.x would be found,
2889 defined', because it would find the 'parent'. s.x would be found,
2855 but since 'x' isn't defined by itself, it would get confused.
2890 but since 'x' isn't defined by itself, it would get confused.
2856 (Magic.magic_run): Fixed pickling problems reported by Ralf
2891 (Magic.magic_run): Fixed pickling problems reported by Ralf
2857 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2892 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2858 that I'd used when Mike Heeter reported similar issues at the
2893 that I'd used when Mike Heeter reported similar issues at the
2859 top-level, but now for @run. It boils down to injecting the
2894 top-level, but now for @run. It boils down to injecting the
2860 namespace where code is being executed with something that looks
2895 namespace where code is being executed with something that looks
2861 enough like a module to fool pickle.dump(). Since a pickle stores
2896 enough like a module to fool pickle.dump(). Since a pickle stores
2862 a named reference to the importing module, we need this for
2897 a named reference to the importing module, we need this for
2863 pickles to save something sensible.
2898 pickles to save something sensible.
2864
2899
2865 * IPython/ipmaker.py (make_IPython): added an autocall option.
2900 * IPython/ipmaker.py (make_IPython): added an autocall option.
2866
2901
2867 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2902 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2868 the auto-eval code. Now autocalling is an option, and the code is
2903 the auto-eval code. Now autocalling is an option, and the code is
2869 also vastly safer. There is no more eval() involved at all.
2904 also vastly safer. There is no more eval() involved at all.
2870
2905
2871 2003-03-01 Fernando Perez <fperez@colorado.edu>
2906 2003-03-01 Fernando Perez <fperez@colorado.edu>
2872
2907
2873 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2908 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2874 dict with named keys instead of a tuple.
2909 dict with named keys instead of a tuple.
2875
2910
2876 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2911 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2877
2912
2878 * setup.py (make_shortcut): Fixed message about directories
2913 * setup.py (make_shortcut): Fixed message about directories
2879 created during Windows installation (the directories were ok, just
2914 created during Windows installation (the directories were ok, just
2880 the printed message was misleading). Thanks to Chris Liechti
2915 the printed message was misleading). Thanks to Chris Liechti
2881 <cliechti-AT-gmx.net> for the heads up.
2916 <cliechti-AT-gmx.net> for the heads up.
2882
2917
2883 2003-02-21 Fernando Perez <fperez@colorado.edu>
2918 2003-02-21 Fernando Perez <fperez@colorado.edu>
2884
2919
2885 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2920 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2886 of ValueError exception when checking for auto-execution. This
2921 of ValueError exception when checking for auto-execution. This
2887 one is raised by things like Numeric arrays arr.flat when the
2922 one is raised by things like Numeric arrays arr.flat when the
2888 array is non-contiguous.
2923 array is non-contiguous.
2889
2924
2890 2003-01-31 Fernando Perez <fperez@colorado.edu>
2925 2003-01-31 Fernando Perez <fperez@colorado.edu>
2891
2926
2892 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2927 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2893 not return any value at all (even though the command would get
2928 not return any value at all (even though the command would get
2894 executed).
2929 executed).
2895 (xsys): Flush stdout right after printing the command to ensure
2930 (xsys): Flush stdout right after printing the command to ensure
2896 proper ordering of commands and command output in the total
2931 proper ordering of commands and command output in the total
2897 output.
2932 output.
2898 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2933 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2899 system/getoutput as defaults. The old ones are kept for
2934 system/getoutput as defaults. The old ones are kept for
2900 compatibility reasons, so no code which uses this library needs
2935 compatibility reasons, so no code which uses this library needs
2901 changing.
2936 changing.
2902
2937
2903 2003-01-27 *** Released version 0.2.14
2938 2003-01-27 *** Released version 0.2.14
2904
2939
2905 2003-01-25 Fernando Perez <fperez@colorado.edu>
2940 2003-01-25 Fernando Perez <fperez@colorado.edu>
2906
2941
2907 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2942 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2908 functions defined in previous edit sessions could not be re-edited
2943 functions defined in previous edit sessions could not be re-edited
2909 (because the temp files were immediately removed). Now temp files
2944 (because the temp files were immediately removed). Now temp files
2910 are removed only at IPython's exit.
2945 are removed only at IPython's exit.
2911 (Magic.magic_run): Improved @run to perform shell-like expansions
2946 (Magic.magic_run): Improved @run to perform shell-like expansions
2912 on its arguments (~users and $VARS). With this, @run becomes more
2947 on its arguments (~users and $VARS). With this, @run becomes more
2913 like a normal command-line.
2948 like a normal command-line.
2914
2949
2915 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2950 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2916 bugs related to embedding and cleaned up that code. A fairly
2951 bugs related to embedding and cleaned up that code. A fairly
2917 important one was the impossibility to access the global namespace
2952 important one was the impossibility to access the global namespace
2918 through the embedded IPython (only local variables were visible).
2953 through the embedded IPython (only local variables were visible).
2919
2954
2920 2003-01-14 Fernando Perez <fperez@colorado.edu>
2955 2003-01-14 Fernando Perez <fperez@colorado.edu>
2921
2956
2922 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2957 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2923 auto-calling to be a bit more conservative. Now it doesn't get
2958 auto-calling to be a bit more conservative. Now it doesn't get
2924 triggered if any of '!=()<>' are in the rest of the input line, to
2959 triggered if any of '!=()<>' are in the rest of the input line, to
2925 allow comparing callables. Thanks to Alex for the heads up.
2960 allow comparing callables. Thanks to Alex for the heads up.
2926
2961
2927 2003-01-07 Fernando Perez <fperez@colorado.edu>
2962 2003-01-07 Fernando Perez <fperez@colorado.edu>
2928
2963
2929 * IPython/genutils.py (page): fixed estimation of the number of
2964 * IPython/genutils.py (page): fixed estimation of the number of
2930 lines in a string to be paged to simply count newlines. This
2965 lines in a string to be paged to simply count newlines. This
2931 prevents over-guessing due to embedded escape sequences. A better
2966 prevents over-guessing due to embedded escape sequences. A better
2932 long-term solution would involve stripping out the control chars
2967 long-term solution would involve stripping out the control chars
2933 for the count, but it's potentially so expensive I just don't
2968 for the count, but it's potentially so expensive I just don't
2934 think it's worth doing.
2969 think it's worth doing.
2935
2970
2936 2002-12-19 *** Released version 0.2.14pre50
2971 2002-12-19 *** Released version 0.2.14pre50
2937
2972
2938 2002-12-19 Fernando Perez <fperez@colorado.edu>
2973 2002-12-19 Fernando Perez <fperez@colorado.edu>
2939
2974
2940 * tools/release (version): Changed release scripts to inform
2975 * tools/release (version): Changed release scripts to inform
2941 Andrea and build a NEWS file with a list of recent changes.
2976 Andrea and build a NEWS file with a list of recent changes.
2942
2977
2943 * IPython/ColorANSI.py (__all__): changed terminal detection
2978 * IPython/ColorANSI.py (__all__): changed terminal detection
2944 code. Seems to work better for xterms without breaking
2979 code. Seems to work better for xterms without breaking
2945 konsole. Will need more testing to determine if WinXP and Mac OSX
2980 konsole. Will need more testing to determine if WinXP and Mac OSX
2946 also work ok.
2981 also work ok.
2947
2982
2948 2002-12-18 *** Released version 0.2.14pre49
2983 2002-12-18 *** Released version 0.2.14pre49
2949
2984
2950 2002-12-18 Fernando Perez <fperez@colorado.edu>
2985 2002-12-18 Fernando Perez <fperez@colorado.edu>
2951
2986
2952 * Docs: added new info about Mac OSX, from Andrea.
2987 * Docs: added new info about Mac OSX, from Andrea.
2953
2988
2954 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2989 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2955 allow direct plotting of python strings whose format is the same
2990 allow direct plotting of python strings whose format is the same
2956 of gnuplot data files.
2991 of gnuplot data files.
2957
2992
2958 2002-12-16 Fernando Perez <fperez@colorado.edu>
2993 2002-12-16 Fernando Perez <fperez@colorado.edu>
2959
2994
2960 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2995 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2961 value of exit question to be acknowledged.
2996 value of exit question to be acknowledged.
2962
2997
2963 2002-12-03 Fernando Perez <fperez@colorado.edu>
2998 2002-12-03 Fernando Perez <fperez@colorado.edu>
2964
2999
2965 * IPython/ipmaker.py: removed generators, which had been added
3000 * IPython/ipmaker.py: removed generators, which had been added
2966 by mistake in an earlier debugging run. This was causing trouble
3001 by mistake in an earlier debugging run. This was causing trouble
2967 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
3002 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2968 for pointing this out.
3003 for pointing this out.
2969
3004
2970 2002-11-17 Fernando Perez <fperez@colorado.edu>
3005 2002-11-17 Fernando Perez <fperez@colorado.edu>
2971
3006
2972 * Manual: updated the Gnuplot section.
3007 * Manual: updated the Gnuplot section.
2973
3008
2974 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
3009 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2975 a much better split of what goes in Runtime and what goes in
3010 a much better split of what goes in Runtime and what goes in
2976 Interactive.
3011 Interactive.
2977
3012
2978 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
3013 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2979 being imported from iplib.
3014 being imported from iplib.
2980
3015
2981 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
3016 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2982 for command-passing. Now the global Gnuplot instance is called
3017 for command-passing. Now the global Gnuplot instance is called
2983 'gp' instead of 'g', which was really a far too fragile and
3018 'gp' instead of 'g', which was really a far too fragile and
2984 common name.
3019 common name.
2985
3020
2986 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
3021 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2987 bounding boxes generated by Gnuplot for square plots.
3022 bounding boxes generated by Gnuplot for square plots.
2988
3023
2989 * IPython/genutils.py (popkey): new function added. I should
3024 * IPython/genutils.py (popkey): new function added. I should
2990 suggest this on c.l.py as a dict method, it seems useful.
3025 suggest this on c.l.py as a dict method, it seems useful.
2991
3026
2992 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
3027 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2993 to transparently handle PostScript generation. MUCH better than
3028 to transparently handle PostScript generation. MUCH better than
2994 the previous plot_eps/replot_eps (which I removed now). The code
3029 the previous plot_eps/replot_eps (which I removed now). The code
2995 is also fairly clean and well documented now (including
3030 is also fairly clean and well documented now (including
2996 docstrings).
3031 docstrings).
2997
3032
2998 2002-11-13 Fernando Perez <fperez@colorado.edu>
3033 2002-11-13 Fernando Perez <fperez@colorado.edu>
2999
3034
3000 * IPython/Magic.py (Magic.magic_edit): fixed docstring
3035 * IPython/Magic.py (Magic.magic_edit): fixed docstring
3001 (inconsistent with options).
3036 (inconsistent with options).
3002
3037
3003 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
3038 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
3004 manually disabled, I don't know why. Fixed it.
3039 manually disabled, I don't know why. Fixed it.
3005 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
3040 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
3006 eps output.
3041 eps output.
3007
3042
3008 2002-11-12 Fernando Perez <fperez@colorado.edu>
3043 2002-11-12 Fernando Perez <fperez@colorado.edu>
3009
3044
3010 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
3045 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
3011 don't propagate up to caller. Fixes crash reported by François
3046 don't propagate up to caller. Fixes crash reported by François
3012 Pinard.
3047 Pinard.
3013
3048
3014 2002-11-09 Fernando Perez <fperez@colorado.edu>
3049 2002-11-09 Fernando Perez <fperez@colorado.edu>
3015
3050
3016 * IPython/ipmaker.py (make_IPython): fixed problem with writing
3051 * IPython/ipmaker.py (make_IPython): fixed problem with writing
3017 history file for new users.
3052 history file for new users.
3018 (make_IPython): fixed bug where initial install would leave the
3053 (make_IPython): fixed bug where initial install would leave the
3019 user running in the .ipython dir.
3054 user running in the .ipython dir.
3020 (make_IPython): fixed bug where config dir .ipython would be
3055 (make_IPython): fixed bug where config dir .ipython would be
3021 created regardless of the given -ipythondir option. Thanks to Cory
3056 created regardless of the given -ipythondir option. Thanks to Cory
3022 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
3057 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
3023
3058
3024 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
3059 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
3025 type confirmations. Will need to use it in all of IPython's code
3060 type confirmations. Will need to use it in all of IPython's code
3026 consistently.
3061 consistently.
3027
3062
3028 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
3063 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
3029 context to print 31 lines instead of the default 5. This will make
3064 context to print 31 lines instead of the default 5. This will make
3030 the crash reports extremely detailed in case the problem is in
3065 the crash reports extremely detailed in case the problem is in
3031 libraries I don't have access to.
3066 libraries I don't have access to.
3032
3067
3033 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
3068 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
3034 line of defense' code to still crash, but giving users fair
3069 line of defense' code to still crash, but giving users fair
3035 warning. I don't want internal errors to go unreported: if there's
3070 warning. I don't want internal errors to go unreported: if there's
3036 an internal problem, IPython should crash and generate a full
3071 an internal problem, IPython should crash and generate a full
3037 report.
3072 report.
3038
3073
3039 2002-11-08 Fernando Perez <fperez@colorado.edu>
3074 2002-11-08 Fernando Perez <fperez@colorado.edu>
3040
3075
3041 * IPython/iplib.py (InteractiveShell.interact): added code to trap
3076 * IPython/iplib.py (InteractiveShell.interact): added code to trap
3042 otherwise uncaught exceptions which can appear if people set
3077 otherwise uncaught exceptions which can appear if people set
3043 sys.stdout to something badly broken. Thanks to a crash report
3078 sys.stdout to something badly broken. Thanks to a crash report
3044 from henni-AT-mail.brainbot.com.
3079 from henni-AT-mail.brainbot.com.
3045
3080
3046 2002-11-04 Fernando Perez <fperez@colorado.edu>
3081 2002-11-04 Fernando Perez <fperez@colorado.edu>
3047
3082
3048 * IPython/iplib.py (InteractiveShell.interact): added
3083 * IPython/iplib.py (InteractiveShell.interact): added
3049 __IPYTHON__active to the builtins. It's a flag which goes on when
3084 __IPYTHON__active to the builtins. It's a flag which goes on when
3050 the interaction starts and goes off again when it stops. This
3085 the interaction starts and goes off again when it stops. This
3051 allows embedding code to detect being inside IPython. Before this
3086 allows embedding code to detect being inside IPython. Before this
3052 was done via __IPYTHON__, but that only shows that an IPython
3087 was done via __IPYTHON__, but that only shows that an IPython
3053 instance has been created.
3088 instance has been created.
3054
3089
3055 * IPython/Magic.py (Magic.magic_env): I realized that in a
3090 * IPython/Magic.py (Magic.magic_env): I realized that in a
3056 UserDict, instance.data holds the data as a normal dict. So I
3091 UserDict, instance.data holds the data as a normal dict. So I
3057 modified @env to return os.environ.data instead of rebuilding a
3092 modified @env to return os.environ.data instead of rebuilding a
3058 dict by hand.
3093 dict by hand.
3059
3094
3060 2002-11-02 Fernando Perez <fperez@colorado.edu>
3095 2002-11-02 Fernando Perez <fperez@colorado.edu>
3061
3096
3062 * IPython/genutils.py (warn): changed so that level 1 prints no
3097 * IPython/genutils.py (warn): changed so that level 1 prints no
3063 header. Level 2 is now the default (with 'WARNING' header, as
3098 header. Level 2 is now the default (with 'WARNING' header, as
3064 before). I think I tracked all places where changes were needed in
3099 before). I think I tracked all places where changes were needed in
3065 IPython, but outside code using the old level numbering may have
3100 IPython, but outside code using the old level numbering may have
3066 broken.
3101 broken.
3067
3102
3068 * IPython/iplib.py (InteractiveShell.runcode): added this to
3103 * IPython/iplib.py (InteractiveShell.runcode): added this to
3069 handle the tracebacks in SystemExit traps correctly. The previous
3104 handle the tracebacks in SystemExit traps correctly. The previous
3070 code (through interact) was printing more of the stack than
3105 code (through interact) was printing more of the stack than
3071 necessary, showing IPython internal code to the user.
3106 necessary, showing IPython internal code to the user.
3072
3107
3073 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
3108 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
3074 default. Now that the default at the confirmation prompt is yes,
3109 default. Now that the default at the confirmation prompt is yes,
3075 it's not so intrusive. François' argument that ipython sessions
3110 it's not so intrusive. François' argument that ipython sessions
3076 tend to be complex enough not to lose them from an accidental C-d,
3111 tend to be complex enough not to lose them from an accidental C-d,
3077 is a valid one.
3112 is a valid one.
3078
3113
3079 * IPython/iplib.py (InteractiveShell.interact): added a
3114 * IPython/iplib.py (InteractiveShell.interact): added a
3080 showtraceback() call to the SystemExit trap, and modified the exit
3115 showtraceback() call to the SystemExit trap, and modified the exit
3081 confirmation to have yes as the default.
3116 confirmation to have yes as the default.
3082
3117
3083 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
3118 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
3084 this file. It's been gone from the code for a long time, this was
3119 this file. It's been gone from the code for a long time, this was
3085 simply leftover junk.
3120 simply leftover junk.
3086
3121
3087 2002-11-01 Fernando Perez <fperez@colorado.edu>
3122 2002-11-01 Fernando Perez <fperez@colorado.edu>
3088
3123
3089 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
3124 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
3090 added. If set, IPython now traps EOF and asks for
3125 added. If set, IPython now traps EOF and asks for
3091 confirmation. After a request by François Pinard.
3126 confirmation. After a request by François Pinard.
3092
3127
3093 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
3128 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
3094 of @abort, and with a new (better) mechanism for handling the
3129 of @abort, and with a new (better) mechanism for handling the
3095 exceptions.
3130 exceptions.
3096
3131
3097 2002-10-27 Fernando Perez <fperez@colorado.edu>
3132 2002-10-27 Fernando Perez <fperez@colorado.edu>
3098
3133
3099 * IPython/usage.py (__doc__): updated the --help information and
3134 * IPython/usage.py (__doc__): updated the --help information and
3100 the ipythonrc file to indicate that -log generates
3135 the ipythonrc file to indicate that -log generates
3101 ./ipython.log. Also fixed the corresponding info in @logstart.
3136 ./ipython.log. Also fixed the corresponding info in @logstart.
3102 This and several other fixes in the manuals thanks to reports by
3137 This and several other fixes in the manuals thanks to reports by
3103 François Pinard <pinard-AT-iro.umontreal.ca>.
3138 François Pinard <pinard-AT-iro.umontreal.ca>.
3104
3139
3105 * IPython/Logger.py (Logger.switch_log): Fixed error message to
3140 * IPython/Logger.py (Logger.switch_log): Fixed error message to
3106 refer to @logstart (instead of @log, which doesn't exist).
3141 refer to @logstart (instead of @log, which doesn't exist).
3107
3142
3108 * IPython/iplib.py (InteractiveShell._prefilter): fixed
3143 * IPython/iplib.py (InteractiveShell._prefilter): fixed
3109 AttributeError crash. Thanks to Christopher Armstrong
3144 AttributeError crash. Thanks to Christopher Armstrong
3110 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
3145 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
3111 introduced recently (in 0.2.14pre37) with the fix to the eval
3146 introduced recently (in 0.2.14pre37) with the fix to the eval
3112 problem mentioned below.
3147 problem mentioned below.
3113
3148
3114 2002-10-17 Fernando Perez <fperez@colorado.edu>
3149 2002-10-17 Fernando Perez <fperez@colorado.edu>
3115
3150
3116 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
3151 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
3117 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
3152 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
3118
3153
3119 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
3154 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
3120 this function to fix a problem reported by Alex Schmolck. He saw
3155 this function to fix a problem reported by Alex Schmolck. He saw
3121 it with list comprehensions and generators, which were getting
3156 it with list comprehensions and generators, which were getting
3122 called twice. The real problem was an 'eval' call in testing for
3157 called twice. The real problem was an 'eval' call in testing for
3123 automagic which was evaluating the input line silently.
3158 automagic which was evaluating the input line silently.
3124
3159
3125 This is a potentially very nasty bug, if the input has side
3160 This is a potentially very nasty bug, if the input has side
3126 effects which must not be repeated. The code is much cleaner now,
3161 effects which must not be repeated. The code is much cleaner now,
3127 without any blanket 'except' left and with a regexp test for
3162 without any blanket 'except' left and with a regexp test for
3128 actual function names.
3163 actual function names.
3129
3164
3130 But an eval remains, which I'm not fully comfortable with. I just
3165 But an eval remains, which I'm not fully comfortable with. I just
3131 don't know how to find out if an expression could be a callable in
3166 don't know how to find out if an expression could be a callable in
3132 the user's namespace without doing an eval on the string. However
3167 the user's namespace without doing an eval on the string. However
3133 that string is now much more strictly checked so that no code
3168 that string is now much more strictly checked so that no code
3134 slips by, so the eval should only happen for things that can
3169 slips by, so the eval should only happen for things that can
3135 really be only function/method names.
3170 really be only function/method names.
3136
3171
3137 2002-10-15 Fernando Perez <fperez@colorado.edu>
3172 2002-10-15 Fernando Perez <fperez@colorado.edu>
3138
3173
3139 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
3174 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
3140 OSX information to main manual, removed README_Mac_OSX file from
3175 OSX information to main manual, removed README_Mac_OSX file from
3141 distribution. Also updated credits for recent additions.
3176 distribution. Also updated credits for recent additions.
3142
3177
3143 2002-10-10 Fernando Perez <fperez@colorado.edu>
3178 2002-10-10 Fernando Perez <fperez@colorado.edu>
3144
3179
3145 * README_Mac_OSX: Added a README for Mac OSX users for fixing
3180 * README_Mac_OSX: Added a README for Mac OSX users for fixing
3146 terminal-related issues. Many thanks to Andrea Riciputi
3181 terminal-related issues. Many thanks to Andrea Riciputi
3147 <andrea.riciputi-AT-libero.it> for writing it.
3182 <andrea.riciputi-AT-libero.it> for writing it.
3148
3183
3149 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
3184 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
3150 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3185 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3151
3186
3152 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
3187 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
3153 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
3188 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
3154 <syver-en-AT-online.no> who both submitted patches for this problem.
3189 <syver-en-AT-online.no> who both submitted patches for this problem.
3155
3190
3156 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
3191 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
3157 global embedding to make sure that things don't overwrite user
3192 global embedding to make sure that things don't overwrite user
3158 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
3193 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
3159
3194
3160 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
3195 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
3161 compatibility. Thanks to Hayden Callow
3196 compatibility. Thanks to Hayden Callow
3162 <h.callow-AT-elec.canterbury.ac.nz>
3197 <h.callow-AT-elec.canterbury.ac.nz>
3163
3198
3164 2002-10-04 Fernando Perez <fperez@colorado.edu>
3199 2002-10-04 Fernando Perez <fperez@colorado.edu>
3165
3200
3166 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
3201 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
3167 Gnuplot.File objects.
3202 Gnuplot.File objects.
3168
3203
3169 2002-07-23 Fernando Perez <fperez@colorado.edu>
3204 2002-07-23 Fernando Perez <fperez@colorado.edu>
3170
3205
3171 * IPython/genutils.py (timing): Added timings() and timing() for
3206 * IPython/genutils.py (timing): Added timings() and timing() for
3172 quick access to the most commonly needed data, the execution
3207 quick access to the most commonly needed data, the execution
3173 times. Old timing() renamed to timings_out().
3208 times. Old timing() renamed to timings_out().
3174
3209
3175 2002-07-18 Fernando Perez <fperez@colorado.edu>
3210 2002-07-18 Fernando Perez <fperez@colorado.edu>
3176
3211
3177 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
3212 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
3178 bug with nested instances disrupting the parent's tab completion.
3213 bug with nested instances disrupting the parent's tab completion.
3179
3214
3180 * IPython/iplib.py (all_completions): Added Alex Schmolck's
3215 * IPython/iplib.py (all_completions): Added Alex Schmolck's
3181 all_completions code to begin the emacs integration.
3216 all_completions code to begin the emacs integration.
3182
3217
3183 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
3218 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
3184 argument to allow titling individual arrays when plotting.
3219 argument to allow titling individual arrays when plotting.
3185
3220
3186 2002-07-15 Fernando Perez <fperez@colorado.edu>
3221 2002-07-15 Fernando Perez <fperez@colorado.edu>
3187
3222
3188 * setup.py (make_shortcut): changed to retrieve the value of
3223 * setup.py (make_shortcut): changed to retrieve the value of
3189 'Program Files' directory from the registry (this value changes in
3224 'Program Files' directory from the registry (this value changes in
3190 non-english versions of Windows). Thanks to Thomas Fanslau
3225 non-english versions of Windows). Thanks to Thomas Fanslau
3191 <tfanslau-AT-gmx.de> for the report.
3226 <tfanslau-AT-gmx.de> for the report.
3192
3227
3193 2002-07-10 Fernando Perez <fperez@colorado.edu>
3228 2002-07-10 Fernando Perez <fperez@colorado.edu>
3194
3229
3195 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
3230 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
3196 a bug in pdb, which crashes if a line with only whitespace is
3231 a bug in pdb, which crashes if a line with only whitespace is
3197 entered. Bug report submitted to sourceforge.
3232 entered. Bug report submitted to sourceforge.
3198
3233
3199 2002-07-09 Fernando Perez <fperez@colorado.edu>
3234 2002-07-09 Fernando Perez <fperez@colorado.edu>
3200
3235
3201 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
3236 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
3202 reporting exceptions (it's a bug in inspect.py, I just set a
3237 reporting exceptions (it's a bug in inspect.py, I just set a
3203 workaround).
3238 workaround).
3204
3239
3205 2002-07-08 Fernando Perez <fperez@colorado.edu>
3240 2002-07-08 Fernando Perez <fperez@colorado.edu>
3206
3241
3207 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
3242 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
3208 __IPYTHON__ in __builtins__ to show up in user_ns.
3243 __IPYTHON__ in __builtins__ to show up in user_ns.
3209
3244
3210 2002-07-03 Fernando Perez <fperez@colorado.edu>
3245 2002-07-03 Fernando Perez <fperez@colorado.edu>
3211
3246
3212 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
3247 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
3213 name from @gp_set_instance to @gp_set_default.
3248 name from @gp_set_instance to @gp_set_default.
3214
3249
3215 * IPython/ipmaker.py (make_IPython): default editor value set to
3250 * IPython/ipmaker.py (make_IPython): default editor value set to
3216 '0' (a string), to match the rc file. Otherwise will crash when
3251 '0' (a string), to match the rc file. Otherwise will crash when
3217 .strip() is called on it.
3252 .strip() is called on it.
3218
3253
3219
3254
3220 2002-06-28 Fernando Perez <fperez@colorado.edu>
3255 2002-06-28 Fernando Perez <fperez@colorado.edu>
3221
3256
3222 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
3257 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
3223 of files in current directory when a file is executed via
3258 of files in current directory when a file is executed via
3224 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
3259 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
3225
3260
3226 * setup.py (manfiles): fix for rpm builds, submitted by RA
3261 * setup.py (manfiles): fix for rpm builds, submitted by RA
3227 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
3262 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
3228
3263
3229 * IPython/ipmaker.py (make_IPython): fixed lookup of default
3264 * IPython/ipmaker.py (make_IPython): fixed lookup of default
3230 editor when set to '0'. Problem was, '0' evaluates to True (it's a
3265 editor when set to '0'. Problem was, '0' evaluates to True (it's a
3231 string!). A. Schmolck caught this one.
3266 string!). A. Schmolck caught this one.
3232
3267
3233 2002-06-27 Fernando Perez <fperez@colorado.edu>
3268 2002-06-27 Fernando Perez <fperez@colorado.edu>
3234
3269
3235 * IPython/ipmaker.py (make_IPython): fixed bug when running user
3270 * IPython/ipmaker.py (make_IPython): fixed bug when running user
3236 defined files at the cmd line. __name__ wasn't being set to
3271 defined files at the cmd line. __name__ wasn't being set to
3237 __main__.
3272 __main__.
3238
3273
3239 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
3274 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
3240 regular lists and tuples besides Numeric arrays.
3275 regular lists and tuples besides Numeric arrays.
3241
3276
3242 * IPython/Prompts.py (CachedOutput.__call__): Added output
3277 * IPython/Prompts.py (CachedOutput.__call__): Added output
3243 supression for input ending with ';'. Similar to Mathematica and
3278 supression for input ending with ';'. Similar to Mathematica and
3244 Matlab. The _* vars and Out[] list are still updated, just like
3279 Matlab. The _* vars and Out[] list are still updated, just like
3245 Mathematica behaves.
3280 Mathematica behaves.
3246
3281
3247 2002-06-25 Fernando Perez <fperez@colorado.edu>
3282 2002-06-25 Fernando Perez <fperez@colorado.edu>
3248
3283
3249 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
3284 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
3250 .ini extensions for profiels under Windows.
3285 .ini extensions for profiels under Windows.
3251
3286
3252 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
3287 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
3253 string form. Fix contributed by Alexander Schmolck
3288 string form. Fix contributed by Alexander Schmolck
3254 <a.schmolck-AT-gmx.net>
3289 <a.schmolck-AT-gmx.net>
3255
3290
3256 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
3291 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
3257 pre-configured Gnuplot instance.
3292 pre-configured Gnuplot instance.
3258
3293
3259 2002-06-21 Fernando Perez <fperez@colorado.edu>
3294 2002-06-21 Fernando Perez <fperez@colorado.edu>
3260
3295
3261 * IPython/numutils.py (exp_safe): new function, works around the
3296 * IPython/numutils.py (exp_safe): new function, works around the
3262 underflow problems in Numeric.
3297 underflow problems in Numeric.
3263 (log2): New fn. Safe log in base 2: returns exact integer answer
3298 (log2): New fn. Safe log in base 2: returns exact integer answer
3264 for exact integer powers of 2.
3299 for exact integer powers of 2.
3265
3300
3266 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
3301 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
3267 properly.
3302 properly.
3268
3303
3269 2002-06-20 Fernando Perez <fperez@colorado.edu>
3304 2002-06-20 Fernando Perez <fperez@colorado.edu>
3270
3305
3271 * IPython/genutils.py (timing): new function like
3306 * IPython/genutils.py (timing): new function like
3272 Mathematica's. Similar to time_test, but returns more info.
3307 Mathematica's. Similar to time_test, but returns more info.
3273
3308
3274 2002-06-18 Fernando Perez <fperez@colorado.edu>
3309 2002-06-18 Fernando Perez <fperez@colorado.edu>
3275
3310
3276 * IPython/Magic.py (Magic.magic_save): modified @save and @r
3311 * IPython/Magic.py (Magic.magic_save): modified @save and @r
3277 according to Mike Heeter's suggestions.
3312 according to Mike Heeter's suggestions.
3278
3313
3279 2002-06-16 Fernando Perez <fperez@colorado.edu>
3314 2002-06-16 Fernando Perez <fperez@colorado.edu>
3280
3315
3281 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
3316 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
3282 system. GnuplotMagic is gone as a user-directory option. New files
3317 system. GnuplotMagic is gone as a user-directory option. New files
3283 make it easier to use all the gnuplot stuff both from external
3318 make it easier to use all the gnuplot stuff both from external
3284 programs as well as from IPython. Had to rewrite part of
3319 programs as well as from IPython. Had to rewrite part of
3285 hardcopy() b/c of a strange bug: often the ps files simply don't
3320 hardcopy() b/c of a strange bug: often the ps files simply don't
3286 get created, and require a repeat of the command (often several
3321 get created, and require a repeat of the command (often several
3287 times).
3322 times).
3288
3323
3289 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
3324 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
3290 resolve output channel at call time, so that if sys.stderr has
3325 resolve output channel at call time, so that if sys.stderr has
3291 been redirected by user this gets honored.
3326 been redirected by user this gets honored.
3292
3327
3293 2002-06-13 Fernando Perez <fperez@colorado.edu>
3328 2002-06-13 Fernando Perez <fperez@colorado.edu>
3294
3329
3295 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
3330 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
3296 IPShell. Kept a copy with the old names to avoid breaking people's
3331 IPShell. Kept a copy with the old names to avoid breaking people's
3297 embedded code.
3332 embedded code.
3298
3333
3299 * IPython/ipython: simplified it to the bare minimum after
3334 * IPython/ipython: simplified it to the bare minimum after
3300 Holger's suggestions. Added info about how to use it in
3335 Holger's suggestions. Added info about how to use it in
3301 PYTHONSTARTUP.
3336 PYTHONSTARTUP.
3302
3337
3303 * IPython/Shell.py (IPythonShell): changed the options passing
3338 * IPython/Shell.py (IPythonShell): changed the options passing
3304 from a string with funky %s replacements to a straight list. Maybe
3339 from a string with funky %s replacements to a straight list. Maybe
3305 a bit more typing, but it follows sys.argv conventions, so there's
3340 a bit more typing, but it follows sys.argv conventions, so there's
3306 less special-casing to remember.
3341 less special-casing to remember.
3307
3342
3308 2002-06-12 Fernando Perez <fperez@colorado.edu>
3343 2002-06-12 Fernando Perez <fperez@colorado.edu>
3309
3344
3310 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
3345 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
3311 command. Thanks to a suggestion by Mike Heeter.
3346 command. Thanks to a suggestion by Mike Heeter.
3312 (Magic.magic_pfile): added behavior to look at filenames if given
3347 (Magic.magic_pfile): added behavior to look at filenames if given
3313 arg is not a defined object.
3348 arg is not a defined object.
3314 (Magic.magic_save): New @save function to save code snippets. Also
3349 (Magic.magic_save): New @save function to save code snippets. Also
3315 a Mike Heeter idea.
3350 a Mike Heeter idea.
3316
3351
3317 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
3352 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
3318 plot() and replot(). Much more convenient now, especially for
3353 plot() and replot(). Much more convenient now, especially for
3319 interactive use.
3354 interactive use.
3320
3355
3321 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
3356 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
3322 filenames.
3357 filenames.
3323
3358
3324 2002-06-02 Fernando Perez <fperez@colorado.edu>
3359 2002-06-02 Fernando Perez <fperez@colorado.edu>
3325
3360
3326 * IPython/Struct.py (Struct.__init__): modified to admit
3361 * IPython/Struct.py (Struct.__init__): modified to admit
3327 initialization via another struct.
3362 initialization via another struct.
3328
3363
3329 * IPython/genutils.py (SystemExec.__init__): New stateful
3364 * IPython/genutils.py (SystemExec.__init__): New stateful
3330 interface to xsys and bq. Useful for writing system scripts.
3365 interface to xsys and bq. Useful for writing system scripts.
3331
3366
3332 2002-05-30 Fernando Perez <fperez@colorado.edu>
3367 2002-05-30 Fernando Perez <fperez@colorado.edu>
3333
3368
3334 * MANIFEST.in: Changed docfile selection to exclude all the lyx
3369 * MANIFEST.in: Changed docfile selection to exclude all the lyx
3335 documents. This will make the user download smaller (it's getting
3370 documents. This will make the user download smaller (it's getting
3336 too big).
3371 too big).
3337
3372
3338 2002-05-29 Fernando Perez <fperez@colorado.edu>
3373 2002-05-29 Fernando Perez <fperez@colorado.edu>
3339
3374
3340 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
3375 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
3341 fix problems with shelve and pickle. Seems to work, but I don't
3376 fix problems with shelve and pickle. Seems to work, but I don't
3342 know if corner cases break it. Thanks to Mike Heeter
3377 know if corner cases break it. Thanks to Mike Heeter
3343 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3378 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3344
3379
3345 2002-05-24 Fernando Perez <fperez@colorado.edu>
3380 2002-05-24 Fernando Perez <fperez@colorado.edu>
3346
3381
3347 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3382 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3348 macros having broken.
3383 macros having broken.
3349
3384
3350 2002-05-21 Fernando Perez <fperez@colorado.edu>
3385 2002-05-21 Fernando Perez <fperez@colorado.edu>
3351
3386
3352 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3387 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3353 introduced logging bug: all history before logging started was
3388 introduced logging bug: all history before logging started was
3354 being written one character per line! This came from the redesign
3389 being written one character per line! This came from the redesign
3355 of the input history as a special list which slices to strings,
3390 of the input history as a special list which slices to strings,
3356 not to lists.
3391 not to lists.
3357
3392
3358 2002-05-20 Fernando Perez <fperez@colorado.edu>
3393 2002-05-20 Fernando Perez <fperez@colorado.edu>
3359
3394
3360 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3395 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3361 be an attribute of all classes in this module. The design of these
3396 be an attribute of all classes in this module. The design of these
3362 classes needs some serious overhauling.
3397 classes needs some serious overhauling.
3363
3398
3364 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3399 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3365 which was ignoring '_' in option names.
3400 which was ignoring '_' in option names.
3366
3401
3367 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3402 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3368 'Verbose_novars' to 'Context' and made it the new default. It's a
3403 'Verbose_novars' to 'Context' and made it the new default. It's a
3369 bit more readable and also safer than verbose.
3404 bit more readable and also safer than verbose.
3370
3405
3371 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3406 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3372 triple-quoted strings.
3407 triple-quoted strings.
3373
3408
3374 * IPython/OInspect.py (__all__): new module exposing the object
3409 * IPython/OInspect.py (__all__): new module exposing the object
3375 introspection facilities. Now the corresponding magics are dummy
3410 introspection facilities. Now the corresponding magics are dummy
3376 wrappers around this. Having this module will make it much easier
3411 wrappers around this. Having this module will make it much easier
3377 to put these functions into our modified pdb.
3412 to put these functions into our modified pdb.
3378 This new object inspector system uses the new colorizing module,
3413 This new object inspector system uses the new colorizing module,
3379 so source code and other things are nicely syntax highlighted.
3414 so source code and other things are nicely syntax highlighted.
3380
3415
3381 2002-05-18 Fernando Perez <fperez@colorado.edu>
3416 2002-05-18 Fernando Perez <fperez@colorado.edu>
3382
3417
3383 * IPython/ColorANSI.py: Split the coloring tools into a separate
3418 * IPython/ColorANSI.py: Split the coloring tools into a separate
3384 module so I can use them in other code easier (they were part of
3419 module so I can use them in other code easier (they were part of
3385 ultraTB).
3420 ultraTB).
3386
3421
3387 2002-05-17 Fernando Perez <fperez@colorado.edu>
3422 2002-05-17 Fernando Perez <fperez@colorado.edu>
3388
3423
3389 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3424 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3390 fixed it to set the global 'g' also to the called instance, as
3425 fixed it to set the global 'g' also to the called instance, as
3391 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3426 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3392 user's 'g' variables).
3427 user's 'g' variables).
3393
3428
3394 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3429 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3395 global variables (aliases to _ih,_oh) so that users which expect
3430 global variables (aliases to _ih,_oh) so that users which expect
3396 In[5] or Out[7] to work aren't unpleasantly surprised.
3431 In[5] or Out[7] to work aren't unpleasantly surprised.
3397 (InputList.__getslice__): new class to allow executing slices of
3432 (InputList.__getslice__): new class to allow executing slices of
3398 input history directly. Very simple class, complements the use of
3433 input history directly. Very simple class, complements the use of
3399 macros.
3434 macros.
3400
3435
3401 2002-05-16 Fernando Perez <fperez@colorado.edu>
3436 2002-05-16 Fernando Perez <fperez@colorado.edu>
3402
3437
3403 * setup.py (docdirbase): make doc directory be just doc/IPython
3438 * setup.py (docdirbase): make doc directory be just doc/IPython
3404 without version numbers, it will reduce clutter for users.
3439 without version numbers, it will reduce clutter for users.
3405
3440
3406 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3441 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3407 execfile call to prevent possible memory leak. See for details:
3442 execfile call to prevent possible memory leak. See for details:
3408 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3443 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3409
3444
3410 2002-05-15 Fernando Perez <fperez@colorado.edu>
3445 2002-05-15 Fernando Perez <fperez@colorado.edu>
3411
3446
3412 * IPython/Magic.py (Magic.magic_psource): made the object
3447 * IPython/Magic.py (Magic.magic_psource): made the object
3413 introspection names be more standard: pdoc, pdef, pfile and
3448 introspection names be more standard: pdoc, pdef, pfile and
3414 psource. They all print/page their output, and it makes
3449 psource. They all print/page their output, and it makes
3415 remembering them easier. Kept old names for compatibility as
3450 remembering them easier. Kept old names for compatibility as
3416 aliases.
3451 aliases.
3417
3452
3418 2002-05-14 Fernando Perez <fperez@colorado.edu>
3453 2002-05-14 Fernando Perez <fperez@colorado.edu>
3419
3454
3420 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3455 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3421 what the mouse problem was. The trick is to use gnuplot with temp
3456 what the mouse problem was. The trick is to use gnuplot with temp
3422 files and NOT with pipes (for data communication), because having
3457 files and NOT with pipes (for data communication), because having
3423 both pipes and the mouse on is bad news.
3458 both pipes and the mouse on is bad news.
3424
3459
3425 2002-05-13 Fernando Perez <fperez@colorado.edu>
3460 2002-05-13 Fernando Perez <fperez@colorado.edu>
3426
3461
3427 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3462 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3428 bug. Information would be reported about builtins even when
3463 bug. Information would be reported about builtins even when
3429 user-defined functions overrode them.
3464 user-defined functions overrode them.
3430
3465
3431 2002-05-11 Fernando Perez <fperez@colorado.edu>
3466 2002-05-11 Fernando Perez <fperez@colorado.edu>
3432
3467
3433 * IPython/__init__.py (__all__): removed FlexCompleter from
3468 * IPython/__init__.py (__all__): removed FlexCompleter from
3434 __all__ so that things don't fail in platforms without readline.
3469 __all__ so that things don't fail in platforms without readline.
3435
3470
3436 2002-05-10 Fernando Perez <fperez@colorado.edu>
3471 2002-05-10 Fernando Perez <fperez@colorado.edu>
3437
3472
3438 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3473 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3439 it requires Numeric, effectively making Numeric a dependency for
3474 it requires Numeric, effectively making Numeric a dependency for
3440 IPython.
3475 IPython.
3441
3476
3442 * Released 0.2.13
3477 * Released 0.2.13
3443
3478
3444 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3479 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3445 profiler interface. Now all the major options from the profiler
3480 profiler interface. Now all the major options from the profiler
3446 module are directly supported in IPython, both for single
3481 module are directly supported in IPython, both for single
3447 expressions (@prun) and for full programs (@run -p).
3482 expressions (@prun) and for full programs (@run -p).
3448
3483
3449 2002-05-09 Fernando Perez <fperez@colorado.edu>
3484 2002-05-09 Fernando Perez <fperez@colorado.edu>
3450
3485
3451 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3486 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3452 magic properly formatted for screen.
3487 magic properly formatted for screen.
3453
3488
3454 * setup.py (make_shortcut): Changed things to put pdf version in
3489 * setup.py (make_shortcut): Changed things to put pdf version in
3455 doc/ instead of doc/manual (had to change lyxport a bit).
3490 doc/ instead of doc/manual (had to change lyxport a bit).
3456
3491
3457 * IPython/Magic.py (Profile.string_stats): made profile runs go
3492 * IPython/Magic.py (Profile.string_stats): made profile runs go
3458 through pager (they are long and a pager allows searching, saving,
3493 through pager (they are long and a pager allows searching, saving,
3459 etc.)
3494 etc.)
3460
3495
3461 2002-05-08 Fernando Perez <fperez@colorado.edu>
3496 2002-05-08 Fernando Perez <fperez@colorado.edu>
3462
3497
3463 * Released 0.2.12
3498 * Released 0.2.12
3464
3499
3465 2002-05-06 Fernando Perez <fperez@colorado.edu>
3500 2002-05-06 Fernando Perez <fperez@colorado.edu>
3466
3501
3467 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3502 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3468 introduced); 'hist n1 n2' was broken.
3503 introduced); 'hist n1 n2' was broken.
3469 (Magic.magic_pdb): added optional on/off arguments to @pdb
3504 (Magic.magic_pdb): added optional on/off arguments to @pdb
3470 (Magic.magic_run): added option -i to @run, which executes code in
3505 (Magic.magic_run): added option -i to @run, which executes code in
3471 the IPython namespace instead of a clean one. Also added @irun as
3506 the IPython namespace instead of a clean one. Also added @irun as
3472 an alias to @run -i.
3507 an alias to @run -i.
3473
3508
3474 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3509 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3475 fixed (it didn't really do anything, the namespaces were wrong).
3510 fixed (it didn't really do anything, the namespaces were wrong).
3476
3511
3477 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3512 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3478
3513
3479 * IPython/__init__.py (__all__): Fixed package namespace, now
3514 * IPython/__init__.py (__all__): Fixed package namespace, now
3480 'import IPython' does give access to IPython.<all> as
3515 'import IPython' does give access to IPython.<all> as
3481 expected. Also renamed __release__ to Release.
3516 expected. Also renamed __release__ to Release.
3482
3517
3483 * IPython/Debugger.py (__license__): created new Pdb class which
3518 * IPython/Debugger.py (__license__): created new Pdb class which
3484 functions like a drop-in for the normal pdb.Pdb but does NOT
3519 functions like a drop-in for the normal pdb.Pdb but does NOT
3485 import readline by default. This way it doesn't muck up IPython's
3520 import readline by default. This way it doesn't muck up IPython's
3486 readline handling, and now tab-completion finally works in the
3521 readline handling, and now tab-completion finally works in the
3487 debugger -- sort of. It completes things globally visible, but the
3522 debugger -- sort of. It completes things globally visible, but the
3488 completer doesn't track the stack as pdb walks it. That's a bit
3523 completer doesn't track the stack as pdb walks it. That's a bit
3489 tricky, and I'll have to implement it later.
3524 tricky, and I'll have to implement it later.
3490
3525
3491 2002-05-05 Fernando Perez <fperez@colorado.edu>
3526 2002-05-05 Fernando Perez <fperez@colorado.edu>
3492
3527
3493 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3528 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3494 magic docstrings when printed via ? (explicit \'s were being
3529 magic docstrings when printed via ? (explicit \'s were being
3495 printed).
3530 printed).
3496
3531
3497 * IPython/ipmaker.py (make_IPython): fixed namespace
3532 * IPython/ipmaker.py (make_IPython): fixed namespace
3498 identification bug. Now variables loaded via logs or command-line
3533 identification bug. Now variables loaded via logs or command-line
3499 files are recognized in the interactive namespace by @who.
3534 files are recognized in the interactive namespace by @who.
3500
3535
3501 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3536 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3502 log replay system stemming from the string form of Structs.
3537 log replay system stemming from the string form of Structs.
3503
3538
3504 * IPython/Magic.py (Macro.__init__): improved macros to properly
3539 * IPython/Magic.py (Macro.__init__): improved macros to properly
3505 handle magic commands in them.
3540 handle magic commands in them.
3506 (Magic.magic_logstart): usernames are now expanded so 'logstart
3541 (Magic.magic_logstart): usernames are now expanded so 'logstart
3507 ~/mylog' now works.
3542 ~/mylog' now works.
3508
3543
3509 * IPython/iplib.py (complete): fixed bug where paths starting with
3544 * IPython/iplib.py (complete): fixed bug where paths starting with
3510 '/' would be completed as magic names.
3545 '/' would be completed as magic names.
3511
3546
3512 2002-05-04 Fernando Perez <fperez@colorado.edu>
3547 2002-05-04 Fernando Perez <fperez@colorado.edu>
3513
3548
3514 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3549 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3515 allow running full programs under the profiler's control.
3550 allow running full programs under the profiler's control.
3516
3551
3517 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3552 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3518 mode to report exceptions verbosely but without formatting
3553 mode to report exceptions verbosely but without formatting
3519 variables. This addresses the issue of ipython 'freezing' (it's
3554 variables. This addresses the issue of ipython 'freezing' (it's
3520 not frozen, but caught in an expensive formatting loop) when huge
3555 not frozen, but caught in an expensive formatting loop) when huge
3521 variables are in the context of an exception.
3556 variables are in the context of an exception.
3522 (VerboseTB.text): Added '--->' markers at line where exception was
3557 (VerboseTB.text): Added '--->' markers at line where exception was
3523 triggered. Much clearer to read, especially in NoColor modes.
3558 triggered. Much clearer to read, especially in NoColor modes.
3524
3559
3525 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3560 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3526 implemented in reverse when changing to the new parse_options().
3561 implemented in reverse when changing to the new parse_options().
3527
3562
3528 2002-05-03 Fernando Perez <fperez@colorado.edu>
3563 2002-05-03 Fernando Perez <fperez@colorado.edu>
3529
3564
3530 * IPython/Magic.py (Magic.parse_options): new function so that
3565 * IPython/Magic.py (Magic.parse_options): new function so that
3531 magics can parse options easier.
3566 magics can parse options easier.
3532 (Magic.magic_prun): new function similar to profile.run(),
3567 (Magic.magic_prun): new function similar to profile.run(),
3533 suggested by Chris Hart.
3568 suggested by Chris Hart.
3534 (Magic.magic_cd): fixed behavior so that it only changes if
3569 (Magic.magic_cd): fixed behavior so that it only changes if
3535 directory actually is in history.
3570 directory actually is in history.
3536
3571
3537 * IPython/usage.py (__doc__): added information about potential
3572 * IPython/usage.py (__doc__): added information about potential
3538 slowness of Verbose exception mode when there are huge data
3573 slowness of Verbose exception mode when there are huge data
3539 structures to be formatted (thanks to Archie Paulson).
3574 structures to be formatted (thanks to Archie Paulson).
3540
3575
3541 * IPython/ipmaker.py (make_IPython): Changed default logging
3576 * IPython/ipmaker.py (make_IPython): Changed default logging
3542 (when simply called with -log) to use curr_dir/ipython.log in
3577 (when simply called with -log) to use curr_dir/ipython.log in
3543 rotate mode. Fixed crash which was occuring with -log before
3578 rotate mode. Fixed crash which was occuring with -log before
3544 (thanks to Jim Boyle).
3579 (thanks to Jim Boyle).
3545
3580
3546 2002-05-01 Fernando Perez <fperez@colorado.edu>
3581 2002-05-01 Fernando Perez <fperez@colorado.edu>
3547
3582
3548 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3583 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3549 was nasty -- though somewhat of a corner case).
3584 was nasty -- though somewhat of a corner case).
3550
3585
3551 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3586 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3552 text (was a bug).
3587 text (was a bug).
3553
3588
3554 2002-04-30 Fernando Perez <fperez@colorado.edu>
3589 2002-04-30 Fernando Perez <fperez@colorado.edu>
3555
3590
3556 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3591 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3557 a print after ^D or ^C from the user so that the In[] prompt
3592 a print after ^D or ^C from the user so that the In[] prompt
3558 doesn't over-run the gnuplot one.
3593 doesn't over-run the gnuplot one.
3559
3594
3560 2002-04-29 Fernando Perez <fperez@colorado.edu>
3595 2002-04-29 Fernando Perez <fperez@colorado.edu>
3561
3596
3562 * Released 0.2.10
3597 * Released 0.2.10
3563
3598
3564 * IPython/__release__.py (version): get date dynamically.
3599 * IPython/__release__.py (version): get date dynamically.
3565
3600
3566 * Misc. documentation updates thanks to Arnd's comments. Also ran
3601 * Misc. documentation updates thanks to Arnd's comments. Also ran
3567 a full spellcheck on the manual (hadn't been done in a while).
3602 a full spellcheck on the manual (hadn't been done in a while).
3568
3603
3569 2002-04-27 Fernando Perez <fperez@colorado.edu>
3604 2002-04-27 Fernando Perez <fperez@colorado.edu>
3570
3605
3571 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3606 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3572 starting a log in mid-session would reset the input history list.
3607 starting a log in mid-session would reset the input history list.
3573
3608
3574 2002-04-26 Fernando Perez <fperez@colorado.edu>
3609 2002-04-26 Fernando Perez <fperez@colorado.edu>
3575
3610
3576 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3611 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3577 all files were being included in an update. Now anything in
3612 all files were being included in an update. Now anything in
3578 UserConfig that matches [A-Za-z]*.py will go (this excludes
3613 UserConfig that matches [A-Za-z]*.py will go (this excludes
3579 __init__.py)
3614 __init__.py)
3580
3615
3581 2002-04-25 Fernando Perez <fperez@colorado.edu>
3616 2002-04-25 Fernando Perez <fperez@colorado.edu>
3582
3617
3583 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3618 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3584 to __builtins__ so that any form of embedded or imported code can
3619 to __builtins__ so that any form of embedded or imported code can
3585 test for being inside IPython.
3620 test for being inside IPython.
3586
3621
3587 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3622 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3588 changed to GnuplotMagic because it's now an importable module,
3623 changed to GnuplotMagic because it's now an importable module,
3589 this makes the name follow that of the standard Gnuplot module.
3624 this makes the name follow that of the standard Gnuplot module.
3590 GnuplotMagic can now be loaded at any time in mid-session.
3625 GnuplotMagic can now be loaded at any time in mid-session.
3591
3626
3592 2002-04-24 Fernando Perez <fperez@colorado.edu>
3627 2002-04-24 Fernando Perez <fperez@colorado.edu>
3593
3628
3594 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3629 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3595 the globals (IPython has its own namespace) and the
3630 the globals (IPython has its own namespace) and the
3596 PhysicalQuantity stuff is much better anyway.
3631 PhysicalQuantity stuff is much better anyway.
3597
3632
3598 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3633 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3599 embedding example to standard user directory for
3634 embedding example to standard user directory for
3600 distribution. Also put it in the manual.
3635 distribution. Also put it in the manual.
3601
3636
3602 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3637 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3603 instance as first argument (so it doesn't rely on some obscure
3638 instance as first argument (so it doesn't rely on some obscure
3604 hidden global).
3639 hidden global).
3605
3640
3606 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3641 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3607 delimiters. While it prevents ().TAB from working, it allows
3642 delimiters. While it prevents ().TAB from working, it allows
3608 completions in open (... expressions. This is by far a more common
3643 completions in open (... expressions. This is by far a more common
3609 case.
3644 case.
3610
3645
3611 2002-04-23 Fernando Perez <fperez@colorado.edu>
3646 2002-04-23 Fernando Perez <fperez@colorado.edu>
3612
3647
3613 * IPython/Extensions/InterpreterPasteInput.py: new
3648 * IPython/Extensions/InterpreterPasteInput.py: new
3614 syntax-processing module for pasting lines with >>> or ... at the
3649 syntax-processing module for pasting lines with >>> or ... at the
3615 start.
3650 start.
3616
3651
3617 * IPython/Extensions/PhysicalQ_Interactive.py
3652 * IPython/Extensions/PhysicalQ_Interactive.py
3618 (PhysicalQuantityInteractive.__int__): fixed to work with either
3653 (PhysicalQuantityInteractive.__int__): fixed to work with either
3619 Numeric or math.
3654 Numeric or math.
3620
3655
3621 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3656 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3622 provided profiles. Now we have:
3657 provided profiles. Now we have:
3623 -math -> math module as * and cmath with its own namespace.
3658 -math -> math module as * and cmath with its own namespace.
3624 -numeric -> Numeric as *, plus gnuplot & grace
3659 -numeric -> Numeric as *, plus gnuplot & grace
3625 -physics -> same as before
3660 -physics -> same as before
3626
3661
3627 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3662 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3628 user-defined magics wouldn't be found by @magic if they were
3663 user-defined magics wouldn't be found by @magic if they were
3629 defined as class methods. Also cleaned up the namespace search
3664 defined as class methods. Also cleaned up the namespace search
3630 logic and the string building (to use %s instead of many repeated
3665 logic and the string building (to use %s instead of many repeated
3631 string adds).
3666 string adds).
3632
3667
3633 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3668 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3634 of user-defined magics to operate with class methods (cleaner, in
3669 of user-defined magics to operate with class methods (cleaner, in
3635 line with the gnuplot code).
3670 line with the gnuplot code).
3636
3671
3637 2002-04-22 Fernando Perez <fperez@colorado.edu>
3672 2002-04-22 Fernando Perez <fperez@colorado.edu>
3638
3673
3639 * setup.py: updated dependency list so that manual is updated when
3674 * setup.py: updated dependency list so that manual is updated when
3640 all included files change.
3675 all included files change.
3641
3676
3642 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3677 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3643 the delimiter removal option (the fix is ugly right now).
3678 the delimiter removal option (the fix is ugly right now).
3644
3679
3645 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3680 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3646 all of the math profile (quicker loading, no conflict between
3681 all of the math profile (quicker loading, no conflict between
3647 g-9.8 and g-gnuplot).
3682 g-9.8 and g-gnuplot).
3648
3683
3649 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3684 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3650 name of post-mortem files to IPython_crash_report.txt.
3685 name of post-mortem files to IPython_crash_report.txt.
3651
3686
3652 * Cleanup/update of the docs. Added all the new readline info and
3687 * Cleanup/update of the docs. Added all the new readline info and
3653 formatted all lists as 'real lists'.
3688 formatted all lists as 'real lists'.
3654
3689
3655 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3690 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3656 tab-completion options, since the full readline parse_and_bind is
3691 tab-completion options, since the full readline parse_and_bind is
3657 now accessible.
3692 now accessible.
3658
3693
3659 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3694 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3660 handling of readline options. Now users can specify any string to
3695 handling of readline options. Now users can specify any string to
3661 be passed to parse_and_bind(), as well as the delimiters to be
3696 be passed to parse_and_bind(), as well as the delimiters to be
3662 removed.
3697 removed.
3663 (InteractiveShell.__init__): Added __name__ to the global
3698 (InteractiveShell.__init__): Added __name__ to the global
3664 namespace so that things like Itpl which rely on its existence
3699 namespace so that things like Itpl which rely on its existence
3665 don't crash.
3700 don't crash.
3666 (InteractiveShell._prefilter): Defined the default with a _ so
3701 (InteractiveShell._prefilter): Defined the default with a _ so
3667 that prefilter() is easier to override, while the default one
3702 that prefilter() is easier to override, while the default one
3668 remains available.
3703 remains available.
3669
3704
3670 2002-04-18 Fernando Perez <fperez@colorado.edu>
3705 2002-04-18 Fernando Perez <fperez@colorado.edu>
3671
3706
3672 * Added information about pdb in the docs.
3707 * Added information about pdb in the docs.
3673
3708
3674 2002-04-17 Fernando Perez <fperez@colorado.edu>
3709 2002-04-17 Fernando Perez <fperez@colorado.edu>
3675
3710
3676 * IPython/ipmaker.py (make_IPython): added rc_override option to
3711 * IPython/ipmaker.py (make_IPython): added rc_override option to
3677 allow passing config options at creation time which may override
3712 allow passing config options at creation time which may override
3678 anything set in the config files or command line. This is
3713 anything set in the config files or command line. This is
3679 particularly useful for configuring embedded instances.
3714 particularly useful for configuring embedded instances.
3680
3715
3681 2002-04-15 Fernando Perez <fperez@colorado.edu>
3716 2002-04-15 Fernando Perez <fperez@colorado.edu>
3682
3717
3683 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3718 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3684 crash embedded instances because of the input cache falling out of
3719 crash embedded instances because of the input cache falling out of
3685 sync with the output counter.
3720 sync with the output counter.
3686
3721
3687 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3722 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3688 mode which calls pdb after an uncaught exception in IPython itself.
3723 mode which calls pdb after an uncaught exception in IPython itself.
3689
3724
3690 2002-04-14 Fernando Perez <fperez@colorado.edu>
3725 2002-04-14 Fernando Perez <fperez@colorado.edu>
3691
3726
3692 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3727 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3693 readline, fix it back after each call.
3728 readline, fix it back after each call.
3694
3729
3695 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3730 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3696 method to force all access via __call__(), which guarantees that
3731 method to force all access via __call__(), which guarantees that
3697 traceback references are properly deleted.
3732 traceback references are properly deleted.
3698
3733
3699 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3734 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3700 improve printing when pprint is in use.
3735 improve printing when pprint is in use.
3701
3736
3702 2002-04-13 Fernando Perez <fperez@colorado.edu>
3737 2002-04-13 Fernando Perez <fperez@colorado.edu>
3703
3738
3704 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3739 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3705 exceptions aren't caught anymore. If the user triggers one, he
3740 exceptions aren't caught anymore. If the user triggers one, he
3706 should know why he's doing it and it should go all the way up,
3741 should know why he's doing it and it should go all the way up,
3707 just like any other exception. So now @abort will fully kill the
3742 just like any other exception. So now @abort will fully kill the
3708 embedded interpreter and the embedding code (unless that happens
3743 embedded interpreter and the embedding code (unless that happens
3709 to catch SystemExit).
3744 to catch SystemExit).
3710
3745
3711 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3746 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3712 and a debugger() method to invoke the interactive pdb debugger
3747 and a debugger() method to invoke the interactive pdb debugger
3713 after printing exception information. Also added the corresponding
3748 after printing exception information. Also added the corresponding
3714 -pdb option and @pdb magic to control this feature, and updated
3749 -pdb option and @pdb magic to control this feature, and updated
3715 the docs. After a suggestion from Christopher Hart
3750 the docs. After a suggestion from Christopher Hart
3716 (hart-AT-caltech.edu).
3751 (hart-AT-caltech.edu).
3717
3752
3718 2002-04-12 Fernando Perez <fperez@colorado.edu>
3753 2002-04-12 Fernando Perez <fperez@colorado.edu>
3719
3754
3720 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3755 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3721 the exception handlers defined by the user (not the CrashHandler)
3756 the exception handlers defined by the user (not the CrashHandler)
3722 so that user exceptions don't trigger an ipython bug report.
3757 so that user exceptions don't trigger an ipython bug report.
3723
3758
3724 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3759 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3725 configurable (it should have always been so).
3760 configurable (it should have always been so).
3726
3761
3727 2002-03-26 Fernando Perez <fperez@colorado.edu>
3762 2002-03-26 Fernando Perez <fperez@colorado.edu>
3728
3763
3729 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3764 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3730 and there to fix embedding namespace issues. This should all be
3765 and there to fix embedding namespace issues. This should all be
3731 done in a more elegant way.
3766 done in a more elegant way.
3732
3767
3733 2002-03-25 Fernando Perez <fperez@colorado.edu>
3768 2002-03-25 Fernando Perez <fperez@colorado.edu>
3734
3769
3735 * IPython/genutils.py (get_home_dir): Try to make it work under
3770 * IPython/genutils.py (get_home_dir): Try to make it work under
3736 win9x also.
3771 win9x also.
3737
3772
3738 2002-03-20 Fernando Perez <fperez@colorado.edu>
3773 2002-03-20 Fernando Perez <fperez@colorado.edu>
3739
3774
3740 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3775 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3741 sys.displayhook untouched upon __init__.
3776 sys.displayhook untouched upon __init__.
3742
3777
3743 2002-03-19 Fernando Perez <fperez@colorado.edu>
3778 2002-03-19 Fernando Perez <fperez@colorado.edu>
3744
3779
3745 * Released 0.2.9 (for embedding bug, basically).
3780 * Released 0.2.9 (for embedding bug, basically).
3746
3781
3747 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3782 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3748 exceptions so that enclosing shell's state can be restored.
3783 exceptions so that enclosing shell's state can be restored.
3749
3784
3750 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3785 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3751 naming conventions in the .ipython/ dir.
3786 naming conventions in the .ipython/ dir.
3752
3787
3753 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3788 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3754 from delimiters list so filenames with - in them get expanded.
3789 from delimiters list so filenames with - in them get expanded.
3755
3790
3756 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3791 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3757 sys.displayhook not being properly restored after an embedded call.
3792 sys.displayhook not being properly restored after an embedded call.
3758
3793
3759 2002-03-18 Fernando Perez <fperez@colorado.edu>
3794 2002-03-18 Fernando Perez <fperez@colorado.edu>
3760
3795
3761 * Released 0.2.8
3796 * Released 0.2.8
3762
3797
3763 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3798 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3764 some files weren't being included in a -upgrade.
3799 some files weren't being included in a -upgrade.
3765 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3800 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3766 on' so that the first tab completes.
3801 on' so that the first tab completes.
3767 (InteractiveShell.handle_magic): fixed bug with spaces around
3802 (InteractiveShell.handle_magic): fixed bug with spaces around
3768 quotes breaking many magic commands.
3803 quotes breaking many magic commands.
3769
3804
3770 * setup.py: added note about ignoring the syntax error messages at
3805 * setup.py: added note about ignoring the syntax error messages at
3771 installation.
3806 installation.
3772
3807
3773 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3808 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3774 streamlining the gnuplot interface, now there's only one magic @gp.
3809 streamlining the gnuplot interface, now there's only one magic @gp.
3775
3810
3776 2002-03-17 Fernando Perez <fperez@colorado.edu>
3811 2002-03-17 Fernando Perez <fperez@colorado.edu>
3777
3812
3778 * IPython/UserConfig/magic_gnuplot.py: new name for the
3813 * IPython/UserConfig/magic_gnuplot.py: new name for the
3779 example-magic_pm.py file. Much enhanced system, now with a shell
3814 example-magic_pm.py file. Much enhanced system, now with a shell
3780 for communicating directly with gnuplot, one command at a time.
3815 for communicating directly with gnuplot, one command at a time.
3781
3816
3782 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3817 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3783 setting __name__=='__main__'.
3818 setting __name__=='__main__'.
3784
3819
3785 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3820 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3786 mini-shell for accessing gnuplot from inside ipython. Should
3821 mini-shell for accessing gnuplot from inside ipython. Should
3787 extend it later for grace access too. Inspired by Arnd's
3822 extend it later for grace access too. Inspired by Arnd's
3788 suggestion.
3823 suggestion.
3789
3824
3790 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3825 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3791 calling magic functions with () in their arguments. Thanks to Arnd
3826 calling magic functions with () in their arguments. Thanks to Arnd
3792 Baecker for pointing this to me.
3827 Baecker for pointing this to me.
3793
3828
3794 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3829 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3795 infinitely for integer or complex arrays (only worked with floats).
3830 infinitely for integer or complex arrays (only worked with floats).
3796
3831
3797 2002-03-16 Fernando Perez <fperez@colorado.edu>
3832 2002-03-16 Fernando Perez <fperez@colorado.edu>
3798
3833
3799 * setup.py: Merged setup and setup_windows into a single script
3834 * setup.py: Merged setup and setup_windows into a single script
3800 which properly handles things for windows users.
3835 which properly handles things for windows users.
3801
3836
3802 2002-03-15 Fernando Perez <fperez@colorado.edu>
3837 2002-03-15 Fernando Perez <fperez@colorado.edu>
3803
3838
3804 * Big change to the manual: now the magics are all automatically
3839 * Big change to the manual: now the magics are all automatically
3805 documented. This information is generated from their docstrings
3840 documented. This information is generated from their docstrings
3806 and put in a latex file included by the manual lyx file. This way
3841 and put in a latex file included by the manual lyx file. This way
3807 we get always up to date information for the magics. The manual
3842 we get always up to date information for the magics. The manual
3808 now also has proper version information, also auto-synced.
3843 now also has proper version information, also auto-synced.
3809
3844
3810 For this to work, an undocumented --magic_docstrings option was added.
3845 For this to work, an undocumented --magic_docstrings option was added.
3811
3846
3812 2002-03-13 Fernando Perez <fperez@colorado.edu>
3847 2002-03-13 Fernando Perez <fperez@colorado.edu>
3813
3848
3814 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3849 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3815 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3850 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3816
3851
3817 2002-03-12 Fernando Perez <fperez@colorado.edu>
3852 2002-03-12 Fernando Perez <fperez@colorado.edu>
3818
3853
3819 * IPython/ultraTB.py (TermColors): changed color escapes again to
3854 * IPython/ultraTB.py (TermColors): changed color escapes again to
3820 fix the (old, reintroduced) line-wrapping bug. Basically, if
3855 fix the (old, reintroduced) line-wrapping bug. Basically, if
3821 \001..\002 aren't given in the color escapes, lines get wrapped
3856 \001..\002 aren't given in the color escapes, lines get wrapped
3822 weirdly. But giving those screws up old xterms and emacs terms. So
3857 weirdly. But giving those screws up old xterms and emacs terms. So
3823 I added some logic for emacs terms to be ok, but I can't identify old
3858 I added some logic for emacs terms to be ok, but I can't identify old
3824 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3859 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3825
3860
3826 2002-03-10 Fernando Perez <fperez@colorado.edu>
3861 2002-03-10 Fernando Perez <fperez@colorado.edu>
3827
3862
3828 * IPython/usage.py (__doc__): Various documentation cleanups and
3863 * IPython/usage.py (__doc__): Various documentation cleanups and
3829 updates, both in usage docstrings and in the manual.
3864 updates, both in usage docstrings and in the manual.
3830
3865
3831 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3866 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3832 handling of caching. Set minimum acceptabe value for having a
3867 handling of caching. Set minimum acceptabe value for having a
3833 cache at 20 values.
3868 cache at 20 values.
3834
3869
3835 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3870 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3836 install_first_time function to a method, renamed it and added an
3871 install_first_time function to a method, renamed it and added an
3837 'upgrade' mode. Now people can update their config directory with
3872 'upgrade' mode. Now people can update their config directory with
3838 a simple command line switch (-upgrade, also new).
3873 a simple command line switch (-upgrade, also new).
3839
3874
3840 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3875 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3841 @file (convenient for automagic users under Python >= 2.2).
3876 @file (convenient for automagic users under Python >= 2.2).
3842 Removed @files (it seemed more like a plural than an abbrev. of
3877 Removed @files (it seemed more like a plural than an abbrev. of
3843 'file show').
3878 'file show').
3844
3879
3845 * IPython/iplib.py (install_first_time): Fixed crash if there were
3880 * IPython/iplib.py (install_first_time): Fixed crash if there were
3846 backup files ('~') in .ipython/ install directory.
3881 backup files ('~') in .ipython/ install directory.
3847
3882
3848 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3883 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3849 system. Things look fine, but these changes are fairly
3884 system. Things look fine, but these changes are fairly
3850 intrusive. Test them for a few days.
3885 intrusive. Test them for a few days.
3851
3886
3852 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3887 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3853 the prompts system. Now all in/out prompt strings are user
3888 the prompts system. Now all in/out prompt strings are user
3854 controllable. This is particularly useful for embedding, as one
3889 controllable. This is particularly useful for embedding, as one
3855 can tag embedded instances with particular prompts.
3890 can tag embedded instances with particular prompts.
3856
3891
3857 Also removed global use of sys.ps1/2, which now allows nested
3892 Also removed global use of sys.ps1/2, which now allows nested
3858 embeddings without any problems. Added command-line options for
3893 embeddings without any problems. Added command-line options for
3859 the prompt strings.
3894 the prompt strings.
3860
3895
3861 2002-03-08 Fernando Perez <fperez@colorado.edu>
3896 2002-03-08 Fernando Perez <fperez@colorado.edu>
3862
3897
3863 * IPython/UserConfig/example-embed-short.py (ipshell): added
3898 * IPython/UserConfig/example-embed-short.py (ipshell): added
3864 example file with the bare minimum code for embedding.
3899 example file with the bare minimum code for embedding.
3865
3900
3866 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3901 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3867 functionality for the embeddable shell to be activated/deactivated
3902 functionality for the embeddable shell to be activated/deactivated
3868 either globally or at each call.
3903 either globally or at each call.
3869
3904
3870 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3905 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3871 rewriting the prompt with '--->' for auto-inputs with proper
3906 rewriting the prompt with '--->' for auto-inputs with proper
3872 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3907 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3873 this is handled by the prompts class itself, as it should.
3908 this is handled by the prompts class itself, as it should.
3874
3909
3875 2002-03-05 Fernando Perez <fperez@colorado.edu>
3910 2002-03-05 Fernando Perez <fperez@colorado.edu>
3876
3911
3877 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3912 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3878 @logstart to avoid name clashes with the math log function.
3913 @logstart to avoid name clashes with the math log function.
3879
3914
3880 * Big updates to X/Emacs section of the manual.
3915 * Big updates to X/Emacs section of the manual.
3881
3916
3882 * Removed ipython_emacs. Milan explained to me how to pass
3917 * Removed ipython_emacs. Milan explained to me how to pass
3883 arguments to ipython through Emacs. Some day I'm going to end up
3918 arguments to ipython through Emacs. Some day I'm going to end up
3884 learning some lisp...
3919 learning some lisp...
3885
3920
3886 2002-03-04 Fernando Perez <fperez@colorado.edu>
3921 2002-03-04 Fernando Perez <fperez@colorado.edu>
3887
3922
3888 * IPython/ipython_emacs: Created script to be used as the
3923 * IPython/ipython_emacs: Created script to be used as the
3889 py-python-command Emacs variable so we can pass IPython
3924 py-python-command Emacs variable so we can pass IPython
3890 parameters. I can't figure out how to tell Emacs directly to pass
3925 parameters. I can't figure out how to tell Emacs directly to pass
3891 parameters to IPython, so a dummy shell script will do it.
3926 parameters to IPython, so a dummy shell script will do it.
3892
3927
3893 Other enhancements made for things to work better under Emacs'
3928 Other enhancements made for things to work better under Emacs'
3894 various types of terminals. Many thanks to Milan Zamazal
3929 various types of terminals. Many thanks to Milan Zamazal
3895 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3930 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3896
3931
3897 2002-03-01 Fernando Perez <fperez@colorado.edu>
3932 2002-03-01 Fernando Perez <fperez@colorado.edu>
3898
3933
3899 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3934 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3900 that loading of readline is now optional. This gives better
3935 that loading of readline is now optional. This gives better
3901 control to emacs users.
3936 control to emacs users.
3902
3937
3903 * IPython/ultraTB.py (__date__): Modified color escape sequences
3938 * IPython/ultraTB.py (__date__): Modified color escape sequences
3904 and now things work fine under xterm and in Emacs' term buffers
3939 and now things work fine under xterm and in Emacs' term buffers
3905 (though not shell ones). Well, in emacs you get colors, but all
3940 (though not shell ones). Well, in emacs you get colors, but all
3906 seem to be 'light' colors (no difference between dark and light
3941 seem to be 'light' colors (no difference between dark and light
3907 ones). But the garbage chars are gone, and also in xterms. It
3942 ones). But the garbage chars are gone, and also in xterms. It
3908 seems that now I'm using 'cleaner' ansi sequences.
3943 seems that now I'm using 'cleaner' ansi sequences.
3909
3944
3910 2002-02-21 Fernando Perez <fperez@colorado.edu>
3945 2002-02-21 Fernando Perez <fperez@colorado.edu>
3911
3946
3912 * Released 0.2.7 (mainly to publish the scoping fix).
3947 * Released 0.2.7 (mainly to publish the scoping fix).
3913
3948
3914 * IPython/Logger.py (Logger.logstate): added. A corresponding
3949 * IPython/Logger.py (Logger.logstate): added. A corresponding
3915 @logstate magic was created.
3950 @logstate magic was created.
3916
3951
3917 * IPython/Magic.py: fixed nested scoping problem under Python
3952 * IPython/Magic.py: fixed nested scoping problem under Python
3918 2.1.x (automagic wasn't working).
3953 2.1.x (automagic wasn't working).
3919
3954
3920 2002-02-20 Fernando Perez <fperez@colorado.edu>
3955 2002-02-20 Fernando Perez <fperez@colorado.edu>
3921
3956
3922 * Released 0.2.6.
3957 * Released 0.2.6.
3923
3958
3924 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3959 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3925 option so that logs can come out without any headers at all.
3960 option so that logs can come out without any headers at all.
3926
3961
3927 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3962 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3928 SciPy.
3963 SciPy.
3929
3964
3930 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3965 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3931 that embedded IPython calls don't require vars() to be explicitly
3966 that embedded IPython calls don't require vars() to be explicitly
3932 passed. Now they are extracted from the caller's frame (code
3967 passed. Now they are extracted from the caller's frame (code
3933 snatched from Eric Jones' weave). Added better documentation to
3968 snatched from Eric Jones' weave). Added better documentation to
3934 the section on embedding and the example file.
3969 the section on embedding and the example file.
3935
3970
3936 * IPython/genutils.py (page): Changed so that under emacs, it just
3971 * IPython/genutils.py (page): Changed so that under emacs, it just
3937 prints the string. You can then page up and down in the emacs
3972 prints the string. You can then page up and down in the emacs
3938 buffer itself. This is how the builtin help() works.
3973 buffer itself. This is how the builtin help() works.
3939
3974
3940 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3975 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3941 macro scoping: macros need to be executed in the user's namespace
3976 macro scoping: macros need to be executed in the user's namespace
3942 to work as if they had been typed by the user.
3977 to work as if they had been typed by the user.
3943
3978
3944 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3979 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3945 execute automatically (no need to type 'exec...'). They then
3980 execute automatically (no need to type 'exec...'). They then
3946 behave like 'true macros'. The printing system was also modified
3981 behave like 'true macros'. The printing system was also modified
3947 for this to work.
3982 for this to work.
3948
3983
3949 2002-02-19 Fernando Perez <fperez@colorado.edu>
3984 2002-02-19 Fernando Perez <fperez@colorado.edu>
3950
3985
3951 * IPython/genutils.py (page_file): new function for paging files
3986 * IPython/genutils.py (page_file): new function for paging files
3952 in an OS-independent way. Also necessary for file viewing to work
3987 in an OS-independent way. Also necessary for file viewing to work
3953 well inside Emacs buffers.
3988 well inside Emacs buffers.
3954 (page): Added checks for being in an emacs buffer.
3989 (page): Added checks for being in an emacs buffer.
3955 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3990 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3956 same bug in iplib.
3991 same bug in iplib.
3957
3992
3958 2002-02-18 Fernando Perez <fperez@colorado.edu>
3993 2002-02-18 Fernando Perez <fperez@colorado.edu>
3959
3994
3960 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3995 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3961 of readline so that IPython can work inside an Emacs buffer.
3996 of readline so that IPython can work inside an Emacs buffer.
3962
3997
3963 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3998 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3964 method signatures (they weren't really bugs, but it looks cleaner
3999 method signatures (they weren't really bugs, but it looks cleaner
3965 and keeps PyChecker happy).
4000 and keeps PyChecker happy).
3966
4001
3967 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
4002 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3968 for implementing various user-defined hooks. Currently only
4003 for implementing various user-defined hooks. Currently only
3969 display is done.
4004 display is done.
3970
4005
3971 * IPython/Prompts.py (CachedOutput._display): changed display
4006 * IPython/Prompts.py (CachedOutput._display): changed display
3972 functions so that they can be dynamically changed by users easily.
4007 functions so that they can be dynamically changed by users easily.
3973
4008
3974 * IPython/Extensions/numeric_formats.py (num_display): added an
4009 * IPython/Extensions/numeric_formats.py (num_display): added an
3975 extension for printing NumPy arrays in flexible manners. It
4010 extension for printing NumPy arrays in flexible manners. It
3976 doesn't do anything yet, but all the structure is in
4011 doesn't do anything yet, but all the structure is in
3977 place. Ultimately the plan is to implement output format control
4012 place. Ultimately the plan is to implement output format control
3978 like in Octave.
4013 like in Octave.
3979
4014
3980 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
4015 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3981 methods are found at run-time by all the automatic machinery.
4016 methods are found at run-time by all the automatic machinery.
3982
4017
3983 2002-02-17 Fernando Perez <fperez@colorado.edu>
4018 2002-02-17 Fernando Perez <fperez@colorado.edu>
3984
4019
3985 * setup_Windows.py (make_shortcut): documented. Cleaned up the
4020 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3986 whole file a little.
4021 whole file a little.
3987
4022
3988 * ToDo: closed this document. Now there's a new_design.lyx
4023 * ToDo: closed this document. Now there's a new_design.lyx
3989 document for all new ideas. Added making a pdf of it for the
4024 document for all new ideas. Added making a pdf of it for the
3990 end-user distro.
4025 end-user distro.
3991
4026
3992 * IPython/Logger.py (Logger.switch_log): Created this to replace
4027 * IPython/Logger.py (Logger.switch_log): Created this to replace
3993 logon() and logoff(). It also fixes a nasty crash reported by
4028 logon() and logoff(). It also fixes a nasty crash reported by
3994 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
4029 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3995
4030
3996 * IPython/iplib.py (complete): got auto-completion to work with
4031 * IPython/iplib.py (complete): got auto-completion to work with
3997 automagic (I had wanted this for a long time).
4032 automagic (I had wanted this for a long time).
3998
4033
3999 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
4034 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
4000 to @file, since file() is now a builtin and clashes with automagic
4035 to @file, since file() is now a builtin and clashes with automagic
4001 for @file.
4036 for @file.
4002
4037
4003 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
4038 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
4004 of this was previously in iplib, which had grown to more than 2000
4039 of this was previously in iplib, which had grown to more than 2000
4005 lines, way too long. No new functionality, but it makes managing
4040 lines, way too long. No new functionality, but it makes managing
4006 the code a bit easier.
4041 the code a bit easier.
4007
4042
4008 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
4043 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
4009 information to crash reports.
4044 information to crash reports.
4010
4045
4011 2002-02-12 Fernando Perez <fperez@colorado.edu>
4046 2002-02-12 Fernando Perez <fperez@colorado.edu>
4012
4047
4013 * Released 0.2.5.
4048 * Released 0.2.5.
4014
4049
4015 2002-02-11 Fernando Perez <fperez@colorado.edu>
4050 2002-02-11 Fernando Perez <fperez@colorado.edu>
4016
4051
4017 * Wrote a relatively complete Windows installer. It puts
4052 * Wrote a relatively complete Windows installer. It puts
4018 everything in place, creates Start Menu entries and fixes the
4053 everything in place, creates Start Menu entries and fixes the
4019 color issues. Nothing fancy, but it works.
4054 color issues. Nothing fancy, but it works.
4020
4055
4021 2002-02-10 Fernando Perez <fperez@colorado.edu>
4056 2002-02-10 Fernando Perez <fperez@colorado.edu>
4022
4057
4023 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
4058 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
4024 os.path.expanduser() call so that we can type @run ~/myfile.py and
4059 os.path.expanduser() call so that we can type @run ~/myfile.py and
4025 have thigs work as expected.
4060 have thigs work as expected.
4026
4061
4027 * IPython/genutils.py (page): fixed exception handling so things
4062 * IPython/genutils.py (page): fixed exception handling so things
4028 work both in Unix and Windows correctly. Quitting a pager triggers
4063 work both in Unix and Windows correctly. Quitting a pager triggers
4029 an IOError/broken pipe in Unix, and in windows not finding a pager
4064 an IOError/broken pipe in Unix, and in windows not finding a pager
4030 is also an IOError, so I had to actually look at the return value
4065 is also an IOError, so I had to actually look at the return value
4031 of the exception, not just the exception itself. Should be ok now.
4066 of the exception, not just the exception itself. Should be ok now.
4032
4067
4033 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
4068 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
4034 modified to allow case-insensitive color scheme changes.
4069 modified to allow case-insensitive color scheme changes.
4035
4070
4036 2002-02-09 Fernando Perez <fperez@colorado.edu>
4071 2002-02-09 Fernando Perez <fperez@colorado.edu>
4037
4072
4038 * IPython/genutils.py (native_line_ends): new function to leave
4073 * IPython/genutils.py (native_line_ends): new function to leave
4039 user config files with os-native line-endings.
4074 user config files with os-native line-endings.
4040
4075
4041 * README and manual updates.
4076 * README and manual updates.
4042
4077
4043 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
4078 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
4044 instead of StringType to catch Unicode strings.
4079 instead of StringType to catch Unicode strings.
4045
4080
4046 * IPython/genutils.py (filefind): fixed bug for paths with
4081 * IPython/genutils.py (filefind): fixed bug for paths with
4047 embedded spaces (very common in Windows).
4082 embedded spaces (very common in Windows).
4048
4083
4049 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
4084 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
4050 files under Windows, so that they get automatically associated
4085 files under Windows, so that they get automatically associated
4051 with a text editor. Windows makes it a pain to handle
4086 with a text editor. Windows makes it a pain to handle
4052 extension-less files.
4087 extension-less files.
4053
4088
4054 * IPython/iplib.py (InteractiveShell.init_readline): Made the
4089 * IPython/iplib.py (InteractiveShell.init_readline): Made the
4055 warning about readline only occur for Posix. In Windows there's no
4090 warning about readline only occur for Posix. In Windows there's no
4056 way to get readline, so why bother with the warning.
4091 way to get readline, so why bother with the warning.
4057
4092
4058 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
4093 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
4059 for __str__ instead of dir(self), since dir() changed in 2.2.
4094 for __str__ instead of dir(self), since dir() changed in 2.2.
4060
4095
4061 * Ported to Windows! Tested on XP, I suspect it should work fine
4096 * Ported to Windows! Tested on XP, I suspect it should work fine
4062 on NT/2000, but I don't think it will work on 98 et al. That
4097 on NT/2000, but I don't think it will work on 98 et al. That
4063 series of Windows is such a piece of junk anyway that I won't try
4098 series of Windows is such a piece of junk anyway that I won't try
4064 porting it there. The XP port was straightforward, showed a few
4099 porting it there. The XP port was straightforward, showed a few
4065 bugs here and there (fixed all), in particular some string
4100 bugs here and there (fixed all), in particular some string
4066 handling stuff which required considering Unicode strings (which
4101 handling stuff which required considering Unicode strings (which
4067 Windows uses). This is good, but hasn't been too tested :) No
4102 Windows uses). This is good, but hasn't been too tested :) No
4068 fancy installer yet, I'll put a note in the manual so people at
4103 fancy installer yet, I'll put a note in the manual so people at
4069 least make manually a shortcut.
4104 least make manually a shortcut.
4070
4105
4071 * IPython/iplib.py (Magic.magic_colors): Unified the color options
4106 * IPython/iplib.py (Magic.magic_colors): Unified the color options
4072 into a single one, "colors". This now controls both prompt and
4107 into a single one, "colors". This now controls both prompt and
4073 exception color schemes, and can be changed both at startup
4108 exception color schemes, and can be changed both at startup
4074 (either via command-line switches or via ipythonrc files) and at
4109 (either via command-line switches or via ipythonrc files) and at
4075 runtime, with @colors.
4110 runtime, with @colors.
4076 (Magic.magic_run): renamed @prun to @run and removed the old
4111 (Magic.magic_run): renamed @prun to @run and removed the old
4077 @run. The two were too similar to warrant keeping both.
4112 @run. The two were too similar to warrant keeping both.
4078
4113
4079 2002-02-03 Fernando Perez <fperez@colorado.edu>
4114 2002-02-03 Fernando Perez <fperez@colorado.edu>
4080
4115
4081 * IPython/iplib.py (install_first_time): Added comment on how to
4116 * IPython/iplib.py (install_first_time): Added comment on how to
4082 configure the color options for first-time users. Put a <return>
4117 configure the color options for first-time users. Put a <return>
4083 request at the end so that small-terminal users get a chance to
4118 request at the end so that small-terminal users get a chance to
4084 read the startup info.
4119 read the startup info.
4085
4120
4086 2002-01-23 Fernando Perez <fperez@colorado.edu>
4121 2002-01-23 Fernando Perez <fperez@colorado.edu>
4087
4122
4088 * IPython/iplib.py (CachedOutput.update): Changed output memory
4123 * IPython/iplib.py (CachedOutput.update): Changed output memory
4089 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
4124 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
4090 input history we still use _i. Did this b/c these variable are
4125 input history we still use _i. Did this b/c these variable are
4091 very commonly used in interactive work, so the less we need to
4126 very commonly used in interactive work, so the less we need to
4092 type the better off we are.
4127 type the better off we are.
4093 (Magic.magic_prun): updated @prun to better handle the namespaces
4128 (Magic.magic_prun): updated @prun to better handle the namespaces
4094 the file will run in, including a fix for __name__ not being set
4129 the file will run in, including a fix for __name__ not being set
4095 before.
4130 before.
4096
4131
4097 2002-01-20 Fernando Perez <fperez@colorado.edu>
4132 2002-01-20 Fernando Perez <fperez@colorado.edu>
4098
4133
4099 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
4134 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
4100 extra garbage for Python 2.2. Need to look more carefully into
4135 extra garbage for Python 2.2. Need to look more carefully into
4101 this later.
4136 this later.
4102
4137
4103 2002-01-19 Fernando Perez <fperez@colorado.edu>
4138 2002-01-19 Fernando Perez <fperez@colorado.edu>
4104
4139
4105 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
4140 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
4106 display SyntaxError exceptions properly formatted when they occur
4141 display SyntaxError exceptions properly formatted when they occur
4107 (they can be triggered by imported code).
4142 (they can be triggered by imported code).
4108
4143
4109 2002-01-18 Fernando Perez <fperez@colorado.edu>
4144 2002-01-18 Fernando Perez <fperez@colorado.edu>
4110
4145
4111 * IPython/iplib.py (InteractiveShell.safe_execfile): now
4146 * IPython/iplib.py (InteractiveShell.safe_execfile): now
4112 SyntaxError exceptions are reported nicely formatted, instead of
4147 SyntaxError exceptions are reported nicely formatted, instead of
4113 spitting out only offset information as before.
4148 spitting out only offset information as before.
4114 (Magic.magic_prun): Added the @prun function for executing
4149 (Magic.magic_prun): Added the @prun function for executing
4115 programs with command line args inside IPython.
4150 programs with command line args inside IPython.
4116
4151
4117 2002-01-16 Fernando Perez <fperez@colorado.edu>
4152 2002-01-16 Fernando Perez <fperez@colorado.edu>
4118
4153
4119 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
4154 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
4120 to *not* include the last item given in a range. This brings their
4155 to *not* include the last item given in a range. This brings their
4121 behavior in line with Python's slicing:
4156 behavior in line with Python's slicing:
4122 a[n1:n2] -> a[n1]...a[n2-1]
4157 a[n1:n2] -> a[n1]...a[n2-1]
4123 It may be a bit less convenient, but I prefer to stick to Python's
4158 It may be a bit less convenient, but I prefer to stick to Python's
4124 conventions *everywhere*, so users never have to wonder.
4159 conventions *everywhere*, so users never have to wonder.
4125 (Magic.magic_macro): Added @macro function to ease the creation of
4160 (Magic.magic_macro): Added @macro function to ease the creation of
4126 macros.
4161 macros.
4127
4162
4128 2002-01-05 Fernando Perez <fperez@colorado.edu>
4163 2002-01-05 Fernando Perez <fperez@colorado.edu>
4129
4164
4130 * Released 0.2.4.
4165 * Released 0.2.4.
4131
4166
4132 * IPython/iplib.py (Magic.magic_pdef):
4167 * IPython/iplib.py (Magic.magic_pdef):
4133 (InteractiveShell.safe_execfile): report magic lines and error
4168 (InteractiveShell.safe_execfile): report magic lines and error
4134 lines without line numbers so one can easily copy/paste them for
4169 lines without line numbers so one can easily copy/paste them for
4135 re-execution.
4170 re-execution.
4136
4171
4137 * Updated manual with recent changes.
4172 * Updated manual with recent changes.
4138
4173
4139 * IPython/iplib.py (Magic.magic_oinfo): added constructor
4174 * IPython/iplib.py (Magic.magic_oinfo): added constructor
4140 docstring printing when class? is called. Very handy for knowing
4175 docstring printing when class? is called. Very handy for knowing
4141 how to create class instances (as long as __init__ is well
4176 how to create class instances (as long as __init__ is well
4142 documented, of course :)
4177 documented, of course :)
4143 (Magic.magic_doc): print both class and constructor docstrings.
4178 (Magic.magic_doc): print both class and constructor docstrings.
4144 (Magic.magic_pdef): give constructor info if passed a class and
4179 (Magic.magic_pdef): give constructor info if passed a class and
4145 __call__ info for callable object instances.
4180 __call__ info for callable object instances.
4146
4181
4147 2002-01-04 Fernando Perez <fperez@colorado.edu>
4182 2002-01-04 Fernando Perez <fperez@colorado.edu>
4148
4183
4149 * Made deep_reload() off by default. It doesn't always work
4184 * Made deep_reload() off by default. It doesn't always work
4150 exactly as intended, so it's probably safer to have it off. It's
4185 exactly as intended, so it's probably safer to have it off. It's
4151 still available as dreload() anyway, so nothing is lost.
4186 still available as dreload() anyway, so nothing is lost.
4152
4187
4153 2002-01-02 Fernando Perez <fperez@colorado.edu>
4188 2002-01-02 Fernando Perez <fperez@colorado.edu>
4154
4189
4155 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
4190 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
4156 so I wanted an updated release).
4191 so I wanted an updated release).
4157
4192
4158 2001-12-27 Fernando Perez <fperez@colorado.edu>
4193 2001-12-27 Fernando Perez <fperez@colorado.edu>
4159
4194
4160 * IPython/iplib.py (InteractiveShell.interact): Added the original
4195 * IPython/iplib.py (InteractiveShell.interact): Added the original
4161 code from 'code.py' for this module in order to change the
4196 code from 'code.py' for this module in order to change the
4162 handling of a KeyboardInterrupt. This was necessary b/c otherwise
4197 handling of a KeyboardInterrupt. This was necessary b/c otherwise
4163 the history cache would break when the user hit Ctrl-C, and
4198 the history cache would break when the user hit Ctrl-C, and
4164 interact() offers no way to add any hooks to it.
4199 interact() offers no way to add any hooks to it.
4165
4200
4166 2001-12-23 Fernando Perez <fperez@colorado.edu>
4201 2001-12-23 Fernando Perez <fperez@colorado.edu>
4167
4202
4168 * setup.py: added check for 'MANIFEST' before trying to remove
4203 * setup.py: added check for 'MANIFEST' before trying to remove
4169 it. Thanks to Sean Reifschneider.
4204 it. Thanks to Sean Reifschneider.
4170
4205
4171 2001-12-22 Fernando Perez <fperez@colorado.edu>
4206 2001-12-22 Fernando Perez <fperez@colorado.edu>
4172
4207
4173 * Released 0.2.2.
4208 * Released 0.2.2.
4174
4209
4175 * Finished (reasonably) writing the manual. Later will add the
4210 * Finished (reasonably) writing the manual. Later will add the
4176 python-standard navigation stylesheets, but for the time being
4211 python-standard navigation stylesheets, but for the time being
4177 it's fairly complete. Distribution will include html and pdf
4212 it's fairly complete. Distribution will include html and pdf
4178 versions.
4213 versions.
4179
4214
4180 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
4215 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
4181 (MayaVi author).
4216 (MayaVi author).
4182
4217
4183 2001-12-21 Fernando Perez <fperez@colorado.edu>
4218 2001-12-21 Fernando Perez <fperez@colorado.edu>
4184
4219
4185 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
4220 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
4186 good public release, I think (with the manual and the distutils
4221 good public release, I think (with the manual and the distutils
4187 installer). The manual can use some work, but that can go
4222 installer). The manual can use some work, but that can go
4188 slowly. Otherwise I think it's quite nice for end users. Next
4223 slowly. Otherwise I think it's quite nice for end users. Next
4189 summer, rewrite the guts of it...
4224 summer, rewrite the guts of it...
4190
4225
4191 * Changed format of ipythonrc files to use whitespace as the
4226 * Changed format of ipythonrc files to use whitespace as the
4192 separator instead of an explicit '='. Cleaner.
4227 separator instead of an explicit '='. Cleaner.
4193
4228
4194 2001-12-20 Fernando Perez <fperez@colorado.edu>
4229 2001-12-20 Fernando Perez <fperez@colorado.edu>
4195
4230
4196 * Started a manual in LyX. For now it's just a quick merge of the
4231 * Started a manual in LyX. For now it's just a quick merge of the
4197 various internal docstrings and READMEs. Later it may grow into a
4232 various internal docstrings and READMEs. Later it may grow into a
4198 nice, full-blown manual.
4233 nice, full-blown manual.
4199
4234
4200 * Set up a distutils based installer. Installation should now be
4235 * Set up a distutils based installer. Installation should now be
4201 trivially simple for end-users.
4236 trivially simple for end-users.
4202
4237
4203 2001-12-11 Fernando Perez <fperez@colorado.edu>
4238 2001-12-11 Fernando Perez <fperez@colorado.edu>
4204
4239
4205 * Released 0.2.0. First public release, announced it at
4240 * Released 0.2.0. First public release, announced it at
4206 comp.lang.python. From now on, just bugfixes...
4241 comp.lang.python. From now on, just bugfixes...
4207
4242
4208 * Went through all the files, set copyright/license notices and
4243 * Went through all the files, set copyright/license notices and
4209 cleaned up things. Ready for release.
4244 cleaned up things. Ready for release.
4210
4245
4211 2001-12-10 Fernando Perez <fperez@colorado.edu>
4246 2001-12-10 Fernando Perez <fperez@colorado.edu>
4212
4247
4213 * Changed the first-time installer not to use tarfiles. It's more
4248 * Changed the first-time installer not to use tarfiles. It's more
4214 robust now and less unix-dependent. Also makes it easier for
4249 robust now and less unix-dependent. Also makes it easier for
4215 people to later upgrade versions.
4250 people to later upgrade versions.
4216
4251
4217 * Changed @exit to @abort to reflect the fact that it's pretty
4252 * Changed @exit to @abort to reflect the fact that it's pretty
4218 brutal (a sys.exit()). The difference between @abort and Ctrl-D
4253 brutal (a sys.exit()). The difference between @abort and Ctrl-D
4219 becomes significant only when IPyhton is embedded: in that case,
4254 becomes significant only when IPyhton is embedded: in that case,
4220 C-D closes IPython only, but @abort kills the enclosing program
4255 C-D closes IPython only, but @abort kills the enclosing program
4221 too (unless it had called IPython inside a try catching
4256 too (unless it had called IPython inside a try catching
4222 SystemExit).
4257 SystemExit).
4223
4258
4224 * Created Shell module which exposes the actuall IPython Shell
4259 * Created Shell module which exposes the actuall IPython Shell
4225 classes, currently the normal and the embeddable one. This at
4260 classes, currently the normal and the embeddable one. This at
4226 least offers a stable interface we won't need to change when
4261 least offers a stable interface we won't need to change when
4227 (later) the internals are rewritten. That rewrite will be confined
4262 (later) the internals are rewritten. That rewrite will be confined
4228 to iplib and ipmaker, but the Shell interface should remain as is.
4263 to iplib and ipmaker, but the Shell interface should remain as is.
4229
4264
4230 * Added embed module which offers an embeddable IPShell object,
4265 * Added embed module which offers an embeddable IPShell object,
4231 useful to fire up IPython *inside* a running program. Great for
4266 useful to fire up IPython *inside* a running program. Great for
4232 debugging or dynamical data analysis.
4267 debugging or dynamical data analysis.
4233
4268
4234 2001-12-08 Fernando Perez <fperez@colorado.edu>
4269 2001-12-08 Fernando Perez <fperez@colorado.edu>
4235
4270
4236 * Fixed small bug preventing seeing info from methods of defined
4271 * Fixed small bug preventing seeing info from methods of defined
4237 objects (incorrect namespace in _ofind()).
4272 objects (incorrect namespace in _ofind()).
4238
4273
4239 * Documentation cleanup. Moved the main usage docstrings to a
4274 * Documentation cleanup. Moved the main usage docstrings to a
4240 separate file, usage.py (cleaner to maintain, and hopefully in the
4275 separate file, usage.py (cleaner to maintain, and hopefully in the
4241 future some perlpod-like way of producing interactive, man and
4276 future some perlpod-like way of producing interactive, man and
4242 html docs out of it will be found).
4277 html docs out of it will be found).
4243
4278
4244 * Added @profile to see your profile at any time.
4279 * Added @profile to see your profile at any time.
4245
4280
4246 * Added @p as an alias for 'print'. It's especially convenient if
4281 * Added @p as an alias for 'print'. It's especially convenient if
4247 using automagic ('p x' prints x).
4282 using automagic ('p x' prints x).
4248
4283
4249 * Small cleanups and fixes after a pychecker run.
4284 * Small cleanups and fixes after a pychecker run.
4250
4285
4251 * Changed the @cd command to handle @cd - and @cd -<n> for
4286 * Changed the @cd command to handle @cd - and @cd -<n> for
4252 visiting any directory in _dh.
4287 visiting any directory in _dh.
4253
4288
4254 * Introduced _dh, a history of visited directories. @dhist prints
4289 * Introduced _dh, a history of visited directories. @dhist prints
4255 it out with numbers.
4290 it out with numbers.
4256
4291
4257 2001-12-07 Fernando Perez <fperez@colorado.edu>
4292 2001-12-07 Fernando Perez <fperez@colorado.edu>
4258
4293
4259 * Released 0.1.22
4294 * Released 0.1.22
4260
4295
4261 * Made initialization a bit more robust against invalid color
4296 * Made initialization a bit more robust against invalid color
4262 options in user input (exit, not traceback-crash).
4297 options in user input (exit, not traceback-crash).
4263
4298
4264 * Changed the bug crash reporter to write the report only in the
4299 * Changed the bug crash reporter to write the report only in the
4265 user's .ipython directory. That way IPython won't litter people's
4300 user's .ipython directory. That way IPython won't litter people's
4266 hard disks with crash files all over the place. Also print on
4301 hard disks with crash files all over the place. Also print on
4267 screen the necessary mail command.
4302 screen the necessary mail command.
4268
4303
4269 * With the new ultraTB, implemented LightBG color scheme for light
4304 * With the new ultraTB, implemented LightBG color scheme for light
4270 background terminals. A lot of people like white backgrounds, so I
4305 background terminals. A lot of people like white backgrounds, so I
4271 guess we should at least give them something readable.
4306 guess we should at least give them something readable.
4272
4307
4273 2001-12-06 Fernando Perez <fperez@colorado.edu>
4308 2001-12-06 Fernando Perez <fperez@colorado.edu>
4274
4309
4275 * Modified the structure of ultraTB. Now there's a proper class
4310 * Modified the structure of ultraTB. Now there's a proper class
4276 for tables of color schemes which allow adding schemes easily and
4311 for tables of color schemes which allow adding schemes easily and
4277 switching the active scheme without creating a new instance every
4312 switching the active scheme without creating a new instance every
4278 time (which was ridiculous). The syntax for creating new schemes
4313 time (which was ridiculous). The syntax for creating new schemes
4279 is also cleaner. I think ultraTB is finally done, with a clean
4314 is also cleaner. I think ultraTB is finally done, with a clean
4280 class structure. Names are also much cleaner (now there's proper
4315 class structure. Names are also much cleaner (now there's proper
4281 color tables, no need for every variable to also have 'color' in
4316 color tables, no need for every variable to also have 'color' in
4282 its name).
4317 its name).
4283
4318
4284 * Broke down genutils into separate files. Now genutils only
4319 * Broke down genutils into separate files. Now genutils only
4285 contains utility functions, and classes have been moved to their
4320 contains utility functions, and classes have been moved to their
4286 own files (they had enough independent functionality to warrant
4321 own files (they had enough independent functionality to warrant
4287 it): ConfigLoader, OutputTrap, Struct.
4322 it): ConfigLoader, OutputTrap, Struct.
4288
4323
4289 2001-12-05 Fernando Perez <fperez@colorado.edu>
4324 2001-12-05 Fernando Perez <fperez@colorado.edu>
4290
4325
4291 * IPython turns 21! Released version 0.1.21, as a candidate for
4326 * IPython turns 21! Released version 0.1.21, as a candidate for
4292 public consumption. If all goes well, release in a few days.
4327 public consumption. If all goes well, release in a few days.
4293
4328
4294 * Fixed path bug (files in Extensions/ directory wouldn't be found
4329 * Fixed path bug (files in Extensions/ directory wouldn't be found
4295 unless IPython/ was explicitly in sys.path).
4330 unless IPython/ was explicitly in sys.path).
4296
4331
4297 * Extended the FlexCompleter class as MagicCompleter to allow
4332 * Extended the FlexCompleter class as MagicCompleter to allow
4298 completion of @-starting lines.
4333 completion of @-starting lines.
4299
4334
4300 * Created __release__.py file as a central repository for release
4335 * Created __release__.py file as a central repository for release
4301 info that other files can read from.
4336 info that other files can read from.
4302
4337
4303 * Fixed small bug in logging: when logging was turned on in
4338 * Fixed small bug in logging: when logging was turned on in
4304 mid-session, old lines with special meanings (!@?) were being
4339 mid-session, old lines with special meanings (!@?) were being
4305 logged without the prepended comment, which is necessary since
4340 logged without the prepended comment, which is necessary since
4306 they are not truly valid python syntax. This should make session
4341 they are not truly valid python syntax. This should make session
4307 restores produce less errors.
4342 restores produce less errors.
4308
4343
4309 * The namespace cleanup forced me to make a FlexCompleter class
4344 * The namespace cleanup forced me to make a FlexCompleter class
4310 which is nothing but a ripoff of rlcompleter, but with selectable
4345 which is nothing but a ripoff of rlcompleter, but with selectable
4311 namespace (rlcompleter only works in __main__.__dict__). I'll try
4346 namespace (rlcompleter only works in __main__.__dict__). I'll try
4312 to submit a note to the authors to see if this change can be
4347 to submit a note to the authors to see if this change can be
4313 incorporated in future rlcompleter releases (Dec.6: done)
4348 incorporated in future rlcompleter releases (Dec.6: done)
4314
4349
4315 * More fixes to namespace handling. It was a mess! Now all
4350 * More fixes to namespace handling. It was a mess! Now all
4316 explicit references to __main__.__dict__ are gone (except when
4351 explicit references to __main__.__dict__ are gone (except when
4317 really needed) and everything is handled through the namespace
4352 really needed) and everything is handled through the namespace
4318 dicts in the IPython instance. We seem to be getting somewhere
4353 dicts in the IPython instance. We seem to be getting somewhere
4319 with this, finally...
4354 with this, finally...
4320
4355
4321 * Small documentation updates.
4356 * Small documentation updates.
4322
4357
4323 * Created the Extensions directory under IPython (with an
4358 * Created the Extensions directory under IPython (with an
4324 __init__.py). Put the PhysicalQ stuff there. This directory should
4359 __init__.py). Put the PhysicalQ stuff there. This directory should
4325 be used for all special-purpose extensions.
4360 be used for all special-purpose extensions.
4326
4361
4327 * File renaming:
4362 * File renaming:
4328 ipythonlib --> ipmaker
4363 ipythonlib --> ipmaker
4329 ipplib --> iplib
4364 ipplib --> iplib
4330 This makes a bit more sense in terms of what these files actually do.
4365 This makes a bit more sense in terms of what these files actually do.
4331
4366
4332 * Moved all the classes and functions in ipythonlib to ipplib, so
4367 * Moved all the classes and functions in ipythonlib to ipplib, so
4333 now ipythonlib only has make_IPython(). This will ease up its
4368 now ipythonlib only has make_IPython(). This will ease up its
4334 splitting in smaller functional chunks later.
4369 splitting in smaller functional chunks later.
4335
4370
4336 * Cleaned up (done, I think) output of @whos. Better column
4371 * Cleaned up (done, I think) output of @whos. Better column
4337 formatting, and now shows str(var) for as much as it can, which is
4372 formatting, and now shows str(var) for as much as it can, which is
4338 typically what one gets with a 'print var'.
4373 typically what one gets with a 'print var'.
4339
4374
4340 2001-12-04 Fernando Perez <fperez@colorado.edu>
4375 2001-12-04 Fernando Perez <fperez@colorado.edu>
4341
4376
4342 * Fixed namespace problems. Now builtin/IPyhton/user names get
4377 * Fixed namespace problems. Now builtin/IPyhton/user names get
4343 properly reported in their namespace. Internal namespace handling
4378 properly reported in their namespace. Internal namespace handling
4344 is finally getting decent (not perfect yet, but much better than
4379 is finally getting decent (not perfect yet, but much better than
4345 the ad-hoc mess we had).
4380 the ad-hoc mess we had).
4346
4381
4347 * Removed -exit option. If people just want to run a python
4382 * Removed -exit option. If people just want to run a python
4348 script, that's what the normal interpreter is for. Less
4383 script, that's what the normal interpreter is for. Less
4349 unnecessary options, less chances for bugs.
4384 unnecessary options, less chances for bugs.
4350
4385
4351 * Added a crash handler which generates a complete post-mortem if
4386 * Added a crash handler which generates a complete post-mortem if
4352 IPython crashes. This will help a lot in tracking bugs down the
4387 IPython crashes. This will help a lot in tracking bugs down the
4353 road.
4388 road.
4354
4389
4355 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4390 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4356 which were boud to functions being reassigned would bypass the
4391 which were boud to functions being reassigned would bypass the
4357 logger, breaking the sync of _il with the prompt counter. This
4392 logger, breaking the sync of _il with the prompt counter. This
4358 would then crash IPython later when a new line was logged.
4393 would then crash IPython later when a new line was logged.
4359
4394
4360 2001-12-02 Fernando Perez <fperez@colorado.edu>
4395 2001-12-02 Fernando Perez <fperez@colorado.edu>
4361
4396
4362 * Made IPython a package. This means people don't have to clutter
4397 * Made IPython a package. This means people don't have to clutter
4363 their sys.path with yet another directory. Changed the INSTALL
4398 their sys.path with yet another directory. Changed the INSTALL
4364 file accordingly.
4399 file accordingly.
4365
4400
4366 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4401 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4367 sorts its output (so @who shows it sorted) and @whos formats the
4402 sorts its output (so @who shows it sorted) and @whos formats the
4368 table according to the width of the first column. Nicer, easier to
4403 table according to the width of the first column. Nicer, easier to
4369 read. Todo: write a generic table_format() which takes a list of
4404 read. Todo: write a generic table_format() which takes a list of
4370 lists and prints it nicely formatted, with optional row/column
4405 lists and prints it nicely formatted, with optional row/column
4371 separators and proper padding and justification.
4406 separators and proper padding and justification.
4372
4407
4373 * Released 0.1.20
4408 * Released 0.1.20
4374
4409
4375 * Fixed bug in @log which would reverse the inputcache list (a
4410 * Fixed bug in @log which would reverse the inputcache list (a
4376 copy operation was missing).
4411 copy operation was missing).
4377
4412
4378 * Code cleanup. @config was changed to use page(). Better, since
4413 * Code cleanup. @config was changed to use page(). Better, since
4379 its output is always quite long.
4414 its output is always quite long.
4380
4415
4381 * Itpl is back as a dependency. I was having too many problems
4416 * Itpl is back as a dependency. I was having too many problems
4382 getting the parametric aliases to work reliably, and it's just
4417 getting the parametric aliases to work reliably, and it's just
4383 easier to code weird string operations with it than playing %()s
4418 easier to code weird string operations with it than playing %()s
4384 games. It's only ~6k, so I don't think it's too big a deal.
4419 games. It's only ~6k, so I don't think it's too big a deal.
4385
4420
4386 * Found (and fixed) a very nasty bug with history. !lines weren't
4421 * Found (and fixed) a very nasty bug with history. !lines weren't
4387 getting cached, and the out of sync caches would crash
4422 getting cached, and the out of sync caches would crash
4388 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4423 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4389 division of labor a bit better. Bug fixed, cleaner structure.
4424 division of labor a bit better. Bug fixed, cleaner structure.
4390
4425
4391 2001-12-01 Fernando Perez <fperez@colorado.edu>
4426 2001-12-01 Fernando Perez <fperez@colorado.edu>
4392
4427
4393 * Released 0.1.19
4428 * Released 0.1.19
4394
4429
4395 * Added option -n to @hist to prevent line number printing. Much
4430 * Added option -n to @hist to prevent line number printing. Much
4396 easier to copy/paste code this way.
4431 easier to copy/paste code this way.
4397
4432
4398 * Created global _il to hold the input list. Allows easy
4433 * Created global _il to hold the input list. Allows easy
4399 re-execution of blocks of code by slicing it (inspired by Janko's
4434 re-execution of blocks of code by slicing it (inspired by Janko's
4400 comment on 'macros').
4435 comment on 'macros').
4401
4436
4402 * Small fixes and doc updates.
4437 * Small fixes and doc updates.
4403
4438
4404 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4439 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4405 much too fragile with automagic. Handles properly multi-line
4440 much too fragile with automagic. Handles properly multi-line
4406 statements and takes parameters.
4441 statements and takes parameters.
4407
4442
4408 2001-11-30 Fernando Perez <fperez@colorado.edu>
4443 2001-11-30 Fernando Perez <fperez@colorado.edu>
4409
4444
4410 * Version 0.1.18 released.
4445 * Version 0.1.18 released.
4411
4446
4412 * Fixed nasty namespace bug in initial module imports.
4447 * Fixed nasty namespace bug in initial module imports.
4413
4448
4414 * Added copyright/license notes to all code files (except
4449 * Added copyright/license notes to all code files (except
4415 DPyGetOpt). For the time being, LGPL. That could change.
4450 DPyGetOpt). For the time being, LGPL. That could change.
4416
4451
4417 * Rewrote a much nicer README, updated INSTALL, cleaned up
4452 * Rewrote a much nicer README, updated INSTALL, cleaned up
4418 ipythonrc-* samples.
4453 ipythonrc-* samples.
4419
4454
4420 * Overall code/documentation cleanup. Basically ready for
4455 * Overall code/documentation cleanup. Basically ready for
4421 release. Only remaining thing: licence decision (LGPL?).
4456 release. Only remaining thing: licence decision (LGPL?).
4422
4457
4423 * Converted load_config to a class, ConfigLoader. Now recursion
4458 * Converted load_config to a class, ConfigLoader. Now recursion
4424 control is better organized. Doesn't include the same file twice.
4459 control is better organized. Doesn't include the same file twice.
4425
4460
4426 2001-11-29 Fernando Perez <fperez@colorado.edu>
4461 2001-11-29 Fernando Perez <fperez@colorado.edu>
4427
4462
4428 * Got input history working. Changed output history variables from
4463 * Got input history working. Changed output history variables from
4429 _p to _o so that _i is for input and _o for output. Just cleaner
4464 _p to _o so that _i is for input and _o for output. Just cleaner
4430 convention.
4465 convention.
4431
4466
4432 * Implemented parametric aliases. This pretty much allows the
4467 * Implemented parametric aliases. This pretty much allows the
4433 alias system to offer full-blown shell convenience, I think.
4468 alias system to offer full-blown shell convenience, I think.
4434
4469
4435 * Version 0.1.17 released, 0.1.18 opened.
4470 * Version 0.1.17 released, 0.1.18 opened.
4436
4471
4437 * dot_ipython/ipythonrc (alias): added documentation.
4472 * dot_ipython/ipythonrc (alias): added documentation.
4438 (xcolor): Fixed small bug (xcolors -> xcolor)
4473 (xcolor): Fixed small bug (xcolors -> xcolor)
4439
4474
4440 * Changed the alias system. Now alias is a magic command to define
4475 * Changed the alias system. Now alias is a magic command to define
4441 aliases just like the shell. Rationale: the builtin magics should
4476 aliases just like the shell. Rationale: the builtin magics should
4442 be there for things deeply connected to IPython's
4477 be there for things deeply connected to IPython's
4443 architecture. And this is a much lighter system for what I think
4478 architecture. And this is a much lighter system for what I think
4444 is the really important feature: allowing users to define quickly
4479 is the really important feature: allowing users to define quickly
4445 magics that will do shell things for them, so they can customize
4480 magics that will do shell things for them, so they can customize
4446 IPython easily to match their work habits. If someone is really
4481 IPython easily to match their work habits. If someone is really
4447 desperate to have another name for a builtin alias, they can
4482 desperate to have another name for a builtin alias, they can
4448 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4483 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4449 works.
4484 works.
4450
4485
4451 2001-11-28 Fernando Perez <fperez@colorado.edu>
4486 2001-11-28 Fernando Perez <fperez@colorado.edu>
4452
4487
4453 * Changed @file so that it opens the source file at the proper
4488 * Changed @file so that it opens the source file at the proper
4454 line. Since it uses less, if your EDITOR environment is
4489 line. Since it uses less, if your EDITOR environment is
4455 configured, typing v will immediately open your editor of choice
4490 configured, typing v will immediately open your editor of choice
4456 right at the line where the object is defined. Not as quick as
4491 right at the line where the object is defined. Not as quick as
4457 having a direct @edit command, but for all intents and purposes it
4492 having a direct @edit command, but for all intents and purposes it
4458 works. And I don't have to worry about writing @edit to deal with
4493 works. And I don't have to worry about writing @edit to deal with
4459 all the editors, less does that.
4494 all the editors, less does that.
4460
4495
4461 * Version 0.1.16 released, 0.1.17 opened.
4496 * Version 0.1.16 released, 0.1.17 opened.
4462
4497
4463 * Fixed some nasty bugs in the page/page_dumb combo that could
4498 * Fixed some nasty bugs in the page/page_dumb combo that could
4464 crash IPython.
4499 crash IPython.
4465
4500
4466 2001-11-27 Fernando Perez <fperez@colorado.edu>
4501 2001-11-27 Fernando Perez <fperez@colorado.edu>
4467
4502
4468 * Version 0.1.15 released, 0.1.16 opened.
4503 * Version 0.1.15 released, 0.1.16 opened.
4469
4504
4470 * Finally got ? and ?? to work for undefined things: now it's
4505 * Finally got ? and ?? to work for undefined things: now it's
4471 possible to type {}.get? and get information about the get method
4506 possible to type {}.get? and get information about the get method
4472 of dicts, or os.path? even if only os is defined (so technically
4507 of dicts, or os.path? even if only os is defined (so technically
4473 os.path isn't). Works at any level. For example, after import os,
4508 os.path isn't). Works at any level. For example, after import os,
4474 os?, os.path?, os.path.abspath? all work. This is great, took some
4509 os?, os.path?, os.path.abspath? all work. This is great, took some
4475 work in _ofind.
4510 work in _ofind.
4476
4511
4477 * Fixed more bugs with logging. The sanest way to do it was to add
4512 * Fixed more bugs with logging. The sanest way to do it was to add
4478 to @log a 'mode' parameter. Killed two in one shot (this mode
4513 to @log a 'mode' parameter. Killed two in one shot (this mode
4479 option was a request of Janko's). I think it's finally clean
4514 option was a request of Janko's). I think it's finally clean
4480 (famous last words).
4515 (famous last words).
4481
4516
4482 * Added a page_dumb() pager which does a decent job of paging on
4517 * Added a page_dumb() pager which does a decent job of paging on
4483 screen, if better things (like less) aren't available. One less
4518 screen, if better things (like less) aren't available. One less
4484 unix dependency (someday maybe somebody will port this to
4519 unix dependency (someday maybe somebody will port this to
4485 windows).
4520 windows).
4486
4521
4487 * Fixed problem in magic_log: would lock of logging out if log
4522 * Fixed problem in magic_log: would lock of logging out if log
4488 creation failed (because it would still think it had succeeded).
4523 creation failed (because it would still think it had succeeded).
4489
4524
4490 * Improved the page() function using curses to auto-detect screen
4525 * Improved the page() function using curses to auto-detect screen
4491 size. Now it can make a much better decision on whether to print
4526 size. Now it can make a much better decision on whether to print
4492 or page a string. Option screen_length was modified: a value 0
4527 or page a string. Option screen_length was modified: a value 0
4493 means auto-detect, and that's the default now.
4528 means auto-detect, and that's the default now.
4494
4529
4495 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4530 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4496 go out. I'll test it for a few days, then talk to Janko about
4531 go out. I'll test it for a few days, then talk to Janko about
4497 licences and announce it.
4532 licences and announce it.
4498
4533
4499 * Fixed the length of the auto-generated ---> prompt which appears
4534 * Fixed the length of the auto-generated ---> prompt which appears
4500 for auto-parens and auto-quotes. Getting this right isn't trivial,
4535 for auto-parens and auto-quotes. Getting this right isn't trivial,
4501 with all the color escapes, different prompt types and optional
4536 with all the color escapes, different prompt types and optional
4502 separators. But it seems to be working in all the combinations.
4537 separators. But it seems to be working in all the combinations.
4503
4538
4504 2001-11-26 Fernando Perez <fperez@colorado.edu>
4539 2001-11-26 Fernando Perez <fperez@colorado.edu>
4505
4540
4506 * Wrote a regexp filter to get option types from the option names
4541 * Wrote a regexp filter to get option types from the option names
4507 string. This eliminates the need to manually keep two duplicate
4542 string. This eliminates the need to manually keep two duplicate
4508 lists.
4543 lists.
4509
4544
4510 * Removed the unneeded check_option_names. Now options are handled
4545 * Removed the unneeded check_option_names. Now options are handled
4511 in a much saner manner and it's easy to visually check that things
4546 in a much saner manner and it's easy to visually check that things
4512 are ok.
4547 are ok.
4513
4548
4514 * Updated version numbers on all files I modified to carry a
4549 * Updated version numbers on all files I modified to carry a
4515 notice so Janko and Nathan have clear version markers.
4550 notice so Janko and Nathan have clear version markers.
4516
4551
4517 * Updated docstring for ultraTB with my changes. I should send
4552 * Updated docstring for ultraTB with my changes. I should send
4518 this to Nathan.
4553 this to Nathan.
4519
4554
4520 * Lots of small fixes. Ran everything through pychecker again.
4555 * Lots of small fixes. Ran everything through pychecker again.
4521
4556
4522 * Made loading of deep_reload an cmd line option. If it's not too
4557 * Made loading of deep_reload an cmd line option. If it's not too
4523 kosher, now people can just disable it. With -nodeep_reload it's
4558 kosher, now people can just disable it. With -nodeep_reload it's
4524 still available as dreload(), it just won't overwrite reload().
4559 still available as dreload(), it just won't overwrite reload().
4525
4560
4526 * Moved many options to the no| form (-opt and -noopt
4561 * Moved many options to the no| form (-opt and -noopt
4527 accepted). Cleaner.
4562 accepted). Cleaner.
4528
4563
4529 * Changed magic_log so that if called with no parameters, it uses
4564 * Changed magic_log so that if called with no parameters, it uses
4530 'rotate' mode. That way auto-generated logs aren't automatically
4565 'rotate' mode. That way auto-generated logs aren't automatically
4531 over-written. For normal logs, now a backup is made if it exists
4566 over-written. For normal logs, now a backup is made if it exists
4532 (only 1 level of backups). A new 'backup' mode was added to the
4567 (only 1 level of backups). A new 'backup' mode was added to the
4533 Logger class to support this. This was a request by Janko.
4568 Logger class to support this. This was a request by Janko.
4534
4569
4535 * Added @logoff/@logon to stop/restart an active log.
4570 * Added @logoff/@logon to stop/restart an active log.
4536
4571
4537 * Fixed a lot of bugs in log saving/replay. It was pretty
4572 * Fixed a lot of bugs in log saving/replay. It was pretty
4538 broken. Now special lines (!@,/) appear properly in the command
4573 broken. Now special lines (!@,/) appear properly in the command
4539 history after a log replay.
4574 history after a log replay.
4540
4575
4541 * Tried and failed to implement full session saving via pickle. My
4576 * Tried and failed to implement full session saving via pickle. My
4542 idea was to pickle __main__.__dict__, but modules can't be
4577 idea was to pickle __main__.__dict__, but modules can't be
4543 pickled. This would be a better alternative to replaying logs, but
4578 pickled. This would be a better alternative to replaying logs, but
4544 seems quite tricky to get to work. Changed -session to be called
4579 seems quite tricky to get to work. Changed -session to be called
4545 -logplay, which more accurately reflects what it does. And if we
4580 -logplay, which more accurately reflects what it does. And if we
4546 ever get real session saving working, -session is now available.
4581 ever get real session saving working, -session is now available.
4547
4582
4548 * Implemented color schemes for prompts also. As for tracebacks,
4583 * Implemented color schemes for prompts also. As for tracebacks,
4549 currently only NoColor and Linux are supported. But now the
4584 currently only NoColor and Linux are supported. But now the
4550 infrastructure is in place, based on a generic ColorScheme
4585 infrastructure is in place, based on a generic ColorScheme
4551 class. So writing and activating new schemes both for the prompts
4586 class. So writing and activating new schemes both for the prompts
4552 and the tracebacks should be straightforward.
4587 and the tracebacks should be straightforward.
4553
4588
4554 * Version 0.1.13 released, 0.1.14 opened.
4589 * Version 0.1.13 released, 0.1.14 opened.
4555
4590
4556 * Changed handling of options for output cache. Now counter is
4591 * Changed handling of options for output cache. Now counter is
4557 hardwired starting at 1 and one specifies the maximum number of
4592 hardwired starting at 1 and one specifies the maximum number of
4558 entries *in the outcache* (not the max prompt counter). This is
4593 entries *in the outcache* (not the max prompt counter). This is
4559 much better, since many statements won't increase the cache
4594 much better, since many statements won't increase the cache
4560 count. It also eliminated some confusing options, now there's only
4595 count. It also eliminated some confusing options, now there's only
4561 one: cache_size.
4596 one: cache_size.
4562
4597
4563 * Added 'alias' magic function and magic_alias option in the
4598 * Added 'alias' magic function and magic_alias option in the
4564 ipythonrc file. Now the user can easily define whatever names he
4599 ipythonrc file. Now the user can easily define whatever names he
4565 wants for the magic functions without having to play weird
4600 wants for the magic functions without having to play weird
4566 namespace games. This gives IPython a real shell-like feel.
4601 namespace games. This gives IPython a real shell-like feel.
4567
4602
4568 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4603 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4569 @ or not).
4604 @ or not).
4570
4605
4571 This was one of the last remaining 'visible' bugs (that I know
4606 This was one of the last remaining 'visible' bugs (that I know
4572 of). I think if I can clean up the session loading so it works
4607 of). I think if I can clean up the session loading so it works
4573 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4608 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4574 about licensing).
4609 about licensing).
4575
4610
4576 2001-11-25 Fernando Perez <fperez@colorado.edu>
4611 2001-11-25 Fernando Perez <fperez@colorado.edu>
4577
4612
4578 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4613 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4579 there's a cleaner distinction between what ? and ?? show.
4614 there's a cleaner distinction between what ? and ?? show.
4580
4615
4581 * Added screen_length option. Now the user can define his own
4616 * Added screen_length option. Now the user can define his own
4582 screen size for page() operations.
4617 screen size for page() operations.
4583
4618
4584 * Implemented magic shell-like functions with automatic code
4619 * Implemented magic shell-like functions with automatic code
4585 generation. Now adding another function is just a matter of adding
4620 generation. Now adding another function is just a matter of adding
4586 an entry to a dict, and the function is dynamically generated at
4621 an entry to a dict, and the function is dynamically generated at
4587 run-time. Python has some really cool features!
4622 run-time. Python has some really cool features!
4588
4623
4589 * Renamed many options to cleanup conventions a little. Now all
4624 * Renamed many options to cleanup conventions a little. Now all
4590 are lowercase, and only underscores where needed. Also in the code
4625 are lowercase, and only underscores where needed. Also in the code
4591 option name tables are clearer.
4626 option name tables are clearer.
4592
4627
4593 * Changed prompts a little. Now input is 'In [n]:' instead of
4628 * Changed prompts a little. Now input is 'In [n]:' instead of
4594 'In[n]:='. This allows it the numbers to be aligned with the
4629 'In[n]:='. This allows it the numbers to be aligned with the
4595 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4630 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4596 Python (it was a Mathematica thing). The '...' continuation prompt
4631 Python (it was a Mathematica thing). The '...' continuation prompt
4597 was also changed a little to align better.
4632 was also changed a little to align better.
4598
4633
4599 * Fixed bug when flushing output cache. Not all _p<n> variables
4634 * Fixed bug when flushing output cache. Not all _p<n> variables
4600 exist, so their deletion needs to be wrapped in a try:
4635 exist, so their deletion needs to be wrapped in a try:
4601
4636
4602 * Figured out how to properly use inspect.formatargspec() (it
4637 * Figured out how to properly use inspect.formatargspec() (it
4603 requires the args preceded by *). So I removed all the code from
4638 requires the args preceded by *). So I removed all the code from
4604 _get_pdef in Magic, which was just replicating that.
4639 _get_pdef in Magic, which was just replicating that.
4605
4640
4606 * Added test to prefilter to allow redefining magic function names
4641 * Added test to prefilter to allow redefining magic function names
4607 as variables. This is ok, since the @ form is always available,
4642 as variables. This is ok, since the @ form is always available,
4608 but whe should allow the user to define a variable called 'ls' if
4643 but whe should allow the user to define a variable called 'ls' if
4609 he needs it.
4644 he needs it.
4610
4645
4611 * Moved the ToDo information from README into a separate ToDo.
4646 * Moved the ToDo information from README into a separate ToDo.
4612
4647
4613 * General code cleanup and small bugfixes. I think it's close to a
4648 * General code cleanup and small bugfixes. I think it's close to a
4614 state where it can be released, obviously with a big 'beta'
4649 state where it can be released, obviously with a big 'beta'
4615 warning on it.
4650 warning on it.
4616
4651
4617 * Got the magic function split to work. Now all magics are defined
4652 * Got the magic function split to work. Now all magics are defined
4618 in a separate class. It just organizes things a bit, and now
4653 in a separate class. It just organizes things a bit, and now
4619 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4654 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4620 was too long).
4655 was too long).
4621
4656
4622 * Changed @clear to @reset to avoid potential confusions with
4657 * Changed @clear to @reset to avoid potential confusions with
4623 the shell command clear. Also renamed @cl to @clear, which does
4658 the shell command clear. Also renamed @cl to @clear, which does
4624 exactly what people expect it to from their shell experience.
4659 exactly what people expect it to from their shell experience.
4625
4660
4626 Added a check to the @reset command (since it's so
4661 Added a check to the @reset command (since it's so
4627 destructive, it's probably a good idea to ask for confirmation).
4662 destructive, it's probably a good idea to ask for confirmation).
4628 But now reset only works for full namespace resetting. Since the
4663 But now reset only works for full namespace resetting. Since the
4629 del keyword is already there for deleting a few specific
4664 del keyword is already there for deleting a few specific
4630 variables, I don't see the point of having a redundant magic
4665 variables, I don't see the point of having a redundant magic
4631 function for the same task.
4666 function for the same task.
4632
4667
4633 2001-11-24 Fernando Perez <fperez@colorado.edu>
4668 2001-11-24 Fernando Perez <fperez@colorado.edu>
4634
4669
4635 * Updated the builtin docs (esp. the ? ones).
4670 * Updated the builtin docs (esp. the ? ones).
4636
4671
4637 * Ran all the code through pychecker. Not terribly impressed with
4672 * Ran all the code through pychecker. Not terribly impressed with
4638 it: lots of spurious warnings and didn't really find anything of
4673 it: lots of spurious warnings and didn't really find anything of
4639 substance (just a few modules being imported and not used).
4674 substance (just a few modules being imported and not used).
4640
4675
4641 * Implemented the new ultraTB functionality into IPython. New
4676 * Implemented the new ultraTB functionality into IPython. New
4642 option: xcolors. This chooses color scheme. xmode now only selects
4677 option: xcolors. This chooses color scheme. xmode now only selects
4643 between Plain and Verbose. Better orthogonality.
4678 between Plain and Verbose. Better orthogonality.
4644
4679
4645 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4680 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4646 mode and color scheme for the exception handlers. Now it's
4681 mode and color scheme for the exception handlers. Now it's
4647 possible to have the verbose traceback with no coloring.
4682 possible to have the verbose traceback with no coloring.
4648
4683
4649 2001-11-23 Fernando Perez <fperez@colorado.edu>
4684 2001-11-23 Fernando Perez <fperez@colorado.edu>
4650
4685
4651 * Version 0.1.12 released, 0.1.13 opened.
4686 * Version 0.1.12 released, 0.1.13 opened.
4652
4687
4653 * Removed option to set auto-quote and auto-paren escapes by
4688 * Removed option to set auto-quote and auto-paren escapes by
4654 user. The chances of breaking valid syntax are just too high. If
4689 user. The chances of breaking valid syntax are just too high. If
4655 someone *really* wants, they can always dig into the code.
4690 someone *really* wants, they can always dig into the code.
4656
4691
4657 * Made prompt separators configurable.
4692 * Made prompt separators configurable.
4658
4693
4659 2001-11-22 Fernando Perez <fperez@colorado.edu>
4694 2001-11-22 Fernando Perez <fperez@colorado.edu>
4660
4695
4661 * Small bugfixes in many places.
4696 * Small bugfixes in many places.
4662
4697
4663 * Removed the MyCompleter class from ipplib. It seemed redundant
4698 * Removed the MyCompleter class from ipplib. It seemed redundant
4664 with the C-p,C-n history search functionality. Less code to
4699 with the C-p,C-n history search functionality. Less code to
4665 maintain.
4700 maintain.
4666
4701
4667 * Moved all the original ipython.py code into ipythonlib.py. Right
4702 * Moved all the original ipython.py code into ipythonlib.py. Right
4668 now it's just one big dump into a function called make_IPython, so
4703 now it's just one big dump into a function called make_IPython, so
4669 no real modularity has been gained. But at least it makes the
4704 no real modularity has been gained. But at least it makes the
4670 wrapper script tiny, and since ipythonlib is a module, it gets
4705 wrapper script tiny, and since ipythonlib is a module, it gets
4671 compiled and startup is much faster.
4706 compiled and startup is much faster.
4672
4707
4673 This is a reasobably 'deep' change, so we should test it for a
4708 This is a reasobably 'deep' change, so we should test it for a
4674 while without messing too much more with the code.
4709 while without messing too much more with the code.
4675
4710
4676 2001-11-21 Fernando Perez <fperez@colorado.edu>
4711 2001-11-21 Fernando Perez <fperez@colorado.edu>
4677
4712
4678 * Version 0.1.11 released, 0.1.12 opened for further work.
4713 * Version 0.1.11 released, 0.1.12 opened for further work.
4679
4714
4680 * Removed dependency on Itpl. It was only needed in one place. It
4715 * Removed dependency on Itpl. It was only needed in one place. It
4681 would be nice if this became part of python, though. It makes life
4716 would be nice if this became part of python, though. It makes life
4682 *a lot* easier in some cases.
4717 *a lot* easier in some cases.
4683
4718
4684 * Simplified the prefilter code a bit. Now all handlers are
4719 * Simplified the prefilter code a bit. Now all handlers are
4685 expected to explicitly return a value (at least a blank string).
4720 expected to explicitly return a value (at least a blank string).
4686
4721
4687 * Heavy edits in ipplib. Removed the help system altogether. Now
4722 * Heavy edits in ipplib. Removed the help system altogether. Now
4688 obj?/?? is used for inspecting objects, a magic @doc prints
4723 obj?/?? is used for inspecting objects, a magic @doc prints
4689 docstrings, and full-blown Python help is accessed via the 'help'
4724 docstrings, and full-blown Python help is accessed via the 'help'
4690 keyword. This cleans up a lot of code (less to maintain) and does
4725 keyword. This cleans up a lot of code (less to maintain) and does
4691 the job. Since 'help' is now a standard Python component, might as
4726 the job. Since 'help' is now a standard Python component, might as
4692 well use it and remove duplicate functionality.
4727 well use it and remove duplicate functionality.
4693
4728
4694 Also removed the option to use ipplib as a standalone program. By
4729 Also removed the option to use ipplib as a standalone program. By
4695 now it's too dependent on other parts of IPython to function alone.
4730 now it's too dependent on other parts of IPython to function alone.
4696
4731
4697 * Fixed bug in genutils.pager. It would crash if the pager was
4732 * Fixed bug in genutils.pager. It would crash if the pager was
4698 exited immediately after opening (broken pipe).
4733 exited immediately after opening (broken pipe).
4699
4734
4700 * Trimmed down the VerboseTB reporting a little. The header is
4735 * Trimmed down the VerboseTB reporting a little. The header is
4701 much shorter now and the repeated exception arguments at the end
4736 much shorter now and the repeated exception arguments at the end
4702 have been removed. For interactive use the old header seemed a bit
4737 have been removed. For interactive use the old header seemed a bit
4703 excessive.
4738 excessive.
4704
4739
4705 * Fixed small bug in output of @whos for variables with multi-word
4740 * Fixed small bug in output of @whos for variables with multi-word
4706 types (only first word was displayed).
4741 types (only first word was displayed).
4707
4742
4708 2001-11-17 Fernando Perez <fperez@colorado.edu>
4743 2001-11-17 Fernando Perez <fperez@colorado.edu>
4709
4744
4710 * Version 0.1.10 released, 0.1.11 opened for further work.
4745 * Version 0.1.10 released, 0.1.11 opened for further work.
4711
4746
4712 * Modified dirs and friends. dirs now *returns* the stack (not
4747 * Modified dirs and friends. dirs now *returns* the stack (not
4713 prints), so one can manipulate it as a variable. Convenient to
4748 prints), so one can manipulate it as a variable. Convenient to
4714 travel along many directories.
4749 travel along many directories.
4715
4750
4716 * Fixed bug in magic_pdef: would only work with functions with
4751 * Fixed bug in magic_pdef: would only work with functions with
4717 arguments with default values.
4752 arguments with default values.
4718
4753
4719 2001-11-14 Fernando Perez <fperez@colorado.edu>
4754 2001-11-14 Fernando Perez <fperez@colorado.edu>
4720
4755
4721 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4756 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4722 example with IPython. Various other minor fixes and cleanups.
4757 example with IPython. Various other minor fixes and cleanups.
4723
4758
4724 * Version 0.1.9 released, 0.1.10 opened for further work.
4759 * Version 0.1.9 released, 0.1.10 opened for further work.
4725
4760
4726 * Added sys.path to the list of directories searched in the
4761 * Added sys.path to the list of directories searched in the
4727 execfile= option. It used to be the current directory and the
4762 execfile= option. It used to be the current directory and the
4728 user's IPYTHONDIR only.
4763 user's IPYTHONDIR only.
4729
4764
4730 2001-11-13 Fernando Perez <fperez@colorado.edu>
4765 2001-11-13 Fernando Perez <fperez@colorado.edu>
4731
4766
4732 * Reinstated the raw_input/prefilter separation that Janko had
4767 * Reinstated the raw_input/prefilter separation that Janko had
4733 initially. This gives a more convenient setup for extending the
4768 initially. This gives a more convenient setup for extending the
4734 pre-processor from the outside: raw_input always gets a string,
4769 pre-processor from the outside: raw_input always gets a string,
4735 and prefilter has to process it. We can then redefine prefilter
4770 and prefilter has to process it. We can then redefine prefilter
4736 from the outside and implement extensions for special
4771 from the outside and implement extensions for special
4737 purposes.
4772 purposes.
4738
4773
4739 Today I got one for inputting PhysicalQuantity objects
4774 Today I got one for inputting PhysicalQuantity objects
4740 (from Scientific) without needing any function calls at
4775 (from Scientific) without needing any function calls at
4741 all. Extremely convenient, and it's all done as a user-level
4776 all. Extremely convenient, and it's all done as a user-level
4742 extension (no IPython code was touched). Now instead of:
4777 extension (no IPython code was touched). Now instead of:
4743 a = PhysicalQuantity(4.2,'m/s**2')
4778 a = PhysicalQuantity(4.2,'m/s**2')
4744 one can simply say
4779 one can simply say
4745 a = 4.2 m/s**2
4780 a = 4.2 m/s**2
4746 or even
4781 or even
4747 a = 4.2 m/s^2
4782 a = 4.2 m/s^2
4748
4783
4749 I use this, but it's also a proof of concept: IPython really is
4784 I use this, but it's also a proof of concept: IPython really is
4750 fully user-extensible, even at the level of the parsing of the
4785 fully user-extensible, even at the level of the parsing of the
4751 command line. It's not trivial, but it's perfectly doable.
4786 command line. It's not trivial, but it's perfectly doable.
4752
4787
4753 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4788 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4754 the problem of modules being loaded in the inverse order in which
4789 the problem of modules being loaded in the inverse order in which
4755 they were defined in
4790 they were defined in
4756
4791
4757 * Version 0.1.8 released, 0.1.9 opened for further work.
4792 * Version 0.1.8 released, 0.1.9 opened for further work.
4758
4793
4759 * Added magics pdef, source and file. They respectively show the
4794 * Added magics pdef, source and file. They respectively show the
4760 definition line ('prototype' in C), source code and full python
4795 definition line ('prototype' in C), source code and full python
4761 file for any callable object. The object inspector oinfo uses
4796 file for any callable object. The object inspector oinfo uses
4762 these to show the same information.
4797 these to show the same information.
4763
4798
4764 * Version 0.1.7 released, 0.1.8 opened for further work.
4799 * Version 0.1.7 released, 0.1.8 opened for further work.
4765
4800
4766 * Separated all the magic functions into a class called Magic. The
4801 * Separated all the magic functions into a class called Magic. The
4767 InteractiveShell class was becoming too big for Xemacs to handle
4802 InteractiveShell class was becoming too big for Xemacs to handle
4768 (de-indenting a line would lock it up for 10 seconds while it
4803 (de-indenting a line would lock it up for 10 seconds while it
4769 backtracked on the whole class!)
4804 backtracked on the whole class!)
4770
4805
4771 FIXME: didn't work. It can be done, but right now namespaces are
4806 FIXME: didn't work. It can be done, but right now namespaces are
4772 all messed up. Do it later (reverted it for now, so at least
4807 all messed up. Do it later (reverted it for now, so at least
4773 everything works as before).
4808 everything works as before).
4774
4809
4775 * Got the object introspection system (magic_oinfo) working! I
4810 * Got the object introspection system (magic_oinfo) working! I
4776 think this is pretty much ready for release to Janko, so he can
4811 think this is pretty much ready for release to Janko, so he can
4777 test it for a while and then announce it. Pretty much 100% of what
4812 test it for a while and then announce it. Pretty much 100% of what
4778 I wanted for the 'phase 1' release is ready. Happy, tired.
4813 I wanted for the 'phase 1' release is ready. Happy, tired.
4779
4814
4780 2001-11-12 Fernando Perez <fperez@colorado.edu>
4815 2001-11-12 Fernando Perez <fperez@colorado.edu>
4781
4816
4782 * Version 0.1.6 released, 0.1.7 opened for further work.
4817 * Version 0.1.6 released, 0.1.7 opened for further work.
4783
4818
4784 * Fixed bug in printing: it used to test for truth before
4819 * Fixed bug in printing: it used to test for truth before
4785 printing, so 0 wouldn't print. Now checks for None.
4820 printing, so 0 wouldn't print. Now checks for None.
4786
4821
4787 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4822 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4788 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4823 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4789 reaches by hand into the outputcache. Think of a better way to do
4824 reaches by hand into the outputcache. Think of a better way to do
4790 this later.
4825 this later.
4791
4826
4792 * Various small fixes thanks to Nathan's comments.
4827 * Various small fixes thanks to Nathan's comments.
4793
4828
4794 * Changed magic_pprint to magic_Pprint. This way it doesn't
4829 * Changed magic_pprint to magic_Pprint. This way it doesn't
4795 collide with pprint() and the name is consistent with the command
4830 collide with pprint() and the name is consistent with the command
4796 line option.
4831 line option.
4797
4832
4798 * Changed prompt counter behavior to be fully like
4833 * Changed prompt counter behavior to be fully like
4799 Mathematica's. That is, even input that doesn't return a result
4834 Mathematica's. That is, even input that doesn't return a result
4800 raises the prompt counter. The old behavior was kind of confusing
4835 raises the prompt counter. The old behavior was kind of confusing
4801 (getting the same prompt number several times if the operation
4836 (getting the same prompt number several times if the operation
4802 didn't return a result).
4837 didn't return a result).
4803
4838
4804 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4839 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4805
4840
4806 * Fixed -Classic mode (wasn't working anymore).
4841 * Fixed -Classic mode (wasn't working anymore).
4807
4842
4808 * Added colored prompts using Nathan's new code. Colors are
4843 * Added colored prompts using Nathan's new code. Colors are
4809 currently hardwired, they can be user-configurable. For
4844 currently hardwired, they can be user-configurable. For
4810 developers, they can be chosen in file ipythonlib.py, at the
4845 developers, they can be chosen in file ipythonlib.py, at the
4811 beginning of the CachedOutput class def.
4846 beginning of the CachedOutput class def.
4812
4847
4813 2001-11-11 Fernando Perez <fperez@colorado.edu>
4848 2001-11-11 Fernando Perez <fperez@colorado.edu>
4814
4849
4815 * Version 0.1.5 released, 0.1.6 opened for further work.
4850 * Version 0.1.5 released, 0.1.6 opened for further work.
4816
4851
4817 * Changed magic_env to *return* the environment as a dict (not to
4852 * Changed magic_env to *return* the environment as a dict (not to
4818 print it). This way it prints, but it can also be processed.
4853 print it). This way it prints, but it can also be processed.
4819
4854
4820 * Added Verbose exception reporting to interactive
4855 * Added Verbose exception reporting to interactive
4821 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4856 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4822 traceback. Had to make some changes to the ultraTB file. This is
4857 traceback. Had to make some changes to the ultraTB file. This is
4823 probably the last 'big' thing in my mental todo list. This ties
4858 probably the last 'big' thing in my mental todo list. This ties
4824 in with the next entry:
4859 in with the next entry:
4825
4860
4826 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4861 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4827 has to specify is Plain, Color or Verbose for all exception
4862 has to specify is Plain, Color or Verbose for all exception
4828 handling.
4863 handling.
4829
4864
4830 * Removed ShellServices option. All this can really be done via
4865 * Removed ShellServices option. All this can really be done via
4831 the magic system. It's easier to extend, cleaner and has automatic
4866 the magic system. It's easier to extend, cleaner and has automatic
4832 namespace protection and documentation.
4867 namespace protection and documentation.
4833
4868
4834 2001-11-09 Fernando Perez <fperez@colorado.edu>
4869 2001-11-09 Fernando Perez <fperez@colorado.edu>
4835
4870
4836 * Fixed bug in output cache flushing (missing parameter to
4871 * Fixed bug in output cache flushing (missing parameter to
4837 __init__). Other small bugs fixed (found using pychecker).
4872 __init__). Other small bugs fixed (found using pychecker).
4838
4873
4839 * Version 0.1.4 opened for bugfixing.
4874 * Version 0.1.4 opened for bugfixing.
4840
4875
4841 2001-11-07 Fernando Perez <fperez@colorado.edu>
4876 2001-11-07 Fernando Perez <fperez@colorado.edu>
4842
4877
4843 * Version 0.1.3 released, mainly because of the raw_input bug.
4878 * Version 0.1.3 released, mainly because of the raw_input bug.
4844
4879
4845 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4880 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4846 and when testing for whether things were callable, a call could
4881 and when testing for whether things were callable, a call could
4847 actually be made to certain functions. They would get called again
4882 actually be made to certain functions. They would get called again
4848 once 'really' executed, with a resulting double call. A disaster
4883 once 'really' executed, with a resulting double call. A disaster
4849 in many cases (list.reverse() would never work!).
4884 in many cases (list.reverse() would never work!).
4850
4885
4851 * Removed prefilter() function, moved its code to raw_input (which
4886 * Removed prefilter() function, moved its code to raw_input (which
4852 after all was just a near-empty caller for prefilter). This saves
4887 after all was just a near-empty caller for prefilter). This saves
4853 a function call on every prompt, and simplifies the class a tiny bit.
4888 a function call on every prompt, and simplifies the class a tiny bit.
4854
4889
4855 * Fix _ip to __ip name in magic example file.
4890 * Fix _ip to __ip name in magic example file.
4856
4891
4857 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4892 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4858 work with non-gnu versions of tar.
4893 work with non-gnu versions of tar.
4859
4894
4860 2001-11-06 Fernando Perez <fperez@colorado.edu>
4895 2001-11-06 Fernando Perez <fperez@colorado.edu>
4861
4896
4862 * Version 0.1.2. Just to keep track of the recent changes.
4897 * Version 0.1.2. Just to keep track of the recent changes.
4863
4898
4864 * Fixed nasty bug in output prompt routine. It used to check 'if
4899 * Fixed nasty bug in output prompt routine. It used to check 'if
4865 arg != None...'. Problem is, this fails if arg implements a
4900 arg != None...'. Problem is, this fails if arg implements a
4866 special comparison (__cmp__) which disallows comparing to
4901 special comparison (__cmp__) which disallows comparing to
4867 None. Found it when trying to use the PhysicalQuantity module from
4902 None. Found it when trying to use the PhysicalQuantity module from
4868 ScientificPython.
4903 ScientificPython.
4869
4904
4870 2001-11-05 Fernando Perez <fperez@colorado.edu>
4905 2001-11-05 Fernando Perez <fperez@colorado.edu>
4871
4906
4872 * Also added dirs. Now the pushd/popd/dirs family functions
4907 * Also added dirs. Now the pushd/popd/dirs family functions
4873 basically like the shell, with the added convenience of going home
4908 basically like the shell, with the added convenience of going home
4874 when called with no args.
4909 when called with no args.
4875
4910
4876 * pushd/popd slightly modified to mimic shell behavior more
4911 * pushd/popd slightly modified to mimic shell behavior more
4877 closely.
4912 closely.
4878
4913
4879 * Added env,pushd,popd from ShellServices as magic functions. I
4914 * Added env,pushd,popd from ShellServices as magic functions. I
4880 think the cleanest will be to port all desired functions from
4915 think the cleanest will be to port all desired functions from
4881 ShellServices as magics and remove ShellServices altogether. This
4916 ShellServices as magics and remove ShellServices altogether. This
4882 will provide a single, clean way of adding functionality
4917 will provide a single, clean way of adding functionality
4883 (shell-type or otherwise) to IP.
4918 (shell-type or otherwise) to IP.
4884
4919
4885 2001-11-04 Fernando Perez <fperez@colorado.edu>
4920 2001-11-04 Fernando Perez <fperez@colorado.edu>
4886
4921
4887 * Added .ipython/ directory to sys.path. This way users can keep
4922 * Added .ipython/ directory to sys.path. This way users can keep
4888 customizations there and access them via import.
4923 customizations there and access them via import.
4889
4924
4890 2001-11-03 Fernando Perez <fperez@colorado.edu>
4925 2001-11-03 Fernando Perez <fperez@colorado.edu>
4891
4926
4892 * Opened version 0.1.1 for new changes.
4927 * Opened version 0.1.1 for new changes.
4893
4928
4894 * Changed version number to 0.1.0: first 'public' release, sent to
4929 * Changed version number to 0.1.0: first 'public' release, sent to
4895 Nathan and Janko.
4930 Nathan and Janko.
4896
4931
4897 * Lots of small fixes and tweaks.
4932 * Lots of small fixes and tweaks.
4898
4933
4899 * Minor changes to whos format. Now strings are shown, snipped if
4934 * Minor changes to whos format. Now strings are shown, snipped if
4900 too long.
4935 too long.
4901
4936
4902 * Changed ShellServices to work on __main__ so they show up in @who
4937 * Changed ShellServices to work on __main__ so they show up in @who
4903
4938
4904 * Help also works with ? at the end of a line:
4939 * Help also works with ? at the end of a line:
4905 ?sin and sin?
4940 ?sin and sin?
4906 both produce the same effect. This is nice, as often I use the
4941 both produce the same effect. This is nice, as often I use the
4907 tab-complete to find the name of a method, but I used to then have
4942 tab-complete to find the name of a method, but I used to then have
4908 to go to the beginning of the line to put a ? if I wanted more
4943 to go to the beginning of the line to put a ? if I wanted more
4909 info. Now I can just add the ? and hit return. Convenient.
4944 info. Now I can just add the ? and hit return. Convenient.
4910
4945
4911 2001-11-02 Fernando Perez <fperez@colorado.edu>
4946 2001-11-02 Fernando Perez <fperez@colorado.edu>
4912
4947
4913 * Python version check (>=2.1) added.
4948 * Python version check (>=2.1) added.
4914
4949
4915 * Added LazyPython documentation. At this point the docs are quite
4950 * Added LazyPython documentation. At this point the docs are quite
4916 a mess. A cleanup is in order.
4951 a mess. A cleanup is in order.
4917
4952
4918 * Auto-installer created. For some bizarre reason, the zipfiles
4953 * Auto-installer created. For some bizarre reason, the zipfiles
4919 module isn't working on my system. So I made a tar version
4954 module isn't working on my system. So I made a tar version
4920 (hopefully the command line options in various systems won't kill
4955 (hopefully the command line options in various systems won't kill
4921 me).
4956 me).
4922
4957
4923 * Fixes to Struct in genutils. Now all dictionary-like methods are
4958 * Fixes to Struct in genutils. Now all dictionary-like methods are
4924 protected (reasonably).
4959 protected (reasonably).
4925
4960
4926 * Added pager function to genutils and changed ? to print usage
4961 * Added pager function to genutils and changed ? to print usage
4927 note through it (it was too long).
4962 note through it (it was too long).
4928
4963
4929 * Added the LazyPython functionality. Works great! I changed the
4964 * Added the LazyPython functionality. Works great! I changed the
4930 auto-quote escape to ';', it's on home row and next to '. But
4965 auto-quote escape to ';', it's on home row and next to '. But
4931 both auto-quote and auto-paren (still /) escapes are command-line
4966 both auto-quote and auto-paren (still /) escapes are command-line
4932 parameters.
4967 parameters.
4933
4968
4934
4969
4935 2001-11-01 Fernando Perez <fperez@colorado.edu>
4970 2001-11-01 Fernando Perez <fperez@colorado.edu>
4936
4971
4937 * Version changed to 0.0.7. Fairly large change: configuration now
4972 * Version changed to 0.0.7. Fairly large change: configuration now
4938 is all stored in a directory, by default .ipython. There, all
4973 is all stored in a directory, by default .ipython. There, all
4939 config files have normal looking names (not .names)
4974 config files have normal looking names (not .names)
4940
4975
4941 * Version 0.0.6 Released first to Lucas and Archie as a test
4976 * Version 0.0.6 Released first to Lucas and Archie as a test
4942 run. Since it's the first 'semi-public' release, change version to
4977 run. Since it's the first 'semi-public' release, change version to
4943 > 0.0.6 for any changes now.
4978 > 0.0.6 for any changes now.
4944
4979
4945 * Stuff I had put in the ipplib.py changelog:
4980 * Stuff I had put in the ipplib.py changelog:
4946
4981
4947 Changes to InteractiveShell:
4982 Changes to InteractiveShell:
4948
4983
4949 - Made the usage message a parameter.
4984 - Made the usage message a parameter.
4950
4985
4951 - Require the name of the shell variable to be given. It's a bit
4986 - Require the name of the shell variable to be given. It's a bit
4952 of a hack, but allows the name 'shell' not to be hardwire in the
4987 of a hack, but allows the name 'shell' not to be hardwire in the
4953 magic (@) handler, which is problematic b/c it requires
4988 magic (@) handler, which is problematic b/c it requires
4954 polluting the global namespace with 'shell'. This in turn is
4989 polluting the global namespace with 'shell'. This in turn is
4955 fragile: if a user redefines a variable called shell, things
4990 fragile: if a user redefines a variable called shell, things
4956 break.
4991 break.
4957
4992
4958 - magic @: all functions available through @ need to be defined
4993 - magic @: all functions available through @ need to be defined
4959 as magic_<name>, even though they can be called simply as
4994 as magic_<name>, even though they can be called simply as
4960 @<name>. This allows the special command @magic to gather
4995 @<name>. This allows the special command @magic to gather
4961 information automatically about all existing magic functions,
4996 information automatically about all existing magic functions,
4962 even if they are run-time user extensions, by parsing the shell
4997 even if they are run-time user extensions, by parsing the shell
4963 instance __dict__ looking for special magic_ names.
4998 instance __dict__ looking for special magic_ names.
4964
4999
4965 - mainloop: added *two* local namespace parameters. This allows
5000 - mainloop: added *two* local namespace parameters. This allows
4966 the class to differentiate between parameters which were there
5001 the class to differentiate between parameters which were there
4967 before and after command line initialization was processed. This
5002 before and after command line initialization was processed. This
4968 way, later @who can show things loaded at startup by the
5003 way, later @who can show things loaded at startup by the
4969 user. This trick was necessary to make session saving/reloading
5004 user. This trick was necessary to make session saving/reloading
4970 really work: ideally after saving/exiting/reloading a session,
5005 really work: ideally after saving/exiting/reloading a session,
4971 *everythin* should look the same, including the output of @who. I
5006 *everythin* should look the same, including the output of @who. I
4972 was only able to make this work with this double namespace
5007 was only able to make this work with this double namespace
4973 trick.
5008 trick.
4974
5009
4975 - added a header to the logfile which allows (almost) full
5010 - added a header to the logfile which allows (almost) full
4976 session restoring.
5011 session restoring.
4977
5012
4978 - prepend lines beginning with @ or !, with a and log
5013 - prepend lines beginning with @ or !, with a and log
4979 them. Why? !lines: may be useful to know what you did @lines:
5014 them. Why? !lines: may be useful to know what you did @lines:
4980 they may affect session state. So when restoring a session, at
5015 they may affect session state. So when restoring a session, at
4981 least inform the user of their presence. I couldn't quite get
5016 least inform the user of their presence. I couldn't quite get
4982 them to properly re-execute, but at least the user is warned.
5017 them to properly re-execute, but at least the user is warned.
4983
5018
4984 * Started ChangeLog.
5019 * Started ChangeLog.
General Comments 0
You need to be logged in to leave comments. Login now