##// END OF EJS Templates
New demo class, very handy for interactive presentations.
fperez -
Show More
@@ -0,0 +1,115 b''
1 """Module for interactive demos using IPython.
2 """
3 #*****************************************************************************
4 # Copyright (C) 2005 Fernando Perez. <Fernando.Perez@colorado.edu>
5 #
6 # Distributed under the terms of the BSD License. The full license is in
7 # the file COPYING, distributed as part of this software.
8 #
9 #*****************************************************************************
10
11 import exceptions
12
13 from IPython.PyColorize import Parser
14 from IPython.genutils import marquee
15
16 class DemoError(exceptions.Exception): pass
17
18 class Demo:
19 def __init__(self,fname,pause_mark='# pause',auto=False):
20
21 self.fname = fname
22 self.pause_mark = pause_mark
23 self.auto = auto
24
25 # get a few things from ipython. While it's a bit ugly design-wise,
26 # it ensures that things like color scheme and the like are always in
27 # sync with the ipython mode being used. This class is only meant to
28 # be used inside ipython anyways, so it's OK.
29 self.ip_showtraceback = __IPYTHON__.showtraceback
30 self.ip_ns = __IPYTHON__.user_ns
31 self.ip_colors = __IPYTHON__.rc['colors']
32
33 # read data and parse into blocks
34 fobj = file(fname,'r')
35 self.src = fobj.read()
36 fobj.close()
37 self.src_blocks = [b.strip() for b in self.src.split(pause_mark) if b]
38 self.nblocks = len(self.src_blocks)
39
40 # try to colorize blocks
41 colorize = Parser().format
42 col_scheme = self.ip_colors
43 self.src_blocks_colored = [colorize(s_blk,'str',col_scheme)
44 for s_blk in self.src_blocks]
45
46 # finish initialization
47 self.reset()
48
49 def reset(self):
50 self.user_ns = {}
51 self.finished = False
52 self.block_index = 0
53
54 def again(self):
55 self.block_index -= 1
56 self()
57
58
59 def _validate_index(self,index):
60 if index<0 or index>=self.nblocks:
61 raise ValueError('invalid block index %s' % index)
62
63 def seek(self,index):
64 self._validate_index(index)
65 self.block_index = index-1
66 self.finished = False
67
68 def show(self,index=None):
69 if index is None:
70 index = self.block_index
71 else:
72 self._validate_index(index)
73 print marquee('<%s> block # %s (%s/%s)' %
74 (self.fname,index,index+1,self.nblocks))
75 print self.src_blocks_colored[index],
76
77 def __call__(self,index=None):
78 """run a block of the demo.
79
80 If index is given, it should be an integer >=1 and <= nblocks. This
81 means that the calling convention is one off from typical Python
82 lists. The reason for the inconsistency is that the demo always
83 prints 'Block n/N, and N is the total, so it would be very odd to use
84 zero-indexing here."""
85
86 if index is None and self.finished:
87 print 'Demo finished. Use reset() if you want to rerun it.'
88 return
89 if index is None:
90 index = self.block_index
91 self._validate_index(index)
92 try:
93 next_block = self.src_blocks[index]
94 self.block_index += 1
95 self.show(index)
96 if not self.auto:
97 print marquee('Press <q> to quit, <Enter> to execute...'),
98 ans = raw_input().strip()
99 if ans:
100 print marquee('Block NOT executed')
101 return
102
103 exec next_block in self.user_ns
104
105 except:
106 self.ip_showtraceback(filename=self.fname)
107 else:
108 self.ip_ns.update(self.user_ns)
109
110 if self.block_index == self.nblocks:
111 print
112 print marquee(' END OF DEMO ')
113 print marquee('Use reset() if you want to rerun it.')
114 self.finished = True
115
@@ -1,1530 +1,1540 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 874 2005-09-20 20:13:04Z fperez $"""
8 $Id: genutils.py 894 2005-09-22 07:16:18Z fperez $"""
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2004 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
24 # required modules
25 import __main__
25 import __main__
26 import types,commands,time,sys,os,re,shutil
26 import types,commands,time,sys,os,re,shutil
27 import tempfile
27 import tempfile
28 from IPython.Itpl import Itpl,itpl,printpl
28 from IPython.Itpl import Itpl,itpl,printpl
29 from IPython import DPyGetOpt
29 from IPython import DPyGetOpt
30
30
31 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
31 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
32 # 2.2-friendly
32 # 2.2-friendly
33 try:
33 try:
34 basestring
34 basestring
35 except NameError:
35 except NameError:
36 import types
36 import types
37 basestring = (types.StringType, types.UnicodeType)
37 basestring = (types.StringType, types.UnicodeType)
38 True = 1==1
38 True = 1==1
39 False = 1==0
39 False = 1==0
40
40
41 def enumerate(obj):
41 def enumerate(obj):
42 i = -1
42 i = -1
43 for item in obj:
43 for item in obj:
44 i += 1
44 i += 1
45 yield i, item
45 yield i, item
46
46
47 # add these to the builtin namespace, so that all modules find them
47 # add these to the builtin namespace, so that all modules find them
48 import __builtin__
48 import __builtin__
49 __builtin__.basestring = basestring
49 __builtin__.basestring = basestring
50 __builtin__.True = True
50 __builtin__.True = True
51 __builtin__.False = False
51 __builtin__.False = False
52 __builtin__.enumerate = enumerate
52 __builtin__.enumerate = enumerate
53
53
54 #****************************************************************************
54 #****************************************************************************
55 # Exceptions
55 # Exceptions
56 class Error(Exception):
56 class Error(Exception):
57 """Base class for exceptions in this module."""
57 """Base class for exceptions in this module."""
58 pass
58 pass
59
59
60 #----------------------------------------------------------------------------
60 #----------------------------------------------------------------------------
61 class IOStream:
61 class IOStream:
62 def __init__(self,stream,fallback):
62 def __init__(self,stream,fallback):
63 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
63 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
64 stream = fallback
64 stream = fallback
65 self.stream = stream
65 self.stream = stream
66 self._swrite = stream.write
66 self._swrite = stream.write
67 self.flush = stream.flush
67 self.flush = stream.flush
68
68
69 def write(self,data):
69 def write(self,data):
70 try:
70 try:
71 self._swrite(data)
71 self._swrite(data)
72 except:
72 except:
73 try:
73 try:
74 # print handles some unicode issues which may trip a plain
74 # print handles some unicode issues which may trip a plain
75 # write() call. Attempt to emulate write() by using a
75 # write() call. Attempt to emulate write() by using a
76 # trailing comma
76 # trailing comma
77 print >> self.stream, data,
77 print >> self.stream, data,
78 except:
78 except:
79 # if we get here, something is seriously broken.
79 # if we get here, something is seriously broken.
80 print >> sys.stderr, \
80 print >> sys.stderr, \
81 'ERROR - failed to write data to stream:', stream
81 'ERROR - failed to write data to stream:', stream
82
82
83 class IOTerm:
83 class IOTerm:
84 """ Term holds the file or file-like objects for handling I/O operations.
84 """ Term holds the file or file-like objects for handling I/O operations.
85
85
86 These are normally just sys.stdin, sys.stdout and sys.stderr but for
86 These are normally just sys.stdin, sys.stdout and sys.stderr but for
87 Windows they can can replaced to allow editing the strings before they are
87 Windows they can can replaced to allow editing the strings before they are
88 displayed."""
88 displayed."""
89
89
90 # In the future, having IPython channel all its I/O operations through
90 # In the future, having IPython channel all its I/O operations through
91 # this class will make it easier to embed it into other environments which
91 # this class will make it easier to embed it into other environments which
92 # are not a normal terminal (such as a GUI-based shell)
92 # are not a normal terminal (such as a GUI-based shell)
93 def __init__(self,cin=None,cout=None,cerr=None):
93 def __init__(self,cin=None,cout=None,cerr=None):
94 self.cin = IOStream(cin,sys.stdin)
94 self.cin = IOStream(cin,sys.stdin)
95 self.cout = IOStream(cout,sys.stdout)
95 self.cout = IOStream(cout,sys.stdout)
96 self.cerr = IOStream(cerr,sys.stderr)
96 self.cerr = IOStream(cerr,sys.stderr)
97
97
98 # Global variable to be used for all I/O
98 # Global variable to be used for all I/O
99 Term = IOTerm()
99 Term = IOTerm()
100
100
101 # Windows-specific code to load Gary Bishop's readline and configure it
101 # Windows-specific code to load Gary Bishop's readline and configure it
102 # automatically for the users
102 # automatically for the users
103 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
103 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
104 # windows. Cygwin returns 'cygwin' for sys.platform.
104 # windows. Cygwin returns 'cygwin' for sys.platform.
105 if os.name == 'nt':
105 if os.name == 'nt':
106 try:
106 try:
107 import readline
107 import readline
108 except ImportError:
108 except ImportError:
109 pass
109 pass
110 else:
110 else:
111 try:
111 try:
112 _out = readline.GetOutputFile()
112 _out = readline.GetOutputFile()
113 except AttributeError:
113 except AttributeError:
114 pass
114 pass
115 else:
115 else:
116 # Remake Term to use the readline i/o facilities
116 # Remake Term to use the readline i/o facilities
117 Term = IOTerm(cout=_out,cerr=_out)
117 Term = IOTerm(cout=_out,cerr=_out)
118 del _out
118 del _out
119
119
120 #****************************************************************************
120 #****************************************************************************
121 # Generic warning/error printer, used by everything else
121 # Generic warning/error printer, used by everything else
122 def warn(msg,level=2,exit_val=1):
122 def warn(msg,level=2,exit_val=1):
123 """Standard warning printer. Gives formatting consistency.
123 """Standard warning printer. Gives formatting consistency.
124
124
125 Output is sent to Term.cerr (sys.stderr by default).
125 Output is sent to Term.cerr (sys.stderr by default).
126
126
127 Options:
127 Options:
128
128
129 -level(2): allows finer control:
129 -level(2): allows finer control:
130 0 -> Do nothing, dummy function.
130 0 -> Do nothing, dummy function.
131 1 -> Print message.
131 1 -> Print message.
132 2 -> Print 'WARNING:' + message. (Default level).
132 2 -> Print 'WARNING:' + message. (Default level).
133 3 -> Print 'ERROR:' + message.
133 3 -> Print 'ERROR:' + message.
134 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
134 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
135
135
136 -exit_val (1): exit value returned by sys.exit() for a level 4
136 -exit_val (1): exit value returned by sys.exit() for a level 4
137 warning. Ignored for all other levels."""
137 warning. Ignored for all other levels."""
138
138
139 if level>0:
139 if level>0:
140 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
140 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
141 print >> Term.cerr, '%s%s' % (header[level],msg)
141 print >> Term.cerr, '%s%s' % (header[level],msg)
142 if level == 4:
142 if level == 4:
143 print >> Term.cerr,'Exiting.\n'
143 print >> Term.cerr,'Exiting.\n'
144 sys.exit(exit_val)
144 sys.exit(exit_val)
145
145
146 def info(msg):
146 def info(msg):
147 """Equivalent to warn(msg,level=1)."""
147 """Equivalent to warn(msg,level=1)."""
148
148
149 warn(msg,level=1)
149 warn(msg,level=1)
150
150
151 def error(msg):
151 def error(msg):
152 """Equivalent to warn(msg,level=3)."""
152 """Equivalent to warn(msg,level=3)."""
153
153
154 warn(msg,level=3)
154 warn(msg,level=3)
155
155
156 def fatal(msg,exit_val=1):
156 def fatal(msg,exit_val=1):
157 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
157 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
158
158
159 warn(msg,exit_val=exit_val,level=4)
159 warn(msg,exit_val=exit_val,level=4)
160
160
161 #----------------------------------------------------------------------------
161 #----------------------------------------------------------------------------
162 StringTypes = types.StringTypes
162 StringTypes = types.StringTypes
163
163
164 # Basic timing functionality
164 # Basic timing functionality
165
165
166 # If possible (Unix), use the resource module instead of time.clock()
166 # If possible (Unix), use the resource module instead of time.clock()
167 try:
167 try:
168 import resource
168 import resource
169 def clock():
169 def clock():
170 """clock() -> floating point number
170 """clock() -> floating point number
171
171
172 Return the CPU time in seconds (user time only, system time is
172 Return the CPU time in seconds (user time only, system time is
173 ignored) since the start of the process. This is done via a call to
173 ignored) since the start of the process. This is done via a call to
174 resource.getrusage, so it avoids the wraparound problems in
174 resource.getrusage, so it avoids the wraparound problems in
175 time.clock()."""
175 time.clock()."""
176
176
177 return resource.getrusage(resource.RUSAGE_SELF)[0]
177 return resource.getrusage(resource.RUSAGE_SELF)[0]
178
178
179 def clock2():
179 def clock2():
180 """clock2() -> (t_user,t_system)
180 """clock2() -> (t_user,t_system)
181
181
182 Similar to clock(), but return a tuple of user/system times."""
182 Similar to clock(), but return a tuple of user/system times."""
183 return resource.getrusage(resource.RUSAGE_SELF)[:2]
183 return resource.getrusage(resource.RUSAGE_SELF)[:2]
184
184
185 except ImportError:
185 except ImportError:
186 clock = time.clock
186 clock = time.clock
187 def clock2():
187 def clock2():
188 """Under windows, system CPU time can't be measured.
188 """Under windows, system CPU time can't be measured.
189
189
190 This just returns clock() and zero."""
190 This just returns clock() and zero."""
191 return time.clock(),0.0
191 return time.clock(),0.0
192
192
193 def timings_out(reps,func,*args,**kw):
193 def timings_out(reps,func,*args,**kw):
194 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
194 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
195
195
196 Execute a function reps times, return a tuple with the elapsed total
196 Execute a function reps times, return a tuple with the elapsed total
197 CPU time in seconds, the time per call and the function's output.
197 CPU time in seconds, the time per call and the function's output.
198
198
199 Under Unix, the return value is the sum of user+system time consumed by
199 Under Unix, the return value is the sum of user+system time consumed by
200 the process, computed via the resource module. This prevents problems
200 the process, computed via the resource module. This prevents problems
201 related to the wraparound effect which the time.clock() function has.
201 related to the wraparound effect which the time.clock() function has.
202
202
203 Under Windows the return value is in wall clock seconds. See the
203 Under Windows the return value is in wall clock seconds. See the
204 documentation for the time module for more details."""
204 documentation for the time module for more details."""
205
205
206 reps = int(reps)
206 reps = int(reps)
207 assert reps >=1, 'reps must be >= 1'
207 assert reps >=1, 'reps must be >= 1'
208 if reps==1:
208 if reps==1:
209 start = clock()
209 start = clock()
210 out = func(*args,**kw)
210 out = func(*args,**kw)
211 tot_time = clock()-start
211 tot_time = clock()-start
212 else:
212 else:
213 rng = xrange(reps-1) # the last time is executed separately to store output
213 rng = xrange(reps-1) # the last time is executed separately to store output
214 start = clock()
214 start = clock()
215 for dummy in rng: func(*args,**kw)
215 for dummy in rng: func(*args,**kw)
216 out = func(*args,**kw) # one last time
216 out = func(*args,**kw) # one last time
217 tot_time = clock()-start
217 tot_time = clock()-start
218 av_time = tot_time / reps
218 av_time = tot_time / reps
219 return tot_time,av_time,out
219 return tot_time,av_time,out
220
220
221 def timings(reps,func,*args,**kw):
221 def timings(reps,func,*args,**kw):
222 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
222 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
223
223
224 Execute a function reps times, return a tuple with the elapsed total CPU
224 Execute a function reps times, return a tuple with the elapsed total CPU
225 time in seconds and the time per call. These are just the first two values
225 time in seconds and the time per call. These are just the first two values
226 in timings_out()."""
226 in timings_out()."""
227
227
228 return timings_out(reps,func,*args,**kw)[0:2]
228 return timings_out(reps,func,*args,**kw)[0:2]
229
229
230 def timing(func,*args,**kw):
230 def timing(func,*args,**kw):
231 """timing(func,*args,**kw) -> t_total
231 """timing(func,*args,**kw) -> t_total
232
232
233 Execute a function once, return the elapsed total CPU time in
233 Execute a function once, return the elapsed total CPU time in
234 seconds. This is just the first value in timings_out()."""
234 seconds. This is just the first value in timings_out()."""
235
235
236 return timings_out(1,func,*args,**kw)[0]
236 return timings_out(1,func,*args,**kw)[0]
237
237
238 #****************************************************************************
238 #****************************************************************************
239 # file and system
239 # file and system
240
240
241 def system(cmd,verbose=0,debug=0,header=''):
241 def system(cmd,verbose=0,debug=0,header=''):
242 """Execute a system command, return its exit status.
242 """Execute a system command, return its exit status.
243
243
244 Options:
244 Options:
245
245
246 - verbose (0): print the command to be executed.
246 - verbose (0): print the command to be executed.
247
247
248 - debug (0): only print, do not actually execute.
248 - debug (0): only print, do not actually execute.
249
249
250 - header (''): Header to print on screen prior to the executed command (it
250 - header (''): Header to print on screen prior to the executed command (it
251 is only prepended to the command, no newlines are added).
251 is only prepended to the command, no newlines are added).
252
252
253 Note: a stateful version of this function is available through the
253 Note: a stateful version of this function is available through the
254 SystemExec class."""
254 SystemExec class."""
255
255
256 stat = 0
256 stat = 0
257 if verbose or debug: print header+cmd
257 if verbose or debug: print header+cmd
258 sys.stdout.flush()
258 sys.stdout.flush()
259 if not debug: stat = os.system(cmd)
259 if not debug: stat = os.system(cmd)
260 return stat
260 return stat
261
261
262 def shell(cmd,verbose=0,debug=0,header=''):
262 def shell(cmd,verbose=0,debug=0,header=''):
263 """Execute a command in the system shell, always return None.
263 """Execute a command in the system shell, always return None.
264
264
265 Options:
265 Options:
266
266
267 - verbose (0): print the command to be executed.
267 - verbose (0): print the command to be executed.
268
268
269 - debug (0): only print, do not actually execute.
269 - debug (0): only print, do not actually execute.
270
270
271 - header (''): Header to print on screen prior to the executed command (it
271 - header (''): Header to print on screen prior to the executed command (it
272 is only prepended to the command, no newlines are added).
272 is only prepended to the command, no newlines are added).
273
273
274 Note: this is similar to genutils.system(), but it returns None so it can
274 Note: this is similar to genutils.system(), but it returns None so it can
275 be conveniently used in interactive loops without getting the return value
275 be conveniently used in interactive loops without getting the return value
276 (typically 0) printed many times."""
276 (typically 0) printed many times."""
277
277
278 stat = 0
278 stat = 0
279 if verbose or debug: print header+cmd
279 if verbose or debug: print header+cmd
280 # flush stdout so we don't mangle python's buffering
280 # flush stdout so we don't mangle python's buffering
281 sys.stdout.flush()
281 sys.stdout.flush()
282 if not debug:
282 if not debug:
283 os.system(cmd)
283 os.system(cmd)
284
284
285 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
285 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
286 """Dummy substitute for perl's backquotes.
286 """Dummy substitute for perl's backquotes.
287
287
288 Executes a command and returns the output.
288 Executes a command and returns the output.
289
289
290 Accepts the same arguments as system(), plus:
290 Accepts the same arguments as system(), plus:
291
291
292 - split(0): if true, the output is returned as a list split on newlines.
292 - split(0): if true, the output is returned as a list split on newlines.
293
293
294 Note: a stateful version of this function is available through the
294 Note: a stateful version of this function is available through the
295 SystemExec class."""
295 SystemExec class."""
296
296
297 if verbose or debug: print header+cmd
297 if verbose or debug: print header+cmd
298 if not debug:
298 if not debug:
299 output = commands.getoutput(cmd)
299 output = commands.getoutput(cmd)
300 if split:
300 if split:
301 return output.split('\n')
301 return output.split('\n')
302 else:
302 else:
303 return output
303 return output
304
304
305 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
305 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
306 """Return (standard output,standard error) of executing cmd in a shell.
306 """Return (standard output,standard error) of executing cmd in a shell.
307
307
308 Accepts the same arguments as system(), plus:
308 Accepts the same arguments as system(), plus:
309
309
310 - split(0): if true, each of stdout/err is returned as a list split on
310 - split(0): if true, each of stdout/err is returned as a list split on
311 newlines.
311 newlines.
312
312
313 Note: a stateful version of this function is available through the
313 Note: a stateful version of this function is available through the
314 SystemExec class."""
314 SystemExec class."""
315
315
316 if verbose or debug: print header+cmd
316 if verbose or debug: print header+cmd
317 if not cmd:
317 if not cmd:
318 if split:
318 if split:
319 return [],[]
319 return [],[]
320 else:
320 else:
321 return '',''
321 return '',''
322 if not debug:
322 if not debug:
323 pin,pout,perr = os.popen3(cmd)
323 pin,pout,perr = os.popen3(cmd)
324 tout = pout.read().rstrip()
324 tout = pout.read().rstrip()
325 terr = perr.read().rstrip()
325 terr = perr.read().rstrip()
326 pin.close()
326 pin.close()
327 pout.close()
327 pout.close()
328 perr.close()
328 perr.close()
329 if split:
329 if split:
330 return tout.split('\n'),terr.split('\n')
330 return tout.split('\n'),terr.split('\n')
331 else:
331 else:
332 return tout,terr
332 return tout,terr
333
333
334 # for compatibility with older naming conventions
334 # for compatibility with older naming conventions
335 xsys = system
335 xsys = system
336 bq = getoutput
336 bq = getoutput
337
337
338 class SystemExec:
338 class SystemExec:
339 """Access the system and getoutput functions through a stateful interface.
339 """Access the system and getoutput functions through a stateful interface.
340
340
341 Note: here we refer to the system and getoutput functions from this
341 Note: here we refer to the system and getoutput functions from this
342 library, not the ones from the standard python library.
342 library, not the ones from the standard python library.
343
343
344 This class offers the system and getoutput functions as methods, but the
344 This class offers the system and getoutput functions as methods, but the
345 verbose, debug and header parameters can be set for the instance (at
345 verbose, debug and header parameters can be set for the instance (at
346 creation time or later) so that they don't need to be specified on each
346 creation time or later) so that they don't need to be specified on each
347 call.
347 call.
348
348
349 For efficiency reasons, there's no way to override the parameters on a
349 For efficiency reasons, there's no way to override the parameters on a
350 per-call basis other than by setting instance attributes. If you need
350 per-call basis other than by setting instance attributes. If you need
351 local overrides, it's best to directly call system() or getoutput().
351 local overrides, it's best to directly call system() or getoutput().
352
352
353 The following names are provided as alternate options:
353 The following names are provided as alternate options:
354 - xsys: alias to system
354 - xsys: alias to system
355 - bq: alias to getoutput
355 - bq: alias to getoutput
356
356
357 An instance can then be created as:
357 An instance can then be created as:
358 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
358 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
359
359
360 And used as:
360 And used as:
361 >>> sysexec.xsys('pwd')
361 >>> sysexec.xsys('pwd')
362 >>> dirlist = sysexec.bq('ls -l')
362 >>> dirlist = sysexec.bq('ls -l')
363 """
363 """
364
364
365 def __init__(self,verbose=0,debug=0,header='',split=0):
365 def __init__(self,verbose=0,debug=0,header='',split=0):
366 """Specify the instance's values for verbose, debug and header."""
366 """Specify the instance's values for verbose, debug and header."""
367 setattr_list(self,'verbose debug header split')
367 setattr_list(self,'verbose debug header split')
368
368
369 def system(self,cmd):
369 def system(self,cmd):
370 """Stateful interface to system(), with the same keyword parameters."""
370 """Stateful interface to system(), with the same keyword parameters."""
371
371
372 system(cmd,self.verbose,self.debug,self.header)
372 system(cmd,self.verbose,self.debug,self.header)
373
373
374 def shell(self,cmd):
374 def shell(self,cmd):
375 """Stateful interface to shell(), with the same keyword parameters."""
375 """Stateful interface to shell(), with the same keyword parameters."""
376
376
377 shell(cmd,self.verbose,self.debug,self.header)
377 shell(cmd,self.verbose,self.debug,self.header)
378
378
379 xsys = system # alias
379 xsys = system # alias
380
380
381 def getoutput(self,cmd):
381 def getoutput(self,cmd):
382 """Stateful interface to getoutput()."""
382 """Stateful interface to getoutput()."""
383
383
384 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
384 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
385
385
386 def getoutputerror(self,cmd):
386 def getoutputerror(self,cmd):
387 """Stateful interface to getoutputerror()."""
387 """Stateful interface to getoutputerror()."""
388
388
389 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
389 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
390
390
391 bq = getoutput # alias
391 bq = getoutput # alias
392
392
393 #-----------------------------------------------------------------------------
393 #-----------------------------------------------------------------------------
394 def mutex_opts(dict,ex_op):
394 def mutex_opts(dict,ex_op):
395 """Check for presence of mutually exclusive keys in a dict.
395 """Check for presence of mutually exclusive keys in a dict.
396
396
397 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
397 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
398 for op1,op2 in ex_op:
398 for op1,op2 in ex_op:
399 if op1 in dict and op2 in dict:
399 if op1 in dict and op2 in dict:
400 raise ValueError,'\n*** ERROR in Arguments *** '\
400 raise ValueError,'\n*** ERROR in Arguments *** '\
401 'Options '+op1+' and '+op2+' are mutually exclusive.'
401 'Options '+op1+' and '+op2+' are mutually exclusive.'
402
402
403 #-----------------------------------------------------------------------------
403 #-----------------------------------------------------------------------------
404 def filefind(fname,alt_dirs = None):
404 def filefind(fname,alt_dirs = None):
405 """Return the given filename either in the current directory, if it
405 """Return the given filename either in the current directory, if it
406 exists, or in a specified list of directories.
406 exists, or in a specified list of directories.
407
407
408 ~ expansion is done on all file and directory names.
408 ~ expansion is done on all file and directory names.
409
409
410 Upon an unsuccessful search, raise an IOError exception."""
410 Upon an unsuccessful search, raise an IOError exception."""
411
411
412 if alt_dirs is None:
412 if alt_dirs is None:
413 try:
413 try:
414 alt_dirs = get_home_dir()
414 alt_dirs = get_home_dir()
415 except HomeDirError:
415 except HomeDirError:
416 alt_dirs = os.getcwd()
416 alt_dirs = os.getcwd()
417 search = [fname] + list_strings(alt_dirs)
417 search = [fname] + list_strings(alt_dirs)
418 search = map(os.path.expanduser,search)
418 search = map(os.path.expanduser,search)
419 #print 'search list for',fname,'list:',search # dbg
419 #print 'search list for',fname,'list:',search # dbg
420 fname = search[0]
420 fname = search[0]
421 if os.path.isfile(fname):
421 if os.path.isfile(fname):
422 return fname
422 return fname
423 for direc in search[1:]:
423 for direc in search[1:]:
424 testname = os.path.join(direc,fname)
424 testname = os.path.join(direc,fname)
425 #print 'testname',testname # dbg
425 #print 'testname',testname # dbg
426 if os.path.isfile(testname):
426 if os.path.isfile(testname):
427 return testname
427 return testname
428 raise IOError,'File' + `fname` + \
428 raise IOError,'File' + `fname` + \
429 ' not found in current or supplied directories:' + `alt_dirs`
429 ' not found in current or supplied directories:' + `alt_dirs`
430
430
431 #----------------------------------------------------------------------------
431 #----------------------------------------------------------------------------
432 def target_outdated(target,deps):
432 def target_outdated(target,deps):
433 """Determine whether a target is out of date.
433 """Determine whether a target is out of date.
434
434
435 target_outdated(target,deps) -> 1/0
435 target_outdated(target,deps) -> 1/0
436
436
437 deps: list of filenames which MUST exist.
437 deps: list of filenames which MUST exist.
438 target: single filename which may or may not exist.
438 target: single filename which may or may not exist.
439
439
440 If target doesn't exist or is older than any file listed in deps, return
440 If target doesn't exist or is older than any file listed in deps, return
441 true, otherwise return false.
441 true, otherwise return false.
442 """
442 """
443 try:
443 try:
444 target_time = os.path.getmtime(target)
444 target_time = os.path.getmtime(target)
445 except os.error:
445 except os.error:
446 return 1
446 return 1
447 for dep in deps:
447 for dep in deps:
448 dep_time = os.path.getmtime(dep)
448 dep_time = os.path.getmtime(dep)
449 if dep_time > target_time:
449 if dep_time > target_time:
450 #print "For target",target,"Dep failed:",dep # dbg
450 #print "For target",target,"Dep failed:",dep # dbg
451 #print "times (dep,tar):",dep_time,target_time # dbg
451 #print "times (dep,tar):",dep_time,target_time # dbg
452 return 1
452 return 1
453 return 0
453 return 0
454
454
455 #-----------------------------------------------------------------------------
455 #-----------------------------------------------------------------------------
456 def target_update(target,deps,cmd):
456 def target_update(target,deps,cmd):
457 """Update a target with a given command given a list of dependencies.
457 """Update a target with a given command given a list of dependencies.
458
458
459 target_update(target,deps,cmd) -> runs cmd if target is outdated.
459 target_update(target,deps,cmd) -> runs cmd if target is outdated.
460
460
461 This is just a wrapper around target_outdated() which calls the given
461 This is just a wrapper around target_outdated() which calls the given
462 command if target is outdated."""
462 command if target is outdated."""
463
463
464 if target_outdated(target,deps):
464 if target_outdated(target,deps):
465 xsys(cmd)
465 xsys(cmd)
466
466
467 #----------------------------------------------------------------------------
467 #----------------------------------------------------------------------------
468 def unquote_ends(istr):
468 def unquote_ends(istr):
469 """Remove a single pair of quotes from the endpoints of a string."""
469 """Remove a single pair of quotes from the endpoints of a string."""
470
470
471 if not istr:
471 if not istr:
472 return istr
472 return istr
473 if (istr[0]=="'" and istr[-1]=="'") or \
473 if (istr[0]=="'" and istr[-1]=="'") or \
474 (istr[0]=='"' and istr[-1]=='"'):
474 (istr[0]=='"' and istr[-1]=='"'):
475 return istr[1:-1]
475 return istr[1:-1]
476 else:
476 else:
477 return istr
477 return istr
478
478
479 #----------------------------------------------------------------------------
479 #----------------------------------------------------------------------------
480 def process_cmdline(argv,names=[],defaults={},usage=''):
480 def process_cmdline(argv,names=[],defaults={},usage=''):
481 """ Process command-line options and arguments.
481 """ Process command-line options and arguments.
482
482
483 Arguments:
483 Arguments:
484
484
485 - argv: list of arguments, typically sys.argv.
485 - argv: list of arguments, typically sys.argv.
486
486
487 - names: list of option names. See DPyGetOpt docs for details on options
487 - names: list of option names. See DPyGetOpt docs for details on options
488 syntax.
488 syntax.
489
489
490 - defaults: dict of default values.
490 - defaults: dict of default values.
491
491
492 - usage: optional usage notice to print if a wrong argument is passed.
492 - usage: optional usage notice to print if a wrong argument is passed.
493
493
494 Return a dict of options and a list of free arguments."""
494 Return a dict of options and a list of free arguments."""
495
495
496 getopt = DPyGetOpt.DPyGetOpt()
496 getopt = DPyGetOpt.DPyGetOpt()
497 getopt.setIgnoreCase(0)
497 getopt.setIgnoreCase(0)
498 getopt.parseConfiguration(names)
498 getopt.parseConfiguration(names)
499
499
500 try:
500 try:
501 getopt.processArguments(argv)
501 getopt.processArguments(argv)
502 except:
502 except:
503 print usage
503 print usage
504 warn(`sys.exc_value`,level=4)
504 warn(`sys.exc_value`,level=4)
505
505
506 defaults.update(getopt.optionValues)
506 defaults.update(getopt.optionValues)
507 args = getopt.freeValues
507 args = getopt.freeValues
508
508
509 return defaults,args
509 return defaults,args
510
510
511 #----------------------------------------------------------------------------
511 #----------------------------------------------------------------------------
512 def optstr2types(ostr):
512 def optstr2types(ostr):
513 """Convert a string of option names to a dict of type mappings.
513 """Convert a string of option names to a dict of type mappings.
514
514
515 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
515 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
516
516
517 This is used to get the types of all the options in a string formatted
517 This is used to get the types of all the options in a string formatted
518 with the conventions of DPyGetOpt. The 'type' None is used for options
518 with the conventions of DPyGetOpt. The 'type' None is used for options
519 which are strings (they need no further conversion). This function's main
519 which are strings (they need no further conversion). This function's main
520 use is to get a typemap for use with read_dict().
520 use is to get a typemap for use with read_dict().
521 """
521 """
522
522
523 typeconv = {None:'',int:'',float:''}
523 typeconv = {None:'',int:'',float:''}
524 typemap = {'s':None,'i':int,'f':float}
524 typemap = {'s':None,'i':int,'f':float}
525 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
525 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
526
526
527 for w in ostr.split():
527 for w in ostr.split():
528 oname,alias,otype = opt_re.match(w).groups()
528 oname,alias,otype = opt_re.match(w).groups()
529 if otype == '' or alias == '!': # simple switches are integers too
529 if otype == '' or alias == '!': # simple switches are integers too
530 otype = 'i'
530 otype = 'i'
531 typeconv[typemap[otype]] += oname + ' '
531 typeconv[typemap[otype]] += oname + ' '
532 return typeconv
532 return typeconv
533
533
534 #----------------------------------------------------------------------------
534 #----------------------------------------------------------------------------
535 def read_dict(filename,type_conv=None,**opt):
535 def read_dict(filename,type_conv=None,**opt):
536
536
537 """Read a dictionary of key=value pairs from an input file, optionally
537 """Read a dictionary of key=value pairs from an input file, optionally
538 performing conversions on the resulting values.
538 performing conversions on the resulting values.
539
539
540 read_dict(filename,type_conv,**opt) -> dict
540 read_dict(filename,type_conv,**opt) -> dict
541
541
542 Only one value per line is accepted, the format should be
542 Only one value per line is accepted, the format should be
543 # optional comments are ignored
543 # optional comments are ignored
544 key value\n
544 key value\n
545
545
546 Args:
546 Args:
547
547
548 - type_conv: A dictionary specifying which keys need to be converted to
548 - type_conv: A dictionary specifying which keys need to be converted to
549 which types. By default all keys are read as strings. This dictionary
549 which types. By default all keys are read as strings. This dictionary
550 should have as its keys valid conversion functions for strings
550 should have as its keys valid conversion functions for strings
551 (int,long,float,complex, or your own). The value for each key
551 (int,long,float,complex, or your own). The value for each key
552 (converter) should be a whitespace separated string containing the names
552 (converter) should be a whitespace separated string containing the names
553 of all the entries in the file to be converted using that function. For
553 of all the entries in the file to be converted using that function. For
554 keys to be left alone, use None as the conversion function (only needed
554 keys to be left alone, use None as the conversion function (only needed
555 with purge=1, see below).
555 with purge=1, see below).
556
556
557 - opt: dictionary with extra options as below (default in parens)
557 - opt: dictionary with extra options as below (default in parens)
558
558
559 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
559 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
560 of the dictionary to be returned. If purge is going to be used, the
560 of the dictionary to be returned. If purge is going to be used, the
561 set of keys to be left as strings also has to be explicitly specified
561 set of keys to be left as strings also has to be explicitly specified
562 using the (non-existent) conversion function None.
562 using the (non-existent) conversion function None.
563
563
564 fs(None): field separator. This is the key/value separator to be used
564 fs(None): field separator. This is the key/value separator to be used
565 when parsing the file. The None default means any whitespace [behavior
565 when parsing the file. The None default means any whitespace [behavior
566 of string.split()].
566 of string.split()].
567
567
568 strip(0): if 1, strip string values of leading/trailinig whitespace.
568 strip(0): if 1, strip string values of leading/trailinig whitespace.
569
569
570 warn(1): warning level if requested keys are not found in file.
570 warn(1): warning level if requested keys are not found in file.
571 - 0: silently ignore.
571 - 0: silently ignore.
572 - 1: inform but proceed.
572 - 1: inform but proceed.
573 - 2: raise KeyError exception.
573 - 2: raise KeyError exception.
574
574
575 no_empty(0): if 1, remove keys with whitespace strings as a value.
575 no_empty(0): if 1, remove keys with whitespace strings as a value.
576
576
577 unique([]): list of keys (or space separated string) which can't be
577 unique([]): list of keys (or space separated string) which can't be
578 repeated. If one such key is found in the file, each new instance
578 repeated. If one such key is found in the file, each new instance
579 overwrites the previous one. For keys not listed here, the behavior is
579 overwrites the previous one. For keys not listed here, the behavior is
580 to make a list of all appearances.
580 to make a list of all appearances.
581
581
582 Example:
582 Example:
583 If the input file test.ini has:
583 If the input file test.ini has:
584 i 3
584 i 3
585 x 4.5
585 x 4.5
586 y 5.5
586 y 5.5
587 s hi ho
587 s hi ho
588 Then:
588 Then:
589
589
590 >>> type_conv={int:'i',float:'x',None:'s'}
590 >>> type_conv={int:'i',float:'x',None:'s'}
591 >>> read_dict('test.ini')
591 >>> read_dict('test.ini')
592 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
592 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
593 >>> read_dict('test.ini',type_conv)
593 >>> read_dict('test.ini',type_conv)
594 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
594 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
595 >>> read_dict('test.ini',type_conv,purge=1)
595 >>> read_dict('test.ini',type_conv,purge=1)
596 {'i': 3, 's': 'hi ho', 'x': 4.5}
596 {'i': 3, 's': 'hi ho', 'x': 4.5}
597 """
597 """
598
598
599 # starting config
599 # starting config
600 opt.setdefault('purge',0)
600 opt.setdefault('purge',0)
601 opt.setdefault('fs',None) # field sep defaults to any whitespace
601 opt.setdefault('fs',None) # field sep defaults to any whitespace
602 opt.setdefault('strip',0)
602 opt.setdefault('strip',0)
603 opt.setdefault('warn',1)
603 opt.setdefault('warn',1)
604 opt.setdefault('no_empty',0)
604 opt.setdefault('no_empty',0)
605 opt.setdefault('unique','')
605 opt.setdefault('unique','')
606 if type(opt['unique']) in StringTypes:
606 if type(opt['unique']) in StringTypes:
607 unique_keys = qw(opt['unique'])
607 unique_keys = qw(opt['unique'])
608 elif type(opt['unique']) in (types.TupleType,types.ListType):
608 elif type(opt['unique']) in (types.TupleType,types.ListType):
609 unique_keys = opt['unique']
609 unique_keys = opt['unique']
610 else:
610 else:
611 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
611 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
612
612
613 dict = {}
613 dict = {}
614 # first read in table of values as strings
614 # first read in table of values as strings
615 file = open(filename,'r')
615 file = open(filename,'r')
616 for line in file.readlines():
616 for line in file.readlines():
617 line = line.strip()
617 line = line.strip()
618 if len(line) and line[0]=='#': continue
618 if len(line) and line[0]=='#': continue
619 if len(line)>0:
619 if len(line)>0:
620 lsplit = line.split(opt['fs'],1)
620 lsplit = line.split(opt['fs'],1)
621 try:
621 try:
622 key,val = lsplit
622 key,val = lsplit
623 except ValueError:
623 except ValueError:
624 key,val = lsplit[0],''
624 key,val = lsplit[0],''
625 key = key.strip()
625 key = key.strip()
626 if opt['strip']: val = val.strip()
626 if opt['strip']: val = val.strip()
627 if val == "''" or val == '""': val = ''
627 if val == "''" or val == '""': val = ''
628 if opt['no_empty'] and (val=='' or val.isspace()):
628 if opt['no_empty'] and (val=='' or val.isspace()):
629 continue
629 continue
630 # if a key is found more than once in the file, build a list
630 # if a key is found more than once in the file, build a list
631 # unless it's in the 'unique' list. In that case, last found in file
631 # unless it's in the 'unique' list. In that case, last found in file
632 # takes precedence. User beware.
632 # takes precedence. User beware.
633 try:
633 try:
634 if dict[key] and key in unique_keys:
634 if dict[key] and key in unique_keys:
635 dict[key] = val
635 dict[key] = val
636 elif type(dict[key]) is types.ListType:
636 elif type(dict[key]) is types.ListType:
637 dict[key].append(val)
637 dict[key].append(val)
638 else:
638 else:
639 dict[key] = [dict[key],val]
639 dict[key] = [dict[key],val]
640 except KeyError:
640 except KeyError:
641 dict[key] = val
641 dict[key] = val
642 # purge if requested
642 # purge if requested
643 if opt['purge']:
643 if opt['purge']:
644 accepted_keys = qwflat(type_conv.values())
644 accepted_keys = qwflat(type_conv.values())
645 for key in dict.keys():
645 for key in dict.keys():
646 if key in accepted_keys: continue
646 if key in accepted_keys: continue
647 del(dict[key])
647 del(dict[key])
648 # now convert if requested
648 # now convert if requested
649 if type_conv==None: return dict
649 if type_conv==None: return dict
650 conversions = type_conv.keys()
650 conversions = type_conv.keys()
651 try: conversions.remove(None)
651 try: conversions.remove(None)
652 except: pass
652 except: pass
653 for convert in conversions:
653 for convert in conversions:
654 for val in qw(type_conv[convert]):
654 for val in qw(type_conv[convert]):
655 try:
655 try:
656 dict[val] = convert(dict[val])
656 dict[val] = convert(dict[val])
657 except KeyError,e:
657 except KeyError,e:
658 if opt['warn'] == 0:
658 if opt['warn'] == 0:
659 pass
659 pass
660 elif opt['warn'] == 1:
660 elif opt['warn'] == 1:
661 print >>sys.stderr, 'Warning: key',val,\
661 print >>sys.stderr, 'Warning: key',val,\
662 'not found in file',filename
662 'not found in file',filename
663 elif opt['warn'] == 2:
663 elif opt['warn'] == 2:
664 raise KeyError,e
664 raise KeyError,e
665 else:
665 else:
666 raise ValueError,'Warning level must be 0,1 or 2'
666 raise ValueError,'Warning level must be 0,1 or 2'
667
667
668 return dict
668 return dict
669
669
670 #----------------------------------------------------------------------------
670 #----------------------------------------------------------------------------
671 def flag_calls(func):
671 def flag_calls(func):
672 """Wrap a function to detect and flag when it gets called.
672 """Wrap a function to detect and flag when it gets called.
673
673
674 This is a decorator which takes a function and wraps it in a function with
674 This is a decorator which takes a function and wraps it in a function with
675 a 'called' attribute. wrapper.called is initialized to False.
675 a 'called' attribute. wrapper.called is initialized to False.
676
676
677 The wrapper.called attribute is set to False right before each call to the
677 The wrapper.called attribute is set to False right before each call to the
678 wrapped function, so if the call fails it remains False. After the call
678 wrapped function, so if the call fails it remains False. After the call
679 completes, wrapper.called is set to True and the output is returned.
679 completes, wrapper.called is set to True and the output is returned.
680
680
681 Testing for truth in wrapper.called allows you to determine if a call to
681 Testing for truth in wrapper.called allows you to determine if a call to
682 func() was attempted and succeeded."""
682 func() was attempted and succeeded."""
683
683
684 def wrapper(*args,**kw):
684 def wrapper(*args,**kw):
685 wrapper.called = False
685 wrapper.called = False
686 out = func(*args,**kw)
686 out = func(*args,**kw)
687 wrapper.called = True
687 wrapper.called = True
688 return out
688 return out
689
689
690 wrapper.called = False
690 wrapper.called = False
691 wrapper.__doc__ = func.__doc__
691 wrapper.__doc__ = func.__doc__
692 return wrapper
692 return wrapper
693
693
694 #----------------------------------------------------------------------------
694 #----------------------------------------------------------------------------
695 class HomeDirError(Error):
695 class HomeDirError(Error):
696 pass
696 pass
697
697
698 def get_home_dir():
698 def get_home_dir():
699 """Return the closest possible equivalent to a 'home' directory.
699 """Return the closest possible equivalent to a 'home' directory.
700
700
701 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
701 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
702
702
703 Currently only Posix and NT are implemented, a HomeDirError exception is
703 Currently only Posix and NT are implemented, a HomeDirError exception is
704 raised for all other OSes. """
704 raised for all other OSes. """
705
705
706 isdir = os.path.isdir
706 isdir = os.path.isdir
707 env = os.environ
707 env = os.environ
708 try:
708 try:
709 homedir = env['HOME']
709 homedir = env['HOME']
710 if not isdir(homedir):
710 if not isdir(homedir):
711 # in case a user stuck some string which does NOT resolve to a
711 # in case a user stuck some string which does NOT resolve to a
712 # valid path, it's as good as if we hadn't foud it
712 # valid path, it's as good as if we hadn't foud it
713 raise KeyError
713 raise KeyError
714 return homedir
714 return homedir
715 except KeyError:
715 except KeyError:
716 if os.name == 'posix':
716 if os.name == 'posix':
717 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
717 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
718 elif os.name == 'nt':
718 elif os.name == 'nt':
719 # For some strange reason, win9x returns 'nt' for os.name.
719 # For some strange reason, win9x returns 'nt' for os.name.
720 try:
720 try:
721 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
721 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
722 if not isdir(homedir):
722 if not isdir(homedir):
723 homedir = os.path.join(env['USERPROFILE'])
723 homedir = os.path.join(env['USERPROFILE'])
724 if not isdir(homedir):
724 if not isdir(homedir):
725 raise HomeDirError
725 raise HomeDirError
726 return homedir
726 return homedir
727 except:
727 except:
728 try:
728 try:
729 # Use the registry to get the 'My Documents' folder.
729 # Use the registry to get the 'My Documents' folder.
730 import _winreg as wreg
730 import _winreg as wreg
731 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
731 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
732 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
732 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
733 homedir = wreg.QueryValueEx(key,'Personal')[0]
733 homedir = wreg.QueryValueEx(key,'Personal')[0]
734 key.Close()
734 key.Close()
735 if not isdir(homedir):
735 if not isdir(homedir):
736 e = ('Invalid "Personal" folder registry key '
736 e = ('Invalid "Personal" folder registry key '
737 'typically "My Documents".\n'
737 'typically "My Documents".\n'
738 'Value: %s\n'
738 'Value: %s\n'
739 'This is not a valid directory on your system.' %
739 'This is not a valid directory on your system.' %
740 homedir)
740 homedir)
741 raise HomeDirError(e)
741 raise HomeDirError(e)
742 return homedir
742 return homedir
743 except HomeDirError:
743 except HomeDirError:
744 raise
744 raise
745 except:
745 except:
746 return 'C:\\'
746 return 'C:\\'
747 elif os.name == 'dos':
747 elif os.name == 'dos':
748 # Desperate, may do absurd things in classic MacOS. May work under DOS.
748 # Desperate, may do absurd things in classic MacOS. May work under DOS.
749 return 'C:\\'
749 return 'C:\\'
750 else:
750 else:
751 raise HomeDirError,'support for your operating system not implemented.'
751 raise HomeDirError,'support for your operating system not implemented.'
752
752
753 #****************************************************************************
753 #****************************************************************************
754 # strings and text
754 # strings and text
755
755
756 class LSString(str):
756 class LSString(str):
757 """String derivative with a special access attributes.
757 """String derivative with a special access attributes.
758
758
759 These are normal strings, but with the special attributes:
759 These are normal strings, but with the special attributes:
760
760
761 .l (or .list) : value as list (split on newlines).
761 .l (or .list) : value as list (split on newlines).
762 .n (or .nlstr): original value (the string itself).
762 .n (or .nlstr): original value (the string itself).
763 .s (or .spstr): value as whitespace-separated string.
763 .s (or .spstr): value as whitespace-separated string.
764
764
765 Any values which require transformations are computed only once and
765 Any values which require transformations are computed only once and
766 cached.
766 cached.
767
767
768 Such strings are very useful to efficiently interact with the shell, which
768 Such strings are very useful to efficiently interact with the shell, which
769 typically only understands whitespace-separated options for commands."""
769 typically only understands whitespace-separated options for commands."""
770
770
771 def get_list(self):
771 def get_list(self):
772 try:
772 try:
773 return self.__list
773 return self.__list
774 except AttributeError:
774 except AttributeError:
775 self.__list = self.split('\n')
775 self.__list = self.split('\n')
776 return self.__list
776 return self.__list
777
777
778 l = list = property(get_list)
778 l = list = property(get_list)
779
779
780 def get_spstr(self):
780 def get_spstr(self):
781 try:
781 try:
782 return self.__spstr
782 return self.__spstr
783 except AttributeError:
783 except AttributeError:
784 self.__spstr = self.replace('\n',' ')
784 self.__spstr = self.replace('\n',' ')
785 return self.__spstr
785 return self.__spstr
786
786
787 s = spstr = property(get_spstr)
787 s = spstr = property(get_spstr)
788
788
789 def get_nlstr(self):
789 def get_nlstr(self):
790 return self
790 return self
791
791
792 n = nlstr = property(get_nlstr)
792 n = nlstr = property(get_nlstr)
793
793
794 class SList(list):
794 class SList(list):
795 """List derivative with a special access attributes.
795 """List derivative with a special access attributes.
796
796
797 These are normal lists, but with the special attributes:
797 These are normal lists, but with the special attributes:
798
798
799 .l (or .list) : value as list (the list itself).
799 .l (or .list) : value as list (the list itself).
800 .n (or .nlstr): value as a string, joined on newlines.
800 .n (or .nlstr): value as a string, joined on newlines.
801 .s (or .spstr): value as a string, joined on spaces.
801 .s (or .spstr): value as a string, joined on spaces.
802
802
803 Any values which require transformations are computed only once and
803 Any values which require transformations are computed only once and
804 cached."""
804 cached."""
805
805
806 def get_list(self):
806 def get_list(self):
807 return self
807 return self
808
808
809 l = list = property(get_list)
809 l = list = property(get_list)
810
810
811 def get_spstr(self):
811 def get_spstr(self):
812 try:
812 try:
813 return self.__spstr
813 return self.__spstr
814 except AttributeError:
814 except AttributeError:
815 self.__spstr = ' '.join(self)
815 self.__spstr = ' '.join(self)
816 return self.__spstr
816 return self.__spstr
817
817
818 s = spstr = property(get_spstr)
818 s = spstr = property(get_spstr)
819
819
820 def get_nlstr(self):
820 def get_nlstr(self):
821 try:
821 try:
822 return self.__nlstr
822 return self.__nlstr
823 except AttributeError:
823 except AttributeError:
824 self.__nlstr = '\n'.join(self)
824 self.__nlstr = '\n'.join(self)
825 return self.__nlstr
825 return self.__nlstr
826
826
827 n = nlstr = property(get_nlstr)
827 n = nlstr = property(get_nlstr)
828
828
829 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
829 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
830 """Take multiple lines of input.
830 """Take multiple lines of input.
831
831
832 A list with each line of input as a separate element is returned when a
832 A list with each line of input as a separate element is returned when a
833 termination string is entered (defaults to a single '.'). Input can also
833 termination string is entered (defaults to a single '.'). Input can also
834 terminate via EOF (^D in Unix, ^Z-RET in Windows).
834 terminate via EOF (^D in Unix, ^Z-RET in Windows).
835
835
836 Lines of input which end in \\ are joined into single entries (and a
836 Lines of input which end in \\ are joined into single entries (and a
837 secondary continuation prompt is issued as long as the user terminates
837 secondary continuation prompt is issued as long as the user terminates
838 lines with \\). This allows entering very long strings which are still
838 lines with \\). This allows entering very long strings which are still
839 meant to be treated as single entities.
839 meant to be treated as single entities.
840 """
840 """
841
841
842 try:
842 try:
843 if header:
843 if header:
844 header += '\n'
844 header += '\n'
845 lines = [raw_input(header + ps1)]
845 lines = [raw_input(header + ps1)]
846 except EOFError:
846 except EOFError:
847 return []
847 return []
848 terminate = [terminate_str]
848 terminate = [terminate_str]
849 try:
849 try:
850 while lines[-1:] != terminate:
850 while lines[-1:] != terminate:
851 new_line = raw_input(ps1)
851 new_line = raw_input(ps1)
852 while new_line.endswith('\\'):
852 while new_line.endswith('\\'):
853 new_line = new_line[:-1] + raw_input(ps2)
853 new_line = new_line[:-1] + raw_input(ps2)
854 lines.append(new_line)
854 lines.append(new_line)
855
855
856 return lines[:-1] # don't return the termination command
856 return lines[:-1] # don't return the termination command
857 except EOFError:
857 except EOFError:
858 print
858 print
859 return lines
859 return lines
860
860
861 #----------------------------------------------------------------------------
861 #----------------------------------------------------------------------------
862 def raw_input_ext(prompt='', ps2='... '):
862 def raw_input_ext(prompt='', ps2='... '):
863 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
863 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
864
864
865 line = raw_input(prompt)
865 line = raw_input(prompt)
866 while line.endswith('\\'):
866 while line.endswith('\\'):
867 line = line[:-1] + raw_input(ps2)
867 line = line[:-1] + raw_input(ps2)
868 return line
868 return line
869
869
870 #----------------------------------------------------------------------------
870 #----------------------------------------------------------------------------
871 def ask_yes_no(prompt,default=None):
871 def ask_yes_no(prompt,default=None):
872 """Asks a question and returns an integer 1/0 (y/n) answer.
872 """Asks a question and returns an integer 1/0 (y/n) answer.
873
873
874 If default is given (one of 'y','n'), it is used if the user input is
874 If default is given (one of 'y','n'), it is used if the user input is
875 empty. Otherwise the question is repeated until an answer is given.
875 empty. Otherwise the question is repeated until an answer is given.
876 If EOF occurs 20 times consecutively, the default answer is assumed,
876 If EOF occurs 20 times consecutively, the default answer is assumed,
877 or if there is no default, an exception is raised to prevent infinite
877 or if there is no default, an exception is raised to prevent infinite
878 loops.
878 loops.
879
879
880 Valid answers are: y/yes/n/no (match is not case sensitive)."""
880 Valid answers are: y/yes/n/no (match is not case sensitive)."""
881
881
882 answers = {'y':1,'n':0,'yes':1,'no':0}
882 answers = {'y':1,'n':0,'yes':1,'no':0}
883 ans = None
883 ans = None
884 eofs, max_eofs = 0, 20
884 eofs, max_eofs = 0, 20
885 while ans not in answers.keys():
885 while ans not in answers.keys():
886 try:
886 try:
887 ans = raw_input(prompt+' ').lower()
887 ans = raw_input(prompt+' ').lower()
888 if not ans: # response was an empty string
888 if not ans: # response was an empty string
889 ans = default
889 ans = default
890 eofs = 0
890 eofs = 0
891 except (EOFError,KeyboardInterrupt):
891 except (EOFError,KeyboardInterrupt):
892 eofs = eofs + 1
892 eofs = eofs + 1
893 if eofs >= max_eofs:
893 if eofs >= max_eofs:
894 if default in answers.keys():
894 if default in answers.keys():
895 ans = default
895 ans = default
896 else:
896 else:
897 raise
897 raise
898
898
899 return answers[ans]
899 return answers[ans]
900
900
901 #----------------------------------------------------------------------------
901 #----------------------------------------------------------------------------
902 def marquee(txt='',width=80,mark='*'):
903 """Return the input string centered in a 'marquee'."""
904 if not txt:
905 return (mark*width)[:width]
906 nmark = (width-len(txt)-2)/len(mark)/2
907 if nmark < 0: nmark =0
908 marks = mark*nmark
909 return '%s %s %s' % (marks,txt,marks)
910
911 #----------------------------------------------------------------------------
902 class EvalDict:
912 class EvalDict:
903 """
913 """
904 Emulate a dict which evaluates its contents in the caller's frame.
914 Emulate a dict which evaluates its contents in the caller's frame.
905
915
906 Usage:
916 Usage:
907 >>>number = 19
917 >>>number = 19
908 >>>text = "python"
918 >>>text = "python"
909 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
919 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
910 """
920 """
911
921
912 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
922 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
913 # modified (shorter) version of:
923 # modified (shorter) version of:
914 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
924 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
915 # Skip Montanaro (skip@pobox.com).
925 # Skip Montanaro (skip@pobox.com).
916
926
917 def __getitem__(self, name):
927 def __getitem__(self, name):
918 frame = sys._getframe(1)
928 frame = sys._getframe(1)
919 return eval(name, frame.f_globals, frame.f_locals)
929 return eval(name, frame.f_globals, frame.f_locals)
920
930
921 EvalString = EvalDict # for backwards compatibility
931 EvalString = EvalDict # for backwards compatibility
922 #----------------------------------------------------------------------------
932 #----------------------------------------------------------------------------
923 def qw(words,flat=0,sep=None,maxsplit=-1):
933 def qw(words,flat=0,sep=None,maxsplit=-1):
924 """Similar to Perl's qw() operator, but with some more options.
934 """Similar to Perl's qw() operator, but with some more options.
925
935
926 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
936 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
927
937
928 words can also be a list itself, and with flat=1, the output will be
938 words can also be a list itself, and with flat=1, the output will be
929 recursively flattened. Examples:
939 recursively flattened. Examples:
930
940
931 >>> qw('1 2')
941 >>> qw('1 2')
932 ['1', '2']
942 ['1', '2']
933 >>> qw(['a b','1 2',['m n','p q']])
943 >>> qw(['a b','1 2',['m n','p q']])
934 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
944 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
935 >>> qw(['a b','1 2',['m n','p q']],flat=1)
945 >>> qw(['a b','1 2',['m n','p q']],flat=1)
936 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
946 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
937
947
938 if type(words) in StringTypes:
948 if type(words) in StringTypes:
939 return [word.strip() for word in words.split(sep,maxsplit)
949 return [word.strip() for word in words.split(sep,maxsplit)
940 if word and not word.isspace() ]
950 if word and not word.isspace() ]
941 if flat:
951 if flat:
942 return flatten(map(qw,words,[1]*len(words)))
952 return flatten(map(qw,words,[1]*len(words)))
943 return map(qw,words)
953 return map(qw,words)
944
954
945 #----------------------------------------------------------------------------
955 #----------------------------------------------------------------------------
946 def qwflat(words,sep=None,maxsplit=-1):
956 def qwflat(words,sep=None,maxsplit=-1):
947 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
957 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
948 return qw(words,1,sep,maxsplit)
958 return qw(words,1,sep,maxsplit)
949
959
950 #-----------------------------------------------------------------------------
960 #-----------------------------------------------------------------------------
951 def list_strings(arg):
961 def list_strings(arg):
952 """Always return a list of strings, given a string or list of strings
962 """Always return a list of strings, given a string or list of strings
953 as input."""
963 as input."""
954
964
955 if type(arg) in StringTypes: return [arg]
965 if type(arg) in StringTypes: return [arg]
956 else: return arg
966 else: return arg
957
967
958 #----------------------------------------------------------------------------
968 #----------------------------------------------------------------------------
959 def grep(pat,list,case=1):
969 def grep(pat,list,case=1):
960 """Simple minded grep-like function.
970 """Simple minded grep-like function.
961 grep(pat,list) returns occurrences of pat in list, None on failure.
971 grep(pat,list) returns occurrences of pat in list, None on failure.
962
972
963 It only does simple string matching, with no support for regexps. Use the
973 It only does simple string matching, with no support for regexps. Use the
964 option case=0 for case-insensitive matching."""
974 option case=0 for case-insensitive matching."""
965
975
966 # This is pretty crude. At least it should implement copying only references
976 # This is pretty crude. At least it should implement copying only references
967 # to the original data in case it's big. Now it copies the data for output.
977 # to the original data in case it's big. Now it copies the data for output.
968 out=[]
978 out=[]
969 if case:
979 if case:
970 for term in list:
980 for term in list:
971 if term.find(pat)>-1: out.append(term)
981 if term.find(pat)>-1: out.append(term)
972 else:
982 else:
973 lpat=pat.lower()
983 lpat=pat.lower()
974 for term in list:
984 for term in list:
975 if term.lower().find(lpat)>-1: out.append(term)
985 if term.lower().find(lpat)>-1: out.append(term)
976
986
977 if len(out): return out
987 if len(out): return out
978 else: return None
988 else: return None
979
989
980 #----------------------------------------------------------------------------
990 #----------------------------------------------------------------------------
981 def dgrep(pat,*opts):
991 def dgrep(pat,*opts):
982 """Return grep() on dir()+dir(__builtins__).
992 """Return grep() on dir()+dir(__builtins__).
983
993
984 A very common use of grep() when working interactively."""
994 A very common use of grep() when working interactively."""
985
995
986 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
996 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
987
997
988 #----------------------------------------------------------------------------
998 #----------------------------------------------------------------------------
989 def idgrep(pat):
999 def idgrep(pat):
990 """Case-insensitive dgrep()"""
1000 """Case-insensitive dgrep()"""
991
1001
992 return dgrep(pat,0)
1002 return dgrep(pat,0)
993
1003
994 #----------------------------------------------------------------------------
1004 #----------------------------------------------------------------------------
995 def igrep(pat,list):
1005 def igrep(pat,list):
996 """Synonym for case-insensitive grep."""
1006 """Synonym for case-insensitive grep."""
997
1007
998 return grep(pat,list,case=0)
1008 return grep(pat,list,case=0)
999
1009
1000 #----------------------------------------------------------------------------
1010 #----------------------------------------------------------------------------
1001 def indent(str,nspaces=4,ntabs=0):
1011 def indent(str,nspaces=4,ntabs=0):
1002 """Indent a string a given number of spaces or tabstops.
1012 """Indent a string a given number of spaces or tabstops.
1003
1013
1004 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1014 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1005 """
1015 """
1006 if str is None:
1016 if str is None:
1007 return
1017 return
1008 ind = '\t'*ntabs+' '*nspaces
1018 ind = '\t'*ntabs+' '*nspaces
1009 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1019 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1010 if outstr.endswith(os.linesep+ind):
1020 if outstr.endswith(os.linesep+ind):
1011 return outstr[:-len(ind)]
1021 return outstr[:-len(ind)]
1012 else:
1022 else:
1013 return outstr
1023 return outstr
1014
1024
1015 #-----------------------------------------------------------------------------
1025 #-----------------------------------------------------------------------------
1016 def native_line_ends(filename,backup=1):
1026 def native_line_ends(filename,backup=1):
1017 """Convert (in-place) a file to line-ends native to the current OS.
1027 """Convert (in-place) a file to line-ends native to the current OS.
1018
1028
1019 If the optional backup argument is given as false, no backup of the
1029 If the optional backup argument is given as false, no backup of the
1020 original file is left. """
1030 original file is left. """
1021
1031
1022 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1032 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1023
1033
1024 bak_filename = filename + backup_suffixes[os.name]
1034 bak_filename = filename + backup_suffixes[os.name]
1025
1035
1026 original = open(filename).read()
1036 original = open(filename).read()
1027 shutil.copy2(filename,bak_filename)
1037 shutil.copy2(filename,bak_filename)
1028 try:
1038 try:
1029 new = open(filename,'wb')
1039 new = open(filename,'wb')
1030 new.write(os.linesep.join(original.splitlines()))
1040 new.write(os.linesep.join(original.splitlines()))
1031 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1041 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1032 new.close()
1042 new.close()
1033 except:
1043 except:
1034 os.rename(bak_filename,filename)
1044 os.rename(bak_filename,filename)
1035 if not backup:
1045 if not backup:
1036 try:
1046 try:
1037 os.remove(bak_filename)
1047 os.remove(bak_filename)
1038 except:
1048 except:
1039 pass
1049 pass
1040
1050
1041 #----------------------------------------------------------------------------
1051 #----------------------------------------------------------------------------
1042 def get_pager_cmd(pager_cmd = None):
1052 def get_pager_cmd(pager_cmd = None):
1043 """Return a pager command.
1053 """Return a pager command.
1044
1054
1045 Makes some attempts at finding an OS-correct one."""
1055 Makes some attempts at finding an OS-correct one."""
1046
1056
1047 if os.name == 'posix':
1057 if os.name == 'posix':
1048 default_pager_cmd = 'less -r' # -r for color control sequences
1058 default_pager_cmd = 'less -r' # -r for color control sequences
1049 elif os.name in ['nt','dos']:
1059 elif os.name in ['nt','dos']:
1050 default_pager_cmd = 'type'
1060 default_pager_cmd = 'type'
1051
1061
1052 if pager_cmd is None:
1062 if pager_cmd is None:
1053 try:
1063 try:
1054 pager_cmd = os.environ['PAGER']
1064 pager_cmd = os.environ['PAGER']
1055 except:
1065 except:
1056 pager_cmd = default_pager_cmd
1066 pager_cmd = default_pager_cmd
1057 return pager_cmd
1067 return pager_cmd
1058
1068
1059 #-----------------------------------------------------------------------------
1069 #-----------------------------------------------------------------------------
1060 def get_pager_start(pager,start):
1070 def get_pager_start(pager,start):
1061 """Return the string for paging files with an offset.
1071 """Return the string for paging files with an offset.
1062
1072
1063 This is the '+N' argument which less and more (under Unix) accept.
1073 This is the '+N' argument which less and more (under Unix) accept.
1064 """
1074 """
1065
1075
1066 if pager in ['less','more']:
1076 if pager in ['less','more']:
1067 if start:
1077 if start:
1068 start_string = '+' + str(start)
1078 start_string = '+' + str(start)
1069 else:
1079 else:
1070 start_string = ''
1080 start_string = ''
1071 else:
1081 else:
1072 start_string = ''
1082 start_string = ''
1073 return start_string
1083 return start_string
1074
1084
1075 #----------------------------------------------------------------------------
1085 #----------------------------------------------------------------------------
1076 def page_dumb(strng,start=0,screen_lines=25):
1086 def page_dumb(strng,start=0,screen_lines=25):
1077 """Very dumb 'pager' in Python, for when nothing else works.
1087 """Very dumb 'pager' in Python, for when nothing else works.
1078
1088
1079 Only moves forward, same interface as page(), except for pager_cmd and
1089 Only moves forward, same interface as page(), except for pager_cmd and
1080 mode."""
1090 mode."""
1081
1091
1082 out_ln = strng.splitlines()[start:]
1092 out_ln = strng.splitlines()[start:]
1083 screens = chop(out_ln,screen_lines-1)
1093 screens = chop(out_ln,screen_lines-1)
1084 if len(screens) == 1:
1094 if len(screens) == 1:
1085 print >>Term.cout, os.linesep.join(screens[0])
1095 print >>Term.cout, os.linesep.join(screens[0])
1086 else:
1096 else:
1087 for scr in screens[0:-1]:
1097 for scr in screens[0:-1]:
1088 print >>Term.cout, os.linesep.join(scr)
1098 print >>Term.cout, os.linesep.join(scr)
1089 ans = raw_input('---Return to continue, q to quit--- ')
1099 ans = raw_input('---Return to continue, q to quit--- ')
1090 if ans.lower().startswith('q'):
1100 if ans.lower().startswith('q'):
1091 return
1101 return
1092 print >>Term.cout, os.linesep.join(screens[-1])
1102 print >>Term.cout, os.linesep.join(screens[-1])
1093
1103
1094 #----------------------------------------------------------------------------
1104 #----------------------------------------------------------------------------
1095 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1105 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1096 """Print a string, piping through a pager after a certain length.
1106 """Print a string, piping through a pager after a certain length.
1097
1107
1098 The screen_lines parameter specifies the number of *usable* lines of your
1108 The screen_lines parameter specifies the number of *usable* lines of your
1099 terminal screen (total lines minus lines you need to reserve to show other
1109 terminal screen (total lines minus lines you need to reserve to show other
1100 information).
1110 information).
1101
1111
1102 If you set screen_lines to a number <=0, page() will try to auto-determine
1112 If you set screen_lines to a number <=0, page() will try to auto-determine
1103 your screen size and will only use up to (screen_size+screen_lines) for
1113 your screen size and will only use up to (screen_size+screen_lines) for
1104 printing, paging after that. That is, if you want auto-detection but need
1114 printing, paging after that. That is, if you want auto-detection but need
1105 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1115 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1106 auto-detection without any lines reserved simply use screen_lines = 0.
1116 auto-detection without any lines reserved simply use screen_lines = 0.
1107
1117
1108 If a string won't fit in the allowed lines, it is sent through the
1118 If a string won't fit in the allowed lines, it is sent through the
1109 specified pager command. If none given, look for PAGER in the environment,
1119 specified pager command. If none given, look for PAGER in the environment,
1110 and ultimately default to less.
1120 and ultimately default to less.
1111
1121
1112 If no system pager works, the string is sent through a 'dumb pager'
1122 If no system pager works, the string is sent through a 'dumb pager'
1113 written in python, very simplistic.
1123 written in python, very simplistic.
1114 """
1124 """
1115
1125
1116 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1126 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1117 TERM = os.environ.get('TERM','dumb')
1127 TERM = os.environ.get('TERM','dumb')
1118 if TERM in ['dumb','emacs'] and os.name != 'nt':
1128 if TERM in ['dumb','emacs'] and os.name != 'nt':
1119 print strng
1129 print strng
1120 return
1130 return
1121 # chop off the topmost part of the string we don't want to see
1131 # chop off the topmost part of the string we don't want to see
1122 str_lines = strng.split(os.linesep)[start:]
1132 str_lines = strng.split(os.linesep)[start:]
1123 str_toprint = os.linesep.join(str_lines)
1133 str_toprint = os.linesep.join(str_lines)
1124 num_newlines = len(str_lines)
1134 num_newlines = len(str_lines)
1125 len_str = len(str_toprint)
1135 len_str = len(str_toprint)
1126
1136
1127 # Dumb heuristics to guesstimate number of on-screen lines the string
1137 # Dumb heuristics to guesstimate number of on-screen lines the string
1128 # takes. Very basic, but good enough for docstrings in reasonable
1138 # takes. Very basic, but good enough for docstrings in reasonable
1129 # terminals. If someone later feels like refining it, it's not hard.
1139 # terminals. If someone later feels like refining it, it's not hard.
1130 numlines = max(num_newlines,int(len_str/80)+1)
1140 numlines = max(num_newlines,int(len_str/80)+1)
1131
1141
1132 screen_lines_def = 25 # default value if we can't auto-determine
1142 screen_lines_def = 25 # default value if we can't auto-determine
1133
1143
1134 # auto-determine screen size
1144 # auto-determine screen size
1135 if screen_lines <= 0:
1145 if screen_lines <= 0:
1136 if TERM=='xterm':
1146 if TERM=='xterm':
1137 try:
1147 try:
1138 import curses
1148 import curses
1139 if hasattr(curses,'initscr'):
1149 if hasattr(curses,'initscr'):
1140 use_curses = 1
1150 use_curses = 1
1141 else:
1151 else:
1142 use_curses = 0
1152 use_curses = 0
1143 except ImportError:
1153 except ImportError:
1144 use_curses = 0
1154 use_curses = 0
1145 else:
1155 else:
1146 # curses causes problems on many terminals other than xterm.
1156 # curses causes problems on many terminals other than xterm.
1147 use_curses = 0
1157 use_curses = 0
1148 if use_curses:
1158 if use_curses:
1149 scr = curses.initscr()
1159 scr = curses.initscr()
1150 screen_lines_real,screen_cols = scr.getmaxyx()
1160 screen_lines_real,screen_cols = scr.getmaxyx()
1151 curses.endwin()
1161 curses.endwin()
1152 screen_lines += screen_lines_real
1162 screen_lines += screen_lines_real
1153 #print '***Screen size:',screen_lines_real,'lines x',\
1163 #print '***Screen size:',screen_lines_real,'lines x',\
1154 #screen_cols,'columns.' # dbg
1164 #screen_cols,'columns.' # dbg
1155 else:
1165 else:
1156 screen_lines += screen_lines_def
1166 screen_lines += screen_lines_def
1157
1167
1158 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1168 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1159 if numlines <= screen_lines :
1169 if numlines <= screen_lines :
1160 #print '*** normal print' # dbg
1170 #print '*** normal print' # dbg
1161 print >>Term.cout, str_toprint
1171 print >>Term.cout, str_toprint
1162 else:
1172 else:
1163 # Try to open pager and default to internal one if that fails.
1173 # Try to open pager and default to internal one if that fails.
1164 # All failure modes are tagged as 'retval=1', to match the return
1174 # All failure modes are tagged as 'retval=1', to match the return
1165 # value of a failed system command. If any intermediate attempt
1175 # value of a failed system command. If any intermediate attempt
1166 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1176 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1167 pager_cmd = get_pager_cmd(pager_cmd)
1177 pager_cmd = get_pager_cmd(pager_cmd)
1168 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1178 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1169 if os.name == 'nt':
1179 if os.name == 'nt':
1170 if pager_cmd.startswith('type'):
1180 if pager_cmd.startswith('type'):
1171 # The default WinXP 'type' command is failing on complex strings.
1181 # The default WinXP 'type' command is failing on complex strings.
1172 retval = 1
1182 retval = 1
1173 else:
1183 else:
1174 tmpname = tempfile.mktemp('.txt')
1184 tmpname = tempfile.mktemp('.txt')
1175 tmpfile = file(tmpname,'wt')
1185 tmpfile = file(tmpname,'wt')
1176 tmpfile.write(strng)
1186 tmpfile.write(strng)
1177 tmpfile.close()
1187 tmpfile.close()
1178 cmd = "%s < %s" % (pager_cmd,tmpname)
1188 cmd = "%s < %s" % (pager_cmd,tmpname)
1179 if os.system(cmd):
1189 if os.system(cmd):
1180 retval = 1
1190 retval = 1
1181 else:
1191 else:
1182 retval = None
1192 retval = None
1183 os.remove(tmpname)
1193 os.remove(tmpname)
1184 else:
1194 else:
1185 try:
1195 try:
1186 retval = None
1196 retval = None
1187 # if I use popen4, things hang. No idea why.
1197 # if I use popen4, things hang. No idea why.
1188 #pager,shell_out = os.popen4(pager_cmd)
1198 #pager,shell_out = os.popen4(pager_cmd)
1189 pager = os.popen(pager_cmd,'w')
1199 pager = os.popen(pager_cmd,'w')
1190 pager.write(strng)
1200 pager.write(strng)
1191 pager.close()
1201 pager.close()
1192 retval = pager.close() # success returns None
1202 retval = pager.close() # success returns None
1193 except IOError,msg: # broken pipe when user quits
1203 except IOError,msg: # broken pipe when user quits
1194 if msg.args == (32,'Broken pipe'):
1204 if msg.args == (32,'Broken pipe'):
1195 retval = None
1205 retval = None
1196 else:
1206 else:
1197 retval = 1
1207 retval = 1
1198 except OSError:
1208 except OSError:
1199 # Other strange problems, sometimes seen in Win2k/cygwin
1209 # Other strange problems, sometimes seen in Win2k/cygwin
1200 retval = 1
1210 retval = 1
1201 if retval is not None:
1211 if retval is not None:
1202 page_dumb(strng,screen_lines=screen_lines)
1212 page_dumb(strng,screen_lines=screen_lines)
1203
1213
1204 #----------------------------------------------------------------------------
1214 #----------------------------------------------------------------------------
1205 def page_file(fname,start = 0, pager_cmd = None):
1215 def page_file(fname,start = 0, pager_cmd = None):
1206 """Page a file, using an optional pager command and starting line.
1216 """Page a file, using an optional pager command and starting line.
1207 """
1217 """
1208
1218
1209 pager_cmd = get_pager_cmd(pager_cmd)
1219 pager_cmd = get_pager_cmd(pager_cmd)
1210 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1220 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1211
1221
1212 try:
1222 try:
1213 if os.environ['TERM'] in ['emacs','dumb']:
1223 if os.environ['TERM'] in ['emacs','dumb']:
1214 raise EnvironmentError
1224 raise EnvironmentError
1215 xsys(pager_cmd + ' ' + fname)
1225 xsys(pager_cmd + ' ' + fname)
1216 except:
1226 except:
1217 try:
1227 try:
1218 if start > 0:
1228 if start > 0:
1219 start -= 1
1229 start -= 1
1220 page(open(fname).read(),start)
1230 page(open(fname).read(),start)
1221 except:
1231 except:
1222 print 'Unable to show file',`fname`
1232 print 'Unable to show file',`fname`
1223
1233
1224 #----------------------------------------------------------------------------
1234 #----------------------------------------------------------------------------
1225 def snip_print(str,width = 75,print_full = 0,header = ''):
1235 def snip_print(str,width = 75,print_full = 0,header = ''):
1226 """Print a string snipping the midsection to fit in width.
1236 """Print a string snipping the midsection to fit in width.
1227
1237
1228 print_full: mode control:
1238 print_full: mode control:
1229 - 0: only snip long strings
1239 - 0: only snip long strings
1230 - 1: send to page() directly.
1240 - 1: send to page() directly.
1231 - 2: snip long strings and ask for full length viewing with page()
1241 - 2: snip long strings and ask for full length viewing with page()
1232 Return 1 if snipping was necessary, 0 otherwise."""
1242 Return 1 if snipping was necessary, 0 otherwise."""
1233
1243
1234 if print_full == 1:
1244 if print_full == 1:
1235 page(header+str)
1245 page(header+str)
1236 return 0
1246 return 0
1237
1247
1238 print header,
1248 print header,
1239 if len(str) < width:
1249 if len(str) < width:
1240 print str
1250 print str
1241 snip = 0
1251 snip = 0
1242 else:
1252 else:
1243 whalf = int((width -5)/2)
1253 whalf = int((width -5)/2)
1244 print str[:whalf] + ' <...> ' + str[-whalf:]
1254 print str[:whalf] + ' <...> ' + str[-whalf:]
1245 snip = 1
1255 snip = 1
1246 if snip and print_full == 2:
1256 if snip and print_full == 2:
1247 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1257 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1248 page(str)
1258 page(str)
1249 return snip
1259 return snip
1250
1260
1251 #****************************************************************************
1261 #****************************************************************************
1252 # lists, dicts and structures
1262 # lists, dicts and structures
1253
1263
1254 def belong(candidates,checklist):
1264 def belong(candidates,checklist):
1255 """Check whether a list of items appear in a given list of options.
1265 """Check whether a list of items appear in a given list of options.
1256
1266
1257 Returns a list of 1 and 0, one for each candidate given."""
1267 Returns a list of 1 and 0, one for each candidate given."""
1258
1268
1259 return [x in checklist for x in candidates]
1269 return [x in checklist for x in candidates]
1260
1270
1261 #----------------------------------------------------------------------------
1271 #----------------------------------------------------------------------------
1262 def uniq_stable(elems):
1272 def uniq_stable(elems):
1263 """uniq_stable(elems) -> list
1273 """uniq_stable(elems) -> list
1264
1274
1265 Return from an iterable, a list of all the unique elements in the input,
1275 Return from an iterable, a list of all the unique elements in the input,
1266 but maintaining the order in which they first appear.
1276 but maintaining the order in which they first appear.
1267
1277
1268 A naive solution to this problem which just makes a dictionary with the
1278 A naive solution to this problem which just makes a dictionary with the
1269 elements as keys fails to respect the stability condition, since
1279 elements as keys fails to respect the stability condition, since
1270 dictionaries are unsorted by nature.
1280 dictionaries are unsorted by nature.
1271
1281
1272 Note: All elements in the input must be valid dictionary keys for this
1282 Note: All elements in the input must be valid dictionary keys for this
1273 routine to work, as it internally uses a dictionary for efficiency
1283 routine to work, as it internally uses a dictionary for efficiency
1274 reasons."""
1284 reasons."""
1275
1285
1276 unique = []
1286 unique = []
1277 unique_dict = {}
1287 unique_dict = {}
1278 for nn in elems:
1288 for nn in elems:
1279 if nn not in unique_dict:
1289 if nn not in unique_dict:
1280 unique.append(nn)
1290 unique.append(nn)
1281 unique_dict[nn] = None
1291 unique_dict[nn] = None
1282 return unique
1292 return unique
1283
1293
1284 #----------------------------------------------------------------------------
1294 #----------------------------------------------------------------------------
1285 class NLprinter:
1295 class NLprinter:
1286 """Print an arbitrarily nested list, indicating index numbers.
1296 """Print an arbitrarily nested list, indicating index numbers.
1287
1297
1288 An instance of this class called nlprint is available and callable as a
1298 An instance of this class called nlprint is available and callable as a
1289 function.
1299 function.
1290
1300
1291 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1301 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1292 and using 'sep' to separate the index from the value. """
1302 and using 'sep' to separate the index from the value. """
1293
1303
1294 def __init__(self):
1304 def __init__(self):
1295 self.depth = 0
1305 self.depth = 0
1296
1306
1297 def __call__(self,lst,pos='',**kw):
1307 def __call__(self,lst,pos='',**kw):
1298 """Prints the nested list numbering levels."""
1308 """Prints the nested list numbering levels."""
1299 kw.setdefault('indent',' ')
1309 kw.setdefault('indent',' ')
1300 kw.setdefault('sep',': ')
1310 kw.setdefault('sep',': ')
1301 kw.setdefault('start',0)
1311 kw.setdefault('start',0)
1302 kw.setdefault('stop',len(lst))
1312 kw.setdefault('stop',len(lst))
1303 # we need to remove start and stop from kw so they don't propagate
1313 # we need to remove start and stop from kw so they don't propagate
1304 # into a recursive call for a nested list.
1314 # into a recursive call for a nested list.
1305 start = kw['start']; del kw['start']
1315 start = kw['start']; del kw['start']
1306 stop = kw['stop']; del kw['stop']
1316 stop = kw['stop']; del kw['stop']
1307 if self.depth == 0 and 'header' in kw.keys():
1317 if self.depth == 0 and 'header' in kw.keys():
1308 print kw['header']
1318 print kw['header']
1309
1319
1310 for idx in range(start,stop):
1320 for idx in range(start,stop):
1311 elem = lst[idx]
1321 elem = lst[idx]
1312 if type(elem)==type([]):
1322 if type(elem)==type([]):
1313 self.depth += 1
1323 self.depth += 1
1314 self.__call__(elem,itpl('$pos$idx,'),**kw)
1324 self.__call__(elem,itpl('$pos$idx,'),**kw)
1315 self.depth -= 1
1325 self.depth -= 1
1316 else:
1326 else:
1317 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1327 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1318
1328
1319 nlprint = NLprinter()
1329 nlprint = NLprinter()
1320 #----------------------------------------------------------------------------
1330 #----------------------------------------------------------------------------
1321 def all_belong(candidates,checklist):
1331 def all_belong(candidates,checklist):
1322 """Check whether a list of items ALL appear in a given list of options.
1332 """Check whether a list of items ALL appear in a given list of options.
1323
1333
1324 Returns a single 1 or 0 value."""
1334 Returns a single 1 or 0 value."""
1325
1335
1326 return 1-(0 in [x in checklist for x in candidates])
1336 return 1-(0 in [x in checklist for x in candidates])
1327
1337
1328 #----------------------------------------------------------------------------
1338 #----------------------------------------------------------------------------
1329 def sort_compare(lst1,lst2,inplace = 1):
1339 def sort_compare(lst1,lst2,inplace = 1):
1330 """Sort and compare two lists.
1340 """Sort and compare two lists.
1331
1341
1332 By default it does it in place, thus modifying the lists. Use inplace = 0
1342 By default it does it in place, thus modifying the lists. Use inplace = 0
1333 to avoid that (at the cost of temporary copy creation)."""
1343 to avoid that (at the cost of temporary copy creation)."""
1334 if not inplace:
1344 if not inplace:
1335 lst1 = lst1[:]
1345 lst1 = lst1[:]
1336 lst2 = lst2[:]
1346 lst2 = lst2[:]
1337 lst1.sort(); lst2.sort()
1347 lst1.sort(); lst2.sort()
1338 return lst1 == lst2
1348 return lst1 == lst2
1339
1349
1340 #----------------------------------------------------------------------------
1350 #----------------------------------------------------------------------------
1341 def mkdict(**kwargs):
1351 def mkdict(**kwargs):
1342 """Return a dict from a keyword list.
1352 """Return a dict from a keyword list.
1343
1353
1344 It's just syntactic sugar for making ditcionary creation more convenient:
1354 It's just syntactic sugar for making ditcionary creation more convenient:
1345 # the standard way
1355 # the standard way
1346 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1356 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1347 # a cleaner way
1357 # a cleaner way
1348 >>>data = dict(red=1, green=2, blue=3)
1358 >>>data = dict(red=1, green=2, blue=3)
1349
1359
1350 If you need more than this, look at the Struct() class."""
1360 If you need more than this, look at the Struct() class."""
1351
1361
1352 return kwargs
1362 return kwargs
1353
1363
1354 #----------------------------------------------------------------------------
1364 #----------------------------------------------------------------------------
1355 def list2dict(lst):
1365 def list2dict(lst):
1356 """Takes a list of (key,value) pairs and turns it into a dict."""
1366 """Takes a list of (key,value) pairs and turns it into a dict."""
1357
1367
1358 dic = {}
1368 dic = {}
1359 for k,v in lst: dic[k] = v
1369 for k,v in lst: dic[k] = v
1360 return dic
1370 return dic
1361
1371
1362 #----------------------------------------------------------------------------
1372 #----------------------------------------------------------------------------
1363 def list2dict2(lst,default=''):
1373 def list2dict2(lst,default=''):
1364 """Takes a list and turns it into a dict.
1374 """Takes a list and turns it into a dict.
1365 Much slower than list2dict, but more versatile. This version can take
1375 Much slower than list2dict, but more versatile. This version can take
1366 lists with sublists of arbitrary length (including sclars)."""
1376 lists with sublists of arbitrary length (including sclars)."""
1367
1377
1368 dic = {}
1378 dic = {}
1369 for elem in lst:
1379 for elem in lst:
1370 if type(elem) in (types.ListType,types.TupleType):
1380 if type(elem) in (types.ListType,types.TupleType):
1371 size = len(elem)
1381 size = len(elem)
1372 if size == 0:
1382 if size == 0:
1373 pass
1383 pass
1374 elif size == 1:
1384 elif size == 1:
1375 dic[elem] = default
1385 dic[elem] = default
1376 else:
1386 else:
1377 k,v = elem[0], elem[1:]
1387 k,v = elem[0], elem[1:]
1378 if len(v) == 1: v = v[0]
1388 if len(v) == 1: v = v[0]
1379 dic[k] = v
1389 dic[k] = v
1380 else:
1390 else:
1381 dic[elem] = default
1391 dic[elem] = default
1382 return dic
1392 return dic
1383
1393
1384 #----------------------------------------------------------------------------
1394 #----------------------------------------------------------------------------
1385 def flatten(seq):
1395 def flatten(seq):
1386 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1396 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1387
1397
1388 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1398 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1389
1399
1390 # if the x=0 isn't made, a *global* variable x is left over after calling
1400 # if the x=0 isn't made, a *global* variable x is left over after calling
1391 # this function, with the value of the last element in the return
1401 # this function, with the value of the last element in the return
1392 # list. This does seem like a bug big time to me.
1402 # list. This does seem like a bug big time to me.
1393
1403
1394 # the problem is fixed with the x=0, which seems to force the creation of
1404 # the problem is fixed with the x=0, which seems to force the creation of
1395 # a local name
1405 # a local name
1396
1406
1397 x = 0
1407 x = 0
1398 return [x for subseq in seq for x in subseq]
1408 return [x for subseq in seq for x in subseq]
1399
1409
1400 #----------------------------------------------------------------------------
1410 #----------------------------------------------------------------------------
1401 def get_slice(seq,start=0,stop=None,step=1):
1411 def get_slice(seq,start=0,stop=None,step=1):
1402 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1412 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1403 if stop == None:
1413 if stop == None:
1404 stop = len(seq)
1414 stop = len(seq)
1405 item = lambda i: seq[i]
1415 item = lambda i: seq[i]
1406 return map(item,xrange(start,stop,step))
1416 return map(item,xrange(start,stop,step))
1407
1417
1408 #----------------------------------------------------------------------------
1418 #----------------------------------------------------------------------------
1409 def chop(seq,size):
1419 def chop(seq,size):
1410 """Chop a sequence into chunks of the given size."""
1420 """Chop a sequence into chunks of the given size."""
1411 chunk = lambda i: seq[i:i+size]
1421 chunk = lambda i: seq[i:i+size]
1412 return map(chunk,xrange(0,len(seq),size))
1422 return map(chunk,xrange(0,len(seq),size))
1413
1423
1414 #----------------------------------------------------------------------------
1424 #----------------------------------------------------------------------------
1415 def with(object, **args):
1425 def with(object, **args):
1416 """Set multiple attributes for an object, similar to Pascal's with.
1426 """Set multiple attributes for an object, similar to Pascal's with.
1417
1427
1418 Example:
1428 Example:
1419 with(jim,
1429 with(jim,
1420 born = 1960,
1430 born = 1960,
1421 haircolour = 'Brown',
1431 haircolour = 'Brown',
1422 eyecolour = 'Green')
1432 eyecolour = 'Green')
1423
1433
1424 Credit: Greg Ewing, in
1434 Credit: Greg Ewing, in
1425 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1435 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1426
1436
1427 object.__dict__.update(args)
1437 object.__dict__.update(args)
1428
1438
1429 #----------------------------------------------------------------------------
1439 #----------------------------------------------------------------------------
1430 def setattr_list(obj,alist,nspace = None):
1440 def setattr_list(obj,alist,nspace = None):
1431 """Set a list of attributes for an object taken from a namespace.
1441 """Set a list of attributes for an object taken from a namespace.
1432
1442
1433 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1443 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1434 alist with their values taken from nspace, which must be a dict (something
1444 alist with their values taken from nspace, which must be a dict (something
1435 like locals() will often do) If nspace isn't given, locals() of the
1445 like locals() will often do) If nspace isn't given, locals() of the
1436 *caller* is used, so in most cases you can omit it.
1446 *caller* is used, so in most cases you can omit it.
1437
1447
1438 Note that alist can be given as a string, which will be automatically
1448 Note that alist can be given as a string, which will be automatically
1439 split into a list on whitespace. If given as a list, it must be a list of
1449 split into a list on whitespace. If given as a list, it must be a list of
1440 *strings* (the variable names themselves), not of variables."""
1450 *strings* (the variable names themselves), not of variables."""
1441
1451
1442 # this grabs the local variables from the *previous* call frame -- that is
1452 # this grabs the local variables from the *previous* call frame -- that is
1443 # the locals from the function that called setattr_list().
1453 # the locals from the function that called setattr_list().
1444 # - snipped from weave.inline()
1454 # - snipped from weave.inline()
1445 if nspace is None:
1455 if nspace is None:
1446 call_frame = sys._getframe().f_back
1456 call_frame = sys._getframe().f_back
1447 nspace = call_frame.f_locals
1457 nspace = call_frame.f_locals
1448
1458
1449 if type(alist) in StringTypes:
1459 if type(alist) in StringTypes:
1450 alist = alist.split()
1460 alist = alist.split()
1451 for attr in alist:
1461 for attr in alist:
1452 val = eval(attr,nspace)
1462 val = eval(attr,nspace)
1453 setattr(obj,attr,val)
1463 setattr(obj,attr,val)
1454
1464
1455 #----------------------------------------------------------------------------
1465 #----------------------------------------------------------------------------
1456 def getattr_list(obj,alist,*args):
1466 def getattr_list(obj,alist,*args):
1457 """getattr_list(obj,alist[, default]) -> attribute list.
1467 """getattr_list(obj,alist[, default]) -> attribute list.
1458
1468
1459 Get a list of named attributes for an object. When a default argument is
1469 Get a list of named attributes for an object. When a default argument is
1460 given, it is returned when the attribute doesn't exist; without it, an
1470 given, it is returned when the attribute doesn't exist; without it, an
1461 exception is raised in that case.
1471 exception is raised in that case.
1462
1472
1463 Note that alist can be given as a string, which will be automatically
1473 Note that alist can be given as a string, which will be automatically
1464 split into a list on whitespace. If given as a list, it must be a list of
1474 split into a list on whitespace. If given as a list, it must be a list of
1465 *strings* (the variable names themselves), not of variables."""
1475 *strings* (the variable names themselves), not of variables."""
1466
1476
1467 if type(alist) in StringTypes:
1477 if type(alist) in StringTypes:
1468 alist = alist.split()
1478 alist = alist.split()
1469 if args:
1479 if args:
1470 if len(args)==1:
1480 if len(args)==1:
1471 default = args[0]
1481 default = args[0]
1472 return map(lambda attr: getattr(obj,attr,default),alist)
1482 return map(lambda attr: getattr(obj,attr,default),alist)
1473 else:
1483 else:
1474 raise ValueError,'getattr_list() takes only one optional argument'
1484 raise ValueError,'getattr_list() takes only one optional argument'
1475 else:
1485 else:
1476 return map(lambda attr: getattr(obj,attr),alist)
1486 return map(lambda attr: getattr(obj,attr),alist)
1477
1487
1478 #----------------------------------------------------------------------------
1488 #----------------------------------------------------------------------------
1479 def map_method(method,object_list,*argseq,**kw):
1489 def map_method(method,object_list,*argseq,**kw):
1480 """map_method(method,object_list,*args,**kw) -> list
1490 """map_method(method,object_list,*args,**kw) -> list
1481
1491
1482 Return a list of the results of applying the methods to the items of the
1492 Return a list of the results of applying the methods to the items of the
1483 argument sequence(s). If more than one sequence is given, the method is
1493 argument sequence(s). If more than one sequence is given, the method is
1484 called with an argument list consisting of the corresponding item of each
1494 called with an argument list consisting of the corresponding item of each
1485 sequence. All sequences must be of the same length.
1495 sequence. All sequences must be of the same length.
1486
1496
1487 Keyword arguments are passed verbatim to all objects called.
1497 Keyword arguments are passed verbatim to all objects called.
1488
1498
1489 This is Python code, so it's not nearly as fast as the builtin map()."""
1499 This is Python code, so it's not nearly as fast as the builtin map()."""
1490
1500
1491 out_list = []
1501 out_list = []
1492 idx = 0
1502 idx = 0
1493 for object in object_list:
1503 for object in object_list:
1494 try:
1504 try:
1495 handler = getattr(object, method)
1505 handler = getattr(object, method)
1496 except AttributeError:
1506 except AttributeError:
1497 out_list.append(None)
1507 out_list.append(None)
1498 else:
1508 else:
1499 if argseq:
1509 if argseq:
1500 args = map(lambda lst:lst[idx],argseq)
1510 args = map(lambda lst:lst[idx],argseq)
1501 #print 'ob',object,'hand',handler,'ar',args # dbg
1511 #print 'ob',object,'hand',handler,'ar',args # dbg
1502 out_list.append(handler(args,**kw))
1512 out_list.append(handler(args,**kw))
1503 else:
1513 else:
1504 out_list.append(handler(**kw))
1514 out_list.append(handler(**kw))
1505 idx += 1
1515 idx += 1
1506 return out_list
1516 return out_list
1507
1517
1508 #----------------------------------------------------------------------------
1518 #----------------------------------------------------------------------------
1509 # Proposed popitem() extension, written as a method
1519 # Proposed popitem() extension, written as a method
1510
1520
1511 class NotGiven: pass
1521 class NotGiven: pass
1512
1522
1513 def popkey(dct,key,default=NotGiven):
1523 def popkey(dct,key,default=NotGiven):
1514 """Return dct[key] and delete dct[key].
1524 """Return dct[key] and delete dct[key].
1515
1525
1516 If default is given, return it if dct[key] doesn't exist, otherwise raise
1526 If default is given, return it if dct[key] doesn't exist, otherwise raise
1517 KeyError. """
1527 KeyError. """
1518
1528
1519 try:
1529 try:
1520 val = dct[key]
1530 val = dct[key]
1521 except KeyError:
1531 except KeyError:
1522 if default is NotGiven:
1532 if default is NotGiven:
1523 raise
1533 raise
1524 else:
1534 else:
1525 return default
1535 return default
1526 else:
1536 else:
1527 del dct[key]
1537 del dct[key]
1528 return val
1538 return val
1529 #*************************** end of file <genutils.py> **********************
1539 #*************************** end of file <genutils.py> **********************
1530
1540
@@ -1,2047 +1,2047 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or newer.
5 Requires Python 2.1 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 874 2005-09-20 20:13:04Z fperez $
9 $Id: iplib.py 894 2005-09-22 07:16:18Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2004 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, much of that class has been copied
20 # Python standard library. Over time, much 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. The Python License (sec. 2) allows for this, but it's always
22 # subclassing. The Python License (sec. 2) allows for this, but it's always
23 # nice to acknowledge credit where credit is due.
23 # nice to acknowledge credit where credit is due.
24 #*****************************************************************************
24 #*****************************************************************************
25
25
26 #****************************************************************************
26 #****************************************************************************
27 # Modules and globals
27 # Modules and globals
28
28
29 from __future__ import generators # for 2.2 backwards-compatibility
29 from __future__ import generators # for 2.2 backwards-compatibility
30
30
31 from IPython import Release
31 from IPython import Release
32 __author__ = '%s <%s>\n%s <%s>' % \
32 __author__ = '%s <%s>\n%s <%s>' % \
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 __license__ = Release.license
34 __license__ = Release.license
35 __version__ = Release.version
35 __version__ = Release.version
36
36
37 # Python standard modules
37 # Python standard modules
38 import __main__
38 import __main__
39 import __builtin__
39 import __builtin__
40 import exceptions
40 import exceptions
41 import keyword
41 import keyword
42 import new
42 import new
43 import os, sys, shutil
43 import os, sys, shutil
44 import code, glob, types, re
44 import code, glob, types, re
45 import string, StringIO
45 import string, StringIO
46 import inspect, pydoc
46 import inspect, pydoc
47 import bdb, pdb
47 import bdb, pdb
48 import UserList # don't subclass list so this works with Python2.1
48 import UserList # don't subclass list so this works with Python2.1
49 from pprint import pprint, pformat
49 from pprint import pprint, pformat
50 import cPickle as pickle
50 import cPickle as pickle
51 import traceback
51 import traceback
52
52
53 # IPython's own modules
53 # IPython's own modules
54 import IPython
54 import IPython
55 from IPython import OInspect,PyColorize,ultraTB
55 from IPython import OInspect,PyColorize,ultraTB
56 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
56 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
57 from IPython.Logger import Logger
57 from IPython.Logger import Logger
58 from IPython.Magic import Magic,magic2python,shlex_split
58 from IPython.Magic import Magic,magic2python,shlex_split
59 from IPython.usage import cmd_line_usage,interactive_usage
59 from IPython.usage import cmd_line_usage,interactive_usage
60 from IPython.Struct import Struct
60 from IPython.Struct import Struct
61 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
61 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
62 from IPython.FakeModule import FakeModule
62 from IPython.FakeModule import FakeModule
63 from IPython.background_jobs import BackgroundJobManager
63 from IPython.background_jobs import BackgroundJobManager
64 from IPython.genutils import *
64 from IPython.genutils import *
65
65
66 # Global pointer to the running
66 # Global pointer to the running
67
67
68 # store the builtin raw_input globally, and use this always, in case user code
68 # store the builtin raw_input globally, and use this always, in case user code
69 # overwrites it (like wx.py.PyShell does)
69 # overwrites it (like wx.py.PyShell does)
70 raw_input_original = raw_input
70 raw_input_original = raw_input
71
71
72 #****************************************************************************
72 #****************************************************************************
73 # Some utility function definitions
73 # Some utility function definitions
74
74
75 class Bunch: pass
75 class Bunch: pass
76
76
77 def esc_quotes(strng):
77 def esc_quotes(strng):
78 """Return the input string with single and double quotes escaped out"""
78 """Return the input string with single and double quotes escaped out"""
79
79
80 return strng.replace('"','\\"').replace("'","\\'")
80 return strng.replace('"','\\"').replace("'","\\'")
81
81
82 def import_fail_info(mod_name,fns=None):
82 def import_fail_info(mod_name,fns=None):
83 """Inform load failure for a module."""
83 """Inform load failure for a module."""
84
84
85 if fns == None:
85 if fns == None:
86 warn("Loading of %s failed.\n" % (mod_name,))
86 warn("Loading of %s failed.\n" % (mod_name,))
87 else:
87 else:
88 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
88 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
89
89
90 def qw_lol(indata):
90 def qw_lol(indata):
91 """qw_lol('a b') -> [['a','b']],
91 """qw_lol('a b') -> [['a','b']],
92 otherwise it's just a call to qw().
92 otherwise it's just a call to qw().
93
93
94 We need this to make sure the modules_some keys *always* end up as a
94 We need this to make sure the modules_some keys *always* end up as a
95 list of lists."""
95 list of lists."""
96
96
97 if type(indata) in StringTypes:
97 if type(indata) in StringTypes:
98 return [qw(indata)]
98 return [qw(indata)]
99 else:
99 else:
100 return qw(indata)
100 return qw(indata)
101
101
102 def ipmagic(arg_s):
102 def ipmagic(arg_s):
103 """Call a magic function by name.
103 """Call a magic function by name.
104
104
105 Input: a string containing the name of the magic function to call and any
105 Input: a string containing the name of the magic function to call and any
106 additional arguments to be passed to the magic.
106 additional arguments to be passed to the magic.
107
107
108 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
108 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
109 prompt:
109 prompt:
110
110
111 In[1]: %name -opt foo bar
111 In[1]: %name -opt foo bar
112
112
113 To call a magic without arguments, simply use ipmagic('name').
113 To call a magic without arguments, simply use ipmagic('name').
114
114
115 This provides a proper Python function to call IPython's magics in any
115 This provides a proper Python function to call IPython's magics in any
116 valid Python code you can type at the interpreter, including loops and
116 valid Python code you can type at the interpreter, including loops and
117 compound statements. It is added by IPython to the Python builtin
117 compound statements. It is added by IPython to the Python builtin
118 namespace upon initialization."""
118 namespace upon initialization."""
119
119
120 args = arg_s.split(' ',1)
120 args = arg_s.split(' ',1)
121 magic_name = args[0]
121 magic_name = args[0]
122 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
122 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
123 magic_name = magic_name[1:]
123 magic_name = magic_name[1:]
124 try:
124 try:
125 magic_args = args[1]
125 magic_args = args[1]
126 except IndexError:
126 except IndexError:
127 magic_args = ''
127 magic_args = ''
128 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
128 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
129 if fn is None:
129 if fn is None:
130 error("Magic function `%s` not found." % magic_name)
130 error("Magic function `%s` not found." % magic_name)
131 else:
131 else:
132 magic_args = __IPYTHON__.var_expand(magic_args)
132 magic_args = __IPYTHON__.var_expand(magic_args)
133 return fn(magic_args)
133 return fn(magic_args)
134
134
135 def ipalias(arg_s):
135 def ipalias(arg_s):
136 """Call an alias by name.
136 """Call an alias by name.
137
137
138 Input: a string containing the name of the alias to call and any
138 Input: a string containing the name of the alias to call and any
139 additional arguments to be passed to the magic.
139 additional arguments to be passed to the magic.
140
140
141 ipalias('name -opt foo bar') is equivalent to typing at the ipython
141 ipalias('name -opt foo bar') is equivalent to typing at the ipython
142 prompt:
142 prompt:
143
143
144 In[1]: name -opt foo bar
144 In[1]: name -opt foo bar
145
145
146 To call an alias without arguments, simply use ipalias('name').
146 To call an alias without arguments, simply use ipalias('name').
147
147
148 This provides a proper Python function to call IPython's aliases in any
148 This provides a proper Python function to call IPython's aliases in any
149 valid Python code you can type at the interpreter, including loops and
149 valid Python code you can type at the interpreter, including loops and
150 compound statements. It is added by IPython to the Python builtin
150 compound statements. It is added by IPython to the Python builtin
151 namespace upon initialization."""
151 namespace upon initialization."""
152
152
153 args = arg_s.split(' ',1)
153 args = arg_s.split(' ',1)
154 alias_name = args[0]
154 alias_name = args[0]
155 try:
155 try:
156 alias_args = args[1]
156 alias_args = args[1]
157 except IndexError:
157 except IndexError:
158 alias_args = ''
158 alias_args = ''
159 if alias_name in __IPYTHON__.alias_table:
159 if alias_name in __IPYTHON__.alias_table:
160 __IPYTHON__.call_alias(alias_name,alias_args)
160 __IPYTHON__.call_alias(alias_name,alias_args)
161 else:
161 else:
162 error("Alias `%s` not found." % alias_name)
162 error("Alias `%s` not found." % alias_name)
163
163
164 #-----------------------------------------------------------------------------
164 #-----------------------------------------------------------------------------
165 # Local use classes
165 # Local use classes
166 try:
166 try:
167 from IPython import FlexCompleter
167 from IPython import FlexCompleter
168
168
169 class MagicCompleter(FlexCompleter.Completer):
169 class MagicCompleter(FlexCompleter.Completer):
170 """Extension of the completer class to work on %-prefixed lines."""
170 """Extension of the completer class to work on %-prefixed lines."""
171
171
172 def __init__(self,shell,namespace=None,omit__names=0,alias_table=None):
172 def __init__(self,shell,namespace=None,omit__names=0,alias_table=None):
173 """MagicCompleter() -> completer
173 """MagicCompleter() -> completer
174
174
175 Return a completer object suitable for use by the readline library
175 Return a completer object suitable for use by the readline library
176 via readline.set_completer().
176 via readline.set_completer().
177
177
178 Inputs:
178 Inputs:
179
179
180 - shell: a pointer to the ipython shell itself. This is needed
180 - shell: a pointer to the ipython shell itself. This is needed
181 because this completer knows about magic functions, and those can
181 because this completer knows about magic functions, and those can
182 only be accessed via the ipython instance.
182 only be accessed via the ipython instance.
183
183
184 - namespace: an optional dict where completions are performed.
184 - namespace: an optional dict where completions are performed.
185
185
186 - The optional omit__names parameter sets the completer to omit the
186 - The optional omit__names parameter sets the completer to omit the
187 'magic' names (__magicname__) for python objects unless the text
187 'magic' names (__magicname__) for python objects unless the text
188 to be completed explicitly starts with one or more underscores.
188 to be completed explicitly starts with one or more underscores.
189
189
190 - If alias_table is supplied, it should be a dictionary of aliases
190 - If alias_table is supplied, it should be a dictionary of aliases
191 to complete. """
191 to complete. """
192
192
193 FlexCompleter.Completer.__init__(self,namespace)
193 FlexCompleter.Completer.__init__(self,namespace)
194 self.magic_prefix = shell.name+'.magic_'
194 self.magic_prefix = shell.name+'.magic_'
195 self.magic_escape = shell.ESC_MAGIC
195 self.magic_escape = shell.ESC_MAGIC
196 self.readline = FlexCompleter.readline
196 self.readline = FlexCompleter.readline
197 delims = self.readline.get_completer_delims()
197 delims = self.readline.get_completer_delims()
198 delims = delims.replace(self.magic_escape,'')
198 delims = delims.replace(self.magic_escape,'')
199 self.readline.set_completer_delims(delims)
199 self.readline.set_completer_delims(delims)
200 self.get_line_buffer = self.readline.get_line_buffer
200 self.get_line_buffer = self.readline.get_line_buffer
201 self.omit__names = omit__names
201 self.omit__names = omit__names
202 self.merge_completions = shell.rc.readline_merge_completions
202 self.merge_completions = shell.rc.readline_merge_completions
203
203
204 if alias_table is None:
204 if alias_table is None:
205 alias_table = {}
205 alias_table = {}
206 self.alias_table = alias_table
206 self.alias_table = alias_table
207 # Regexp to split filenames with spaces in them
207 # Regexp to split filenames with spaces in them
208 self.space_name_re = re.compile(r'([^\\] )')
208 self.space_name_re = re.compile(r'([^\\] )')
209 # Hold a local ref. to glob.glob for speed
209 # Hold a local ref. to glob.glob for speed
210 self.glob = glob.glob
210 self.glob = glob.glob
211 # Special handling of backslashes needed in win32 platforms
211 # Special handling of backslashes needed in win32 platforms
212 if sys.platform == "win32":
212 if sys.platform == "win32":
213 self.clean_glob = self._clean_glob_win32
213 self.clean_glob = self._clean_glob_win32
214 else:
214 else:
215 self.clean_glob = self._clean_glob
215 self.clean_glob = self._clean_glob
216 self.matchers = [self.python_matches,
216 self.matchers = [self.python_matches,
217 self.file_matches,
217 self.file_matches,
218 self.alias_matches,
218 self.alias_matches,
219 self.python_func_kw_matches]
219 self.python_func_kw_matches]
220
220
221 # Code contributed by Alex Schmolck, for ipython/emacs integration
221 # Code contributed by Alex Schmolck, for ipython/emacs integration
222 def all_completions(self, text):
222 def all_completions(self, text):
223 """Return all possible completions for the benefit of emacs."""
223 """Return all possible completions for the benefit of emacs."""
224
224
225 completions = []
225 completions = []
226 try:
226 try:
227 for i in xrange(sys.maxint):
227 for i in xrange(sys.maxint):
228 res = self.complete(text, i)
228 res = self.complete(text, i)
229
229
230 if not res: break
230 if not res: break
231
231
232 completions.append(res)
232 completions.append(res)
233 #XXX workaround for ``notDefined.<tab>``
233 #XXX workaround for ``notDefined.<tab>``
234 except NameError:
234 except NameError:
235 pass
235 pass
236 return completions
236 return completions
237 # /end Alex Schmolck code.
237 # /end Alex Schmolck code.
238
238
239 def _clean_glob(self,text):
239 def _clean_glob(self,text):
240 return self.glob("%s*" % text)
240 return self.glob("%s*" % text)
241
241
242 def _clean_glob_win32(self,text):
242 def _clean_glob_win32(self,text):
243 return [f.replace("\\","/")
243 return [f.replace("\\","/")
244 for f in self.glob("%s*" % text)]
244 for f in self.glob("%s*" % text)]
245
245
246 def file_matches(self, text):
246 def file_matches(self, text):
247 """Match filneames, expanding ~USER type strings.
247 """Match filneames, expanding ~USER type strings.
248
248
249 Most of the seemingly convoluted logic in this completer is an
249 Most of the seemingly convoluted logic in this completer is an
250 attempt to handle filenames with spaces in them. And yet it's not
250 attempt to handle filenames with spaces in them. And yet it's not
251 quite perfect, because Python's readline doesn't expose all of the
251 quite perfect, because Python's readline doesn't expose all of the
252 GNU readline details needed for this to be done correctly.
252 GNU readline details needed for this to be done correctly.
253
253
254 For a filename with a space in it, the printed completions will be
254 For a filename with a space in it, the printed completions will be
255 only the parts after what's already been typed (instead of the
255 only the parts after what's already been typed (instead of the
256 full completions, as is normally done). I don't think with the
256 full completions, as is normally done). I don't think with the
257 current (as of Python 2.3) Python readline it's possible to do
257 current (as of Python 2.3) Python readline it's possible to do
258 better."""
258 better."""
259
259
260 #print 'Completer->file_matches: <%s>' % text # dbg
260 #print 'Completer->file_matches: <%s>' % text # dbg
261
261
262 # chars that require escaping with backslash - i.e. chars
262 # chars that require escaping with backslash - i.e. chars
263 # that readline treats incorrectly as delimiters, but we
263 # that readline treats incorrectly as delimiters, but we
264 # don't want to treat as delimiters in filename matching
264 # don't want to treat as delimiters in filename matching
265 # when escaped with backslash
265 # when escaped with backslash
266
266
267 protectables = ' ()[]{}'
267 protectables = ' ()[]{}'
268
268
269 def protect_filename(s):
269 def protect_filename(s):
270 return "".join([(ch in protectables and '\\' + ch or ch)
270 return "".join([(ch in protectables and '\\' + ch or ch)
271 for ch in s])
271 for ch in s])
272
272
273 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
273 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
274 open_quotes = 0 # track strings with open quotes
274 open_quotes = 0 # track strings with open quotes
275 try:
275 try:
276 lsplit = shlex_split(lbuf)[-1]
276 lsplit = shlex_split(lbuf)[-1]
277 except ValueError:
277 except ValueError:
278 # typically an unmatched ", or backslash without escaped char.
278 # typically an unmatched ", or backslash without escaped char.
279 if lbuf.count('"')==1:
279 if lbuf.count('"')==1:
280 open_quotes = 1
280 open_quotes = 1
281 lsplit = lbuf.split('"')[-1]
281 lsplit = lbuf.split('"')[-1]
282 elif lbuf.count("'")==1:
282 elif lbuf.count("'")==1:
283 open_quotes = 1
283 open_quotes = 1
284 lsplit = lbuf.split("'")[-1]
284 lsplit = lbuf.split("'")[-1]
285 else:
285 else:
286 return None
286 return None
287 except IndexError:
287 except IndexError:
288 # tab pressed on empty line
288 # tab pressed on empty line
289 lsplit = ""
289 lsplit = ""
290
290
291 if lsplit != protect_filename(lsplit):
291 if lsplit != protect_filename(lsplit):
292 # if protectables are found, do matching on the whole escaped
292 # if protectables are found, do matching on the whole escaped
293 # name
293 # name
294 has_protectables = 1
294 has_protectables = 1
295 text0,text = text,lsplit
295 text0,text = text,lsplit
296 else:
296 else:
297 has_protectables = 0
297 has_protectables = 0
298 text = os.path.expanduser(text)
298 text = os.path.expanduser(text)
299
299
300 if text == "":
300 if text == "":
301 return [protect_filename(f) for f in self.glob("*")]
301 return [protect_filename(f) for f in self.glob("*")]
302
302
303 m0 = self.clean_glob(text.replace('\\',''))
303 m0 = self.clean_glob(text.replace('\\',''))
304 if has_protectables:
304 if has_protectables:
305 # If we had protectables, we need to revert our changes to the
305 # If we had protectables, we need to revert our changes to the
306 # beginning of filename so that we don't double-write the part
306 # beginning of filename so that we don't double-write the part
307 # of the filename we have so far
307 # of the filename we have so far
308 len_lsplit = len(lsplit)
308 len_lsplit = len(lsplit)
309 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
309 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
310 else:
310 else:
311 if open_quotes:
311 if open_quotes:
312 # if we have a string with an open quote, we don't need to
312 # if we have a string with an open quote, we don't need to
313 # protect the names at all (and we _shouldn't_, as it
313 # protect the names at all (and we _shouldn't_, as it
314 # would cause bugs when the filesystem call is made).
314 # would cause bugs when the filesystem call is made).
315 matches = m0
315 matches = m0
316 else:
316 else:
317 matches = [protect_filename(f) for f in m0]
317 matches = [protect_filename(f) for f in m0]
318 if len(matches) == 1 and os.path.isdir(matches[0]):
318 if len(matches) == 1 and os.path.isdir(matches[0]):
319 # Takes care of links to directories also. Use '/'
319 # Takes care of links to directories also. Use '/'
320 # explicitly, even under Windows, so that name completions
320 # explicitly, even under Windows, so that name completions
321 # don't end up escaped.
321 # don't end up escaped.
322 matches[0] += '/'
322 matches[0] += '/'
323 return matches
323 return matches
324
324
325 def alias_matches(self, text):
325 def alias_matches(self, text):
326 """Match internal system aliases"""
326 """Match internal system aliases"""
327 #print 'Completer->alias_matches:',text # dbg
327 #print 'Completer->alias_matches:',text # dbg
328 text = os.path.expanduser(text)
328 text = os.path.expanduser(text)
329 aliases = self.alias_table.keys()
329 aliases = self.alias_table.keys()
330 if text == "":
330 if text == "":
331 return aliases
331 return aliases
332 else:
332 else:
333 return [alias for alias in aliases if alias.startswith(text)]
333 return [alias for alias in aliases if alias.startswith(text)]
334
334
335 def python_matches(self,text):
335 def python_matches(self,text):
336 """Match attributes or global python names"""
336 """Match attributes or global python names"""
337 #print 'Completer->python_matches' # dbg
337 #print 'Completer->python_matches' # dbg
338 if "." in text:
338 if "." in text:
339 try:
339 try:
340 matches = self.attr_matches(text)
340 matches = self.attr_matches(text)
341 if text.endswith('.') and self.omit__names:
341 if text.endswith('.') and self.omit__names:
342 if self.omit__names == 1:
342 if self.omit__names == 1:
343 # true if txt is _not_ a __ name, false otherwise:
343 # true if txt is _not_ a __ name, false otherwise:
344 no__name = (lambda txt:
344 no__name = (lambda txt:
345 re.match(r'.*\.__.*?__',txt) is None)
345 re.match(r'.*\.__.*?__',txt) is None)
346 else:
346 else:
347 # true if txt is _not_ a _ name, false otherwise:
347 # true if txt is _not_ a _ name, false otherwise:
348 no__name = (lambda txt:
348 no__name = (lambda txt:
349 re.match(r'.*\._.*?',txt) is None)
349 re.match(r'.*\._.*?',txt) is None)
350 matches = filter(no__name, matches)
350 matches = filter(no__name, matches)
351 except NameError:
351 except NameError:
352 # catches <undefined attributes>.<tab>
352 # catches <undefined attributes>.<tab>
353 matches = []
353 matches = []
354 else:
354 else:
355 matches = self.global_matches(text)
355 matches = self.global_matches(text)
356 # this is so completion finds magics when automagic is on:
356 # this is so completion finds magics when automagic is on:
357 if matches == [] and not text.startswith(os.sep):
357 if matches == [] and not text.startswith(os.sep):
358 matches = self.attr_matches(self.magic_prefix+text)
358 matches = self.attr_matches(self.magic_prefix+text)
359 return matches
359 return matches
360
360
361 def _default_arguments(self, obj):
361 def _default_arguments(self, obj):
362 """Return the list of default arguments of obj if it is callable,
362 """Return the list of default arguments of obj if it is callable,
363 or empty list otherwise."""
363 or empty list otherwise."""
364
364
365 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
365 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
366 # for classes, check for __init__,__new__
366 # for classes, check for __init__,__new__
367 if inspect.isclass(obj):
367 if inspect.isclass(obj):
368 obj = (getattr(obj,'__init__',None) or
368 obj = (getattr(obj,'__init__',None) or
369 getattr(obj,'__new__',None))
369 getattr(obj,'__new__',None))
370 # for all others, check if they are __call__able
370 # for all others, check if they are __call__able
371 elif hasattr(obj, '__call__'):
371 elif hasattr(obj, '__call__'):
372 obj = obj.__call__
372 obj = obj.__call__
373 # XXX: is there a way to handle the builtins ?
373 # XXX: is there a way to handle the builtins ?
374 try:
374 try:
375 args,_,_1,defaults = inspect.getargspec(obj)
375 args,_,_1,defaults = inspect.getargspec(obj)
376 if defaults:
376 if defaults:
377 return args[-len(defaults):]
377 return args[-len(defaults):]
378 except TypeError: pass
378 except TypeError: pass
379 return []
379 return []
380
380
381 def python_func_kw_matches(self,text):
381 def python_func_kw_matches(self,text):
382 """Match named parameters (kwargs) of the last open function"""
382 """Match named parameters (kwargs) of the last open function"""
383
383
384 if "." in text: # a parameter cannot be dotted
384 if "." in text: # a parameter cannot be dotted
385 return []
385 return []
386 try: regexp = self.__funcParamsRegex
386 try: regexp = self.__funcParamsRegex
387 except AttributeError:
387 except AttributeError:
388 regexp = self.__funcParamsRegex = re.compile(r'''
388 regexp = self.__funcParamsRegex = re.compile(r'''
389 '.*?' | # single quoted strings or
389 '.*?' | # single quoted strings or
390 ".*?" | # double quoted strings or
390 ".*?" | # double quoted strings or
391 \w+ | # identifier
391 \w+ | # identifier
392 \S # other characters
392 \S # other characters
393 ''', re.VERBOSE | re.DOTALL)
393 ''', re.VERBOSE | re.DOTALL)
394 # 1. find the nearest identifier that comes before an unclosed
394 # 1. find the nearest identifier that comes before an unclosed
395 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
395 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
396 tokens = regexp.findall(self.get_line_buffer())
396 tokens = regexp.findall(self.get_line_buffer())
397 tokens.reverse()
397 tokens.reverse()
398 iterTokens = iter(tokens); openPar = 0
398 iterTokens = iter(tokens); openPar = 0
399 for token in iterTokens:
399 for token in iterTokens:
400 if token == ')':
400 if token == ')':
401 openPar -= 1
401 openPar -= 1
402 elif token == '(':
402 elif token == '(':
403 openPar += 1
403 openPar += 1
404 if openPar > 0:
404 if openPar > 0:
405 # found the last unclosed parenthesis
405 # found the last unclosed parenthesis
406 break
406 break
407 else:
407 else:
408 return []
408 return []
409 # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
409 # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
410 ids = []
410 ids = []
411 isId = re.compile(r'\w+$').match
411 isId = re.compile(r'\w+$').match
412 while True:
412 while True:
413 try:
413 try:
414 ids.append(iterTokens.next())
414 ids.append(iterTokens.next())
415 if not isId(ids[-1]):
415 if not isId(ids[-1]):
416 ids.pop(); break
416 ids.pop(); break
417 if not iterTokens.next() == '.':
417 if not iterTokens.next() == '.':
418 break
418 break
419 except StopIteration:
419 except StopIteration:
420 break
420 break
421 # lookup the candidate callable matches either using global_matches
421 # lookup the candidate callable matches either using global_matches
422 # or attr_matches for dotted names
422 # or attr_matches for dotted names
423 if len(ids) == 1:
423 if len(ids) == 1:
424 callableMatches = self.global_matches(ids[0])
424 callableMatches = self.global_matches(ids[0])
425 else:
425 else:
426 callableMatches = self.attr_matches('.'.join(ids[::-1]))
426 callableMatches = self.attr_matches('.'.join(ids[::-1]))
427 argMatches = []
427 argMatches = []
428 for callableMatch in callableMatches:
428 for callableMatch in callableMatches:
429 try: namedArgs = self._default_arguments(eval(callableMatch,
429 try: namedArgs = self._default_arguments(eval(callableMatch,
430 self.namespace))
430 self.namespace))
431 except: continue
431 except: continue
432 for namedArg in namedArgs:
432 for namedArg in namedArgs:
433 if namedArg.startswith(text):
433 if namedArg.startswith(text):
434 argMatches.append("%s=" %namedArg)
434 argMatches.append("%s=" %namedArg)
435 return argMatches
435 return argMatches
436
436
437 def complete(self, text, state):
437 def complete(self, text, state):
438 """Return the next possible completion for 'text'.
438 """Return the next possible completion for 'text'.
439
439
440 This is called successively with state == 0, 1, 2, ... until it
440 This is called successively with state == 0, 1, 2, ... until it
441 returns None. The completion should begin with 'text'. """
441 returns None. The completion should begin with 'text'. """
442
442
443 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
443 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
444 magic_escape = self.magic_escape
444 magic_escape = self.magic_escape
445 magic_prefix = self.magic_prefix
445 magic_prefix = self.magic_prefix
446
446
447 try:
447 try:
448 if text.startswith(magic_escape):
448 if text.startswith(magic_escape):
449 text = text.replace(magic_escape,magic_prefix)
449 text = text.replace(magic_escape,magic_prefix)
450 elif text.startswith('~'):
450 elif text.startswith('~'):
451 text = os.path.expanduser(text)
451 text = os.path.expanduser(text)
452 if state == 0:
452 if state == 0:
453 # Extend the list of completions with the results of each
453 # Extend the list of completions with the results of each
454 # matcher, so we return results to the user from all
454 # matcher, so we return results to the user from all
455 # namespaces.
455 # namespaces.
456 if self.merge_completions:
456 if self.merge_completions:
457 self.matches = []
457 self.matches = []
458 for matcher in self.matchers:
458 for matcher in self.matchers:
459 self.matches.extend(matcher(text))
459 self.matches.extend(matcher(text))
460 else:
460 else:
461 for matcher in self.matchers:
461 for matcher in self.matchers:
462 self.matches = matcher(text)
462 self.matches = matcher(text)
463 if self.matches:
463 if self.matches:
464 break
464 break
465
465
466 try:
466 try:
467 return self.matches[state].replace(magic_prefix,magic_escape)
467 return self.matches[state].replace(magic_prefix,magic_escape)
468 except IndexError:
468 except IndexError:
469 return None
469 return None
470 except:
470 except:
471 # If completion fails, don't annoy the user.
471 # If completion fails, don't annoy the user.
472 pass
472 pass
473
473
474 except ImportError:
474 except ImportError:
475 pass # no readline support
475 pass # no readline support
476
476
477 except KeyError:
477 except KeyError:
478 pass # Windows doesn't set TERM, it doesn't matter
478 pass # Windows doesn't set TERM, it doesn't matter
479
479
480
480
481 class InputList(UserList.UserList):
481 class InputList(UserList.UserList):
482 """Class to store user input.
482 """Class to store user input.
483
483
484 It's basically a list, but slices return a string instead of a list, thus
484 It's basically a list, but slices return a string instead of a list, thus
485 allowing things like (assuming 'In' is an instance):
485 allowing things like (assuming 'In' is an instance):
486
486
487 exec In[4:7]
487 exec In[4:7]
488
488
489 or
489 or
490
490
491 exec In[5:9] + In[14] + In[21:25]"""
491 exec In[5:9] + In[14] + In[21:25]"""
492
492
493 def __getslice__(self,i,j):
493 def __getslice__(self,i,j):
494 return ''.join(UserList.UserList.__getslice__(self,i,j))
494 return ''.join(UserList.UserList.__getslice__(self,i,j))
495
495
496 #****************************************************************************
496 #****************************************************************************
497 # Local use exceptions
497 # Local use exceptions
498 class SpaceInInput(exceptions.Exception):
498 class SpaceInInput(exceptions.Exception):
499 pass
499 pass
500
500
501 #****************************************************************************
501 #****************************************************************************
502 # Main IPython class
502 # Main IPython class
503
503
504 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
504 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
505 """An enhanced console for Python."""
505 """An enhanced console for Python."""
506
506
507 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
507 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
508 user_ns = None,banner2='',
508 user_ns = None,banner2='',
509 custom_exceptions=((),None)):
509 custom_exceptions=((),None)):
510
510
511 # Put a reference to self in builtins so that any form of embedded or
511 # Put a reference to self in builtins so that any form of embedded or
512 # imported code can test for being inside IPython.
512 # imported code can test for being inside IPython.
513 __builtin__.__IPYTHON__ = self
513 __builtin__.__IPYTHON__ = self
514
514
515 # And load into builtins ipmagic/ipalias as well
515 # And load into builtins ipmagic/ipalias as well
516 __builtin__.ipmagic = ipmagic
516 __builtin__.ipmagic = ipmagic
517 __builtin__.ipalias = ipalias
517 __builtin__.ipalias = ipalias
518
518
519 # Add to __builtin__ other parts of IPython's public API
519 # Add to __builtin__ other parts of IPython's public API
520 __builtin__.ip_set_hook = self.set_hook
520 __builtin__.ip_set_hook = self.set_hook
521
521
522 # Keep in the builtins a flag for when IPython is active. We set it
522 # Keep in the builtins a flag for when IPython is active. We set it
523 # with setdefault so that multiple nested IPythons don't clobber one
523 # with setdefault so that multiple nested IPythons don't clobber one
524 # another. Each will increase its value by one upon being activated,
524 # another. Each will increase its value by one upon being activated,
525 # which also gives us a way to determine the nesting level.
525 # which also gives us a way to determine the nesting level.
526 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
526 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
527
527
528 # Inform the user of ipython's fast exit magics.
528 # Inform the user of ipython's fast exit magics.
529 _exit = ' Use %Exit or %Quit to exit without confirmation.'
529 _exit = ' Use %Exit or %Quit to exit without confirmation.'
530 __builtin__.exit += _exit
530 __builtin__.exit += _exit
531 __builtin__.quit += _exit
531 __builtin__.quit += _exit
532
532
533 # Create the namespace where the user will operate:
533 # Create the namespace where the user will operate:
534
534
535 # FIXME. For some strange reason, __builtins__ is showing up at user
535 # FIXME. For some strange reason, __builtins__ is showing up at user
536 # level as a dict instead of a module. This is a manual fix, but I
536 # level as a dict instead of a module. This is a manual fix, but I
537 # should really track down where the problem is coming from. Alex
537 # should really track down where the problem is coming from. Alex
538 # Schmolck reported this problem first.
538 # Schmolck reported this problem first.
539
539
540 # A useful post by Alex Martelli on this topic:
540 # A useful post by Alex Martelli on this topic:
541 # Re: inconsistent value from __builtins__
541 # Re: inconsistent value from __builtins__
542 # Von: Alex Martelli <aleaxit@yahoo.com>
542 # Von: Alex Martelli <aleaxit@yahoo.com>
543 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
543 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
544 # Gruppen: comp.lang.python
544 # Gruppen: comp.lang.python
545 # Referenzen: 1
545 # Referenzen: 1
546
546
547 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
547 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
548 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
548 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
549 # > <type 'dict'>
549 # > <type 'dict'>
550 # > >>> print type(__builtins__)
550 # > >>> print type(__builtins__)
551 # > <type 'module'>
551 # > <type 'module'>
552 # > Is this difference in return value intentional?
552 # > Is this difference in return value intentional?
553
553
554 # Well, it's documented that '__builtins__' can be either a dictionary
554 # Well, it's documented that '__builtins__' can be either a dictionary
555 # or a module, and it's been that way for a long time. Whether it's
555 # or a module, and it's been that way for a long time. Whether it's
556 # intentional (or sensible), I don't know. In any case, the idea is that
556 # intentional (or sensible), I don't know. In any case, the idea is that
557 # if you need to access the built-in namespace directly, you should start
557 # if you need to access the built-in namespace directly, you should start
558 # with "import __builtin__" (note, no 's') which will definitely give you
558 # with "import __builtin__" (note, no 's') which will definitely give you
559 # a module. Yeah, it's somewhatΒ confusing:-(.
559 # a module. Yeah, it's somewhatΒ confusing:-(.
560
560
561 if user_ns is None:
561 if user_ns is None:
562 # Set __name__ to __main__ to better match the behavior of the
562 # Set __name__ to __main__ to better match the behavior of the
563 # normal interpreter.
563 # normal interpreter.
564 self.user_ns = {'__name__' :'__main__',
564 self.user_ns = {'__name__' :'__main__',
565 '__builtins__' : __builtin__,
565 '__builtins__' : __builtin__,
566 }
566 }
567 else:
567 else:
568 self.user_ns = user_ns
568 self.user_ns = user_ns
569
569
570 # The user namespace MUST have a pointer to the shell itself.
570 # The user namespace MUST have a pointer to the shell itself.
571 self.user_ns[name] = self
571 self.user_ns[name] = self
572
572
573 # We need to insert into sys.modules something that looks like a
573 # We need to insert into sys.modules something that looks like a
574 # module but which accesses the IPython namespace, for shelve and
574 # module but which accesses the IPython namespace, for shelve and
575 # pickle to work interactively. Normally they rely on getting
575 # pickle to work interactively. Normally they rely on getting
576 # everything out of __main__, but for embedding purposes each IPython
576 # everything out of __main__, but for embedding purposes each IPython
577 # instance has its own private namespace, so we can't go shoving
577 # instance has its own private namespace, so we can't go shoving
578 # everything into __main__.
578 # everything into __main__.
579
579
580 try:
580 try:
581 main_name = self.user_ns['__name__']
581 main_name = self.user_ns['__name__']
582 except KeyError:
582 except KeyError:
583 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
583 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
584 else:
584 else:
585 #print "pickle hack in place" # dbg
585 #print "pickle hack in place" # dbg
586 sys.modules[main_name] = FakeModule(self.user_ns)
586 sys.modules[main_name] = FakeModule(self.user_ns)
587
587
588 # List of input with multi-line handling.
588 # List of input with multi-line handling.
589 # Fill its zero entry, user counter starts at 1
589 # Fill its zero entry, user counter starts at 1
590 self.input_hist = InputList(['\n'])
590 self.input_hist = InputList(['\n'])
591
591
592 # list of visited directories
592 # list of visited directories
593 try:
593 try:
594 self.dir_hist = [os.getcwd()]
594 self.dir_hist = [os.getcwd()]
595 except IOError, e:
595 except IOError, e:
596 self.dir_hist = []
596 self.dir_hist = []
597
597
598 # dict of output history
598 # dict of output history
599 self.output_hist = {}
599 self.output_hist = {}
600
600
601 # dict of names to be treated as system aliases. Each entry in the
601 # dict of names to be treated as system aliases. Each entry in the
602 # alias table must be a 2-tuple of the form (N,name), where N is the
602 # alias table must be a 2-tuple of the form (N,name), where N is the
603 # number of positional arguments of the alias.
603 # number of positional arguments of the alias.
604 self.alias_table = {}
604 self.alias_table = {}
605
605
606 # dict of things NOT to alias (keywords, builtins and some special magics)
606 # dict of things NOT to alias (keywords, builtins and some special magics)
607 no_alias = {}
607 no_alias = {}
608 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
608 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
609 for key in keyword.kwlist + no_alias_magics:
609 for key in keyword.kwlist + no_alias_magics:
610 no_alias[key] = 1
610 no_alias[key] = 1
611 no_alias.update(__builtin__.__dict__)
611 no_alias.update(__builtin__.__dict__)
612 self.no_alias = no_alias
612 self.no_alias = no_alias
613
613
614
614
615 # make global variables for user access to these
615 # make global variables for user access to these
616 self.user_ns['_ih'] = self.input_hist
616 self.user_ns['_ih'] = self.input_hist
617 self.user_ns['_oh'] = self.output_hist
617 self.user_ns['_oh'] = self.output_hist
618 self.user_ns['_dh'] = self.dir_hist
618 self.user_ns['_dh'] = self.dir_hist
619
619
620 # user aliases to input and output histories
620 # user aliases to input and output histories
621 self.user_ns['In'] = self.input_hist
621 self.user_ns['In'] = self.input_hist
622 self.user_ns['Out'] = self.output_hist
622 self.user_ns['Out'] = self.output_hist
623
623
624 # Store the actual shell's name
624 # Store the actual shell's name
625 self.name = name
625 self.name = name
626
626
627 # Object variable to store code object waiting execution. This is
627 # Object variable to store code object waiting execution. This is
628 # used mainly by the multithreaded shells, but it can come in handy in
628 # used mainly by the multithreaded shells, but it can come in handy in
629 # other situations. No need to use a Queue here, since it's a single
629 # other situations. No need to use a Queue here, since it's a single
630 # item which gets cleared once run.
630 # item which gets cleared once run.
631 self.code_to_run = None
631 self.code_to_run = None
632
632
633 # Job manager (for jobs run as background threads)
633 # Job manager (for jobs run as background threads)
634 self.jobs = BackgroundJobManager()
634 self.jobs = BackgroundJobManager()
635 # Put the job manager into builtins so it's always there.
635 # Put the job manager into builtins so it's always there.
636 __builtin__.jobs = self.jobs
636 __builtin__.jobs = self.jobs
637
637
638 # escapes for automatic behavior on the command line
638 # escapes for automatic behavior on the command line
639 self.ESC_SHELL = '!'
639 self.ESC_SHELL = '!'
640 self.ESC_HELP = '?'
640 self.ESC_HELP = '?'
641 self.ESC_MAGIC = '%'
641 self.ESC_MAGIC = '%'
642 self.ESC_QUOTE = ','
642 self.ESC_QUOTE = ','
643 self.ESC_QUOTE2 = ';'
643 self.ESC_QUOTE2 = ';'
644 self.ESC_PAREN = '/'
644 self.ESC_PAREN = '/'
645
645
646 # And their associated handlers
646 # And their associated handlers
647 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
647 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
648 self.ESC_QUOTE:self.handle_auto,
648 self.ESC_QUOTE:self.handle_auto,
649 self.ESC_QUOTE2:self.handle_auto,
649 self.ESC_QUOTE2:self.handle_auto,
650 self.ESC_MAGIC:self.handle_magic,
650 self.ESC_MAGIC:self.handle_magic,
651 self.ESC_HELP:self.handle_help,
651 self.ESC_HELP:self.handle_help,
652 self.ESC_SHELL:self.handle_shell_escape,
652 self.ESC_SHELL:self.handle_shell_escape,
653 }
653 }
654
654
655 # class initializations
655 # class initializations
656 code.InteractiveConsole.__init__(self,locals = self.user_ns)
656 code.InteractiveConsole.__init__(self,locals = self.user_ns)
657 Logger.__init__(self,log_ns = self.user_ns)
657 Logger.__init__(self,log_ns = self.user_ns)
658 Magic.__init__(self,self)
658 Magic.__init__(self,self)
659
659
660 # an ugly hack to get a pointer to the shell, so I can start writing
660 # an ugly hack to get a pointer to the shell, so I can start writing
661 # magic code via this pointer instead of the current mixin salad.
661 # magic code via this pointer instead of the current mixin salad.
662 Magic.set_shell(self,self)
662 Magic.set_shell(self,self)
663
663
664 # hooks holds pointers used for user-side customizations
664 # hooks holds pointers used for user-side customizations
665 self.hooks = Struct()
665 self.hooks = Struct()
666
666
667 # Set all default hooks, defined in the IPython.hooks module.
667 # Set all default hooks, defined in the IPython.hooks module.
668 hooks = IPython.hooks
668 hooks = IPython.hooks
669 for hook_name in hooks.__all__:
669 for hook_name in hooks.__all__:
670 self.set_hook(hook_name,getattr(hooks,hook_name))
670 self.set_hook(hook_name,getattr(hooks,hook_name))
671
671
672 # Flag to mark unconditional exit
672 # Flag to mark unconditional exit
673 self.exit_now = False
673 self.exit_now = False
674
674
675 self.usage_min = """\
675 self.usage_min = """\
676 An enhanced console for Python.
676 An enhanced console for Python.
677 Some of its features are:
677 Some of its features are:
678 - Readline support if the readline library is present.
678 - Readline support if the readline library is present.
679 - Tab completion in the local namespace.
679 - Tab completion in the local namespace.
680 - Logging of input, see command-line options.
680 - Logging of input, see command-line options.
681 - System shell escape via ! , eg !ls.
681 - System shell escape via ! , eg !ls.
682 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
682 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
683 - Keeps track of locally defined variables via %who, %whos.
683 - Keeps track of locally defined variables via %who, %whos.
684 - Show object information with a ? eg ?x or x? (use ?? for more info).
684 - Show object information with a ? eg ?x or x? (use ?? for more info).
685 """
685 """
686 if usage: self.usage = usage
686 if usage: self.usage = usage
687 else: self.usage = self.usage_min
687 else: self.usage = self.usage_min
688
688
689 # Storage
689 # Storage
690 self.rc = rc # This will hold all configuration information
690 self.rc = rc # This will hold all configuration information
691 self.inputcache = []
691 self.inputcache = []
692 self._boundcache = []
692 self._boundcache = []
693 self.pager = 'less'
693 self.pager = 'less'
694 # temporary files used for various purposes. Deleted at exit.
694 # temporary files used for various purposes. Deleted at exit.
695 self.tempfiles = []
695 self.tempfiles = []
696
696
697 # Keep track of readline usage (later set by init_readline)
697 # Keep track of readline usage (later set by init_readline)
698 self.has_readline = 0
698 self.has_readline = 0
699
699
700 # for pushd/popd management
700 # for pushd/popd management
701 try:
701 try:
702 self.home_dir = get_home_dir()
702 self.home_dir = get_home_dir()
703 except HomeDirError,msg:
703 except HomeDirError,msg:
704 fatal(msg)
704 fatal(msg)
705
705
706 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
706 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
707
707
708 # Functions to call the underlying shell.
708 # Functions to call the underlying shell.
709
709
710 # utility to expand user variables via Itpl
710 # utility to expand user variables via Itpl
711 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
711 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
712 self.user_ns))
712 self.user_ns))
713 # The first is similar to os.system, but it doesn't return a value,
713 # The first is similar to os.system, but it doesn't return a value,
714 # and it allows interpolation of variables in the user's namespace.
714 # and it allows interpolation of variables in the user's namespace.
715 self.system = lambda cmd: shell(self.var_expand(cmd),
715 self.system = lambda cmd: shell(self.var_expand(cmd),
716 header='IPython system call: ',
716 header='IPython system call: ',
717 verbose=self.rc.system_verbose)
717 verbose=self.rc.system_verbose)
718 # These are for getoutput and getoutputerror:
718 # These are for getoutput and getoutputerror:
719 self.getoutput = lambda cmd: \
719 self.getoutput = lambda cmd: \
720 getoutput(self.var_expand(cmd),
720 getoutput(self.var_expand(cmd),
721 header='IPython system call: ',
721 header='IPython system call: ',
722 verbose=self.rc.system_verbose)
722 verbose=self.rc.system_verbose)
723 self.getoutputerror = lambda cmd: \
723 self.getoutputerror = lambda cmd: \
724 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
724 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
725 self.user_ns)),
725 self.user_ns)),
726 header='IPython system call: ',
726 header='IPython system call: ',
727 verbose=self.rc.system_verbose)
727 verbose=self.rc.system_verbose)
728
728
729 # RegExp for splitting line contents into pre-char//first
729 # RegExp for splitting line contents into pre-char//first
730 # word-method//rest. For clarity, each group in on one line.
730 # word-method//rest. For clarity, each group in on one line.
731
731
732 # WARNING: update the regexp if the above escapes are changed, as they
732 # WARNING: update the regexp if the above escapes are changed, as they
733 # are hardwired in.
733 # are hardwired in.
734
734
735 # Don't get carried away with trying to make the autocalling catch too
735 # Don't get carried away with trying to make the autocalling catch too
736 # much: it's better to be conservative rather than to trigger hidden
736 # much: it's better to be conservative rather than to trigger hidden
737 # evals() somewhere and end up causing side effects.
737 # evals() somewhere and end up causing side effects.
738
738
739 self.line_split = re.compile(r'^([\s*,;/])'
739 self.line_split = re.compile(r'^([\s*,;/])'
740 r'([\?\w\.]+\w*\s*)'
740 r'([\?\w\.]+\w*\s*)'
741 r'(\(?.*$)')
741 r'(\(?.*$)')
742
742
743 # Original re, keep around for a while in case changes break something
743 # Original re, keep around for a while in case changes break something
744 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
744 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
745 # r'(\s*[\?\w\.]+\w*\s*)'
745 # r'(\s*[\?\w\.]+\w*\s*)'
746 # r'(\(?.*$)')
746 # r'(\(?.*$)')
747
747
748 # RegExp to identify potential function names
748 # RegExp to identify potential function names
749 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
749 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
750 # RegExp to exclude strings with this start from autocalling
750 # RegExp to exclude strings with this start from autocalling
751 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
751 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
752 # try to catch also methods for stuff in lists/tuples/dicts: off
752 # try to catch also methods for stuff in lists/tuples/dicts: off
753 # (experimental). For this to work, the line_split regexp would need
753 # (experimental). For this to work, the line_split regexp would need
754 # to be modified so it wouldn't break things at '['. That line is
754 # to be modified so it wouldn't break things at '['. That line is
755 # nasty enough that I shouldn't change it until I can test it _well_.
755 # nasty enough that I shouldn't change it until I can test it _well_.
756 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
756 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
757
757
758 # keep track of where we started running (mainly for crash post-mortem)
758 # keep track of where we started running (mainly for crash post-mortem)
759 self.starting_dir = os.getcwd()
759 self.starting_dir = os.getcwd()
760
760
761 # Attributes for Logger mixin class, make defaults here
761 # Attributes for Logger mixin class, make defaults here
762 self._dolog = 0
762 self._dolog = 0
763 self.LOG = ''
763 self.LOG = ''
764 self.LOGDEF = '.InteractiveShell.log'
764 self.LOGDEF = '.InteractiveShell.log'
765 self.LOGMODE = 'over'
765 self.LOGMODE = 'over'
766 self.LOGHEAD = Itpl(
766 self.LOGHEAD = Itpl(
767 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
767 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
768 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
768 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
769 #log# opts = $self.rc.opts
769 #log# opts = $self.rc.opts
770 #log# args = $self.rc.args
770 #log# args = $self.rc.args
771 #log# It is safe to make manual edits below here.
771 #log# It is safe to make manual edits below here.
772 #log#-----------------------------------------------------------------------
772 #log#-----------------------------------------------------------------------
773 """)
773 """)
774 # Various switches which can be set
774 # Various switches which can be set
775 self.CACHELENGTH = 5000 # this is cheap, it's just text
775 self.CACHELENGTH = 5000 # this is cheap, it's just text
776 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
776 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
777 self.banner2 = banner2
777 self.banner2 = banner2
778
778
779 # TraceBack handlers:
779 # TraceBack handlers:
780 # Need two, one for syntax errors and one for other exceptions.
780 # Need two, one for syntax errors and one for other exceptions.
781 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
781 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
782 # This one is initialized with an offset, meaning we always want to
782 # This one is initialized with an offset, meaning we always want to
783 # remove the topmost item in the traceback, which is our own internal
783 # remove the topmost item in the traceback, which is our own internal
784 # code. Valid modes: ['Plain','Context','Verbose']
784 # code. Valid modes: ['Plain','Context','Verbose']
785 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
785 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
786 color_scheme='NoColor',
786 color_scheme='NoColor',
787 tb_offset = 1)
787 tb_offset = 1)
788 # and add any custom exception handlers the user may have specified
788 # and add any custom exception handlers the user may have specified
789 self.set_custom_exc(*custom_exceptions)
789 self.set_custom_exc(*custom_exceptions)
790
790
791 # Object inspector
791 # Object inspector
792 ins_colors = OInspect.InspectColors
792 ins_colors = OInspect.InspectColors
793 code_colors = PyColorize.ANSICodeColors
793 code_colors = PyColorize.ANSICodeColors
794 self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
794 self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
795 self.autoindent = 0
795 self.autoindent = 0
796
796
797 # Make some aliases automatically
797 # Make some aliases automatically
798 # Prepare list of shell aliases to auto-define
798 # Prepare list of shell aliases to auto-define
799 if os.name == 'posix':
799 if os.name == 'posix':
800 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
800 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
801 'mv mv -i','rm rm -i','cp cp -i',
801 'mv mv -i','rm rm -i','cp cp -i',
802 'cat cat','less less','clear clear',
802 'cat cat','less less','clear clear',
803 # a better ls
803 # a better ls
804 'ls ls -F',
804 'ls ls -F',
805 # long ls
805 # long ls
806 'll ls -lF',
806 'll ls -lF',
807 # color ls
807 # color ls
808 'lc ls -F -o --color',
808 'lc ls -F -o --color',
809 # ls normal files only
809 # ls normal files only
810 'lf ls -F -o --color %l | grep ^-',
810 'lf ls -F -o --color %l | grep ^-',
811 # ls symbolic links
811 # ls symbolic links
812 'lk ls -F -o --color %l | grep ^l',
812 'lk ls -F -o --color %l | grep ^l',
813 # directories or links to directories,
813 # directories or links to directories,
814 'ldir ls -F -o --color %l | grep /$',
814 'ldir ls -F -o --color %l | grep /$',
815 # things which are executable
815 # things which are executable
816 'lx ls -F -o --color %l | grep ^-..x',
816 'lx ls -F -o --color %l | grep ^-..x',
817 )
817 )
818 elif os.name in ['nt','dos']:
818 elif os.name in ['nt','dos']:
819 auto_alias = ('dir dir /on', 'ls dir /on',
819 auto_alias = ('dir dir /on', 'ls dir /on',
820 'ddir dir /ad /on', 'ldir dir /ad /on',
820 'ddir dir /ad /on', 'ldir dir /ad /on',
821 'mkdir mkdir','rmdir rmdir','echo echo',
821 'mkdir mkdir','rmdir rmdir','echo echo',
822 'ren ren','cls cls','copy copy')
822 'ren ren','cls cls','copy copy')
823 else:
823 else:
824 auto_alias = ()
824 auto_alias = ()
825 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
825 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
826 # Call the actual (public) initializer
826 # Call the actual (public) initializer
827 self.init_auto_alias()
827 self.init_auto_alias()
828 # end __init__
828 # end __init__
829
829
830 def set_hook(self,name,hook):
830 def set_hook(self,name,hook):
831 """set_hook(name,hook) -> sets an internal IPython hook.
831 """set_hook(name,hook) -> sets an internal IPython hook.
832
832
833 IPython exposes some of its internal API as user-modifiable hooks. By
833 IPython exposes some of its internal API as user-modifiable hooks. By
834 resetting one of these hooks, you can modify IPython's behavior to
834 resetting one of these hooks, you can modify IPython's behavior to
835 call at runtime your own routines."""
835 call at runtime your own routines."""
836
836
837 # At some point in the future, this should validate the hook before it
837 # At some point in the future, this should validate the hook before it
838 # accepts it. Probably at least check that the hook takes the number
838 # accepts it. Probably at least check that the hook takes the number
839 # of args it's supposed to.
839 # of args it's supposed to.
840 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
840 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
841
841
842 def set_custom_exc(self,exc_tuple,handler):
842 def set_custom_exc(self,exc_tuple,handler):
843 """set_custom_exc(exc_tuple,handler)
843 """set_custom_exc(exc_tuple,handler)
844
844
845 Set a custom exception handler, which will be called if any of the
845 Set a custom exception handler, which will be called if any of the
846 exceptions in exc_tuple occur in the mainloop (specifically, in the
846 exceptions in exc_tuple occur in the mainloop (specifically, in the
847 runcode() method.
847 runcode() method.
848
848
849 Inputs:
849 Inputs:
850
850
851 - exc_tuple: a *tuple* of valid exceptions to call the defined
851 - exc_tuple: a *tuple* of valid exceptions to call the defined
852 handler for. It is very important that you use a tuple, and NOT A
852 handler for. It is very important that you use a tuple, and NOT A
853 LIST here, because of the way Python's except statement works. If
853 LIST here, because of the way Python's except statement works. If
854 you only want to trap a single exception, use a singleton tuple:
854 you only want to trap a single exception, use a singleton tuple:
855
855
856 exc_tuple == (MyCustomException,)
856 exc_tuple == (MyCustomException,)
857
857
858 - handler: this must be defined as a function with the following
858 - handler: this must be defined as a function with the following
859 basic interface: def my_handler(self,etype,value,tb).
859 basic interface: def my_handler(self,etype,value,tb).
860
860
861 This will be made into an instance method (via new.instancemethod)
861 This will be made into an instance method (via new.instancemethod)
862 of IPython itself, and it will be called if any of the exceptions
862 of IPython itself, and it will be called if any of the exceptions
863 listed in the exc_tuple are caught. If the handler is None, an
863 listed in the exc_tuple are caught. If the handler is None, an
864 internal basic one is used, which just prints basic info.
864 internal basic one is used, which just prints basic info.
865
865
866 WARNING: by putting in your own exception handler into IPython's main
866 WARNING: by putting in your own exception handler into IPython's main
867 execution loop, you run a very good chance of nasty crashes. This
867 execution loop, you run a very good chance of nasty crashes. This
868 facility should only be used if you really know what you are doing."""
868 facility should only be used if you really know what you are doing."""
869
869
870 assert type(exc_tuple)==type(()) , \
870 assert type(exc_tuple)==type(()) , \
871 "The custom exceptions must be given AS A TUPLE."
871 "The custom exceptions must be given AS A TUPLE."
872
872
873 def dummy_handler(self,etype,value,tb):
873 def dummy_handler(self,etype,value,tb):
874 print '*** Simple custom exception handler ***'
874 print '*** Simple custom exception handler ***'
875 print 'Exception type :',etype
875 print 'Exception type :',etype
876 print 'Exception value:',value
876 print 'Exception value:',value
877 print 'Traceback :',tb
877 print 'Traceback :',tb
878 print 'Source code :','\n'.join(self.buffer)
878 print 'Source code :','\n'.join(self.buffer)
879
879
880 if handler is None: handler = dummy_handler
880 if handler is None: handler = dummy_handler
881
881
882 self.CustomTB = new.instancemethod(handler,self,self.__class__)
882 self.CustomTB = new.instancemethod(handler,self,self.__class__)
883 self.custom_exceptions = exc_tuple
883 self.custom_exceptions = exc_tuple
884
884
885 def set_custom_completer(self,completer,pos=0):
885 def set_custom_completer(self,completer,pos=0):
886 """set_custom_completer(completer,pos=0)
886 """set_custom_completer(completer,pos=0)
887
887
888 Adds a new custom completer function.
888 Adds a new custom completer function.
889
889
890 The position argument (defaults to 0) is the index in the completers
890 The position argument (defaults to 0) is the index in the completers
891 list where you want the completer to be inserted."""
891 list where you want the completer to be inserted."""
892
892
893 newcomp = new.instancemethod(completer,self.Completer,
893 newcomp = new.instancemethod(completer,self.Completer,
894 self.Completer.__class__)
894 self.Completer.__class__)
895 self.Completer.matchers.insert(pos,newcomp)
895 self.Completer.matchers.insert(pos,newcomp)
896
896
897 def complete(self,text):
897 def complete(self,text):
898 """Return a sorted list of all possible completions on text.
898 """Return a sorted list of all possible completions on text.
899
899
900 Inputs:
900 Inputs:
901
901
902 - text: a string of text to be completed on.
902 - text: a string of text to be completed on.
903
903
904 This is a wrapper around the completion mechanism, similar to what
904 This is a wrapper around the completion mechanism, similar to what
905 readline does at the command line when the TAB key is hit. By
905 readline does at the command line when the TAB key is hit. By
906 exposing it as a method, it can be used by other non-readline
906 exposing it as a method, it can be used by other non-readline
907 environments (such as GUIs) for text completion.
907 environments (such as GUIs) for text completion.
908
908
909 Simple usage example:
909 Simple usage example:
910
910
911 In [1]: x = 'hello'
911 In [1]: x = 'hello'
912
912
913 In [2]: __IP.complete('x.l')
913 In [2]: __IP.complete('x.l')
914 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
914 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
915
915
916 complete = self.Completer.complete
916 complete = self.Completer.complete
917 state = 0
917 state = 0
918 # use a dict so we get unique keys, since ipyhton's multiple
918 # use a dict so we get unique keys, since ipyhton's multiple
919 # completers can return duplicates.
919 # completers can return duplicates.
920 comps = {}
920 comps = {}
921 while True:
921 while True:
922 newcomp = complete(text,state)
922 newcomp = complete(text,state)
923 if newcomp is None:
923 if newcomp is None:
924 break
924 break
925 comps[newcomp] = 1
925 comps[newcomp] = 1
926 state += 1
926 state += 1
927 outcomps = comps.keys()
927 outcomps = comps.keys()
928 outcomps.sort()
928 outcomps.sort()
929 return outcomps
929 return outcomps
930
930
931 def post_config_initialization(self):
931 def post_config_initialization(self):
932 """Post configuration init method
932 """Post configuration init method
933
933
934 This is called after the configuration files have been processed to
934 This is called after the configuration files have been processed to
935 'finalize' the initialization."""
935 'finalize' the initialization."""
936
936
937 # dynamic data that survives through sessions
937 # dynamic data that survives through sessions
938 # XXX make the filename a config option?
938 # XXX make the filename a config option?
939 persist_base = 'persist'
939 persist_base = 'persist'
940 if self.rc.profile:
940 if self.rc.profile:
941 persist_base += '_%s' % self.rc.profile
941 persist_base += '_%s' % self.rc.profile
942 self.persist_fname = os.path.join(self.rc.ipythondir,persist_base)
942 self.persist_fname = os.path.join(self.rc.ipythondir,persist_base)
943
943
944 try:
944 try:
945 self.persist = pickle.load(file(self.persist_fname))
945 self.persist = pickle.load(file(self.persist_fname))
946 except:
946 except:
947 self.persist = {}
947 self.persist = {}
948
948
949 def init_auto_alias(self):
949 def init_auto_alias(self):
950 """Define some aliases automatically.
950 """Define some aliases automatically.
951
951
952 These are ALL parameter-less aliases"""
952 These are ALL parameter-less aliases"""
953 for alias,cmd in self.auto_alias:
953 for alias,cmd in self.auto_alias:
954 self.alias_table[alias] = (0,cmd)
954 self.alias_table[alias] = (0,cmd)
955
955
956 def alias_table_validate(self,verbose=0):
956 def alias_table_validate(self,verbose=0):
957 """Update information about the alias table.
957 """Update information about the alias table.
958
958
959 In particular, make sure no Python keywords/builtins are in it."""
959 In particular, make sure no Python keywords/builtins are in it."""
960
960
961 no_alias = self.no_alias
961 no_alias = self.no_alias
962 for k in self.alias_table.keys():
962 for k in self.alias_table.keys():
963 if k in no_alias:
963 if k in no_alias:
964 del self.alias_table[k]
964 del self.alias_table[k]
965 if verbose:
965 if verbose:
966 print ("Deleting alias <%s>, it's a Python "
966 print ("Deleting alias <%s>, it's a Python "
967 "keyword or builtin." % k)
967 "keyword or builtin." % k)
968
968
969 def set_autoindent(self,value=None):
969 def set_autoindent(self,value=None):
970 """Set the autoindent flag, checking for readline support.
970 """Set the autoindent flag, checking for readline support.
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 not self.has_readline:
974 if not self.has_readline:
975 if os.name == 'posix':
975 if os.name == 'posix':
976 warn("The auto-indent feature requires the readline library")
976 warn("The auto-indent feature requires the readline library")
977 self.autoindent = 0
977 self.autoindent = 0
978 return
978 return
979 if value is None:
979 if value is None:
980 self.autoindent = not self.autoindent
980 self.autoindent = not self.autoindent
981 else:
981 else:
982 self.autoindent = value
982 self.autoindent = value
983
983
984 def rc_set_toggle(self,rc_field,value=None):
984 def rc_set_toggle(self,rc_field,value=None):
985 """Set or toggle a field in IPython's rc config. structure.
985 """Set or toggle a field in IPython's rc config. structure.
986
986
987 If called with no arguments, it acts as a toggle.
987 If called with no arguments, it acts as a toggle.
988
988
989 If called with a non-existent field, the resulting AttributeError
989 If called with a non-existent field, the resulting AttributeError
990 exception will propagate out."""
990 exception will propagate out."""
991
991
992 rc_val = getattr(self.rc,rc_field)
992 rc_val = getattr(self.rc,rc_field)
993 if value is None:
993 if value is None:
994 value = not rc_val
994 value = not rc_val
995 setattr(self.rc,rc_field,value)
995 setattr(self.rc,rc_field,value)
996
996
997 def user_setup(self,ipythondir,rc_suffix,mode='install'):
997 def user_setup(self,ipythondir,rc_suffix,mode='install'):
998 """Install the user configuration directory.
998 """Install the user configuration directory.
999
999
1000 Can be called when running for the first time or to upgrade the user's
1000 Can be called when running for the first time or to upgrade the user's
1001 .ipython/ directory with the mode parameter. Valid modes are 'install'
1001 .ipython/ directory with the mode parameter. Valid modes are 'install'
1002 and 'upgrade'."""
1002 and 'upgrade'."""
1003
1003
1004 def wait():
1004 def wait():
1005 try:
1005 try:
1006 raw_input("Please press <RETURN> to start IPython.")
1006 raw_input("Please press <RETURN> to start IPython.")
1007 except EOFError:
1007 except EOFError:
1008 print >> Term.cout
1008 print >> Term.cout
1009 print '*'*70
1009 print '*'*70
1010
1010
1011 cwd = os.getcwd() # remember where we started
1011 cwd = os.getcwd() # remember where we started
1012 glb = glob.glob
1012 glb = glob.glob
1013 print '*'*70
1013 print '*'*70
1014 if mode == 'install':
1014 if mode == 'install':
1015 print \
1015 print \
1016 """Welcome to IPython. I will try to create a personal configuration directory
1016 """Welcome to IPython. I will try to create a personal configuration directory
1017 where you can customize many aspects of IPython's functionality in:\n"""
1017 where you can customize many aspects of IPython's functionality in:\n"""
1018 else:
1018 else:
1019 print 'I am going to upgrade your configuration in:'
1019 print 'I am going to upgrade your configuration in:'
1020
1020
1021 print ipythondir
1021 print ipythondir
1022
1022
1023 rcdirend = os.path.join('IPython','UserConfig')
1023 rcdirend = os.path.join('IPython','UserConfig')
1024 cfg = lambda d: os.path.join(d,rcdirend)
1024 cfg = lambda d: os.path.join(d,rcdirend)
1025 try:
1025 try:
1026 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1026 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1027 except IOError:
1027 except IOError:
1028 warning = """
1028 warning = """
1029 Installation error. IPython's directory was not found.
1029 Installation error. IPython's directory was not found.
1030
1030
1031 Check the following:
1031 Check the following:
1032
1032
1033 The ipython/IPython directory should be in a directory belonging to your
1033 The ipython/IPython directory should be in a directory belonging to your
1034 PYTHONPATH environment variable (that is, it should be in a directory
1034 PYTHONPATH environment variable (that is, it should be in a directory
1035 belonging to sys.path). You can copy it explicitly there or just link to it.
1035 belonging to sys.path). You can copy it explicitly there or just link to it.
1036
1036
1037 IPython will proceed with builtin defaults.
1037 IPython will proceed with builtin defaults.
1038 """
1038 """
1039 warn(warning)
1039 warn(warning)
1040 wait()
1040 wait()
1041 return
1041 return
1042
1042
1043 if mode == 'install':
1043 if mode == 'install':
1044 try:
1044 try:
1045 shutil.copytree(rcdir,ipythondir)
1045 shutil.copytree(rcdir,ipythondir)
1046 os.chdir(ipythondir)
1046 os.chdir(ipythondir)
1047 rc_files = glb("ipythonrc*")
1047 rc_files = glb("ipythonrc*")
1048 for rc_file in rc_files:
1048 for rc_file in rc_files:
1049 os.rename(rc_file,rc_file+rc_suffix)
1049 os.rename(rc_file,rc_file+rc_suffix)
1050 except:
1050 except:
1051 warning = """
1051 warning = """
1052
1052
1053 There was a problem with the installation:
1053 There was a problem with the installation:
1054 %s
1054 %s
1055 Try to correct it or contact the developers if you think it's a bug.
1055 Try to correct it or contact the developers if you think it's a bug.
1056 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1056 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1057 warn(warning)
1057 warn(warning)
1058 wait()
1058 wait()
1059 return
1059 return
1060
1060
1061 elif mode == 'upgrade':
1061 elif mode == 'upgrade':
1062 try:
1062 try:
1063 os.chdir(ipythondir)
1063 os.chdir(ipythondir)
1064 except:
1064 except:
1065 print """
1065 print """
1066 Can not upgrade: changing to directory %s failed. Details:
1066 Can not upgrade: changing to directory %s failed. Details:
1067 %s
1067 %s
1068 """ % (ipythondir,sys.exc_info()[1])
1068 """ % (ipythondir,sys.exc_info()[1])
1069 wait()
1069 wait()
1070 return
1070 return
1071 else:
1071 else:
1072 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1072 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1073 for new_full_path in sources:
1073 for new_full_path in sources:
1074 new_filename = os.path.basename(new_full_path)
1074 new_filename = os.path.basename(new_full_path)
1075 if new_filename.startswith('ipythonrc'):
1075 if new_filename.startswith('ipythonrc'):
1076 new_filename = new_filename + rc_suffix
1076 new_filename = new_filename + rc_suffix
1077 # The config directory should only contain files, skip any
1077 # The config directory should only contain files, skip any
1078 # directories which may be there (like CVS)
1078 # directories which may be there (like CVS)
1079 if os.path.isdir(new_full_path):
1079 if os.path.isdir(new_full_path):
1080 continue
1080 continue
1081 if os.path.exists(new_filename):
1081 if os.path.exists(new_filename):
1082 old_file = new_filename+'.old'
1082 old_file = new_filename+'.old'
1083 if os.path.exists(old_file):
1083 if os.path.exists(old_file):
1084 os.remove(old_file)
1084 os.remove(old_file)
1085 os.rename(new_filename,old_file)
1085 os.rename(new_filename,old_file)
1086 shutil.copy(new_full_path,new_filename)
1086 shutil.copy(new_full_path,new_filename)
1087 else:
1087 else:
1088 raise ValueError,'unrecognized mode for install:',`mode`
1088 raise ValueError,'unrecognized mode for install:',`mode`
1089
1089
1090 # Fix line-endings to those native to each platform in the config
1090 # Fix line-endings to those native to each platform in the config
1091 # directory.
1091 # directory.
1092 try:
1092 try:
1093 os.chdir(ipythondir)
1093 os.chdir(ipythondir)
1094 except:
1094 except:
1095 print """
1095 print """
1096 Problem: changing to directory %s failed.
1096 Problem: changing to directory %s failed.
1097 Details:
1097 Details:
1098 %s
1098 %s
1099
1099
1100 Some configuration files may have incorrect line endings. This should not
1100 Some configuration files may have incorrect line endings. This should not
1101 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1101 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1102 wait()
1102 wait()
1103 else:
1103 else:
1104 for fname in glb('ipythonrc*'):
1104 for fname in glb('ipythonrc*'):
1105 try:
1105 try:
1106 native_line_ends(fname,backup=0)
1106 native_line_ends(fname,backup=0)
1107 except IOError:
1107 except IOError:
1108 pass
1108 pass
1109
1109
1110 if mode == 'install':
1110 if mode == 'install':
1111 print """
1111 print """
1112 Successful installation!
1112 Successful installation!
1113
1113
1114 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1114 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1115 IPython manual (there are both HTML and PDF versions supplied with the
1115 IPython manual (there are both HTML and PDF versions supplied with the
1116 distribution) to make sure that your system environment is properly configured
1116 distribution) to make sure that your system environment is properly configured
1117 to take advantage of IPython's features."""
1117 to take advantage of IPython's features."""
1118 else:
1118 else:
1119 print """
1119 print """
1120 Successful upgrade!
1120 Successful upgrade!
1121
1121
1122 All files in your directory:
1122 All files in your directory:
1123 %(ipythondir)s
1123 %(ipythondir)s
1124 which would have been overwritten by the upgrade were backed up with a .old
1124 which would have been overwritten by the upgrade were backed up with a .old
1125 extension. If you had made particular customizations in those files you may
1125 extension. If you had made particular customizations in those files you may
1126 want to merge them back into the new files.""" % locals()
1126 want to merge them back into the new files.""" % locals()
1127 wait()
1127 wait()
1128 os.chdir(cwd)
1128 os.chdir(cwd)
1129 # end user_setup()
1129 # end user_setup()
1130
1130
1131 def atexit_operations(self):
1131 def atexit_operations(self):
1132 """This will be executed at the time of exit.
1132 """This will be executed at the time of exit.
1133
1133
1134 Saving of persistent data should be performed here. """
1134 Saving of persistent data should be performed here. """
1135
1135
1136 # input history
1136 # input history
1137 self.savehist()
1137 self.savehist()
1138
1138
1139 # Cleanup all tempfiles left around
1139 # Cleanup all tempfiles left around
1140 for tfile in self.tempfiles:
1140 for tfile in self.tempfiles:
1141 try:
1141 try:
1142 os.unlink(tfile)
1142 os.unlink(tfile)
1143 except OSError:
1143 except OSError:
1144 pass
1144 pass
1145
1145
1146 # save the "persistent data" catch-all dictionary
1146 # save the "persistent data" catch-all dictionary
1147 try:
1147 try:
1148 pickle.dump(self.persist, open(self.persist_fname,"w"))
1148 pickle.dump(self.persist, open(self.persist_fname,"w"))
1149 except:
1149 except:
1150 print "*** ERROR *** persistent data saving failed."
1150 print "*** ERROR *** persistent data saving failed."
1151
1151
1152 def savehist(self):
1152 def savehist(self):
1153 """Save input history to a file (via readline library)."""
1153 """Save input history to a file (via readline library)."""
1154 try:
1154 try:
1155 self.readline.write_history_file(self.histfile)
1155 self.readline.write_history_file(self.histfile)
1156 except:
1156 except:
1157 print 'Unable to save IPython command history to file: ' + \
1157 print 'Unable to save IPython command history to file: ' + \
1158 `self.histfile`
1158 `self.histfile`
1159
1159
1160 def pre_readline(self):
1160 def pre_readline(self):
1161 """readline hook to be used at the start of each line.
1161 """readline hook to be used at the start of each line.
1162
1162
1163 Currently it handles auto-indent only."""
1163 Currently it handles auto-indent only."""
1164
1164
1165 self.readline.insert_text(' '* self.readline_indent)
1165 self.readline.insert_text(' '* self.readline_indent)
1166
1166
1167 def init_readline(self):
1167 def init_readline(self):
1168 """Command history completion/saving/reloading."""
1168 """Command history completion/saving/reloading."""
1169 try:
1169 try:
1170 import readline
1170 import readline
1171 self.Completer = MagicCompleter(self,
1171 self.Completer = MagicCompleter(self,
1172 self.user_ns,
1172 self.user_ns,
1173 self.rc.readline_omit__names,
1173 self.rc.readline_omit__names,
1174 self.alias_table)
1174 self.alias_table)
1175 except ImportError,NameError:
1175 except ImportError,NameError:
1176 # If FlexCompleter failed to import, MagicCompleter won't be
1176 # If FlexCompleter failed to import, MagicCompleter won't be
1177 # defined. This can happen because of a problem with readline
1177 # defined. This can happen because of a problem with readline
1178 self.has_readline = 0
1178 self.has_readline = 0
1179 # no point in bugging windows users with this every time:
1179 # no point in bugging windows users with this every time:
1180 if os.name == 'posix':
1180 if os.name == 'posix':
1181 warn('Readline services not available on this platform.')
1181 warn('Readline services not available on this platform.')
1182 else:
1182 else:
1183 import atexit
1183 import atexit
1184
1184
1185 # Platform-specific configuration
1185 # Platform-specific configuration
1186 if os.name == 'nt':
1186 if os.name == 'nt':
1187 # readline under Windows modifies the default exit behavior
1187 # readline under Windows modifies the default exit behavior
1188 # from being Ctrl-Z/Return to the Unix Ctrl-D one.
1188 # from being Ctrl-Z/Return to the Unix Ctrl-D one.
1189 __builtin__.exit = __builtin__.quit = \
1189 __builtin__.exit = __builtin__.quit = \
1190 ('Use Ctrl-D (i.e. EOF) to exit. '
1190 ('Use Ctrl-D (i.e. EOF) to exit. '
1191 'Use %Exit or %Quit to exit without confirmation.')
1191 'Use %Exit or %Quit to exit without confirmation.')
1192 self.readline_startup_hook = readline.set_pre_input_hook
1192 self.readline_startup_hook = readline.set_pre_input_hook
1193 else:
1193 else:
1194 self.readline_startup_hook = readline.set_startup_hook
1194 self.readline_startup_hook = readline.set_startup_hook
1195
1195
1196 # Load user's initrc file (readline config)
1196 # Load user's initrc file (readline config)
1197 inputrc_name = os.environ.get('INPUTRC')
1197 inputrc_name = os.environ.get('INPUTRC')
1198 if inputrc_name is None:
1198 if inputrc_name is None:
1199 home_dir = get_home_dir()
1199 home_dir = get_home_dir()
1200 if home_dir is not None:
1200 if home_dir is not None:
1201 inputrc_name = os.path.join(home_dir,'.inputrc')
1201 inputrc_name = os.path.join(home_dir,'.inputrc')
1202 if os.path.isfile(inputrc_name):
1202 if os.path.isfile(inputrc_name):
1203 try:
1203 try:
1204 readline.read_init_file(inputrc_name)
1204 readline.read_init_file(inputrc_name)
1205 except:
1205 except:
1206 warn('Problems reading readline initialization file <%s>'
1206 warn('Problems reading readline initialization file <%s>'
1207 % inputrc_name)
1207 % inputrc_name)
1208
1208
1209 self.has_readline = 1
1209 self.has_readline = 1
1210 self.readline = readline
1210 self.readline = readline
1211 self.readline_indent = 0 # for auto-indenting via readline
1211 self.readline_indent = 0 # for auto-indenting via readline
1212 # save this in sys so embedded copies can restore it properly
1212 # save this in sys so embedded copies can restore it properly
1213 sys.ipcompleter = self.Completer.complete
1213 sys.ipcompleter = self.Completer.complete
1214 readline.set_completer(self.Completer.complete)
1214 readline.set_completer(self.Completer.complete)
1215
1215
1216 # Configure readline according to user's prefs
1216 # Configure readline according to user's prefs
1217 for rlcommand in self.rc.readline_parse_and_bind:
1217 for rlcommand in self.rc.readline_parse_and_bind:
1218 readline.parse_and_bind(rlcommand)
1218 readline.parse_and_bind(rlcommand)
1219
1219
1220 # remove some chars from the delimiters list
1220 # remove some chars from the delimiters list
1221 delims = readline.get_completer_delims()
1221 delims = readline.get_completer_delims()
1222 delims = delims.translate(string._idmap,
1222 delims = delims.translate(string._idmap,
1223 self.rc.readline_remove_delims)
1223 self.rc.readline_remove_delims)
1224 readline.set_completer_delims(delims)
1224 readline.set_completer_delims(delims)
1225 # otherwise we end up with a monster history after a while:
1225 # otherwise we end up with a monster history after a while:
1226 readline.set_history_length(1000)
1226 readline.set_history_length(1000)
1227 try:
1227 try:
1228 #print '*** Reading readline history' # dbg
1228 #print '*** Reading readline history' # dbg
1229 readline.read_history_file(self.histfile)
1229 readline.read_history_file(self.histfile)
1230 except IOError:
1230 except IOError:
1231 pass # It doesn't exist yet.
1231 pass # It doesn't exist yet.
1232
1232
1233 atexit.register(self.atexit_operations)
1233 atexit.register(self.atexit_operations)
1234 del atexit
1234 del atexit
1235
1235
1236 # Configure auto-indent for all platforms
1236 # Configure auto-indent for all platforms
1237 self.set_autoindent(self.rc.autoindent)
1237 self.set_autoindent(self.rc.autoindent)
1238
1238
1239 def showsyntaxerror(self, filename=None):
1239 def showsyntaxerror(self, filename=None):
1240 """Display the syntax error that just occurred.
1240 """Display the syntax error that just occurred.
1241
1241
1242 This doesn't display a stack trace because there isn't one.
1242 This doesn't display a stack trace because there isn't one.
1243
1243
1244 If a filename is given, it is stuffed in the exception instead
1244 If a filename is given, it is stuffed in the exception instead
1245 of what was there before (because Python's parser always uses
1245 of what was there before (because Python's parser always uses
1246 "<string>" when reading from a string).
1246 "<string>" when reading from a string).
1247 """
1247 """
1248 type, value, sys.last_traceback = sys.exc_info()
1248 type, value, sys.last_traceback = sys.exc_info()
1249 sys.last_type = type
1249 sys.last_type = type
1250 sys.last_value = value
1250 sys.last_value = value
1251 if filename and type is SyntaxError:
1251 if filename and type is SyntaxError:
1252 # Work hard to stuff the correct filename in the exception
1252 # Work hard to stuff the correct filename in the exception
1253 try:
1253 try:
1254 msg, (dummy_filename, lineno, offset, line) = value
1254 msg, (dummy_filename, lineno, offset, line) = value
1255 except:
1255 except:
1256 # Not the format we expect; leave it alone
1256 # Not the format we expect; leave it alone
1257 pass
1257 pass
1258 else:
1258 else:
1259 # Stuff in the right filename
1259 # Stuff in the right filename
1260 try:
1260 try:
1261 # Assume SyntaxError is a class exception
1261 # Assume SyntaxError is a class exception
1262 value = SyntaxError(msg, (filename, lineno, offset, line))
1262 value = SyntaxError(msg, (filename, lineno, offset, line))
1263 except:
1263 except:
1264 # If that failed, assume SyntaxError is a string
1264 # If that failed, assume SyntaxError is a string
1265 value = msg, (filename, lineno, offset, line)
1265 value = msg, (filename, lineno, offset, line)
1266 self.SyntaxTB(type,value,[])
1266 self.SyntaxTB(type,value,[])
1267
1267
1268 def debugger(self):
1268 def debugger(self):
1269 """Call the pdb debugger."""
1269 """Call the pdb debugger."""
1270
1270
1271 if not self.rc.pdb:
1271 if not self.rc.pdb:
1272 return
1272 return
1273 pdb.pm()
1273 pdb.pm()
1274
1274
1275 def showtraceback(self,exc_tuple = None):
1275 def showtraceback(self,exc_tuple = None,filename=None):
1276 """Display the exception that just occurred."""
1276 """Display the exception that just occurred."""
1277
1277
1278 # Though this won't be called by syntax errors in the input line,
1278 # Though this won't be called by syntax errors in the input line,
1279 # there may be SyntaxError cases whith imported code.
1279 # there may be SyntaxError cases whith imported code.
1280 if exc_tuple is None:
1280 if exc_tuple is None:
1281 type, value, tb = sys.exc_info()
1281 type, value, tb = sys.exc_info()
1282 else:
1282 else:
1283 type, value, tb = exc_tuple
1283 type, value, tb = exc_tuple
1284 if type is SyntaxError:
1284 if type is SyntaxError:
1285 self.showsyntaxerror()
1285 self.showsyntaxerror(filename)
1286 else:
1286 else:
1287 sys.last_type = type
1287 sys.last_type = type
1288 sys.last_value = value
1288 sys.last_value = value
1289 sys.last_traceback = tb
1289 sys.last_traceback = tb
1290 self.InteractiveTB()
1290 self.InteractiveTB()
1291 if self.InteractiveTB.call_pdb and self.has_readline:
1291 if self.InteractiveTB.call_pdb and self.has_readline:
1292 # pdb mucks up readline, fix it back
1292 # pdb mucks up readline, fix it back
1293 self.readline.set_completer(self.Completer.complete)
1293 self.readline.set_completer(self.Completer.complete)
1294
1294
1295 def update_cache(self, line):
1295 def update_cache(self, line):
1296 """puts line into cache"""
1296 """puts line into cache"""
1297 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1297 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1298 if len(self.inputcache) >= self.CACHELENGTH:
1298 if len(self.inputcache) >= self.CACHELENGTH:
1299 self.inputcache.pop() # This not :-)
1299 self.inputcache.pop() # This not :-)
1300
1300
1301 def name_space_init(self):
1301 def name_space_init(self):
1302 """Create local namespace."""
1302 """Create local namespace."""
1303 # We want this to be a method to facilitate embedded initialization.
1303 # We want this to be a method to facilitate embedded initialization.
1304 code.InteractiveConsole.__init__(self,self.user_ns)
1304 code.InteractiveConsole.__init__(self,self.user_ns)
1305
1305
1306 def mainloop(self,banner=None):
1306 def mainloop(self,banner=None):
1307 """Creates the local namespace and starts the mainloop.
1307 """Creates the local namespace and starts the mainloop.
1308
1308
1309 If an optional banner argument is given, it will override the
1309 If an optional banner argument is given, it will override the
1310 internally created default banner."""
1310 internally created default banner."""
1311
1311
1312 self.name_space_init()
1312 self.name_space_init()
1313 if self.rc.c: # Emulate Python's -c option
1313 if self.rc.c: # Emulate Python's -c option
1314 self.exec_init_cmd()
1314 self.exec_init_cmd()
1315 if banner is None:
1315 if banner is None:
1316 if self.rc.banner:
1316 if self.rc.banner:
1317 banner = self.BANNER+self.banner2
1317 banner = self.BANNER+self.banner2
1318 else:
1318 else:
1319 banner = ''
1319 banner = ''
1320 self.interact(banner)
1320 self.interact(banner)
1321
1321
1322 def exec_init_cmd(self):
1322 def exec_init_cmd(self):
1323 """Execute a command given at the command line.
1323 """Execute a command given at the command line.
1324
1324
1325 This emulates Python's -c option."""
1325 This emulates Python's -c option."""
1326
1326
1327 sys.argv = ['-c']
1327 sys.argv = ['-c']
1328 self.push(self.rc.c)
1328 self.push(self.rc.c)
1329
1329
1330 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1330 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1331 """Embeds IPython into a running python program.
1331 """Embeds IPython into a running python program.
1332
1332
1333 Input:
1333 Input:
1334
1334
1335 - header: An optional header message can be specified.
1335 - header: An optional header message can be specified.
1336
1336
1337 - local_ns, global_ns: working namespaces. If given as None, the
1337 - local_ns, global_ns: working namespaces. If given as None, the
1338 IPython-initialized one is updated with __main__.__dict__, so that
1338 IPython-initialized one is updated with __main__.__dict__, so that
1339 program variables become visible but user-specific configuration
1339 program variables become visible but user-specific configuration
1340 remains possible.
1340 remains possible.
1341
1341
1342 - stack_depth: specifies how many levels in the stack to go to
1342 - stack_depth: specifies how many levels in the stack to go to
1343 looking for namespaces (when local_ns and global_ns are None). This
1343 looking for namespaces (when local_ns and global_ns are None). This
1344 allows an intermediate caller to make sure that this function gets
1344 allows an intermediate caller to make sure that this function gets
1345 the namespace from the intended level in the stack. By default (0)
1345 the namespace from the intended level in the stack. By default (0)
1346 it will get its locals and globals from the immediate caller.
1346 it will get its locals and globals from the immediate caller.
1347
1347
1348 Warning: it's possible to use this in a program which is being run by
1348 Warning: it's possible to use this in a program which is being run by
1349 IPython itself (via %run), but some funny things will happen (a few
1349 IPython itself (via %run), but some funny things will happen (a few
1350 globals get overwritten). In the future this will be cleaned up, as
1350 globals get overwritten). In the future this will be cleaned up, as
1351 there is no fundamental reason why it can't work perfectly."""
1351 there is no fundamental reason why it can't work perfectly."""
1352
1352
1353 # Patch for global embedding to make sure that things don't overwrite
1353 # Patch for global embedding to make sure that things don't overwrite
1354 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1354 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1355 # FIXME. Test this a bit more carefully (the if.. is new)
1355 # FIXME. Test this a bit more carefully (the if.. is new)
1356 if local_ns is None and global_ns is None:
1356 if local_ns is None and global_ns is None:
1357 self.user_ns.update(__main__.__dict__)
1357 self.user_ns.update(__main__.__dict__)
1358
1358
1359 # Get locals and globals from caller
1359 # Get locals and globals from caller
1360 if local_ns is None or global_ns is None:
1360 if local_ns is None or global_ns is None:
1361 call_frame = sys._getframe(stack_depth).f_back
1361 call_frame = sys._getframe(stack_depth).f_back
1362
1362
1363 if local_ns is None:
1363 if local_ns is None:
1364 local_ns = call_frame.f_locals
1364 local_ns = call_frame.f_locals
1365 if global_ns is None:
1365 if global_ns is None:
1366 global_ns = call_frame.f_globals
1366 global_ns = call_frame.f_globals
1367
1367
1368 # Update namespaces and fire up interpreter
1368 # Update namespaces and fire up interpreter
1369 self.user_ns.update(local_ns)
1369 self.user_ns.update(local_ns)
1370 self.interact(header)
1370 self.interact(header)
1371
1371
1372 # Remove locals from namespace
1372 # Remove locals from namespace
1373 for k in local_ns:
1373 for k in local_ns:
1374 del self.user_ns[k]
1374 del self.user_ns[k]
1375
1375
1376 def interact(self, banner=None):
1376 def interact(self, banner=None):
1377 """Closely emulate the interactive Python console.
1377 """Closely emulate the interactive Python console.
1378
1378
1379 The optional banner argument specify the banner to print
1379 The optional banner argument specify the banner to print
1380 before the first interaction; by default it prints a banner
1380 before the first interaction; by default it prints a banner
1381 similar to the one printed by the real Python interpreter,
1381 similar to the one printed by the real Python interpreter,
1382 followed by the current class name in parentheses (so as not
1382 followed by the current class name in parentheses (so as not
1383 to confuse this with the real interpreter -- since it's so
1383 to confuse this with the real interpreter -- since it's so
1384 close!).
1384 close!).
1385
1385
1386 """
1386 """
1387 cprt = 'Type "copyright", "credits" or "license" for more information.'
1387 cprt = 'Type "copyright", "credits" or "license" for more information.'
1388 if banner is None:
1388 if banner is None:
1389 self.write("Python %s on %s\n%s\n(%s)\n" %
1389 self.write("Python %s on %s\n%s\n(%s)\n" %
1390 (sys.version, sys.platform, cprt,
1390 (sys.version, sys.platform, cprt,
1391 self.__class__.__name__))
1391 self.__class__.__name__))
1392 else:
1392 else:
1393 self.write(banner)
1393 self.write(banner)
1394
1394
1395 more = 0
1395 more = 0
1396
1396
1397 # Mark activity in the builtins
1397 # Mark activity in the builtins
1398 __builtin__.__dict__['__IPYTHON__active'] += 1
1398 __builtin__.__dict__['__IPYTHON__active'] += 1
1399
1399
1400 # exit_now is set by a call to %Exit or %Quit
1400 # exit_now is set by a call to %Exit or %Quit
1401 while not self.exit_now:
1401 while not self.exit_now:
1402 try:
1402 try:
1403 if more:
1403 if more:
1404 prompt = self.outputcache.prompt2
1404 prompt = self.outputcache.prompt2
1405 if self.autoindent:
1405 if self.autoindent:
1406 self.readline_startup_hook(self.pre_readline)
1406 self.readline_startup_hook(self.pre_readline)
1407 else:
1407 else:
1408 prompt = self.outputcache.prompt1
1408 prompt = self.outputcache.prompt1
1409 try:
1409 try:
1410 line = self.raw_input(prompt)
1410 line = self.raw_input(prompt)
1411 if self.autoindent:
1411 if self.autoindent:
1412 self.readline_startup_hook(None)
1412 self.readline_startup_hook(None)
1413 except EOFError:
1413 except EOFError:
1414 if self.autoindent:
1414 if self.autoindent:
1415 self.readline_startup_hook(None)
1415 self.readline_startup_hook(None)
1416 self.write("\n")
1416 self.write("\n")
1417 if self.rc.confirm_exit:
1417 if self.rc.confirm_exit:
1418 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1418 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1419 break
1419 break
1420 else:
1420 else:
1421 break
1421 break
1422 else:
1422 else:
1423 more = self.push(line)
1423 more = self.push(line)
1424 # Auto-indent management
1424 # Auto-indent management
1425 if self.autoindent:
1425 if self.autoindent:
1426 if line:
1426 if line:
1427 ini_spaces = re.match('^(\s+)',line)
1427 ini_spaces = re.match('^(\s+)',line)
1428 if ini_spaces:
1428 if ini_spaces:
1429 nspaces = ini_spaces.end()
1429 nspaces = ini_spaces.end()
1430 else:
1430 else:
1431 nspaces = 0
1431 nspaces = 0
1432 self.readline_indent = nspaces
1432 self.readline_indent = nspaces
1433
1433
1434 if line[-1] == ':':
1434 if line[-1] == ':':
1435 self.readline_indent += 4
1435 self.readline_indent += 4
1436 elif re.match(r'^\s+raise|^\s+return',line):
1436 elif re.match(r'^\s+raise|^\s+return',line):
1437 self.readline_indent -= 4
1437 self.readline_indent -= 4
1438 else:
1438 else:
1439 self.readline_indent = 0
1439 self.readline_indent = 0
1440
1440
1441 except KeyboardInterrupt:
1441 except KeyboardInterrupt:
1442 self.write("\nKeyboardInterrupt\n")
1442 self.write("\nKeyboardInterrupt\n")
1443 self.resetbuffer()
1443 self.resetbuffer()
1444 more = 0
1444 more = 0
1445 # keep cache in sync with the prompt counter:
1445 # keep cache in sync with the prompt counter:
1446 self.outputcache.prompt_count -= 1
1446 self.outputcache.prompt_count -= 1
1447
1447
1448 if self.autoindent:
1448 if self.autoindent:
1449 self.readline_indent = 0
1449 self.readline_indent = 0
1450
1450
1451 except bdb.BdbQuit:
1451 except bdb.BdbQuit:
1452 warn("The Python debugger has exited with a BdbQuit exception.\n"
1452 warn("The Python debugger has exited with a BdbQuit exception.\n"
1453 "Because of how pdb handles the stack, it is impossible\n"
1453 "Because of how pdb handles the stack, it is impossible\n"
1454 "for IPython to properly format this particular exception.\n"
1454 "for IPython to properly format this particular exception.\n"
1455 "IPython will resume normal operation.")
1455 "IPython will resume normal operation.")
1456
1456
1457 # We are off again...
1457 # We are off again...
1458 __builtin__.__dict__['__IPYTHON__active'] -= 1
1458 __builtin__.__dict__['__IPYTHON__active'] -= 1
1459
1459
1460 def excepthook(self, type, value, tb):
1460 def excepthook(self, type, value, tb):
1461 """One more defense for GUI apps that call sys.excepthook.
1461 """One more defense for GUI apps that call sys.excepthook.
1462
1462
1463 GUI frameworks like wxPython trap exceptions and call
1463 GUI frameworks like wxPython trap exceptions and call
1464 sys.excepthook themselves. I guess this is a feature that
1464 sys.excepthook themselves. I guess this is a feature that
1465 enables them to keep running after exceptions that would
1465 enables them to keep running after exceptions that would
1466 otherwise kill their mainloop. This is a bother for IPython
1466 otherwise kill their mainloop. This is a bother for IPython
1467 which excepts to catch all of the program exceptions with a try:
1467 which excepts to catch all of the program exceptions with a try:
1468 except: statement.
1468 except: statement.
1469
1469
1470 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1470 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1471 any app directly invokes sys.excepthook, it will look to the user like
1471 any app directly invokes sys.excepthook, it will look to the user like
1472 IPython crashed. In order to work around this, we can disable the
1472 IPython crashed. In order to work around this, we can disable the
1473 CrashHandler and replace it with this excepthook instead, which prints a
1473 CrashHandler and replace it with this excepthook instead, which prints a
1474 regular traceback using our InteractiveTB. In this fashion, apps which
1474 regular traceback using our InteractiveTB. In this fashion, apps which
1475 call sys.excepthook will generate a regular-looking exception from
1475 call sys.excepthook will generate a regular-looking exception from
1476 IPython, and the CrashHandler will only be triggered by real IPython
1476 IPython, and the CrashHandler will only be triggered by real IPython
1477 crashes.
1477 crashes.
1478
1478
1479 This hook should be used sparingly, only in places which are not likely
1479 This hook should be used sparingly, only in places which are not likely
1480 to be true IPython errors.
1480 to be true IPython errors.
1481 """
1481 """
1482
1482
1483 self.InteractiveTB(type, value, tb, tb_offset=0)
1483 self.InteractiveTB(type, value, tb, tb_offset=0)
1484 if self.InteractiveTB.call_pdb and self.has_readline:
1484 if self.InteractiveTB.call_pdb and self.has_readline:
1485 self.readline.set_completer(self.Completer.complete)
1485 self.readline.set_completer(self.Completer.complete)
1486
1486
1487 def call_alias(self,alias,rest=''):
1487 def call_alias(self,alias,rest=''):
1488 """Call an alias given its name and the rest of the line.
1488 """Call an alias given its name and the rest of the line.
1489
1489
1490 This function MUST be given a proper alias, because it doesn't make
1490 This function MUST be given a proper alias, because it doesn't make
1491 any checks when looking up into the alias table. The caller is
1491 any checks when looking up into the alias table. The caller is
1492 responsible for invoking it only with a valid alias."""
1492 responsible for invoking it only with a valid alias."""
1493
1493
1494 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1494 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1495 nargs,cmd = self.alias_table[alias]
1495 nargs,cmd = self.alias_table[alias]
1496 # Expand the %l special to be the user's input line
1496 # Expand the %l special to be the user's input line
1497 if cmd.find('%l') >= 0:
1497 if cmd.find('%l') >= 0:
1498 cmd = cmd.replace('%l',rest)
1498 cmd = cmd.replace('%l',rest)
1499 rest = ''
1499 rest = ''
1500 if nargs==0:
1500 if nargs==0:
1501 # Simple, argument-less aliases
1501 # Simple, argument-less aliases
1502 cmd = '%s %s' % (cmd,rest)
1502 cmd = '%s %s' % (cmd,rest)
1503 else:
1503 else:
1504 # Handle aliases with positional arguments
1504 # Handle aliases with positional arguments
1505 args = rest.split(None,nargs)
1505 args = rest.split(None,nargs)
1506 if len(args)< nargs:
1506 if len(args)< nargs:
1507 error('Alias <%s> requires %s arguments, %s given.' %
1507 error('Alias <%s> requires %s arguments, %s given.' %
1508 (alias,nargs,len(args)))
1508 (alias,nargs,len(args)))
1509 return
1509 return
1510 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1510 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1511 # Now call the macro, evaluating in the user's namespace
1511 # Now call the macro, evaluating in the user's namespace
1512 try:
1512 try:
1513 self.system(cmd)
1513 self.system(cmd)
1514 except:
1514 except:
1515 self.showtraceback()
1515 self.showtraceback()
1516
1516
1517 def runlines(self,lines):
1517 def runlines(self,lines):
1518 """Run a string of one or more lines of source.
1518 """Run a string of one or more lines of source.
1519
1519
1520 This method is capable of running a string containing multiple source
1520 This method is capable of running a string containing multiple source
1521 lines, as if they had been entered at the IPython prompt. Since it
1521 lines, as if they had been entered at the IPython prompt. Since it
1522 exposes IPython's processing machinery, the given strings can contain
1522 exposes IPython's processing machinery, the given strings can contain
1523 magic calls (%magic), special shell access (!cmd), etc."""
1523 magic calls (%magic), special shell access (!cmd), etc."""
1524
1524
1525 # We must start with a clean buffer, in case this is run from an
1525 # We must start with a clean buffer, in case this is run from an
1526 # interactive IPython session (via a magic, for example).
1526 # interactive IPython session (via a magic, for example).
1527 self.resetbuffer()
1527 self.resetbuffer()
1528 lines = lines.split('\n')
1528 lines = lines.split('\n')
1529 more = 0
1529 more = 0
1530 for line in lines:
1530 for line in lines:
1531 # skip blank lines so we don't mess up the prompt counter, but do
1531 # skip blank lines so we don't mess up the prompt counter, but do
1532 # NOT skip even a blank line if we are in a code block (more is
1532 # NOT skip even a blank line if we are in a code block (more is
1533 # true)
1533 # true)
1534 if line or more:
1534 if line or more:
1535 more = self.push((self.prefilter(line,more)))
1535 more = self.push((self.prefilter(line,more)))
1536 # IPython's runsource returns None if there was an error
1536 # IPython's runsource returns None if there was an error
1537 # compiling the code. This allows us to stop processing right
1537 # compiling the code. This allows us to stop processing right
1538 # away, so the user gets the error message at the right place.
1538 # away, so the user gets the error message at the right place.
1539 if more is None:
1539 if more is None:
1540 break
1540 break
1541 # final newline in case the input didn't have it, so that the code
1541 # final newline in case the input didn't have it, so that the code
1542 # actually does get executed
1542 # actually does get executed
1543 if more:
1543 if more:
1544 self.push('\n')
1544 self.push('\n')
1545
1545
1546 def runsource(self, source, filename="<input>", symbol="single"):
1546 def runsource(self, source, filename="<input>", symbol="single"):
1547 """Compile and run some source in the interpreter.
1547 """Compile and run some source in the interpreter.
1548
1548
1549 Arguments are as for compile_command().
1549 Arguments are as for compile_command().
1550
1550
1551 One several things can happen:
1551 One several things can happen:
1552
1552
1553 1) The input is incorrect; compile_command() raised an
1553 1) The input is incorrect; compile_command() raised an
1554 exception (SyntaxError or OverflowError). A syntax traceback
1554 exception (SyntaxError or OverflowError). A syntax traceback
1555 will be printed by calling the showsyntaxerror() method.
1555 will be printed by calling the showsyntaxerror() method.
1556
1556
1557 2) The input is incomplete, and more input is required;
1557 2) The input is incomplete, and more input is required;
1558 compile_command() returned None. Nothing happens.
1558 compile_command() returned None. Nothing happens.
1559
1559
1560 3) The input is complete; compile_command() returned a code
1560 3) The input is complete; compile_command() returned a code
1561 object. The code is executed by calling self.runcode() (which
1561 object. The code is executed by calling self.runcode() (which
1562 also handles run-time exceptions, except for SystemExit).
1562 also handles run-time exceptions, except for SystemExit).
1563
1563
1564 The return value is:
1564 The return value is:
1565
1565
1566 - True in case 2
1566 - True in case 2
1567
1567
1568 - False in the other cases, unless an exception is raised, where
1568 - False in the other cases, unless an exception is raised, where
1569 None is returned instead. This can be used by external callers to
1569 None is returned instead. This can be used by external callers to
1570 know whether to continue feeding input or not.
1570 know whether to continue feeding input or not.
1571
1571
1572 The return value can be used to decide whether to use sys.ps1 or
1572 The return value can be used to decide whether to use sys.ps1 or
1573 sys.ps2 to prompt the next line."""
1573 sys.ps2 to prompt the next line."""
1574
1574
1575 try:
1575 try:
1576 code = self.compile(source, filename, symbol)
1576 code = self.compile(source, filename, symbol)
1577 except (OverflowError, SyntaxError, ValueError):
1577 except (OverflowError, SyntaxError, ValueError):
1578 # Case 1
1578 # Case 1
1579 self.showsyntaxerror(filename)
1579 self.showsyntaxerror(filename)
1580 return None
1580 return None
1581
1581
1582 if code is None:
1582 if code is None:
1583 # Case 2
1583 # Case 2
1584 return True
1584 return True
1585
1585
1586 # Case 3
1586 # Case 3
1587 # We store the code object so that threaded shells and
1587 # We store the code object so that threaded shells and
1588 # custom exception handlers can access all this info if needed.
1588 # custom exception handlers can access all this info if needed.
1589 # The source corresponding to this can be obtained from the
1589 # The source corresponding to this can be obtained from the
1590 # buffer attribute as '\n'.join(self.buffer).
1590 # buffer attribute as '\n'.join(self.buffer).
1591 self.code_to_run = code
1591 self.code_to_run = code
1592 # now actually execute the code object
1592 # now actually execute the code object
1593 if self.runcode(code) == 0:
1593 if self.runcode(code) == 0:
1594 return False
1594 return False
1595 else:
1595 else:
1596 return None
1596 return None
1597
1597
1598 def runcode(self,code_obj):
1598 def runcode(self,code_obj):
1599 """Execute a code object.
1599 """Execute a code object.
1600
1600
1601 When an exception occurs, self.showtraceback() is called to display a
1601 When an exception occurs, self.showtraceback() is called to display a
1602 traceback.
1602 traceback.
1603
1603
1604 Return value: a flag indicating whether the code to be run completed
1604 Return value: a flag indicating whether the code to be run completed
1605 successfully:
1605 successfully:
1606
1606
1607 - 0: successful execution.
1607 - 0: successful execution.
1608 - 1: an error occurred.
1608 - 1: an error occurred.
1609 """
1609 """
1610
1610
1611 # Set our own excepthook in case the user code tries to call it
1611 # Set our own excepthook in case the user code tries to call it
1612 # directly, so that the IPython crash handler doesn't get triggered
1612 # directly, so that the IPython crash handler doesn't get triggered
1613 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1613 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1614 outflag = 1 # happens in more places, so it's easier as default
1614 outflag = 1 # happens in more places, so it's easier as default
1615 try:
1615 try:
1616 try:
1616 try:
1617 exec code_obj in self.locals
1617 exec code_obj in self.locals
1618 finally:
1618 finally:
1619 # Reset our crash handler in place
1619 # Reset our crash handler in place
1620 sys.excepthook = old_excepthook
1620 sys.excepthook = old_excepthook
1621 except SystemExit:
1621 except SystemExit:
1622 self.resetbuffer()
1622 self.resetbuffer()
1623 self.showtraceback()
1623 self.showtraceback()
1624 warn( __builtin__.exit,level=1)
1624 warn( __builtin__.exit,level=1)
1625 except self.custom_exceptions:
1625 except self.custom_exceptions:
1626 etype,value,tb = sys.exc_info()
1626 etype,value,tb = sys.exc_info()
1627 self.CustomTB(etype,value,tb)
1627 self.CustomTB(etype,value,tb)
1628 except:
1628 except:
1629 self.showtraceback()
1629 self.showtraceback()
1630 else:
1630 else:
1631 outflag = 0
1631 outflag = 0
1632 if code.softspace(sys.stdout, 0):
1632 if code.softspace(sys.stdout, 0):
1633 print
1633 print
1634 # Flush out code object which has been run (and source)
1634 # Flush out code object which has been run (and source)
1635 self.code_to_run = None
1635 self.code_to_run = None
1636 return outflag
1636 return outflag
1637
1637
1638 def raw_input(self, prompt=""):
1638 def raw_input(self, prompt=""):
1639 """Write a prompt and read a line.
1639 """Write a prompt and read a line.
1640
1640
1641 The returned line does not include the trailing newline.
1641 The returned line does not include the trailing newline.
1642 When the user enters the EOF key sequence, EOFError is raised.
1642 When the user enters the EOF key sequence, EOFError is raised.
1643
1643
1644 The base implementation uses the built-in function
1644 The base implementation uses the built-in function
1645 raw_input(); a subclass may replace this with a different
1645 raw_input(); a subclass may replace this with a different
1646 implementation.
1646 implementation.
1647 """
1647 """
1648 return self.prefilter(raw_input_original(prompt),
1648 return self.prefilter(raw_input_original(prompt),
1649 prompt==self.outputcache.prompt2)
1649 prompt==self.outputcache.prompt2)
1650
1650
1651 def split_user_input(self,line):
1651 def split_user_input(self,line):
1652 """Split user input into pre-char, function part and rest."""
1652 """Split user input into pre-char, function part and rest."""
1653
1653
1654 lsplit = self.line_split.match(line)
1654 lsplit = self.line_split.match(line)
1655 if lsplit is None: # no regexp match returns None
1655 if lsplit is None: # no regexp match returns None
1656 try:
1656 try:
1657 iFun,theRest = line.split(None,1)
1657 iFun,theRest = line.split(None,1)
1658 except ValueError:
1658 except ValueError:
1659 iFun,theRest = line,''
1659 iFun,theRest = line,''
1660 pre = re.match('^(\s*)(.*)',line).groups()[0]
1660 pre = re.match('^(\s*)(.*)',line).groups()[0]
1661 else:
1661 else:
1662 pre,iFun,theRest = lsplit.groups()
1662 pre,iFun,theRest = lsplit.groups()
1663
1663
1664 #print 'line:<%s>' % line # dbg
1664 #print 'line:<%s>' % line # dbg
1665 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1665 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1666 return pre,iFun.strip(),theRest
1666 return pre,iFun.strip(),theRest
1667
1667
1668 def _prefilter(self, line, continue_prompt):
1668 def _prefilter(self, line, continue_prompt):
1669 """Calls different preprocessors, depending on the form of line."""
1669 """Calls different preprocessors, depending on the form of line."""
1670
1670
1671 # All handlers *must* return a value, even if it's blank ('').
1671 # All handlers *must* return a value, even if it's blank ('').
1672
1672
1673 # Lines are NOT logged here. Handlers should process the line as
1673 # Lines are NOT logged here. Handlers should process the line as
1674 # needed, update the cache AND log it (so that the input cache array
1674 # needed, update the cache AND log it (so that the input cache array
1675 # stays synced).
1675 # stays synced).
1676
1676
1677 # This function is _very_ delicate, and since it's also the one which
1677 # This function is _very_ delicate, and since it's also the one which
1678 # determines IPython's response to user input, it must be as efficient
1678 # determines IPython's response to user input, it must be as efficient
1679 # as possible. For this reason it has _many_ returns in it, trying
1679 # as possible. For this reason it has _many_ returns in it, trying
1680 # always to exit as quickly as it can figure out what it needs to do.
1680 # always to exit as quickly as it can figure out what it needs to do.
1681
1681
1682 # This function is the main responsible for maintaining IPython's
1682 # This function is the main responsible for maintaining IPython's
1683 # behavior respectful of Python's semantics. So be _very_ careful if
1683 # behavior respectful of Python's semantics. So be _very_ careful if
1684 # making changes to anything here.
1684 # making changes to anything here.
1685
1685
1686 #.....................................................................
1686 #.....................................................................
1687 # Code begins
1687 # Code begins
1688
1688
1689 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1689 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1690
1690
1691 # save the line away in case we crash, so the post-mortem handler can
1691 # save the line away in case we crash, so the post-mortem handler can
1692 # record it
1692 # record it
1693 self._last_input_line = line
1693 self._last_input_line = line
1694
1694
1695 #print '***line: <%s>' % line # dbg
1695 #print '***line: <%s>' % line # dbg
1696
1696
1697 # the input history needs to track even empty lines
1697 # the input history needs to track even empty lines
1698 if not line.strip():
1698 if not line.strip():
1699 if not continue_prompt:
1699 if not continue_prompt:
1700 self.outputcache.prompt_count -= 1
1700 self.outputcache.prompt_count -= 1
1701 return self.handle_normal('',continue_prompt)
1701 return self.handle_normal('',continue_prompt)
1702
1702
1703 # print '***cont',continue_prompt # dbg
1703 # print '***cont',continue_prompt # dbg
1704 # special handlers are only allowed for single line statements
1704 # special handlers are only allowed for single line statements
1705 if continue_prompt and not self.rc.multi_line_specials:
1705 if continue_prompt and not self.rc.multi_line_specials:
1706 return self.handle_normal(line,continue_prompt)
1706 return self.handle_normal(line,continue_prompt)
1707
1707
1708 # For the rest, we need the structure of the input
1708 # For the rest, we need the structure of the input
1709 pre,iFun,theRest = self.split_user_input(line)
1709 pre,iFun,theRest = self.split_user_input(line)
1710 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1710 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1711
1711
1712 # First check for explicit escapes in the last/first character
1712 # First check for explicit escapes in the last/first character
1713 handler = None
1713 handler = None
1714 if line[-1] == self.ESC_HELP:
1714 if line[-1] == self.ESC_HELP:
1715 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1715 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1716 if handler is None:
1716 if handler is None:
1717 # look at the first character of iFun, NOT of line, so we skip
1717 # look at the first character of iFun, NOT of line, so we skip
1718 # leading whitespace in multiline input
1718 # leading whitespace in multiline input
1719 handler = self.esc_handlers.get(iFun[0:1])
1719 handler = self.esc_handlers.get(iFun[0:1])
1720 if handler is not None:
1720 if handler is not None:
1721 return handler(line,continue_prompt,pre,iFun,theRest)
1721 return handler(line,continue_prompt,pre,iFun,theRest)
1722 # Emacs ipython-mode tags certain input lines
1722 # Emacs ipython-mode tags certain input lines
1723 if line.endswith('# PYTHON-MODE'):
1723 if line.endswith('# PYTHON-MODE'):
1724 return self.handle_emacs(line,continue_prompt)
1724 return self.handle_emacs(line,continue_prompt)
1725
1725
1726 # Next, check if we can automatically execute this thing
1726 # Next, check if we can automatically execute this thing
1727
1727
1728 # Allow ! in multi-line statements if multi_line_specials is on:
1728 # Allow ! in multi-line statements if multi_line_specials is on:
1729 if continue_prompt and self.rc.multi_line_specials and \
1729 if continue_prompt and self.rc.multi_line_specials and \
1730 iFun.startswith(self.ESC_SHELL):
1730 iFun.startswith(self.ESC_SHELL):
1731 return self.handle_shell_escape(line,continue_prompt,
1731 return self.handle_shell_escape(line,continue_prompt,
1732 pre=pre,iFun=iFun,
1732 pre=pre,iFun=iFun,
1733 theRest=theRest)
1733 theRest=theRest)
1734
1734
1735 # Let's try to find if the input line is a magic fn
1735 # Let's try to find if the input line is a magic fn
1736 oinfo = None
1736 oinfo = None
1737 if hasattr(self,'magic_'+iFun):
1737 if hasattr(self,'magic_'+iFun):
1738 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1738 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1739 if oinfo['ismagic']:
1739 if oinfo['ismagic']:
1740 # Be careful not to call magics when a variable assignment is
1740 # Be careful not to call magics when a variable assignment is
1741 # being made (ls='hi', for example)
1741 # being made (ls='hi', for example)
1742 if self.rc.automagic and \
1742 if self.rc.automagic and \
1743 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1743 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1744 (self.rc.multi_line_specials or not continue_prompt):
1744 (self.rc.multi_line_specials or not continue_prompt):
1745 return self.handle_magic(line,continue_prompt,
1745 return self.handle_magic(line,continue_prompt,
1746 pre,iFun,theRest)
1746 pre,iFun,theRest)
1747 else:
1747 else:
1748 return self.handle_normal(line,continue_prompt)
1748 return self.handle_normal(line,continue_prompt)
1749
1749
1750 # If the rest of the line begins with an (in)equality, assginment or
1750 # If the rest of the line begins with an (in)equality, assginment or
1751 # function call, we should not call _ofind but simply execute it.
1751 # function call, we should not call _ofind but simply execute it.
1752 # This avoids spurious geattr() accesses on objects upon assignment.
1752 # This avoids spurious geattr() accesses on objects upon assignment.
1753 #
1753 #
1754 # It also allows users to assign to either alias or magic names true
1754 # It also allows users to assign to either alias or magic names true
1755 # python variables (the magic/alias systems always take second seat to
1755 # python variables (the magic/alias systems always take second seat to
1756 # true python code).
1756 # true python code).
1757 if theRest and theRest[0] in '!=()':
1757 if theRest and theRest[0] in '!=()':
1758 return self.handle_normal(line,continue_prompt)
1758 return self.handle_normal(line,continue_prompt)
1759
1759
1760 if oinfo is None:
1760 if oinfo is None:
1761 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1761 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1762
1762
1763 if not oinfo['found']:
1763 if not oinfo['found']:
1764 return self.handle_normal(line,continue_prompt)
1764 return self.handle_normal(line,continue_prompt)
1765 else:
1765 else:
1766 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1766 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1767 if oinfo['isalias']:
1767 if oinfo['isalias']:
1768 return self.handle_alias(line,continue_prompt,
1768 return self.handle_alias(line,continue_prompt,
1769 pre,iFun,theRest)
1769 pre,iFun,theRest)
1770
1770
1771 if self.rc.autocall and \
1771 if self.rc.autocall and \
1772 not self.re_exclude_auto.match(theRest) and \
1772 not self.re_exclude_auto.match(theRest) and \
1773 self.re_fun_name.match(iFun) and \
1773 self.re_fun_name.match(iFun) and \
1774 callable(oinfo['obj']) :
1774 callable(oinfo['obj']) :
1775 #print 'going auto' # dbg
1775 #print 'going auto' # dbg
1776 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1776 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1777 else:
1777 else:
1778 #print 'was callable?', callable(oinfo['obj']) # dbg
1778 #print 'was callable?', callable(oinfo['obj']) # dbg
1779 return self.handle_normal(line,continue_prompt)
1779 return self.handle_normal(line,continue_prompt)
1780
1780
1781 # If we get here, we have a normal Python line. Log and return.
1781 # If we get here, we have a normal Python line. Log and return.
1782 return self.handle_normal(line,continue_prompt)
1782 return self.handle_normal(line,continue_prompt)
1783
1783
1784 def _prefilter_dumb(self, line, continue_prompt):
1784 def _prefilter_dumb(self, line, continue_prompt):
1785 """simple prefilter function, for debugging"""
1785 """simple prefilter function, for debugging"""
1786 return self.handle_normal(line,continue_prompt)
1786 return self.handle_normal(line,continue_prompt)
1787
1787
1788 # Set the default prefilter() function (this can be user-overridden)
1788 # Set the default prefilter() function (this can be user-overridden)
1789 prefilter = _prefilter
1789 prefilter = _prefilter
1790
1790
1791 def handle_normal(self,line,continue_prompt=None,
1791 def handle_normal(self,line,continue_prompt=None,
1792 pre=None,iFun=None,theRest=None):
1792 pre=None,iFun=None,theRest=None):
1793 """Handle normal input lines. Use as a template for handlers."""
1793 """Handle normal input lines. Use as a template for handlers."""
1794
1794
1795 self.log(line,continue_prompt)
1795 self.log(line,continue_prompt)
1796 self.update_cache(line)
1796 self.update_cache(line)
1797 return line
1797 return line
1798
1798
1799 def handle_alias(self,line,continue_prompt=None,
1799 def handle_alias(self,line,continue_prompt=None,
1800 pre=None,iFun=None,theRest=None):
1800 pre=None,iFun=None,theRest=None):
1801 """Handle alias input lines. """
1801 """Handle alias input lines. """
1802
1802
1803 theRest = esc_quotes(theRest)
1803 theRest = esc_quotes(theRest)
1804 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1804 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1805 self.log(line_out,continue_prompt)
1805 self.log(line_out,continue_prompt)
1806 self.update_cache(line_out)
1806 self.update_cache(line_out)
1807 return line_out
1807 return line_out
1808
1808
1809 def handle_shell_escape(self, line, continue_prompt=None,
1809 def handle_shell_escape(self, line, continue_prompt=None,
1810 pre=None,iFun=None,theRest=None):
1810 pre=None,iFun=None,theRest=None):
1811 """Execute the line in a shell, empty return value"""
1811 """Execute the line in a shell, empty return value"""
1812
1812
1813 #print 'line in :', `line` # dbg
1813 #print 'line in :', `line` # dbg
1814 # Example of a special handler. Others follow a similar pattern.
1814 # Example of a special handler. Others follow a similar pattern.
1815 if continue_prompt: # multi-line statements
1815 if continue_prompt: # multi-line statements
1816 if iFun.startswith('!!'):
1816 if iFun.startswith('!!'):
1817 print 'SyntaxError: !! is not allowed in multiline statements'
1817 print 'SyntaxError: !! is not allowed in multiline statements'
1818 return pre
1818 return pre
1819 else:
1819 else:
1820 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1820 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1821 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1821 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1822 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1822 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1823 else: # single-line input
1823 else: # single-line input
1824 if line.startswith('!!'):
1824 if line.startswith('!!'):
1825 # rewrite iFun/theRest to properly hold the call to %sx and
1825 # rewrite iFun/theRest to properly hold the call to %sx and
1826 # the actual command to be executed, so handle_magic can work
1826 # the actual command to be executed, so handle_magic can work
1827 # correctly
1827 # correctly
1828 theRest = '%s %s' % (iFun[2:],theRest)
1828 theRest = '%s %s' % (iFun[2:],theRest)
1829 iFun = 'sx'
1829 iFun = 'sx'
1830 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1830 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1831 continue_prompt,pre,iFun,theRest)
1831 continue_prompt,pre,iFun,theRest)
1832 else:
1832 else:
1833 cmd = esc_quotes(line[1:])
1833 cmd = esc_quotes(line[1:])
1834 line_out = '%s.system("%s")' % (self.name,cmd)
1834 line_out = '%s.system("%s")' % (self.name,cmd)
1835 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1835 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1836 # update cache/log and return
1836 # update cache/log and return
1837 self.log(line_out,continue_prompt)
1837 self.log(line_out,continue_prompt)
1838 self.update_cache(line_out) # readline cache gets normal line
1838 self.update_cache(line_out) # readline cache gets normal line
1839 #print 'line out r:', `line_out` # dbg
1839 #print 'line out r:', `line_out` # dbg
1840 #print 'line out s:', line_out # dbg
1840 #print 'line out s:', line_out # dbg
1841 return line_out
1841 return line_out
1842
1842
1843 def handle_magic(self, line, continue_prompt=None,
1843 def handle_magic(self, line, continue_prompt=None,
1844 pre=None,iFun=None,theRest=None):
1844 pre=None,iFun=None,theRest=None):
1845 """Execute magic functions.
1845 """Execute magic functions.
1846
1846
1847 Also log them with a prepended # so the log is clean Python."""
1847 Also log them with a prepended # so the log is clean Python."""
1848
1848
1849 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1849 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1850 self.log(cmd,continue_prompt)
1850 self.log(cmd,continue_prompt)
1851 self.update_cache(line)
1851 self.update_cache(line)
1852 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1852 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1853 return cmd
1853 return cmd
1854
1854
1855 def handle_auto(self, line, continue_prompt=None,
1855 def handle_auto(self, line, continue_prompt=None,
1856 pre=None,iFun=None,theRest=None):
1856 pre=None,iFun=None,theRest=None):
1857 """Hande lines which can be auto-executed, quoting if requested."""
1857 """Hande lines which can be auto-executed, quoting if requested."""
1858
1858
1859 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1859 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1860
1860
1861 # This should only be active for single-line input!
1861 # This should only be active for single-line input!
1862 if continue_prompt:
1862 if continue_prompt:
1863 return line
1863 return line
1864
1864
1865 if pre == self.ESC_QUOTE:
1865 if pre == self.ESC_QUOTE:
1866 # Auto-quote splitting on whitespace
1866 # Auto-quote splitting on whitespace
1867 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1867 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1868 elif pre == self.ESC_QUOTE2:
1868 elif pre == self.ESC_QUOTE2:
1869 # Auto-quote whole string
1869 # Auto-quote whole string
1870 newcmd = '%s("%s")' % (iFun,theRest)
1870 newcmd = '%s("%s")' % (iFun,theRest)
1871 else:
1871 else:
1872 # Auto-paren
1872 # Auto-paren
1873 if theRest[0:1] in ('=','['):
1873 if theRest[0:1] in ('=','['):
1874 # Don't autocall in these cases. They can be either
1874 # Don't autocall in these cases. They can be either
1875 # rebindings of an existing callable's name, or item access
1875 # rebindings of an existing callable's name, or item access
1876 # for an object which is BOTH callable and implements
1876 # for an object which is BOTH callable and implements
1877 # __getitem__.
1877 # __getitem__.
1878 return '%s %s' % (iFun,theRest)
1878 return '%s %s' % (iFun,theRest)
1879 if theRest.endswith(';'):
1879 if theRest.endswith(';'):
1880 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1880 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1881 else:
1881 else:
1882 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1882 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1883
1883
1884 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1884 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1885 # log what is now valid Python, not the actual user input (without the
1885 # log what is now valid Python, not the actual user input (without the
1886 # final newline)
1886 # final newline)
1887 self.log(newcmd,continue_prompt)
1887 self.log(newcmd,continue_prompt)
1888 return newcmd
1888 return newcmd
1889
1889
1890 def handle_help(self, line, continue_prompt=None,
1890 def handle_help(self, line, continue_prompt=None,
1891 pre=None,iFun=None,theRest=None):
1891 pre=None,iFun=None,theRest=None):
1892 """Try to get some help for the object.
1892 """Try to get some help for the object.
1893
1893
1894 obj? or ?obj -> basic information.
1894 obj? or ?obj -> basic information.
1895 obj?? or ??obj -> more details.
1895 obj?? or ??obj -> more details.
1896 """
1896 """
1897
1897
1898 # We need to make sure that we don't process lines which would be
1898 # We need to make sure that we don't process lines which would be
1899 # otherwise valid python, such as "x=1 # what?"
1899 # otherwise valid python, such as "x=1 # what?"
1900 try:
1900 try:
1901 code.compile_command(line)
1901 code.compile_command(line)
1902 except SyntaxError:
1902 except SyntaxError:
1903 # We should only handle as help stuff which is NOT valid syntax
1903 # We should only handle as help stuff which is NOT valid syntax
1904 if line[0]==self.ESC_HELP:
1904 if line[0]==self.ESC_HELP:
1905 line = line[1:]
1905 line = line[1:]
1906 elif line[-1]==self.ESC_HELP:
1906 elif line[-1]==self.ESC_HELP:
1907 line = line[:-1]
1907 line = line[:-1]
1908 self.log('#?'+line)
1908 self.log('#?'+line)
1909 self.update_cache(line)
1909 self.update_cache(line)
1910 if line:
1910 if line:
1911 self.magic_pinfo(line)
1911 self.magic_pinfo(line)
1912 else:
1912 else:
1913 page(self.usage,screen_lines=self.rc.screen_length)
1913 page(self.usage,screen_lines=self.rc.screen_length)
1914 return '' # Empty string is needed here!
1914 return '' # Empty string is needed here!
1915 except:
1915 except:
1916 # Pass any other exceptions through to the normal handler
1916 # Pass any other exceptions through to the normal handler
1917 return self.handle_normal(line,continue_prompt)
1917 return self.handle_normal(line,continue_prompt)
1918 else:
1918 else:
1919 # If the code compiles ok, we should handle it normally
1919 # If the code compiles ok, we should handle it normally
1920 return self.handle_normal(line,continue_prompt)
1920 return self.handle_normal(line,continue_prompt)
1921
1921
1922 def handle_emacs(self,line,continue_prompt=None,
1922 def handle_emacs(self,line,continue_prompt=None,
1923 pre=None,iFun=None,theRest=None):
1923 pre=None,iFun=None,theRest=None):
1924 """Handle input lines marked by python-mode."""
1924 """Handle input lines marked by python-mode."""
1925
1925
1926 # Currently, nothing is done. Later more functionality can be added
1926 # Currently, nothing is done. Later more functionality can be added
1927 # here if needed.
1927 # here if needed.
1928
1928
1929 # The input cache shouldn't be updated
1929 # The input cache shouldn't be updated
1930
1930
1931 return line
1931 return line
1932
1932
1933 def write(self,data):
1933 def write(self,data):
1934 """Write a string to the default output"""
1934 """Write a string to the default output"""
1935 Term.cout.write(data)
1935 Term.cout.write(data)
1936
1936
1937 def write_err(self,data):
1937 def write_err(self,data):
1938 """Write a string to the default error output"""
1938 """Write a string to the default error output"""
1939 Term.cerr.write(data)
1939 Term.cerr.write(data)
1940
1940
1941 def safe_execfile(self,fname,*where,**kw):
1941 def safe_execfile(self,fname,*where,**kw):
1942 fname = os.path.expanduser(fname)
1942 fname = os.path.expanduser(fname)
1943
1943
1944 # find things also in current directory
1944 # find things also in current directory
1945 dname = os.path.dirname(fname)
1945 dname = os.path.dirname(fname)
1946 if not sys.path.count(dname):
1946 if not sys.path.count(dname):
1947 sys.path.append(dname)
1947 sys.path.append(dname)
1948
1948
1949 try:
1949 try:
1950 xfile = open(fname)
1950 xfile = open(fname)
1951 except:
1951 except:
1952 print >> Term.cerr, \
1952 print >> Term.cerr, \
1953 'Could not open file <%s> for safe execution.' % fname
1953 'Could not open file <%s> for safe execution.' % fname
1954 return None
1954 return None
1955
1955
1956 kw.setdefault('islog',0)
1956 kw.setdefault('islog',0)
1957 kw.setdefault('quiet',1)
1957 kw.setdefault('quiet',1)
1958 kw.setdefault('exit_ignore',0)
1958 kw.setdefault('exit_ignore',0)
1959 first = xfile.readline()
1959 first = xfile.readline()
1960 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1960 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1961 xfile.close()
1961 xfile.close()
1962 # line by line execution
1962 # line by line execution
1963 if first.startswith(_LOGHEAD) or kw['islog']:
1963 if first.startswith(_LOGHEAD) or kw['islog']:
1964 print 'Loading log file <%s> one line at a time...' % fname
1964 print 'Loading log file <%s> one line at a time...' % fname
1965 if kw['quiet']:
1965 if kw['quiet']:
1966 stdout_save = sys.stdout
1966 stdout_save = sys.stdout
1967 sys.stdout = StringIO.StringIO()
1967 sys.stdout = StringIO.StringIO()
1968 try:
1968 try:
1969 globs,locs = where[0:2]
1969 globs,locs = where[0:2]
1970 except:
1970 except:
1971 try:
1971 try:
1972 globs = locs = where[0]
1972 globs = locs = where[0]
1973 except:
1973 except:
1974 globs = locs = globals()
1974 globs = locs = globals()
1975 badblocks = []
1975 badblocks = []
1976
1976
1977 # we also need to identify indented blocks of code when replaying
1977 # we also need to identify indented blocks of code when replaying
1978 # logs and put them together before passing them to an exec
1978 # logs and put them together before passing them to an exec
1979 # statement. This takes a bit of regexp and look-ahead work in the
1979 # statement. This takes a bit of regexp and look-ahead work in the
1980 # file. It's easiest if we swallow the whole thing in memory
1980 # file. It's easiest if we swallow the whole thing in memory
1981 # first, and manually walk through the lines list moving the
1981 # first, and manually walk through the lines list moving the
1982 # counter ourselves.
1982 # counter ourselves.
1983 indent_re = re.compile('\s+\S')
1983 indent_re = re.compile('\s+\S')
1984 xfile = open(fname)
1984 xfile = open(fname)
1985 filelines = xfile.readlines()
1985 filelines = xfile.readlines()
1986 xfile.close()
1986 xfile.close()
1987 nlines = len(filelines)
1987 nlines = len(filelines)
1988 lnum = 0
1988 lnum = 0
1989 while lnum < nlines:
1989 while lnum < nlines:
1990 line = filelines[lnum]
1990 line = filelines[lnum]
1991 lnum += 1
1991 lnum += 1
1992 # don't re-insert logger status info into cache
1992 # don't re-insert logger status info into cache
1993 if line.startswith('#log#'):
1993 if line.startswith('#log#'):
1994 continue
1994 continue
1995 elif line.startswith('#%s'% self.ESC_MAGIC):
1995 elif line.startswith('#%s'% self.ESC_MAGIC):
1996 self.update_cache(line[1:])
1996 self.update_cache(line[1:])
1997 line = magic2python(line)
1997 line = magic2python(line)
1998 elif line.startswith('#!'):
1998 elif line.startswith('#!'):
1999 self.update_cache(line[1:])
1999 self.update_cache(line[1:])
2000 else:
2000 else:
2001 # build a block of code (maybe a single line) for execution
2001 # build a block of code (maybe a single line) for execution
2002 block = line
2002 block = line
2003 try:
2003 try:
2004 next = filelines[lnum] # lnum has already incremented
2004 next = filelines[lnum] # lnum has already incremented
2005 except:
2005 except:
2006 next = None
2006 next = None
2007 while next and indent_re.match(next):
2007 while next and indent_re.match(next):
2008 block += next
2008 block += next
2009 lnum += 1
2009 lnum += 1
2010 try:
2010 try:
2011 next = filelines[lnum]
2011 next = filelines[lnum]
2012 except:
2012 except:
2013 next = None
2013 next = None
2014 # now execute the block of one or more lines
2014 # now execute the block of one or more lines
2015 try:
2015 try:
2016 exec block in globs,locs
2016 exec block in globs,locs
2017 self.update_cache(block.rstrip())
2017 self.update_cache(block.rstrip())
2018 except SystemExit:
2018 except SystemExit:
2019 pass
2019 pass
2020 except:
2020 except:
2021 badblocks.append(block.rstrip())
2021 badblocks.append(block.rstrip())
2022 if kw['quiet']: # restore stdout
2022 if kw['quiet']: # restore stdout
2023 sys.stdout.close()
2023 sys.stdout.close()
2024 sys.stdout = stdout_save
2024 sys.stdout = stdout_save
2025 print 'Finished replaying log file <%s>' % fname
2025 print 'Finished replaying log file <%s>' % fname
2026 if badblocks:
2026 if badblocks:
2027 print >> sys.stderr, \
2027 print >> sys.stderr, \
2028 '\nThe following lines/blocks in file <%s> reported errors:' \
2028 '\nThe following lines/blocks in file <%s> reported errors:' \
2029 % fname
2029 % fname
2030 for badline in badblocks:
2030 for badline in badblocks:
2031 print >> sys.stderr, badline
2031 print >> sys.stderr, badline
2032 else: # regular file execution
2032 else: # regular file execution
2033 try:
2033 try:
2034 execfile(fname,*where)
2034 execfile(fname,*where)
2035 except SyntaxError:
2035 except SyntaxError:
2036 etype, evalue = sys.exc_info()[0:2]
2036 etype, evalue = sys.exc_info()[0:2]
2037 self.SyntaxTB(etype,evalue,[])
2037 self.SyntaxTB(etype,evalue,[])
2038 warn('Failure executing file: <%s>' % fname)
2038 warn('Failure executing file: <%s>' % fname)
2039 except SystemExit,status:
2039 except SystemExit,status:
2040 if not kw['exit_ignore']:
2040 if not kw['exit_ignore']:
2041 self.InteractiveTB()
2041 self.InteractiveTB()
2042 warn('Failure executing file: <%s>' % fname)
2042 warn('Failure executing file: <%s>' % fname)
2043 except:
2043 except:
2044 self.InteractiveTB()
2044 self.InteractiveTB()
2045 warn('Failure executing file: <%s>' % fname)
2045 warn('Failure executing file: <%s>' % fname)
2046
2046
2047 #************************* end of file <iplib.py> *****************************
2047 #************************* end of file <iplib.py> *****************************
@@ -1,4370 +1,4381 b''
1 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
2
3 * IPython/genutils.py (marquee): little utility used by the demo
4 code, handy in general.
5
6 * IPython/demo.py (Demo.__init__): new class for interactive
7 demos. Not documented yet, I just wrote it in a hurry for
8 scipy'05. Will docstring later.
9
1 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
10 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
2
11
3 * IPython/Shell.py (sigint_handler): Drastic simplification which
12 * IPython/Shell.py (sigint_handler): Drastic simplification which
4 also seems to make Ctrl-C work correctly across threads! This is
13 also seems to make Ctrl-C work correctly across threads! This is
5 so simple, that I can't beleive I'd missed it before. Needs more
14 so simple, that I can't beleive I'd missed it before. Needs more
6 testing, though.
15 testing, though.
16 (KBINT): Never mind, revert changes. I'm sure I'd tried something
17 like this before...
7
18
8 * IPython/genutils.py (get_home_dir): add protection against
19 * IPython/genutils.py (get_home_dir): add protection against
9 non-dirs in win32 registry.
20 non-dirs in win32 registry.
10
21
11 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
22 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
12 bug where dict was mutated while iterating (pysh crash).
23 bug where dict was mutated while iterating (pysh crash).
13
24
14 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
25 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
15
26
16 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
27 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
17 spurious newlines added by this routine. After a report by
28 spurious newlines added by this routine. After a report by
18 F. Mantegazza.
29 F. Mantegazza.
19
30
20 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
31 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
21
32
22 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
33 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
23 calls. These were a leftover from the GTK 1.x days, and can cause
34 calls. These were a leftover from the GTK 1.x days, and can cause
24 problems in certain cases (after a report by John Hunter).
35 problems in certain cases (after a report by John Hunter).
25
36
26 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
37 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
27 os.getcwd() fails at init time. Thanks to patch from David Remahl
38 os.getcwd() fails at init time. Thanks to patch from David Remahl
28 <chmod007 AT mac.com>.
39 <chmod007 AT mac.com>.
29 (InteractiveShell.__init__): prevent certain special magics from
40 (InteractiveShell.__init__): prevent certain special magics from
30 being shadowed by aliases. Closes
41 being shadowed by aliases. Closes
31 http://www.scipy.net/roundup/ipython/issue41.
42 http://www.scipy.net/roundup/ipython/issue41.
32
43
33 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
44 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
34
45
35 * IPython/iplib.py (InteractiveShell.complete): Added new
46 * IPython/iplib.py (InteractiveShell.complete): Added new
36 top-level completion method to expose the completion mechanism
47 top-level completion method to expose the completion mechanism
37 beyond readline-based environments.
48 beyond readline-based environments.
38
49
39 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
50 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
40
51
41 * tools/ipsvnc (svnversion): fix svnversion capture.
52 * tools/ipsvnc (svnversion): fix svnversion capture.
42
53
43 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
54 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
44 attribute to self, which was missing. Before, it was set by a
55 attribute to self, which was missing. Before, it was set by a
45 routine which in certain cases wasn't being called, so the
56 routine which in certain cases wasn't being called, so the
46 instance could end up missing the attribute. This caused a crash.
57 instance could end up missing the attribute. This caused a crash.
47 Closes http://www.scipy.net/roundup/ipython/issue40.
58 Closes http://www.scipy.net/roundup/ipython/issue40.
48
59
49 2005-08-16 Fernando Perez <fperez@colorado.edu>
60 2005-08-16 Fernando Perez <fperez@colorado.edu>
50
61
51 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
62 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
52 contains non-string attribute. Closes
63 contains non-string attribute. Closes
53 http://www.scipy.net/roundup/ipython/issue38.
64 http://www.scipy.net/roundup/ipython/issue38.
54
65
55 2005-08-14 Fernando Perez <fperez@colorado.edu>
66 2005-08-14 Fernando Perez <fperez@colorado.edu>
56
67
57 * tools/ipsvnc: Minor improvements, to add changeset info.
68 * tools/ipsvnc: Minor improvements, to add changeset info.
58
69
59 2005-08-12 Fernando Perez <fperez@colorado.edu>
70 2005-08-12 Fernando Perez <fperez@colorado.edu>
60
71
61 * IPython/iplib.py (runsource): remove self.code_to_run_src
72 * IPython/iplib.py (runsource): remove self.code_to_run_src
62 attribute. I realized this is nothing more than
73 attribute. I realized this is nothing more than
63 '\n'.join(self.buffer), and having the same data in two different
74 '\n'.join(self.buffer), and having the same data in two different
64 places is just asking for synchronization bugs. This may impact
75 places is just asking for synchronization bugs. This may impact
65 people who have custom exception handlers, so I need to warn
76 people who have custom exception handlers, so I need to warn
66 ipython-dev about it (F. Mantegazza may use them).
77 ipython-dev about it (F. Mantegazza may use them).
67
78
68 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
79 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
69
80
70 * IPython/genutils.py: fix 2.2 compatibility (generators)
81 * IPython/genutils.py: fix 2.2 compatibility (generators)
71
82
72 2005-07-18 Fernando Perez <fperez@colorado.edu>
83 2005-07-18 Fernando Perez <fperez@colorado.edu>
73
84
74 * IPython/genutils.py (get_home_dir): fix to help users with
85 * IPython/genutils.py (get_home_dir): fix to help users with
75 invalid $HOME under win32.
86 invalid $HOME under win32.
76
87
77 2005-07-17 Fernando Perez <fperez@colorado.edu>
88 2005-07-17 Fernando Perez <fperez@colorado.edu>
78
89
79 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
90 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
80 some old hacks and clean up a bit other routines; code should be
91 some old hacks and clean up a bit other routines; code should be
81 simpler and a bit faster.
92 simpler and a bit faster.
82
93
83 * IPython/iplib.py (interact): removed some last-resort attempts
94 * IPython/iplib.py (interact): removed some last-resort attempts
84 to survive broken stdout/stderr. That code was only making it
95 to survive broken stdout/stderr. That code was only making it
85 harder to abstract out the i/o (necessary for gui integration),
96 harder to abstract out the i/o (necessary for gui integration),
86 and the crashes it could prevent were extremely rare in practice
97 and the crashes it could prevent were extremely rare in practice
87 (besides being fully user-induced in a pretty violent manner).
98 (besides being fully user-induced in a pretty violent manner).
88
99
89 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
100 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
90 Nothing major yet, but the code is simpler to read; this should
101 Nothing major yet, but the code is simpler to read; this should
91 make it easier to do more serious modifications in the future.
102 make it easier to do more serious modifications in the future.
92
103
93 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
104 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
94 which broke in .15 (thanks to a report by Ville).
105 which broke in .15 (thanks to a report by Ville).
95
106
96 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
107 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
97 be quite correct, I know next to nothing about unicode). This
108 be quite correct, I know next to nothing about unicode). This
98 will allow unicode strings to be used in prompts, amongst other
109 will allow unicode strings to be used in prompts, amongst other
99 cases. It also will prevent ipython from crashing when unicode
110 cases. It also will prevent ipython from crashing when unicode
100 shows up unexpectedly in many places. If ascii encoding fails, we
111 shows up unexpectedly in many places. If ascii encoding fails, we
101 assume utf_8. Currently the encoding is not a user-visible
112 assume utf_8. Currently the encoding is not a user-visible
102 setting, though it could be made so if there is demand for it.
113 setting, though it could be made so if there is demand for it.
103
114
104 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
115 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
105
116
106 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
117 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
107
118
108 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
119 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
109
120
110 * IPython/genutils.py: Add 2.2 compatibility here, so all other
121 * IPython/genutils.py: Add 2.2 compatibility here, so all other
111 code can work transparently for 2.2/2.3.
122 code can work transparently for 2.2/2.3.
112
123
113 2005-07-16 Fernando Perez <fperez@colorado.edu>
124 2005-07-16 Fernando Perez <fperez@colorado.edu>
114
125
115 * IPython/ultraTB.py (ExceptionColors): Make a global variable
126 * IPython/ultraTB.py (ExceptionColors): Make a global variable
116 out of the color scheme table used for coloring exception
127 out of the color scheme table used for coloring exception
117 tracebacks. This allows user code to add new schemes at runtime.
128 tracebacks. This allows user code to add new schemes at runtime.
118 This is a minimally modified version of the patch at
129 This is a minimally modified version of the patch at
119 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
130 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
120 for the contribution.
131 for the contribution.
121
132
122 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
133 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
123 slightly modified version of the patch in
134 slightly modified version of the patch in
124 http://www.scipy.net/roundup/ipython/issue34, which also allows me
135 http://www.scipy.net/roundup/ipython/issue34, which also allows me
125 to remove the previous try/except solution (which was costlier).
136 to remove the previous try/except solution (which was costlier).
126 Thanks to Gaetan Lehmann <gaetan.lehmann AT jouy.inra.fr> for the fix.
137 Thanks to Gaetan Lehmann <gaetan.lehmann AT jouy.inra.fr> for the fix.
127
138
128 2005-06-08 Fernando Perez <fperez@colorado.edu>
139 2005-06-08 Fernando Perez <fperez@colorado.edu>
129
140
130 * IPython/iplib.py (write/write_err): Add methods to abstract all
141 * IPython/iplib.py (write/write_err): Add methods to abstract all
131 I/O a bit more.
142 I/O a bit more.
132
143
133 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
144 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
134 warning, reported by Aric Hagberg, fix by JD Hunter.
145 warning, reported by Aric Hagberg, fix by JD Hunter.
135
146
136 2005-06-02 *** Released version 0.6.15
147 2005-06-02 *** Released version 0.6.15
137
148
138 2005-06-01 Fernando Perez <fperez@colorado.edu>
149 2005-06-01 Fernando Perez <fperez@colorado.edu>
139
150
140 * IPython/iplib.py (MagicCompleter.file_matches): Fix
151 * IPython/iplib.py (MagicCompleter.file_matches): Fix
141 tab-completion of filenames within open-quoted strings. Note that
152 tab-completion of filenames within open-quoted strings. Note that
142 this requires that in ~/.ipython/ipythonrc, users change the
153 this requires that in ~/.ipython/ipythonrc, users change the
143 readline delimiters configuration to read:
154 readline delimiters configuration to read:
144
155
145 readline_remove_delims -/~
156 readline_remove_delims -/~
146
157
147
158
148 2005-05-31 *** Released version 0.6.14
159 2005-05-31 *** Released version 0.6.14
149
160
150 2005-05-29 Fernando Perez <fperez@colorado.edu>
161 2005-05-29 Fernando Perez <fperez@colorado.edu>
151
162
152 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
163 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
153 with files not on the filesystem. Reported by Eliyahu Sandler
164 with files not on the filesystem. Reported by Eliyahu Sandler
154 <eli@gondolin.net>
165 <eli@gondolin.net>
155
166
156 2005-05-22 Fernando Perez <fperez@colorado.edu>
167 2005-05-22 Fernando Perez <fperez@colorado.edu>
157
168
158 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
169 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
159 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
170 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
160
171
161 2005-05-19 Fernando Perez <fperez@colorado.edu>
172 2005-05-19 Fernando Perez <fperez@colorado.edu>
162
173
163 * IPython/iplib.py (safe_execfile): close a file which could be
174 * IPython/iplib.py (safe_execfile): close a file which could be
164 left open (causing problems in win32, which locks open files).
175 left open (causing problems in win32, which locks open files).
165 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
176 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
166
177
167 2005-05-18 Fernando Perez <fperez@colorado.edu>
178 2005-05-18 Fernando Perez <fperez@colorado.edu>
168
179
169 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
180 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
170 keyword arguments correctly to safe_execfile().
181 keyword arguments correctly to safe_execfile().
171
182
172 2005-05-13 Fernando Perez <fperez@colorado.edu>
183 2005-05-13 Fernando Perez <fperez@colorado.edu>
173
184
174 * ipython.1: Added info about Qt to manpage, and threads warning
185 * ipython.1: Added info about Qt to manpage, and threads warning
175 to usage page (invoked with --help).
186 to usage page (invoked with --help).
176
187
177 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
188 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
178 new matcher (it goes at the end of the priority list) to do
189 new matcher (it goes at the end of the priority list) to do
179 tab-completion on named function arguments. Submitted by George
190 tab-completion on named function arguments. Submitted by George
180 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
191 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
181 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
192 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
182 for more details.
193 for more details.
183
194
184 * IPython/Magic.py (magic_run): Added new -e flag to ignore
195 * IPython/Magic.py (magic_run): Added new -e flag to ignore
185 SystemExit exceptions in the script being run. Thanks to a report
196 SystemExit exceptions in the script being run. Thanks to a report
186 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
197 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
187 producing very annoying behavior when running unit tests.
198 producing very annoying behavior when running unit tests.
188
199
189 2005-05-12 Fernando Perez <fperez@colorado.edu>
200 2005-05-12 Fernando Perez <fperez@colorado.edu>
190
201
191 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
202 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
192 which I'd broken (again) due to a changed regexp. In the process,
203 which I'd broken (again) due to a changed regexp. In the process,
193 added ';' as an escape to auto-quote the whole line without
204 added ';' as an escape to auto-quote the whole line without
194 splitting its arguments. Thanks to a report by Jerry McRae
205 splitting its arguments. Thanks to a report by Jerry McRae
195 <qrs0xyc02-AT-sneakemail.com>.
206 <qrs0xyc02-AT-sneakemail.com>.
196
207
197 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
208 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
198 possible crashes caused by a TokenError. Reported by Ed Schofield
209 possible crashes caused by a TokenError. Reported by Ed Schofield
199 <schofield-AT-ftw.at>.
210 <schofield-AT-ftw.at>.
200
211
201 2005-05-06 Fernando Perez <fperez@colorado.edu>
212 2005-05-06 Fernando Perez <fperez@colorado.edu>
202
213
203 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
214 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
204
215
205 2005-04-29 Fernando Perez <fperez@colorado.edu>
216 2005-04-29 Fernando Perez <fperez@colorado.edu>
206
217
207 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
218 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
208 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
219 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
209 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
220 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
210 which provides support for Qt interactive usage (similar to the
221 which provides support for Qt interactive usage (similar to the
211 existing one for WX and GTK). This had been often requested.
222 existing one for WX and GTK). This had been often requested.
212
223
213 2005-04-14 *** Released version 0.6.13
224 2005-04-14 *** Released version 0.6.13
214
225
215 2005-04-08 Fernando Perez <fperez@colorado.edu>
226 2005-04-08 Fernando Perez <fperez@colorado.edu>
216
227
217 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
228 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
218 from _ofind, which gets called on almost every input line. Now,
229 from _ofind, which gets called on almost every input line. Now,
219 we only try to get docstrings if they are actually going to be
230 we only try to get docstrings if they are actually going to be
220 used (the overhead of fetching unnecessary docstrings can be
231 used (the overhead of fetching unnecessary docstrings can be
221 noticeable for certain objects, such as Pyro proxies).
232 noticeable for certain objects, such as Pyro proxies).
222
233
223 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
234 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
224 for completers. For some reason I had been passing them the state
235 for completers. For some reason I had been passing them the state
225 variable, which completers never actually need, and was in
236 variable, which completers never actually need, and was in
226 conflict with the rlcompleter API. Custom completers ONLY need to
237 conflict with the rlcompleter API. Custom completers ONLY need to
227 take the text parameter.
238 take the text parameter.
228
239
229 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
240 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
230 work correctly in pysh. I've also moved all the logic which used
241 work correctly in pysh. I've also moved all the logic which used
231 to be in pysh.py here, which will prevent problems with future
242 to be in pysh.py here, which will prevent problems with future
232 upgrades. However, this time I must warn users to update their
243 upgrades. However, this time I must warn users to update their
233 pysh profile to include the line
244 pysh profile to include the line
234
245
235 import_all IPython.Extensions.InterpreterExec
246 import_all IPython.Extensions.InterpreterExec
236
247
237 because otherwise things won't work for them. They MUST also
248 because otherwise things won't work for them. They MUST also
238 delete pysh.py and the line
249 delete pysh.py and the line
239
250
240 execfile pysh.py
251 execfile pysh.py
241
252
242 from their ipythonrc-pysh.
253 from their ipythonrc-pysh.
243
254
244 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
255 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
245 robust in the face of objects whose dir() returns non-strings
256 robust in the face of objects whose dir() returns non-strings
246 (which it shouldn't, but some broken libs like ITK do). Thanks to
257 (which it shouldn't, but some broken libs like ITK do). Thanks to
247 a patch by John Hunter (implemented differently, though). Also
258 a patch by John Hunter (implemented differently, though). Also
248 minor improvements by using .extend instead of + on lists.
259 minor improvements by using .extend instead of + on lists.
249
260
250 * pysh.py:
261 * pysh.py:
251
262
252 2005-04-06 Fernando Perez <fperez@colorado.edu>
263 2005-04-06 Fernando Perez <fperez@colorado.edu>
253
264
254 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
265 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
255 by default, so that all users benefit from it. Those who don't
266 by default, so that all users benefit from it. Those who don't
256 want it can still turn it off.
267 want it can still turn it off.
257
268
258 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
269 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
259 config file, I'd forgotten about this, so users were getting it
270 config file, I'd forgotten about this, so users were getting it
260 off by default.
271 off by default.
261
272
262 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
273 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
263 consistency. Now magics can be called in multiline statements,
274 consistency. Now magics can be called in multiline statements,
264 and python variables can be expanded in magic calls via $var.
275 and python variables can be expanded in magic calls via $var.
265 This makes the magic system behave just like aliases or !system
276 This makes the magic system behave just like aliases or !system
266 calls.
277 calls.
267
278
268 2005-03-28 Fernando Perez <fperez@colorado.edu>
279 2005-03-28 Fernando Perez <fperez@colorado.edu>
269
280
270 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
281 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
271 expensive string additions for building command. Add support for
282 expensive string additions for building command. Add support for
272 trailing ';' when autocall is used.
283 trailing ';' when autocall is used.
273
284
274 2005-03-26 Fernando Perez <fperez@colorado.edu>
285 2005-03-26 Fernando Perez <fperez@colorado.edu>
275
286
276 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
287 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
277 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
288 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
278 ipython.el robust against prompts with any number of spaces
289 ipython.el robust against prompts with any number of spaces
279 (including 0) after the ':' character.
290 (including 0) after the ':' character.
280
291
281 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
292 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
282 continuation prompt, which misled users to think the line was
293 continuation prompt, which misled users to think the line was
283 already indented. Closes debian Bug#300847, reported to me by
294 already indented. Closes debian Bug#300847, reported to me by
284 Norbert Tretkowski <tretkowski-AT-inittab.de>.
295 Norbert Tretkowski <tretkowski-AT-inittab.de>.
285
296
286 2005-03-23 Fernando Perez <fperez@colorado.edu>
297 2005-03-23 Fernando Perez <fperez@colorado.edu>
287
298
288 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
299 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
289 properly aligned if they have embedded newlines.
300 properly aligned if they have embedded newlines.
290
301
291 * IPython/iplib.py (runlines): Add a public method to expose
302 * IPython/iplib.py (runlines): Add a public method to expose
292 IPython's code execution machinery, so that users can run strings
303 IPython's code execution machinery, so that users can run strings
293 as if they had been typed at the prompt interactively.
304 as if they had been typed at the prompt interactively.
294 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
305 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
295 methods which can call the system shell, but with python variable
306 methods which can call the system shell, but with python variable
296 expansion. The three such methods are: __IPYTHON__.system,
307 expansion. The three such methods are: __IPYTHON__.system,
297 .getoutput and .getoutputerror. These need to be documented in a
308 .getoutput and .getoutputerror. These need to be documented in a
298 'public API' section (to be written) of the manual.
309 'public API' section (to be written) of the manual.
299
310
300 2005-03-20 Fernando Perez <fperez@colorado.edu>
311 2005-03-20 Fernando Perez <fperez@colorado.edu>
301
312
302 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
313 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
303 for custom exception handling. This is quite powerful, and it
314 for custom exception handling. This is quite powerful, and it
304 allows for user-installable exception handlers which can trap
315 allows for user-installable exception handlers which can trap
305 custom exceptions at runtime and treat them separately from
316 custom exceptions at runtime and treat them separately from
306 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
317 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
307 Mantegazza <mantegazza-AT-ill.fr>.
318 Mantegazza <mantegazza-AT-ill.fr>.
308 (InteractiveShell.set_custom_completer): public API function to
319 (InteractiveShell.set_custom_completer): public API function to
309 add new completers at runtime.
320 add new completers at runtime.
310
321
311 2005-03-19 Fernando Perez <fperez@colorado.edu>
322 2005-03-19 Fernando Perez <fperez@colorado.edu>
312
323
313 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
324 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
314 allow objects which provide their docstrings via non-standard
325 allow objects which provide their docstrings via non-standard
315 mechanisms (like Pyro proxies) to still be inspected by ipython's
326 mechanisms (like Pyro proxies) to still be inspected by ipython's
316 ? system.
327 ? system.
317
328
318 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
329 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
319 automatic capture system. I tried quite hard to make it work
330 automatic capture system. I tried quite hard to make it work
320 reliably, and simply failed. I tried many combinations with the
331 reliably, and simply failed. I tried many combinations with the
321 subprocess module, but eventually nothing worked in all needed
332 subprocess module, but eventually nothing worked in all needed
322 cases (not blocking stdin for the child, duplicating stdout
333 cases (not blocking stdin for the child, duplicating stdout
323 without blocking, etc). The new %sc/%sx still do capture to these
334 without blocking, etc). The new %sc/%sx still do capture to these
324 magical list/string objects which make shell use much more
335 magical list/string objects which make shell use much more
325 conveninent, so not all is lost.
336 conveninent, so not all is lost.
326
337
327 XXX - FIX MANUAL for the change above!
338 XXX - FIX MANUAL for the change above!
328
339
329 (runsource): I copied code.py's runsource() into ipython to modify
340 (runsource): I copied code.py's runsource() into ipython to modify
330 it a bit. Now the code object and source to be executed are
341 it a bit. Now the code object and source to be executed are
331 stored in ipython. This makes this info accessible to third-party
342 stored in ipython. This makes this info accessible to third-party
332 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
343 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
333 Mantegazza <mantegazza-AT-ill.fr>.
344 Mantegazza <mantegazza-AT-ill.fr>.
334
345
335 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
346 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
336 history-search via readline (like C-p/C-n). I'd wanted this for a
347 history-search via readline (like C-p/C-n). I'd wanted this for a
337 long time, but only recently found out how to do it. For users
348 long time, but only recently found out how to do it. For users
338 who already have their ipythonrc files made and want this, just
349 who already have their ipythonrc files made and want this, just
339 add:
350 add:
340
351
341 readline_parse_and_bind "\e[A": history-search-backward
352 readline_parse_and_bind "\e[A": history-search-backward
342 readline_parse_and_bind "\e[B": history-search-forward
353 readline_parse_and_bind "\e[B": history-search-forward
343
354
344 2005-03-18 Fernando Perez <fperez@colorado.edu>
355 2005-03-18 Fernando Perez <fperez@colorado.edu>
345
356
346 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
357 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
347 LSString and SList classes which allow transparent conversions
358 LSString and SList classes which allow transparent conversions
348 between list mode and whitespace-separated string.
359 between list mode and whitespace-separated string.
349 (magic_r): Fix recursion problem in %r.
360 (magic_r): Fix recursion problem in %r.
350
361
351 * IPython/genutils.py (LSString): New class to be used for
362 * IPython/genutils.py (LSString): New class to be used for
352 automatic storage of the results of all alias/system calls in _o
363 automatic storage of the results of all alias/system calls in _o
353 and _e (stdout/err). These provide a .l/.list attribute which
364 and _e (stdout/err). These provide a .l/.list attribute which
354 does automatic splitting on newlines. This means that for most
365 does automatic splitting on newlines. This means that for most
355 uses, you'll never need to do capturing of output with %sc/%sx
366 uses, you'll never need to do capturing of output with %sc/%sx
356 anymore, since ipython keeps this always done for you. Note that
367 anymore, since ipython keeps this always done for you. Note that
357 only the LAST results are stored, the _o/e variables are
368 only the LAST results are stored, the _o/e variables are
358 overwritten on each call. If you need to save their contents
369 overwritten on each call. If you need to save their contents
359 further, simply bind them to any other name.
370 further, simply bind them to any other name.
360
371
361 2005-03-17 Fernando Perez <fperez@colorado.edu>
372 2005-03-17 Fernando Perez <fperez@colorado.edu>
362
373
363 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
374 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
364 prompt namespace handling.
375 prompt namespace handling.
365
376
366 2005-03-16 Fernando Perez <fperez@colorado.edu>
377 2005-03-16 Fernando Perez <fperez@colorado.edu>
367
378
368 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
379 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
369 classic prompts to be '>>> ' (final space was missing, and it
380 classic prompts to be '>>> ' (final space was missing, and it
370 trips the emacs python mode).
381 trips the emacs python mode).
371 (BasePrompt.__str__): Added safe support for dynamic prompt
382 (BasePrompt.__str__): Added safe support for dynamic prompt
372 strings. Now you can set your prompt string to be '$x', and the
383 strings. Now you can set your prompt string to be '$x', and the
373 value of x will be printed from your interactive namespace. The
384 value of x will be printed from your interactive namespace. The
374 interpolation syntax includes the full Itpl support, so
385 interpolation syntax includes the full Itpl support, so
375 ${foo()+x+bar()} is a valid prompt string now, and the function
386 ${foo()+x+bar()} is a valid prompt string now, and the function
376 calls will be made at runtime.
387 calls will be made at runtime.
377
388
378 2005-03-15 Fernando Perez <fperez@colorado.edu>
389 2005-03-15 Fernando Perez <fperez@colorado.edu>
379
390
380 * IPython/Magic.py (magic_history): renamed %hist to %history, to
391 * IPython/Magic.py (magic_history): renamed %hist to %history, to
381 avoid name clashes in pylab. %hist still works, it just forwards
392 avoid name clashes in pylab. %hist still works, it just forwards
382 the call to %history.
393 the call to %history.
383
394
384 2005-03-02 *** Released version 0.6.12
395 2005-03-02 *** Released version 0.6.12
385
396
386 2005-03-02 Fernando Perez <fperez@colorado.edu>
397 2005-03-02 Fernando Perez <fperez@colorado.edu>
387
398
388 * IPython/iplib.py (handle_magic): log magic calls properly as
399 * IPython/iplib.py (handle_magic): log magic calls properly as
389 ipmagic() function calls.
400 ipmagic() function calls.
390
401
391 * IPython/Magic.py (magic_time): Improved %time to support
402 * IPython/Magic.py (magic_time): Improved %time to support
392 statements and provide wall-clock as well as CPU time.
403 statements and provide wall-clock as well as CPU time.
393
404
394 2005-02-27 Fernando Perez <fperez@colorado.edu>
405 2005-02-27 Fernando Perez <fperez@colorado.edu>
395
406
396 * IPython/hooks.py: New hooks module, to expose user-modifiable
407 * IPython/hooks.py: New hooks module, to expose user-modifiable
397 IPython functionality in a clean manner. For now only the editor
408 IPython functionality in a clean manner. For now only the editor
398 hook is actually written, and other thigns which I intend to turn
409 hook is actually written, and other thigns which I intend to turn
399 into proper hooks aren't yet there. The display and prefilter
410 into proper hooks aren't yet there. The display and prefilter
400 stuff, for example, should be hooks. But at least now the
411 stuff, for example, should be hooks. But at least now the
401 framework is in place, and the rest can be moved here with more
412 framework is in place, and the rest can be moved here with more
402 time later. IPython had had a .hooks variable for a long time for
413 time later. IPython had had a .hooks variable for a long time for
403 this purpose, but I'd never actually used it for anything.
414 this purpose, but I'd never actually used it for anything.
404
415
405 2005-02-26 Fernando Perez <fperez@colorado.edu>
416 2005-02-26 Fernando Perez <fperez@colorado.edu>
406
417
407 * IPython/ipmaker.py (make_IPython): make the default ipython
418 * IPython/ipmaker.py (make_IPython): make the default ipython
408 directory be called _ipython under win32, to follow more the
419 directory be called _ipython under win32, to follow more the
409 naming peculiarities of that platform (where buggy software like
420 naming peculiarities of that platform (where buggy software like
410 Visual Sourcesafe breaks with .named directories). Reported by
421 Visual Sourcesafe breaks with .named directories). Reported by
411 Ville Vainio.
422 Ville Vainio.
412
423
413 2005-02-23 Fernando Perez <fperez@colorado.edu>
424 2005-02-23 Fernando Perez <fperez@colorado.edu>
414
425
415 * IPython/iplib.py (InteractiveShell.__init__): removed a few
426 * IPython/iplib.py (InteractiveShell.__init__): removed a few
416 auto_aliases for win32 which were causing problems. Users can
427 auto_aliases for win32 which were causing problems. Users can
417 define the ones they personally like.
428 define the ones they personally like.
418
429
419 2005-02-21 Fernando Perez <fperez@colorado.edu>
430 2005-02-21 Fernando Perez <fperez@colorado.edu>
420
431
421 * IPython/Magic.py (magic_time): new magic to time execution of
432 * IPython/Magic.py (magic_time): new magic to time execution of
422 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
433 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
423
434
424 2005-02-19 Fernando Perez <fperez@colorado.edu>
435 2005-02-19 Fernando Perez <fperez@colorado.edu>
425
436
426 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
437 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
427 into keys (for prompts, for example).
438 into keys (for prompts, for example).
428
439
429 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
440 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
430 prompts in case users want them. This introduces a small behavior
441 prompts in case users want them. This introduces a small behavior
431 change: ipython does not automatically add a space to all prompts
442 change: ipython does not automatically add a space to all prompts
432 anymore. To get the old prompts with a space, users should add it
443 anymore. To get the old prompts with a space, users should add it
433 manually to their ipythonrc file, so for example prompt_in1 should
444 manually to their ipythonrc file, so for example prompt_in1 should
434 now read 'In [\#]: ' instead of 'In [\#]:'.
445 now read 'In [\#]: ' instead of 'In [\#]:'.
435 (BasePrompt.__init__): New option prompts_pad_left (only in rc
446 (BasePrompt.__init__): New option prompts_pad_left (only in rc
436 file) to control left-padding of secondary prompts.
447 file) to control left-padding of secondary prompts.
437
448
438 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
449 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
439 the profiler can't be imported. Fix for Debian, which removed
450 the profiler can't be imported. Fix for Debian, which removed
440 profile.py because of License issues. I applied a slightly
451 profile.py because of License issues. I applied a slightly
441 modified version of the original Debian patch at
452 modified version of the original Debian patch at
442 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
453 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
443
454
444 2005-02-17 Fernando Perez <fperez@colorado.edu>
455 2005-02-17 Fernando Perez <fperez@colorado.edu>
445
456
446 * IPython/genutils.py (native_line_ends): Fix bug which would
457 * IPython/genutils.py (native_line_ends): Fix bug which would
447 cause improper line-ends under win32 b/c I was not opening files
458 cause improper line-ends under win32 b/c I was not opening files
448 in binary mode. Bug report and fix thanks to Ville.
459 in binary mode. Bug report and fix thanks to Ville.
449
460
450 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
461 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
451 trying to catch spurious foo[1] autocalls. My fix actually broke
462 trying to catch spurious foo[1] autocalls. My fix actually broke
452 ',/' autoquote/call with explicit escape (bad regexp).
463 ',/' autoquote/call with explicit escape (bad regexp).
453
464
454 2005-02-15 *** Released version 0.6.11
465 2005-02-15 *** Released version 0.6.11
455
466
456 2005-02-14 Fernando Perez <fperez@colorado.edu>
467 2005-02-14 Fernando Perez <fperez@colorado.edu>
457
468
458 * IPython/background_jobs.py: New background job management
469 * IPython/background_jobs.py: New background job management
459 subsystem. This is implemented via a new set of classes, and
470 subsystem. This is implemented via a new set of classes, and
460 IPython now provides a builtin 'jobs' object for background job
471 IPython now provides a builtin 'jobs' object for background job
461 execution. A convenience %bg magic serves as a lightweight
472 execution. A convenience %bg magic serves as a lightweight
462 frontend for starting the more common type of calls. This was
473 frontend for starting the more common type of calls. This was
463 inspired by discussions with B. Granger and the BackgroundCommand
474 inspired by discussions with B. Granger and the BackgroundCommand
464 class described in the book Python Scripting for Computational
475 class described in the book Python Scripting for Computational
465 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
476 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
466 (although ultimately no code from this text was used, as IPython's
477 (although ultimately no code from this text was used, as IPython's
467 system is a separate implementation).
478 system is a separate implementation).
468
479
469 * IPython/iplib.py (MagicCompleter.python_matches): add new option
480 * IPython/iplib.py (MagicCompleter.python_matches): add new option
470 to control the completion of single/double underscore names
481 to control the completion of single/double underscore names
471 separately. As documented in the example ipytonrc file, the
482 separately. As documented in the example ipytonrc file, the
472 readline_omit__names variable can now be set to 2, to omit even
483 readline_omit__names variable can now be set to 2, to omit even
473 single underscore names. Thanks to a patch by Brian Wong
484 single underscore names. Thanks to a patch by Brian Wong
474 <BrianWong-AT-AirgoNetworks.Com>.
485 <BrianWong-AT-AirgoNetworks.Com>.
475 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
486 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
476 be autocalled as foo([1]) if foo were callable. A problem for
487 be autocalled as foo([1]) if foo were callable. A problem for
477 things which are both callable and implement __getitem__.
488 things which are both callable and implement __getitem__.
478 (init_readline): Fix autoindentation for win32. Thanks to a patch
489 (init_readline): Fix autoindentation for win32. Thanks to a patch
479 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
490 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
480
491
481 2005-02-12 Fernando Perez <fperez@colorado.edu>
492 2005-02-12 Fernando Perez <fperez@colorado.edu>
482
493
483 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
494 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
484 which I had written long ago to sort out user error messages which
495 which I had written long ago to sort out user error messages which
485 may occur during startup. This seemed like a good idea initially,
496 may occur during startup. This seemed like a good idea initially,
486 but it has proven a disaster in retrospect. I don't want to
497 but it has proven a disaster in retrospect. I don't want to
487 change much code for now, so my fix is to set the internal 'debug'
498 change much code for now, so my fix is to set the internal 'debug'
488 flag to true everywhere, whose only job was precisely to control
499 flag to true everywhere, whose only job was precisely to control
489 this subsystem. This closes issue 28 (as well as avoiding all
500 this subsystem. This closes issue 28 (as well as avoiding all
490 sorts of strange hangups which occur from time to time).
501 sorts of strange hangups which occur from time to time).
491
502
492 2005-02-07 Fernando Perez <fperez@colorado.edu>
503 2005-02-07 Fernando Perez <fperez@colorado.edu>
493
504
494 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
505 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
495 previous call produced a syntax error.
506 previous call produced a syntax error.
496
507
497 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
508 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
498 classes without constructor.
509 classes without constructor.
499
510
500 2005-02-06 Fernando Perez <fperez@colorado.edu>
511 2005-02-06 Fernando Perez <fperez@colorado.edu>
501
512
502 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
513 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
503 completions with the results of each matcher, so we return results
514 completions with the results of each matcher, so we return results
504 to the user from all namespaces. This breaks with ipython
515 to the user from all namespaces. This breaks with ipython
505 tradition, but I think it's a nicer behavior. Now you get all
516 tradition, but I think it's a nicer behavior. Now you get all
506 possible completions listed, from all possible namespaces (python,
517 possible completions listed, from all possible namespaces (python,
507 filesystem, magics...) After a request by John Hunter
518 filesystem, magics...) After a request by John Hunter
508 <jdhunter-AT-nitace.bsd.uchicago.edu>.
519 <jdhunter-AT-nitace.bsd.uchicago.edu>.
509
520
510 2005-02-05 Fernando Perez <fperez@colorado.edu>
521 2005-02-05 Fernando Perez <fperez@colorado.edu>
511
522
512 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
523 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
513 the call had quote characters in it (the quotes were stripped).
524 the call had quote characters in it (the quotes were stripped).
514
525
515 2005-01-31 Fernando Perez <fperez@colorado.edu>
526 2005-01-31 Fernando Perez <fperez@colorado.edu>
516
527
517 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
528 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
518 Itpl.itpl() to make the code more robust against psyco
529 Itpl.itpl() to make the code more robust against psyco
519 optimizations.
530 optimizations.
520
531
521 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
532 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
522 of causing an exception. Quicker, cleaner.
533 of causing an exception. Quicker, cleaner.
523
534
524 2005-01-28 Fernando Perez <fperez@colorado.edu>
535 2005-01-28 Fernando Perez <fperez@colorado.edu>
525
536
526 * scripts/ipython_win_post_install.py (install): hardcode
537 * scripts/ipython_win_post_install.py (install): hardcode
527 sys.prefix+'python.exe' as the executable path. It turns out that
538 sys.prefix+'python.exe' as the executable path. It turns out that
528 during the post-installation run, sys.executable resolves to the
539 during the post-installation run, sys.executable resolves to the
529 name of the binary installer! I should report this as a distutils
540 name of the binary installer! I should report this as a distutils
530 bug, I think. I updated the .10 release with this tiny fix, to
541 bug, I think. I updated the .10 release with this tiny fix, to
531 avoid annoying the lists further.
542 avoid annoying the lists further.
532
543
533 2005-01-27 *** Released version 0.6.10
544 2005-01-27 *** Released version 0.6.10
534
545
535 2005-01-27 Fernando Perez <fperez@colorado.edu>
546 2005-01-27 Fernando Perez <fperez@colorado.edu>
536
547
537 * IPython/numutils.py (norm): Added 'inf' as optional name for
548 * IPython/numutils.py (norm): Added 'inf' as optional name for
538 L-infinity norm, included references to mathworld.com for vector
549 L-infinity norm, included references to mathworld.com for vector
539 norm definitions.
550 norm definitions.
540 (amin/amax): added amin/amax for array min/max. Similar to what
551 (amin/amax): added amin/amax for array min/max. Similar to what
541 pylab ships with after the recent reorganization of names.
552 pylab ships with after the recent reorganization of names.
542 (spike/spike_odd): removed deprecated spike/spike_odd functions.
553 (spike/spike_odd): removed deprecated spike/spike_odd functions.
543
554
544 * ipython.el: committed Alex's recent fixes and improvements.
555 * ipython.el: committed Alex's recent fixes and improvements.
545 Tested with python-mode from CVS, and it looks excellent. Since
556 Tested with python-mode from CVS, and it looks excellent. Since
546 python-mode hasn't released anything in a while, I'm temporarily
557 python-mode hasn't released anything in a while, I'm temporarily
547 putting a copy of today's CVS (v 4.70) of python-mode in:
558 putting a copy of today's CVS (v 4.70) of python-mode in:
548 http://ipython.scipy.org/tmp/python-mode.el
559 http://ipython.scipy.org/tmp/python-mode.el
549
560
550 * scripts/ipython_win_post_install.py (install): Win32 fix to use
561 * scripts/ipython_win_post_install.py (install): Win32 fix to use
551 sys.executable for the executable name, instead of assuming it's
562 sys.executable for the executable name, instead of assuming it's
552 called 'python.exe' (the post-installer would have produced broken
563 called 'python.exe' (the post-installer would have produced broken
553 setups on systems with a differently named python binary).
564 setups on systems with a differently named python binary).
554
565
555 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
566 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
556 references to os.linesep, to make the code more
567 references to os.linesep, to make the code more
557 platform-independent. This is also part of the win32 coloring
568 platform-independent. This is also part of the win32 coloring
558 fixes.
569 fixes.
559
570
560 * IPython/genutils.py (page_dumb): Remove attempts to chop long
571 * IPython/genutils.py (page_dumb): Remove attempts to chop long
561 lines, which actually cause coloring bugs because the length of
572 lines, which actually cause coloring bugs because the length of
562 the line is very difficult to correctly compute with embedded
573 the line is very difficult to correctly compute with embedded
563 escapes. This was the source of all the coloring problems under
574 escapes. This was the source of all the coloring problems under
564 Win32. I think that _finally_, Win32 users have a properly
575 Win32. I think that _finally_, Win32 users have a properly
565 working ipython in all respects. This would never have happened
576 working ipython in all respects. This would never have happened
566 if not for Gary Bishop and Viktor Ransmayr's great help and work.
577 if not for Gary Bishop and Viktor Ransmayr's great help and work.
567
578
568 2005-01-26 *** Released version 0.6.9
579 2005-01-26 *** Released version 0.6.9
569
580
570 2005-01-25 Fernando Perez <fperez@colorado.edu>
581 2005-01-25 Fernando Perez <fperez@colorado.edu>
571
582
572 * setup.py: finally, we have a true Windows installer, thanks to
583 * setup.py: finally, we have a true Windows installer, thanks to
573 the excellent work of Viktor Ransmayr
584 the excellent work of Viktor Ransmayr
574 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
585 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
575 Windows users. The setup routine is quite a bit cleaner thanks to
586 Windows users. The setup routine is quite a bit cleaner thanks to
576 this, and the post-install script uses the proper functions to
587 this, and the post-install script uses the proper functions to
577 allow a clean de-installation using the standard Windows Control
588 allow a clean de-installation using the standard Windows Control
578 Panel.
589 Panel.
579
590
580 * IPython/genutils.py (get_home_dir): changed to use the $HOME
591 * IPython/genutils.py (get_home_dir): changed to use the $HOME
581 environment variable under all OSes (including win32) if
592 environment variable under all OSes (including win32) if
582 available. This will give consistency to win32 users who have set
593 available. This will give consistency to win32 users who have set
583 this variable for any reason. If os.environ['HOME'] fails, the
594 this variable for any reason. If os.environ['HOME'] fails, the
584 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
595 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
585
596
586 2005-01-24 Fernando Perez <fperez@colorado.edu>
597 2005-01-24 Fernando Perez <fperez@colorado.edu>
587
598
588 * IPython/numutils.py (empty_like): add empty_like(), similar to
599 * IPython/numutils.py (empty_like): add empty_like(), similar to
589 zeros_like() but taking advantage of the new empty() Numeric routine.
600 zeros_like() but taking advantage of the new empty() Numeric routine.
590
601
591 2005-01-23 *** Released version 0.6.8
602 2005-01-23 *** Released version 0.6.8
592
603
593 2005-01-22 Fernando Perez <fperez@colorado.edu>
604 2005-01-22 Fernando Perez <fperez@colorado.edu>
594
605
595 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
606 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
596 automatic show() calls. After discussing things with JDH, it
607 automatic show() calls. After discussing things with JDH, it
597 turns out there are too many corner cases where this can go wrong.
608 turns out there are too many corner cases where this can go wrong.
598 It's best not to try to be 'too smart', and simply have ipython
609 It's best not to try to be 'too smart', and simply have ipython
599 reproduce as much as possible the default behavior of a normal
610 reproduce as much as possible the default behavior of a normal
600 python shell.
611 python shell.
601
612
602 * IPython/iplib.py (InteractiveShell.__init__): Modified the
613 * IPython/iplib.py (InteractiveShell.__init__): Modified the
603 line-splitting regexp and _prefilter() to avoid calling getattr()
614 line-splitting regexp and _prefilter() to avoid calling getattr()
604 on assignments. This closes
615 on assignments. This closes
605 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
616 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
606 readline uses getattr(), so a simple <TAB> keypress is still
617 readline uses getattr(), so a simple <TAB> keypress is still
607 enough to trigger getattr() calls on an object.
618 enough to trigger getattr() calls on an object.
608
619
609 2005-01-21 Fernando Perez <fperez@colorado.edu>
620 2005-01-21 Fernando Perez <fperez@colorado.edu>
610
621
611 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
622 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
612 docstring under pylab so it doesn't mask the original.
623 docstring under pylab so it doesn't mask the original.
613
624
614 2005-01-21 *** Released version 0.6.7
625 2005-01-21 *** Released version 0.6.7
615
626
616 2005-01-21 Fernando Perez <fperez@colorado.edu>
627 2005-01-21 Fernando Perez <fperez@colorado.edu>
617
628
618 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
629 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
619 signal handling for win32 users in multithreaded mode.
630 signal handling for win32 users in multithreaded mode.
620
631
621 2005-01-17 Fernando Perez <fperez@colorado.edu>
632 2005-01-17 Fernando Perez <fperez@colorado.edu>
622
633
623 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
634 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
624 instances with no __init__. After a crash report by Norbert Nemec
635 instances with no __init__. After a crash report by Norbert Nemec
625 <Norbert-AT-nemec-online.de>.
636 <Norbert-AT-nemec-online.de>.
626
637
627 2005-01-14 Fernando Perez <fperez@colorado.edu>
638 2005-01-14 Fernando Perez <fperez@colorado.edu>
628
639
629 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
640 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
630 names for verbose exceptions, when multiple dotted names and the
641 names for verbose exceptions, when multiple dotted names and the
631 'parent' object were present on the same line.
642 'parent' object were present on the same line.
632
643
633 2005-01-11 Fernando Perez <fperez@colorado.edu>
644 2005-01-11 Fernando Perez <fperez@colorado.edu>
634
645
635 * IPython/genutils.py (flag_calls): new utility to trap and flag
646 * IPython/genutils.py (flag_calls): new utility to trap and flag
636 calls in functions. I need it to clean up matplotlib support.
647 calls in functions. I need it to clean up matplotlib support.
637 Also removed some deprecated code in genutils.
648 Also removed some deprecated code in genutils.
638
649
639 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
650 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
640 that matplotlib scripts called with %run, which don't call show()
651 that matplotlib scripts called with %run, which don't call show()
641 themselves, still have their plotting windows open.
652 themselves, still have their plotting windows open.
642
653
643 2005-01-05 Fernando Perez <fperez@colorado.edu>
654 2005-01-05 Fernando Perez <fperez@colorado.edu>
644
655
645 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
656 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
646 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
657 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
647
658
648 2004-12-19 Fernando Perez <fperez@colorado.edu>
659 2004-12-19 Fernando Perez <fperez@colorado.edu>
649
660
650 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
661 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
651 parent_runcode, which was an eyesore. The same result can be
662 parent_runcode, which was an eyesore. The same result can be
652 obtained with Python's regular superclass mechanisms.
663 obtained with Python's regular superclass mechanisms.
653
664
654 2004-12-17 Fernando Perez <fperez@colorado.edu>
665 2004-12-17 Fernando Perez <fperez@colorado.edu>
655
666
656 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
667 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
657 reported by Prabhu.
668 reported by Prabhu.
658 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
669 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
659 sys.stderr) instead of explicitly calling sys.stderr. This helps
670 sys.stderr) instead of explicitly calling sys.stderr. This helps
660 maintain our I/O abstractions clean, for future GUI embeddings.
671 maintain our I/O abstractions clean, for future GUI embeddings.
661
672
662 * IPython/genutils.py (info): added new utility for sys.stderr
673 * IPython/genutils.py (info): added new utility for sys.stderr
663 unified info message handling (thin wrapper around warn()).
674 unified info message handling (thin wrapper around warn()).
664
675
665 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
676 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
666 composite (dotted) names on verbose exceptions.
677 composite (dotted) names on verbose exceptions.
667 (VerboseTB.nullrepr): harden against another kind of errors which
678 (VerboseTB.nullrepr): harden against another kind of errors which
668 Python's inspect module can trigger, and which were crashing
679 Python's inspect module can trigger, and which were crashing
669 IPython. Thanks to a report by Marco Lombardi
680 IPython. Thanks to a report by Marco Lombardi
670 <mlombard-AT-ma010192.hq.eso.org>.
681 <mlombard-AT-ma010192.hq.eso.org>.
671
682
672 2004-12-13 *** Released version 0.6.6
683 2004-12-13 *** Released version 0.6.6
673
684
674 2004-12-12 Fernando Perez <fperez@colorado.edu>
685 2004-12-12 Fernando Perez <fperez@colorado.edu>
675
686
676 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
687 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
677 generated by pygtk upon initialization if it was built without
688 generated by pygtk upon initialization if it was built without
678 threads (for matplotlib users). After a crash reported by
689 threads (for matplotlib users). After a crash reported by
679 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
690 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
680
691
681 * IPython/ipmaker.py (make_IPython): fix small bug in the
692 * IPython/ipmaker.py (make_IPython): fix small bug in the
682 import_some parameter for multiple imports.
693 import_some parameter for multiple imports.
683
694
684 * IPython/iplib.py (ipmagic): simplified the interface of
695 * IPython/iplib.py (ipmagic): simplified the interface of
685 ipmagic() to take a single string argument, just as it would be
696 ipmagic() to take a single string argument, just as it would be
686 typed at the IPython cmd line.
697 typed at the IPython cmd line.
687 (ipalias): Added new ipalias() with an interface identical to
698 (ipalias): Added new ipalias() with an interface identical to
688 ipmagic(). This completes exposing a pure python interface to the
699 ipmagic(). This completes exposing a pure python interface to the
689 alias and magic system, which can be used in loops or more complex
700 alias and magic system, which can be used in loops or more complex
690 code where IPython's automatic line mangling is not active.
701 code where IPython's automatic line mangling is not active.
691
702
692 * IPython/genutils.py (timing): changed interface of timing to
703 * IPython/genutils.py (timing): changed interface of timing to
693 simply run code once, which is the most common case. timings()
704 simply run code once, which is the most common case. timings()
694 remains unchanged, for the cases where you want multiple runs.
705 remains unchanged, for the cases where you want multiple runs.
695
706
696 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
707 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
697 bug where Python2.2 crashes with exec'ing code which does not end
708 bug where Python2.2 crashes with exec'ing code which does not end
698 in a single newline. Python 2.3 is OK, so I hadn't noticed this
709 in a single newline. Python 2.3 is OK, so I hadn't noticed this
699 before.
710 before.
700
711
701 2004-12-10 Fernando Perez <fperez@colorado.edu>
712 2004-12-10 Fernando Perez <fperez@colorado.edu>
702
713
703 * IPython/Magic.py (Magic.magic_prun): changed name of option from
714 * IPython/Magic.py (Magic.magic_prun): changed name of option from
704 -t to -T, to accomodate the new -t flag in %run (the %run and
715 -t to -T, to accomodate the new -t flag in %run (the %run and
705 %prun options are kind of intermixed, and it's not easy to change
716 %prun options are kind of intermixed, and it's not easy to change
706 this with the limitations of python's getopt).
717 this with the limitations of python's getopt).
707
718
708 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
719 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
709 the execution of scripts. It's not as fine-tuned as timeit.py,
720 the execution of scripts. It's not as fine-tuned as timeit.py,
710 but it works from inside ipython (and under 2.2, which lacks
721 but it works from inside ipython (and under 2.2, which lacks
711 timeit.py). Optionally a number of runs > 1 can be given for
722 timeit.py). Optionally a number of runs > 1 can be given for
712 timing very short-running code.
723 timing very short-running code.
713
724
714 * IPython/genutils.py (uniq_stable): new routine which returns a
725 * IPython/genutils.py (uniq_stable): new routine which returns a
715 list of unique elements in any iterable, but in stable order of
726 list of unique elements in any iterable, but in stable order of
716 appearance. I needed this for the ultraTB fixes, and it's a handy
727 appearance. I needed this for the ultraTB fixes, and it's a handy
717 utility.
728 utility.
718
729
719 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
730 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
720 dotted names in Verbose exceptions. This had been broken since
731 dotted names in Verbose exceptions. This had been broken since
721 the very start, now x.y will properly be printed in a Verbose
732 the very start, now x.y will properly be printed in a Verbose
722 traceback, instead of x being shown and y appearing always as an
733 traceback, instead of x being shown and y appearing always as an
723 'undefined global'. Getting this to work was a bit tricky,
734 'undefined global'. Getting this to work was a bit tricky,
724 because by default python tokenizers are stateless. Saved by
735 because by default python tokenizers are stateless. Saved by
725 python's ability to easily add a bit of state to an arbitrary
736 python's ability to easily add a bit of state to an arbitrary
726 function (without needing to build a full-blown callable object).
737 function (without needing to build a full-blown callable object).
727
738
728 Also big cleanup of this code, which had horrendous runtime
739 Also big cleanup of this code, which had horrendous runtime
729 lookups of zillions of attributes for colorization. Moved all
740 lookups of zillions of attributes for colorization. Moved all
730 this code into a few templates, which make it cleaner and quicker.
741 this code into a few templates, which make it cleaner and quicker.
731
742
732 Printout quality was also improved for Verbose exceptions: one
743 Printout quality was also improved for Verbose exceptions: one
733 variable per line, and memory addresses are printed (this can be
744 variable per line, and memory addresses are printed (this can be
734 quite handy in nasty debugging situations, which is what Verbose
745 quite handy in nasty debugging situations, which is what Verbose
735 is for).
746 is for).
736
747
737 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
748 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
738 the command line as scripts to be loaded by embedded instances.
749 the command line as scripts to be loaded by embedded instances.
739 Doing so has the potential for an infinite recursion if there are
750 Doing so has the potential for an infinite recursion if there are
740 exceptions thrown in the process. This fixes a strange crash
751 exceptions thrown in the process. This fixes a strange crash
741 reported by Philippe MULLER <muller-AT-irit.fr>.
752 reported by Philippe MULLER <muller-AT-irit.fr>.
742
753
743 2004-12-09 Fernando Perez <fperez@colorado.edu>
754 2004-12-09 Fernando Perez <fperez@colorado.edu>
744
755
745 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
756 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
746 to reflect new names in matplotlib, which now expose the
757 to reflect new names in matplotlib, which now expose the
747 matlab-compatible interface via a pylab module instead of the
758 matlab-compatible interface via a pylab module instead of the
748 'matlab' name. The new code is backwards compatible, so users of
759 'matlab' name. The new code is backwards compatible, so users of
749 all matplotlib versions are OK. Patch by J. Hunter.
760 all matplotlib versions are OK. Patch by J. Hunter.
750
761
751 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
762 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
752 of __init__ docstrings for instances (class docstrings are already
763 of __init__ docstrings for instances (class docstrings are already
753 automatically printed). Instances with customized docstrings
764 automatically printed). Instances with customized docstrings
754 (indep. of the class) are also recognized and all 3 separate
765 (indep. of the class) are also recognized and all 3 separate
755 docstrings are printed (instance, class, constructor). After some
766 docstrings are printed (instance, class, constructor). After some
756 comments/suggestions by J. Hunter.
767 comments/suggestions by J. Hunter.
757
768
758 2004-12-05 Fernando Perez <fperez@colorado.edu>
769 2004-12-05 Fernando Perez <fperez@colorado.edu>
759
770
760 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
771 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
761 warnings when tab-completion fails and triggers an exception.
772 warnings when tab-completion fails and triggers an exception.
762
773
763 2004-12-03 Fernando Perez <fperez@colorado.edu>
774 2004-12-03 Fernando Perez <fperez@colorado.edu>
764
775
765 * IPython/Magic.py (magic_prun): Fix bug where an exception would
776 * IPython/Magic.py (magic_prun): Fix bug where an exception would
766 be triggered when using 'run -p'. An incorrect option flag was
777 be triggered when using 'run -p'. An incorrect option flag was
767 being set ('d' instead of 'D').
778 being set ('d' instead of 'D').
768 (manpage): fix missing escaped \- sign.
779 (manpage): fix missing escaped \- sign.
769
780
770 2004-11-30 *** Released version 0.6.5
781 2004-11-30 *** Released version 0.6.5
771
782
772 2004-11-30 Fernando Perez <fperez@colorado.edu>
783 2004-11-30 Fernando Perez <fperez@colorado.edu>
773
784
774 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
785 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
775 setting with -d option.
786 setting with -d option.
776
787
777 * setup.py (docfiles): Fix problem where the doc glob I was using
788 * setup.py (docfiles): Fix problem where the doc glob I was using
778 was COMPLETELY BROKEN. It was giving the right files by pure
789 was COMPLETELY BROKEN. It was giving the right files by pure
779 accident, but failed once I tried to include ipython.el. Note:
790 accident, but failed once I tried to include ipython.el. Note:
780 glob() does NOT allow you to do exclusion on multiple endings!
791 glob() does NOT allow you to do exclusion on multiple endings!
781
792
782 2004-11-29 Fernando Perez <fperez@colorado.edu>
793 2004-11-29 Fernando Perez <fperez@colorado.edu>
783
794
784 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
795 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
785 the manpage as the source. Better formatting & consistency.
796 the manpage as the source. Better formatting & consistency.
786
797
787 * IPython/Magic.py (magic_run): Added new -d option, to run
798 * IPython/Magic.py (magic_run): Added new -d option, to run
788 scripts under the control of the python pdb debugger. Note that
799 scripts under the control of the python pdb debugger. Note that
789 this required changing the %prun option -d to -D, to avoid a clash
800 this required changing the %prun option -d to -D, to avoid a clash
790 (since %run must pass options to %prun, and getopt is too dumb to
801 (since %run must pass options to %prun, and getopt is too dumb to
791 handle options with string values with embedded spaces). Thanks
802 handle options with string values with embedded spaces). Thanks
792 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
803 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
793 (magic_who_ls): added type matching to %who and %whos, so that one
804 (magic_who_ls): added type matching to %who and %whos, so that one
794 can filter their output to only include variables of certain
805 can filter their output to only include variables of certain
795 types. Another suggestion by Matthew.
806 types. Another suggestion by Matthew.
796 (magic_whos): Added memory summaries in kb and Mb for arrays.
807 (magic_whos): Added memory summaries in kb and Mb for arrays.
797 (magic_who): Improve formatting (break lines every 9 vars).
808 (magic_who): Improve formatting (break lines every 9 vars).
798
809
799 2004-11-28 Fernando Perez <fperez@colorado.edu>
810 2004-11-28 Fernando Perez <fperez@colorado.edu>
800
811
801 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
812 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
802 cache when empty lines were present.
813 cache when empty lines were present.
803
814
804 2004-11-24 Fernando Perez <fperez@colorado.edu>
815 2004-11-24 Fernando Perez <fperez@colorado.edu>
805
816
806 * IPython/usage.py (__doc__): document the re-activated threading
817 * IPython/usage.py (__doc__): document the re-activated threading
807 options for WX and GTK.
818 options for WX and GTK.
808
819
809 2004-11-23 Fernando Perez <fperez@colorado.edu>
820 2004-11-23 Fernando Perez <fperez@colorado.edu>
810
821
811 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
822 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
812 the -wthread and -gthread options, along with a new -tk one to try
823 the -wthread and -gthread options, along with a new -tk one to try
813 and coordinate Tk threading with wx/gtk. The tk support is very
824 and coordinate Tk threading with wx/gtk. The tk support is very
814 platform dependent, since it seems to require Tcl and Tk to be
825 platform dependent, since it seems to require Tcl and Tk to be
815 built with threads (Fedora1/2 appears NOT to have it, but in
826 built with threads (Fedora1/2 appears NOT to have it, but in
816 Prabhu's Debian boxes it works OK). But even with some Tk
827 Prabhu's Debian boxes it works OK). But even with some Tk
817 limitations, this is a great improvement.
828 limitations, this is a great improvement.
818
829
819 * IPython/Prompts.py (prompt_specials_color): Added \t for time
830 * IPython/Prompts.py (prompt_specials_color): Added \t for time
820 info in user prompts. Patch by Prabhu.
831 info in user prompts. Patch by Prabhu.
821
832
822 2004-11-18 Fernando Perez <fperez@colorado.edu>
833 2004-11-18 Fernando Perez <fperez@colorado.edu>
823
834
824 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
835 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
825 EOFErrors and bail, to avoid infinite loops if a non-terminating
836 EOFErrors and bail, to avoid infinite loops if a non-terminating
826 file is fed into ipython. Patch submitted in issue 19 by user,
837 file is fed into ipython. Patch submitted in issue 19 by user,
827 many thanks.
838 many thanks.
828
839
829 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
840 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
830 autoquote/parens in continuation prompts, which can cause lots of
841 autoquote/parens in continuation prompts, which can cause lots of
831 problems. Closes roundup issue 20.
842 problems. Closes roundup issue 20.
832
843
833 2004-11-17 Fernando Perez <fperez@colorado.edu>
844 2004-11-17 Fernando Perez <fperez@colorado.edu>
834
845
835 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
846 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
836 reported as debian bug #280505. I'm not sure my local changelog
847 reported as debian bug #280505. I'm not sure my local changelog
837 entry has the proper debian format (Jack?).
848 entry has the proper debian format (Jack?).
838
849
839 2004-11-08 *** Released version 0.6.4
850 2004-11-08 *** Released version 0.6.4
840
851
841 2004-11-08 Fernando Perez <fperez@colorado.edu>
852 2004-11-08 Fernando Perez <fperez@colorado.edu>
842
853
843 * IPython/iplib.py (init_readline): Fix exit message for Windows
854 * IPython/iplib.py (init_readline): Fix exit message for Windows
844 when readline is active. Thanks to a report by Eric Jones
855 when readline is active. Thanks to a report by Eric Jones
845 <eric-AT-enthought.com>.
856 <eric-AT-enthought.com>.
846
857
847 2004-11-07 Fernando Perez <fperez@colorado.edu>
858 2004-11-07 Fernando Perez <fperez@colorado.edu>
848
859
849 * IPython/genutils.py (page): Add a trap for OSError exceptions,
860 * IPython/genutils.py (page): Add a trap for OSError exceptions,
850 sometimes seen by win2k/cygwin users.
861 sometimes seen by win2k/cygwin users.
851
862
852 2004-11-06 Fernando Perez <fperez@colorado.edu>
863 2004-11-06 Fernando Perez <fperez@colorado.edu>
853
864
854 * IPython/iplib.py (interact): Change the handling of %Exit from
865 * IPython/iplib.py (interact): Change the handling of %Exit from
855 trying to propagate a SystemExit to an internal ipython flag.
866 trying to propagate a SystemExit to an internal ipython flag.
856 This is less elegant than using Python's exception mechanism, but
867 This is less elegant than using Python's exception mechanism, but
857 I can't get that to work reliably with threads, so under -pylab
868 I can't get that to work reliably with threads, so under -pylab
858 %Exit was hanging IPython. Cross-thread exception handling is
869 %Exit was hanging IPython. Cross-thread exception handling is
859 really a bitch. Thaks to a bug report by Stephen Walton
870 really a bitch. Thaks to a bug report by Stephen Walton
860 <stephen.walton-AT-csun.edu>.
871 <stephen.walton-AT-csun.edu>.
861
872
862 2004-11-04 Fernando Perez <fperez@colorado.edu>
873 2004-11-04 Fernando Perez <fperez@colorado.edu>
863
874
864 * IPython/iplib.py (raw_input_original): store a pointer to the
875 * IPython/iplib.py (raw_input_original): store a pointer to the
865 true raw_input to harden against code which can modify it
876 true raw_input to harden against code which can modify it
866 (wx.py.PyShell does this and would otherwise crash ipython).
877 (wx.py.PyShell does this and would otherwise crash ipython).
867 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
878 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
868
879
869 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
880 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
870 Ctrl-C problem, which does not mess up the input line.
881 Ctrl-C problem, which does not mess up the input line.
871
882
872 2004-11-03 Fernando Perez <fperez@colorado.edu>
883 2004-11-03 Fernando Perez <fperez@colorado.edu>
873
884
874 * IPython/Release.py: Changed licensing to BSD, in all files.
885 * IPython/Release.py: Changed licensing to BSD, in all files.
875 (name): lowercase name for tarball/RPM release.
886 (name): lowercase name for tarball/RPM release.
876
887
877 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
888 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
878 use throughout ipython.
889 use throughout ipython.
879
890
880 * IPython/Magic.py (Magic._ofind): Switch to using the new
891 * IPython/Magic.py (Magic._ofind): Switch to using the new
881 OInspect.getdoc() function.
892 OInspect.getdoc() function.
882
893
883 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
894 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
884 of the line currently being canceled via Ctrl-C. It's extremely
895 of the line currently being canceled via Ctrl-C. It's extremely
885 ugly, but I don't know how to do it better (the problem is one of
896 ugly, but I don't know how to do it better (the problem is one of
886 handling cross-thread exceptions).
897 handling cross-thread exceptions).
887
898
888 2004-10-28 Fernando Perez <fperez@colorado.edu>
899 2004-10-28 Fernando Perez <fperez@colorado.edu>
889
900
890 * IPython/Shell.py (signal_handler): add signal handlers to trap
901 * IPython/Shell.py (signal_handler): add signal handlers to trap
891 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
902 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
892 report by Francesc Alted.
903 report by Francesc Alted.
893
904
894 2004-10-21 Fernando Perez <fperez@colorado.edu>
905 2004-10-21 Fernando Perez <fperez@colorado.edu>
895
906
896 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
907 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
897 to % for pysh syntax extensions.
908 to % for pysh syntax extensions.
898
909
899 2004-10-09 Fernando Perez <fperez@colorado.edu>
910 2004-10-09 Fernando Perez <fperez@colorado.edu>
900
911
901 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
912 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
902 arrays to print a more useful summary, without calling str(arr).
913 arrays to print a more useful summary, without calling str(arr).
903 This avoids the problem of extremely lengthy computations which
914 This avoids the problem of extremely lengthy computations which
904 occur if arr is large, and appear to the user as a system lockup
915 occur if arr is large, and appear to the user as a system lockup
905 with 100% cpu activity. After a suggestion by Kristian Sandberg
916 with 100% cpu activity. After a suggestion by Kristian Sandberg
906 <Kristian.Sandberg@colorado.edu>.
917 <Kristian.Sandberg@colorado.edu>.
907 (Magic.__init__): fix bug in global magic escapes not being
918 (Magic.__init__): fix bug in global magic escapes not being
908 correctly set.
919 correctly set.
909
920
910 2004-10-08 Fernando Perez <fperez@colorado.edu>
921 2004-10-08 Fernando Perez <fperez@colorado.edu>
911
922
912 * IPython/Magic.py (__license__): change to absolute imports of
923 * IPython/Magic.py (__license__): change to absolute imports of
913 ipython's own internal packages, to start adapting to the absolute
924 ipython's own internal packages, to start adapting to the absolute
914 import requirement of PEP-328.
925 import requirement of PEP-328.
915
926
916 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
927 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
917 files, and standardize author/license marks through the Release
928 files, and standardize author/license marks through the Release
918 module instead of having per/file stuff (except for files with
929 module instead of having per/file stuff (except for files with
919 particular licenses, like the MIT/PSF-licensed codes).
930 particular licenses, like the MIT/PSF-licensed codes).
920
931
921 * IPython/Debugger.py: remove dead code for python 2.1
932 * IPython/Debugger.py: remove dead code for python 2.1
922
933
923 2004-10-04 Fernando Perez <fperez@colorado.edu>
934 2004-10-04 Fernando Perez <fperez@colorado.edu>
924
935
925 * IPython/iplib.py (ipmagic): New function for accessing magics
936 * IPython/iplib.py (ipmagic): New function for accessing magics
926 via a normal python function call.
937 via a normal python function call.
927
938
928 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
939 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
929 from '@' to '%', to accomodate the new @decorator syntax of python
940 from '@' to '%', to accomodate the new @decorator syntax of python
930 2.4.
941 2.4.
931
942
932 2004-09-29 Fernando Perez <fperez@colorado.edu>
943 2004-09-29 Fernando Perez <fperez@colorado.edu>
933
944
934 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
945 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
935 matplotlib.use to prevent running scripts which try to switch
946 matplotlib.use to prevent running scripts which try to switch
936 interactive backends from within ipython. This will just crash
947 interactive backends from within ipython. This will just crash
937 the python interpreter, so we can't allow it (but a detailed error
948 the python interpreter, so we can't allow it (but a detailed error
938 is given to the user).
949 is given to the user).
939
950
940 2004-09-28 Fernando Perez <fperez@colorado.edu>
951 2004-09-28 Fernando Perez <fperez@colorado.edu>
941
952
942 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
953 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
943 matplotlib-related fixes so that using @run with non-matplotlib
954 matplotlib-related fixes so that using @run with non-matplotlib
944 scripts doesn't pop up spurious plot windows. This requires
955 scripts doesn't pop up spurious plot windows. This requires
945 matplotlib >= 0.63, where I had to make some changes as well.
956 matplotlib >= 0.63, where I had to make some changes as well.
946
957
947 * IPython/ipmaker.py (make_IPython): update version requirement to
958 * IPython/ipmaker.py (make_IPython): update version requirement to
948 python 2.2.
959 python 2.2.
949
960
950 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
961 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
951 banner arg for embedded customization.
962 banner arg for embedded customization.
952
963
953 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
964 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
954 explicit uses of __IP as the IPython's instance name. Now things
965 explicit uses of __IP as the IPython's instance name. Now things
955 are properly handled via the shell.name value. The actual code
966 are properly handled via the shell.name value. The actual code
956 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
967 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
957 is much better than before. I'll clean things completely when the
968 is much better than before. I'll clean things completely when the
958 magic stuff gets a real overhaul.
969 magic stuff gets a real overhaul.
959
970
960 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
971 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
961 minor changes to debian dir.
972 minor changes to debian dir.
962
973
963 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
974 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
964 pointer to the shell itself in the interactive namespace even when
975 pointer to the shell itself in the interactive namespace even when
965 a user-supplied dict is provided. This is needed for embedding
976 a user-supplied dict is provided. This is needed for embedding
966 purposes (found by tests with Michel Sanner).
977 purposes (found by tests with Michel Sanner).
967
978
968 2004-09-27 Fernando Perez <fperez@colorado.edu>
979 2004-09-27 Fernando Perez <fperez@colorado.edu>
969
980
970 * IPython/UserConfig/ipythonrc: remove []{} from
981 * IPython/UserConfig/ipythonrc: remove []{} from
971 readline_remove_delims, so that things like [modname.<TAB> do
982 readline_remove_delims, so that things like [modname.<TAB> do
972 proper completion. This disables [].TAB, but that's a less common
983 proper completion. This disables [].TAB, but that's a less common
973 case than module names in list comprehensions, for example.
984 case than module names in list comprehensions, for example.
974 Thanks to a report by Andrea Riciputi.
985 Thanks to a report by Andrea Riciputi.
975
986
976 2004-09-09 Fernando Perez <fperez@colorado.edu>
987 2004-09-09 Fernando Perez <fperez@colorado.edu>
977
988
978 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
989 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
979 blocking problems in win32 and osx. Fix by John.
990 blocking problems in win32 and osx. Fix by John.
980
991
981 2004-09-08 Fernando Perez <fperez@colorado.edu>
992 2004-09-08 Fernando Perez <fperez@colorado.edu>
982
993
983 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
994 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
984 for Win32 and OSX. Fix by John Hunter.
995 for Win32 and OSX. Fix by John Hunter.
985
996
986 2004-08-30 *** Released version 0.6.3
997 2004-08-30 *** Released version 0.6.3
987
998
988 2004-08-30 Fernando Perez <fperez@colorado.edu>
999 2004-08-30 Fernando Perez <fperez@colorado.edu>
989
1000
990 * setup.py (isfile): Add manpages to list of dependent files to be
1001 * setup.py (isfile): Add manpages to list of dependent files to be
991 updated.
1002 updated.
992
1003
993 2004-08-27 Fernando Perez <fperez@colorado.edu>
1004 2004-08-27 Fernando Perez <fperez@colorado.edu>
994
1005
995 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1006 * IPython/Shell.py (start): I've disabled -wthread and -gthread
996 for now. They don't really work with standalone WX/GTK code
1007 for now. They don't really work with standalone WX/GTK code
997 (though matplotlib IS working fine with both of those backends).
1008 (though matplotlib IS working fine with both of those backends).
998 This will neeed much more testing. I disabled most things with
1009 This will neeed much more testing. I disabled most things with
999 comments, so turning it back on later should be pretty easy.
1010 comments, so turning it back on later should be pretty easy.
1000
1011
1001 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1012 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1002 autocalling of expressions like r'foo', by modifying the line
1013 autocalling of expressions like r'foo', by modifying the line
1003 split regexp. Closes
1014 split regexp. Closes
1004 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1015 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1005 Riley <ipythonbugs-AT-sabi.net>.
1016 Riley <ipythonbugs-AT-sabi.net>.
1006 (InteractiveShell.mainloop): honor --nobanner with banner
1017 (InteractiveShell.mainloop): honor --nobanner with banner
1007 extensions.
1018 extensions.
1008
1019
1009 * IPython/Shell.py: Significant refactoring of all classes, so
1020 * IPython/Shell.py: Significant refactoring of all classes, so
1010 that we can really support ALL matplotlib backends and threading
1021 that we can really support ALL matplotlib backends and threading
1011 models (John spotted a bug with Tk which required this). Now we
1022 models (John spotted a bug with Tk which required this). Now we
1012 should support single-threaded, WX-threads and GTK-threads, both
1023 should support single-threaded, WX-threads and GTK-threads, both
1013 for generic code and for matplotlib.
1024 for generic code and for matplotlib.
1014
1025
1015 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1026 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1016 -pylab, to simplify things for users. Will also remove the pylab
1027 -pylab, to simplify things for users. Will also remove the pylab
1017 profile, since now all of matplotlib configuration is directly
1028 profile, since now all of matplotlib configuration is directly
1018 handled here. This also reduces startup time.
1029 handled here. This also reduces startup time.
1019
1030
1020 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1031 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1021 shell wasn't being correctly called. Also in IPShellWX.
1032 shell wasn't being correctly called. Also in IPShellWX.
1022
1033
1023 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1034 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1024 fine-tune banner.
1035 fine-tune banner.
1025
1036
1026 * IPython/numutils.py (spike): Deprecate these spike functions,
1037 * IPython/numutils.py (spike): Deprecate these spike functions,
1027 delete (long deprecated) gnuplot_exec handler.
1038 delete (long deprecated) gnuplot_exec handler.
1028
1039
1029 2004-08-26 Fernando Perez <fperez@colorado.edu>
1040 2004-08-26 Fernando Perez <fperez@colorado.edu>
1030
1041
1031 * ipython.1: Update for threading options, plus some others which
1042 * ipython.1: Update for threading options, plus some others which
1032 were missing.
1043 were missing.
1033
1044
1034 * IPython/ipmaker.py (__call__): Added -wthread option for
1045 * IPython/ipmaker.py (__call__): Added -wthread option for
1035 wxpython thread handling. Make sure threading options are only
1046 wxpython thread handling. Make sure threading options are only
1036 valid at the command line.
1047 valid at the command line.
1037
1048
1038 * scripts/ipython: moved shell selection into a factory function
1049 * scripts/ipython: moved shell selection into a factory function
1039 in Shell.py, to keep the starter script to a minimum.
1050 in Shell.py, to keep the starter script to a minimum.
1040
1051
1041 2004-08-25 Fernando Perez <fperez@colorado.edu>
1052 2004-08-25 Fernando Perez <fperez@colorado.edu>
1042
1053
1043 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1054 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1044 John. Along with some recent changes he made to matplotlib, the
1055 John. Along with some recent changes he made to matplotlib, the
1045 next versions of both systems should work very well together.
1056 next versions of both systems should work very well together.
1046
1057
1047 2004-08-24 Fernando Perez <fperez@colorado.edu>
1058 2004-08-24 Fernando Perez <fperez@colorado.edu>
1048
1059
1049 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1060 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1050 tried to switch the profiling to using hotshot, but I'm getting
1061 tried to switch the profiling to using hotshot, but I'm getting
1051 strange errors from prof.runctx() there. I may be misreading the
1062 strange errors from prof.runctx() there. I may be misreading the
1052 docs, but it looks weird. For now the profiling code will
1063 docs, but it looks weird. For now the profiling code will
1053 continue to use the standard profiler.
1064 continue to use the standard profiler.
1054
1065
1055 2004-08-23 Fernando Perez <fperez@colorado.edu>
1066 2004-08-23 Fernando Perez <fperez@colorado.edu>
1056
1067
1057 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1068 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1058 threaded shell, by John Hunter. It's not quite ready yet, but
1069 threaded shell, by John Hunter. It's not quite ready yet, but
1059 close.
1070 close.
1060
1071
1061 2004-08-22 Fernando Perez <fperez@colorado.edu>
1072 2004-08-22 Fernando Perez <fperez@colorado.edu>
1062
1073
1063 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1074 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1064 in Magic and ultraTB.
1075 in Magic and ultraTB.
1065
1076
1066 * ipython.1: document threading options in manpage.
1077 * ipython.1: document threading options in manpage.
1067
1078
1068 * scripts/ipython: Changed name of -thread option to -gthread,
1079 * scripts/ipython: Changed name of -thread option to -gthread,
1069 since this is GTK specific. I want to leave the door open for a
1080 since this is GTK specific. I want to leave the door open for a
1070 -wthread option for WX, which will most likely be necessary. This
1081 -wthread option for WX, which will most likely be necessary. This
1071 change affects usage and ipmaker as well.
1082 change affects usage and ipmaker as well.
1072
1083
1073 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1084 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1074 handle the matplotlib shell issues. Code by John Hunter
1085 handle the matplotlib shell issues. Code by John Hunter
1075 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1086 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1076 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1087 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1077 broken (and disabled for end users) for now, but it puts the
1088 broken (and disabled for end users) for now, but it puts the
1078 infrastructure in place.
1089 infrastructure in place.
1079
1090
1080 2004-08-21 Fernando Perez <fperez@colorado.edu>
1091 2004-08-21 Fernando Perez <fperez@colorado.edu>
1081
1092
1082 * ipythonrc-pylab: Add matplotlib support.
1093 * ipythonrc-pylab: Add matplotlib support.
1083
1094
1084 * matplotlib_config.py: new files for matplotlib support, part of
1095 * matplotlib_config.py: new files for matplotlib support, part of
1085 the pylab profile.
1096 the pylab profile.
1086
1097
1087 * IPython/usage.py (__doc__): documented the threading options.
1098 * IPython/usage.py (__doc__): documented the threading options.
1088
1099
1089 2004-08-20 Fernando Perez <fperez@colorado.edu>
1100 2004-08-20 Fernando Perez <fperez@colorado.edu>
1090
1101
1091 * ipython: Modified the main calling routine to handle the -thread
1102 * ipython: Modified the main calling routine to handle the -thread
1092 and -mpthread options. This needs to be done as a top-level hack,
1103 and -mpthread options. This needs to be done as a top-level hack,
1093 because it determines which class to instantiate for IPython
1104 because it determines which class to instantiate for IPython
1094 itself.
1105 itself.
1095
1106
1096 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1107 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1097 classes to support multithreaded GTK operation without blocking,
1108 classes to support multithreaded GTK operation without blocking,
1098 and matplotlib with all backends. This is a lot of still very
1109 and matplotlib with all backends. This is a lot of still very
1099 experimental code, and threads are tricky. So it may still have a
1110 experimental code, and threads are tricky. So it may still have a
1100 few rough edges... This code owes a lot to
1111 few rough edges... This code owes a lot to
1101 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1112 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1102 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1113 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1103 to John Hunter for all the matplotlib work.
1114 to John Hunter for all the matplotlib work.
1104
1115
1105 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1116 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1106 options for gtk thread and matplotlib support.
1117 options for gtk thread and matplotlib support.
1107
1118
1108 2004-08-16 Fernando Perez <fperez@colorado.edu>
1119 2004-08-16 Fernando Perez <fperez@colorado.edu>
1109
1120
1110 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1121 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1111 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1122 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1112 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1123 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1113
1124
1114 2004-08-11 Fernando Perez <fperez@colorado.edu>
1125 2004-08-11 Fernando Perez <fperez@colorado.edu>
1115
1126
1116 * setup.py (isfile): Fix build so documentation gets updated for
1127 * setup.py (isfile): Fix build so documentation gets updated for
1117 rpms (it was only done for .tgz builds).
1128 rpms (it was only done for .tgz builds).
1118
1129
1119 2004-08-10 Fernando Perez <fperez@colorado.edu>
1130 2004-08-10 Fernando Perez <fperez@colorado.edu>
1120
1131
1121 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1132 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1122
1133
1123 * iplib.py : Silence syntax error exceptions in tab-completion.
1134 * iplib.py : Silence syntax error exceptions in tab-completion.
1124
1135
1125 2004-08-05 Fernando Perez <fperez@colorado.edu>
1136 2004-08-05 Fernando Perez <fperez@colorado.edu>
1126
1137
1127 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1138 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1128 'color off' mark for continuation prompts. This was causing long
1139 'color off' mark for continuation prompts. This was causing long
1129 continuation lines to mis-wrap.
1140 continuation lines to mis-wrap.
1130
1141
1131 2004-08-01 Fernando Perez <fperez@colorado.edu>
1142 2004-08-01 Fernando Perez <fperez@colorado.edu>
1132
1143
1133 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1144 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1134 for building ipython to be a parameter. All this is necessary
1145 for building ipython to be a parameter. All this is necessary
1135 right now to have a multithreaded version, but this insane
1146 right now to have a multithreaded version, but this insane
1136 non-design will be cleaned up soon. For now, it's a hack that
1147 non-design will be cleaned up soon. For now, it's a hack that
1137 works.
1148 works.
1138
1149
1139 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1150 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1140 args in various places. No bugs so far, but it's a dangerous
1151 args in various places. No bugs so far, but it's a dangerous
1141 practice.
1152 practice.
1142
1153
1143 2004-07-31 Fernando Perez <fperez@colorado.edu>
1154 2004-07-31 Fernando Perez <fperez@colorado.edu>
1144
1155
1145 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1156 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1146 fix completion of files with dots in their names under most
1157 fix completion of files with dots in their names under most
1147 profiles (pysh was OK because the completion order is different).
1158 profiles (pysh was OK because the completion order is different).
1148
1159
1149 2004-07-27 Fernando Perez <fperez@colorado.edu>
1160 2004-07-27 Fernando Perez <fperez@colorado.edu>
1150
1161
1151 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1162 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1152 keywords manually, b/c the one in keyword.py was removed in python
1163 keywords manually, b/c the one in keyword.py was removed in python
1153 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1164 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1154 This is NOT a bug under python 2.3 and earlier.
1165 This is NOT a bug under python 2.3 and earlier.
1155
1166
1156 2004-07-26 Fernando Perez <fperez@colorado.edu>
1167 2004-07-26 Fernando Perez <fperez@colorado.edu>
1157
1168
1158 * IPython/ultraTB.py (VerboseTB.text): Add another
1169 * IPython/ultraTB.py (VerboseTB.text): Add another
1159 linecache.checkcache() call to try to prevent inspect.py from
1170 linecache.checkcache() call to try to prevent inspect.py from
1160 crashing under python 2.3. I think this fixes
1171 crashing under python 2.3. I think this fixes
1161 http://www.scipy.net/roundup/ipython/issue17.
1172 http://www.scipy.net/roundup/ipython/issue17.
1162
1173
1163 2004-07-26 *** Released version 0.6.2
1174 2004-07-26 *** Released version 0.6.2
1164
1175
1165 2004-07-26 Fernando Perez <fperez@colorado.edu>
1176 2004-07-26 Fernando Perez <fperez@colorado.edu>
1166
1177
1167 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1178 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1168 fail for any number.
1179 fail for any number.
1169 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1180 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1170 empty bookmarks.
1181 empty bookmarks.
1171
1182
1172 2004-07-26 *** Released version 0.6.1
1183 2004-07-26 *** Released version 0.6.1
1173
1184
1174 2004-07-26 Fernando Perez <fperez@colorado.edu>
1185 2004-07-26 Fernando Perez <fperez@colorado.edu>
1175
1186
1176 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1187 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1177
1188
1178 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1189 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1179 escaping '()[]{}' in filenames.
1190 escaping '()[]{}' in filenames.
1180
1191
1181 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1192 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1182 Python 2.2 users who lack a proper shlex.split.
1193 Python 2.2 users who lack a proper shlex.split.
1183
1194
1184 2004-07-19 Fernando Perez <fperez@colorado.edu>
1195 2004-07-19 Fernando Perez <fperez@colorado.edu>
1185
1196
1186 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1197 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1187 for reading readline's init file. I follow the normal chain:
1198 for reading readline's init file. I follow the normal chain:
1188 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1199 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1189 report by Mike Heeter. This closes
1200 report by Mike Heeter. This closes
1190 http://www.scipy.net/roundup/ipython/issue16.
1201 http://www.scipy.net/roundup/ipython/issue16.
1191
1202
1192 2004-07-18 Fernando Perez <fperez@colorado.edu>
1203 2004-07-18 Fernando Perez <fperez@colorado.edu>
1193
1204
1194 * IPython/iplib.py (__init__): Add better handling of '\' under
1205 * IPython/iplib.py (__init__): Add better handling of '\' under
1195 Win32 for filenames. After a patch by Ville.
1206 Win32 for filenames. After a patch by Ville.
1196
1207
1197 2004-07-17 Fernando Perez <fperez@colorado.edu>
1208 2004-07-17 Fernando Perez <fperez@colorado.edu>
1198
1209
1199 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1210 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1200 autocalling would be triggered for 'foo is bar' if foo is
1211 autocalling would be triggered for 'foo is bar' if foo is
1201 callable. I also cleaned up the autocall detection code to use a
1212 callable. I also cleaned up the autocall detection code to use a
1202 regexp, which is faster. Bug reported by Alexander Schmolck.
1213 regexp, which is faster. Bug reported by Alexander Schmolck.
1203
1214
1204 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1215 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1205 '?' in them would confuse the help system. Reported by Alex
1216 '?' in them would confuse the help system. Reported by Alex
1206 Schmolck.
1217 Schmolck.
1207
1218
1208 2004-07-16 Fernando Perez <fperez@colorado.edu>
1219 2004-07-16 Fernando Perez <fperez@colorado.edu>
1209
1220
1210 * IPython/GnuplotInteractive.py (__all__): added plot2.
1221 * IPython/GnuplotInteractive.py (__all__): added plot2.
1211
1222
1212 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1223 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1213 plotting dictionaries, lists or tuples of 1d arrays.
1224 plotting dictionaries, lists or tuples of 1d arrays.
1214
1225
1215 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1226 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1216 optimizations.
1227 optimizations.
1217
1228
1218 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1229 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1219 the information which was there from Janko's original IPP code:
1230 the information which was there from Janko's original IPP code:
1220
1231
1221 03.05.99 20:53 porto.ifm.uni-kiel.de
1232 03.05.99 20:53 porto.ifm.uni-kiel.de
1222 --Started changelog.
1233 --Started changelog.
1223 --make clear do what it say it does
1234 --make clear do what it say it does
1224 --added pretty output of lines from inputcache
1235 --added pretty output of lines from inputcache
1225 --Made Logger a mixin class, simplifies handling of switches
1236 --Made Logger a mixin class, simplifies handling of switches
1226 --Added own completer class. .string<TAB> expands to last history
1237 --Added own completer class. .string<TAB> expands to last history
1227 line which starts with string. The new expansion is also present
1238 line which starts with string. The new expansion is also present
1228 with Ctrl-r from the readline library. But this shows, who this
1239 with Ctrl-r from the readline library. But this shows, who this
1229 can be done for other cases.
1240 can be done for other cases.
1230 --Added convention that all shell functions should accept a
1241 --Added convention that all shell functions should accept a
1231 parameter_string This opens the door for different behaviour for
1242 parameter_string This opens the door for different behaviour for
1232 each function. @cd is a good example of this.
1243 each function. @cd is a good example of this.
1233
1244
1234 04.05.99 12:12 porto.ifm.uni-kiel.de
1245 04.05.99 12:12 porto.ifm.uni-kiel.de
1235 --added logfile rotation
1246 --added logfile rotation
1236 --added new mainloop method which freezes first the namespace
1247 --added new mainloop method which freezes first the namespace
1237
1248
1238 07.05.99 21:24 porto.ifm.uni-kiel.de
1249 07.05.99 21:24 porto.ifm.uni-kiel.de
1239 --added the docreader classes. Now there is a help system.
1250 --added the docreader classes. Now there is a help system.
1240 -This is only a first try. Currently it's not easy to put new
1251 -This is only a first try. Currently it's not easy to put new
1241 stuff in the indices. But this is the way to go. Info would be
1252 stuff in the indices. But this is the way to go. Info would be
1242 better, but HTML is every where and not everybody has an info
1253 better, but HTML is every where and not everybody has an info
1243 system installed and it's not so easy to change html-docs to info.
1254 system installed and it's not so easy to change html-docs to info.
1244 --added global logfile option
1255 --added global logfile option
1245 --there is now a hook for object inspection method pinfo needs to
1256 --there is now a hook for object inspection method pinfo needs to
1246 be provided for this. Can be reached by two '??'.
1257 be provided for this. Can be reached by two '??'.
1247
1258
1248 08.05.99 20:51 porto.ifm.uni-kiel.de
1259 08.05.99 20:51 porto.ifm.uni-kiel.de
1249 --added a README
1260 --added a README
1250 --bug in rc file. Something has changed so functions in the rc
1261 --bug in rc file. Something has changed so functions in the rc
1251 file need to reference the shell and not self. Not clear if it's a
1262 file need to reference the shell and not self. Not clear if it's a
1252 bug or feature.
1263 bug or feature.
1253 --changed rc file for new behavior
1264 --changed rc file for new behavior
1254
1265
1255 2004-07-15 Fernando Perez <fperez@colorado.edu>
1266 2004-07-15 Fernando Perez <fperez@colorado.edu>
1256
1267
1257 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1268 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1258 cache was falling out of sync in bizarre manners when multi-line
1269 cache was falling out of sync in bizarre manners when multi-line
1259 input was present. Minor optimizations and cleanup.
1270 input was present. Minor optimizations and cleanup.
1260
1271
1261 (Logger): Remove old Changelog info for cleanup. This is the
1272 (Logger): Remove old Changelog info for cleanup. This is the
1262 information which was there from Janko's original code:
1273 information which was there from Janko's original code:
1263
1274
1264 Changes to Logger: - made the default log filename a parameter
1275 Changes to Logger: - made the default log filename a parameter
1265
1276
1266 - put a check for lines beginning with !@? in log(). Needed
1277 - put a check for lines beginning with !@? in log(). Needed
1267 (even if the handlers properly log their lines) for mid-session
1278 (even if the handlers properly log their lines) for mid-session
1268 logging activation to work properly. Without this, lines logged
1279 logging activation to work properly. Without this, lines logged
1269 in mid session, which get read from the cache, would end up
1280 in mid session, which get read from the cache, would end up
1270 'bare' (with !@? in the open) in the log. Now they are caught
1281 'bare' (with !@? in the open) in the log. Now they are caught
1271 and prepended with a #.
1282 and prepended with a #.
1272
1283
1273 * IPython/iplib.py (InteractiveShell.init_readline): added check
1284 * IPython/iplib.py (InteractiveShell.init_readline): added check
1274 in case MagicCompleter fails to be defined, so we don't crash.
1285 in case MagicCompleter fails to be defined, so we don't crash.
1275
1286
1276 2004-07-13 Fernando Perez <fperez@colorado.edu>
1287 2004-07-13 Fernando Perez <fperez@colorado.edu>
1277
1288
1278 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1289 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1279 of EPS if the requested filename ends in '.eps'.
1290 of EPS if the requested filename ends in '.eps'.
1280
1291
1281 2004-07-04 Fernando Perez <fperez@colorado.edu>
1292 2004-07-04 Fernando Perez <fperez@colorado.edu>
1282
1293
1283 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1294 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1284 escaping of quotes when calling the shell.
1295 escaping of quotes when calling the shell.
1285
1296
1286 2004-07-02 Fernando Perez <fperez@colorado.edu>
1297 2004-07-02 Fernando Perez <fperez@colorado.edu>
1287
1298
1288 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1299 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1289 gettext not working because we were clobbering '_'. Fixes
1300 gettext not working because we were clobbering '_'. Fixes
1290 http://www.scipy.net/roundup/ipython/issue6.
1301 http://www.scipy.net/roundup/ipython/issue6.
1291
1302
1292 2004-07-01 Fernando Perez <fperez@colorado.edu>
1303 2004-07-01 Fernando Perez <fperez@colorado.edu>
1293
1304
1294 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1305 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1295 into @cd. Patch by Ville.
1306 into @cd. Patch by Ville.
1296
1307
1297 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1308 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1298 new function to store things after ipmaker runs. Patch by Ville.
1309 new function to store things after ipmaker runs. Patch by Ville.
1299 Eventually this will go away once ipmaker is removed and the class
1310 Eventually this will go away once ipmaker is removed and the class
1300 gets cleaned up, but for now it's ok. Key functionality here is
1311 gets cleaned up, but for now it's ok. Key functionality here is
1301 the addition of the persistent storage mechanism, a dict for
1312 the addition of the persistent storage mechanism, a dict for
1302 keeping data across sessions (for now just bookmarks, but more can
1313 keeping data across sessions (for now just bookmarks, but more can
1303 be implemented later).
1314 be implemented later).
1304
1315
1305 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1316 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1306 persistent across sections. Patch by Ville, I modified it
1317 persistent across sections. Patch by Ville, I modified it
1307 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1318 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1308 added a '-l' option to list all bookmarks.
1319 added a '-l' option to list all bookmarks.
1309
1320
1310 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1321 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1311 center for cleanup. Registered with atexit.register(). I moved
1322 center for cleanup. Registered with atexit.register(). I moved
1312 here the old exit_cleanup(). After a patch by Ville.
1323 here the old exit_cleanup(). After a patch by Ville.
1313
1324
1314 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1325 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1315 characters in the hacked shlex_split for python 2.2.
1326 characters in the hacked shlex_split for python 2.2.
1316
1327
1317 * IPython/iplib.py (file_matches): more fixes to filenames with
1328 * IPython/iplib.py (file_matches): more fixes to filenames with
1318 whitespace in them. It's not perfect, but limitations in python's
1329 whitespace in them. It's not perfect, but limitations in python's
1319 readline make it impossible to go further.
1330 readline make it impossible to go further.
1320
1331
1321 2004-06-29 Fernando Perez <fperez@colorado.edu>
1332 2004-06-29 Fernando Perez <fperez@colorado.edu>
1322
1333
1323 * IPython/iplib.py (file_matches): escape whitespace correctly in
1334 * IPython/iplib.py (file_matches): escape whitespace correctly in
1324 filename completions. Bug reported by Ville.
1335 filename completions. Bug reported by Ville.
1325
1336
1326 2004-06-28 Fernando Perez <fperez@colorado.edu>
1337 2004-06-28 Fernando Perez <fperez@colorado.edu>
1327
1338
1328 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1339 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1329 the history file will be called 'history-PROFNAME' (or just
1340 the history file will be called 'history-PROFNAME' (or just
1330 'history' if no profile is loaded). I was getting annoyed at
1341 'history' if no profile is loaded). I was getting annoyed at
1331 getting my Numerical work history clobbered by pysh sessions.
1342 getting my Numerical work history clobbered by pysh sessions.
1332
1343
1333 * IPython/iplib.py (InteractiveShell.__init__): Internal
1344 * IPython/iplib.py (InteractiveShell.__init__): Internal
1334 getoutputerror() function so that we can honor the system_verbose
1345 getoutputerror() function so that we can honor the system_verbose
1335 flag for _all_ system calls. I also added escaping of #
1346 flag for _all_ system calls. I also added escaping of #
1336 characters here to avoid confusing Itpl.
1347 characters here to avoid confusing Itpl.
1337
1348
1338 * IPython/Magic.py (shlex_split): removed call to shell in
1349 * IPython/Magic.py (shlex_split): removed call to shell in
1339 parse_options and replaced it with shlex.split(). The annoying
1350 parse_options and replaced it with shlex.split(). The annoying
1340 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1351 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1341 to backport it from 2.3, with several frail hacks (the shlex
1352 to backport it from 2.3, with several frail hacks (the shlex
1342 module is rather limited in 2.2). Thanks to a suggestion by Ville
1353 module is rather limited in 2.2). Thanks to a suggestion by Ville
1343 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1354 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1344 problem.
1355 problem.
1345
1356
1346 (Magic.magic_system_verbose): new toggle to print the actual
1357 (Magic.magic_system_verbose): new toggle to print the actual
1347 system calls made by ipython. Mainly for debugging purposes.
1358 system calls made by ipython. Mainly for debugging purposes.
1348
1359
1349 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1360 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1350 doesn't support persistence. Reported (and fix suggested) by
1361 doesn't support persistence. Reported (and fix suggested) by
1351 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1362 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1352
1363
1353 2004-06-26 Fernando Perez <fperez@colorado.edu>
1364 2004-06-26 Fernando Perez <fperez@colorado.edu>
1354
1365
1355 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1366 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1356 continue prompts.
1367 continue prompts.
1357
1368
1358 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1369 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1359 function (basically a big docstring) and a few more things here to
1370 function (basically a big docstring) and a few more things here to
1360 speedup startup. pysh.py is now very lightweight. We want because
1371 speedup startup. pysh.py is now very lightweight. We want because
1361 it gets execfile'd, while InterpreterExec gets imported, so
1372 it gets execfile'd, while InterpreterExec gets imported, so
1362 byte-compilation saves time.
1373 byte-compilation saves time.
1363
1374
1364 2004-06-25 Fernando Perez <fperez@colorado.edu>
1375 2004-06-25 Fernando Perez <fperez@colorado.edu>
1365
1376
1366 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1377 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1367 -NUM', which was recently broken.
1378 -NUM', which was recently broken.
1368
1379
1369 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1380 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1370 in multi-line input (but not !!, which doesn't make sense there).
1381 in multi-line input (but not !!, which doesn't make sense there).
1371
1382
1372 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1383 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1373 It's just too useful, and people can turn it off in the less
1384 It's just too useful, and people can turn it off in the less
1374 common cases where it's a problem.
1385 common cases where it's a problem.
1375
1386
1376 2004-06-24 Fernando Perez <fperez@colorado.edu>
1387 2004-06-24 Fernando Perez <fperez@colorado.edu>
1377
1388
1378 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1389 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1379 special syntaxes (like alias calling) is now allied in multi-line
1390 special syntaxes (like alias calling) is now allied in multi-line
1380 input. This is still _very_ experimental, but it's necessary for
1391 input. This is still _very_ experimental, but it's necessary for
1381 efficient shell usage combining python looping syntax with system
1392 efficient shell usage combining python looping syntax with system
1382 calls. For now it's restricted to aliases, I don't think it
1393 calls. For now it's restricted to aliases, I don't think it
1383 really even makes sense to have this for magics.
1394 really even makes sense to have this for magics.
1384
1395
1385 2004-06-23 Fernando Perez <fperez@colorado.edu>
1396 2004-06-23 Fernando Perez <fperez@colorado.edu>
1386
1397
1387 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1398 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1388 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1399 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1389
1400
1390 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1401 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1391 extensions under Windows (after code sent by Gary Bishop). The
1402 extensions under Windows (after code sent by Gary Bishop). The
1392 extensions considered 'executable' are stored in IPython's rc
1403 extensions considered 'executable' are stored in IPython's rc
1393 structure as win_exec_ext.
1404 structure as win_exec_ext.
1394
1405
1395 * IPython/genutils.py (shell): new function, like system() but
1406 * IPython/genutils.py (shell): new function, like system() but
1396 without return value. Very useful for interactive shell work.
1407 without return value. Very useful for interactive shell work.
1397
1408
1398 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1409 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1399 delete aliases.
1410 delete aliases.
1400
1411
1401 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1412 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1402 sure that the alias table doesn't contain python keywords.
1413 sure that the alias table doesn't contain python keywords.
1403
1414
1404 2004-06-21 Fernando Perez <fperez@colorado.edu>
1415 2004-06-21 Fernando Perez <fperez@colorado.edu>
1405
1416
1406 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1417 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1407 non-existent items are found in $PATH. Reported by Thorsten.
1418 non-existent items are found in $PATH. Reported by Thorsten.
1408
1419
1409 2004-06-20 Fernando Perez <fperez@colorado.edu>
1420 2004-06-20 Fernando Perez <fperez@colorado.edu>
1410
1421
1411 * IPython/iplib.py (complete): modified the completer so that the
1422 * IPython/iplib.py (complete): modified the completer so that the
1412 order of priorities can be easily changed at runtime.
1423 order of priorities can be easily changed at runtime.
1413
1424
1414 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1425 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1415 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1426 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1416
1427
1417 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1428 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1418 expand Python variables prepended with $ in all system calls. The
1429 expand Python variables prepended with $ in all system calls. The
1419 same was done to InteractiveShell.handle_shell_escape. Now all
1430 same was done to InteractiveShell.handle_shell_escape. Now all
1420 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1431 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1421 expansion of python variables and expressions according to the
1432 expansion of python variables and expressions according to the
1422 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1433 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1423
1434
1424 Though PEP-215 has been rejected, a similar (but simpler) one
1435 Though PEP-215 has been rejected, a similar (but simpler) one
1425 seems like it will go into Python 2.4, PEP-292 -
1436 seems like it will go into Python 2.4, PEP-292 -
1426 http://www.python.org/peps/pep-0292.html.
1437 http://www.python.org/peps/pep-0292.html.
1427
1438
1428 I'll keep the full syntax of PEP-215, since IPython has since the
1439 I'll keep the full syntax of PEP-215, since IPython has since the
1429 start used Ka-Ping Yee's reference implementation discussed there
1440 start used Ka-Ping Yee's reference implementation discussed there
1430 (Itpl), and I actually like the powerful semantics it offers.
1441 (Itpl), and I actually like the powerful semantics it offers.
1431
1442
1432 In order to access normal shell variables, the $ has to be escaped
1443 In order to access normal shell variables, the $ has to be escaped
1433 via an extra $. For example:
1444 via an extra $. For example:
1434
1445
1435 In [7]: PATH='a python variable'
1446 In [7]: PATH='a python variable'
1436
1447
1437 In [8]: !echo $PATH
1448 In [8]: !echo $PATH
1438 a python variable
1449 a python variable
1439
1450
1440 In [9]: !echo $$PATH
1451 In [9]: !echo $$PATH
1441 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1452 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1442
1453
1443 (Magic.parse_options): escape $ so the shell doesn't evaluate
1454 (Magic.parse_options): escape $ so the shell doesn't evaluate
1444 things prematurely.
1455 things prematurely.
1445
1456
1446 * IPython/iplib.py (InteractiveShell.call_alias): added the
1457 * IPython/iplib.py (InteractiveShell.call_alias): added the
1447 ability for aliases to expand python variables via $.
1458 ability for aliases to expand python variables via $.
1448
1459
1449 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1460 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1450 system, now there's a @rehash/@rehashx pair of magics. These work
1461 system, now there's a @rehash/@rehashx pair of magics. These work
1451 like the csh rehash command, and can be invoked at any time. They
1462 like the csh rehash command, and can be invoked at any time. They
1452 build a table of aliases to everything in the user's $PATH
1463 build a table of aliases to everything in the user's $PATH
1453 (@rehash uses everything, @rehashx is slower but only adds
1464 (@rehash uses everything, @rehashx is slower but only adds
1454 executable files). With this, the pysh.py-based shell profile can
1465 executable files). With this, the pysh.py-based shell profile can
1455 now simply call rehash upon startup, and full access to all
1466 now simply call rehash upon startup, and full access to all
1456 programs in the user's path is obtained.
1467 programs in the user's path is obtained.
1457
1468
1458 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1469 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1459 functionality is now fully in place. I removed the old dynamic
1470 functionality is now fully in place. I removed the old dynamic
1460 code generation based approach, in favor of a much lighter one
1471 code generation based approach, in favor of a much lighter one
1461 based on a simple dict. The advantage is that this allows me to
1472 based on a simple dict. The advantage is that this allows me to
1462 now have thousands of aliases with negligible cost (unthinkable
1473 now have thousands of aliases with negligible cost (unthinkable
1463 with the old system).
1474 with the old system).
1464
1475
1465 2004-06-19 Fernando Perez <fperez@colorado.edu>
1476 2004-06-19 Fernando Perez <fperez@colorado.edu>
1466
1477
1467 * IPython/iplib.py (__init__): extended MagicCompleter class to
1478 * IPython/iplib.py (__init__): extended MagicCompleter class to
1468 also complete (last in priority) on user aliases.
1479 also complete (last in priority) on user aliases.
1469
1480
1470 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1481 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1471 call to eval.
1482 call to eval.
1472 (ItplNS.__init__): Added a new class which functions like Itpl,
1483 (ItplNS.__init__): Added a new class which functions like Itpl,
1473 but allows configuring the namespace for the evaluation to occur
1484 but allows configuring the namespace for the evaluation to occur
1474 in.
1485 in.
1475
1486
1476 2004-06-18 Fernando Perez <fperez@colorado.edu>
1487 2004-06-18 Fernando Perez <fperez@colorado.edu>
1477
1488
1478 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1489 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1479 better message when 'exit' or 'quit' are typed (a common newbie
1490 better message when 'exit' or 'quit' are typed (a common newbie
1480 confusion).
1491 confusion).
1481
1492
1482 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1493 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1483 check for Windows users.
1494 check for Windows users.
1484
1495
1485 * IPython/iplib.py (InteractiveShell.user_setup): removed
1496 * IPython/iplib.py (InteractiveShell.user_setup): removed
1486 disabling of colors for Windows. I'll test at runtime and issue a
1497 disabling of colors for Windows. I'll test at runtime and issue a
1487 warning if Gary's readline isn't found, as to nudge users to
1498 warning if Gary's readline isn't found, as to nudge users to
1488 download it.
1499 download it.
1489
1500
1490 2004-06-16 Fernando Perez <fperez@colorado.edu>
1501 2004-06-16 Fernando Perez <fperez@colorado.edu>
1491
1502
1492 * IPython/genutils.py (Stream.__init__): changed to print errors
1503 * IPython/genutils.py (Stream.__init__): changed to print errors
1493 to sys.stderr. I had a circular dependency here. Now it's
1504 to sys.stderr. I had a circular dependency here. Now it's
1494 possible to run ipython as IDLE's shell (consider this pre-alpha,
1505 possible to run ipython as IDLE's shell (consider this pre-alpha,
1495 since true stdout things end up in the starting terminal instead
1506 since true stdout things end up in the starting terminal instead
1496 of IDLE's out).
1507 of IDLE's out).
1497
1508
1498 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1509 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1499 users who haven't # updated their prompt_in2 definitions. Remove
1510 users who haven't # updated their prompt_in2 definitions. Remove
1500 eventually.
1511 eventually.
1501 (multiple_replace): added credit to original ASPN recipe.
1512 (multiple_replace): added credit to original ASPN recipe.
1502
1513
1503 2004-06-15 Fernando Perez <fperez@colorado.edu>
1514 2004-06-15 Fernando Perez <fperez@colorado.edu>
1504
1515
1505 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1516 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1506 list of auto-defined aliases.
1517 list of auto-defined aliases.
1507
1518
1508 2004-06-13 Fernando Perez <fperez@colorado.edu>
1519 2004-06-13 Fernando Perez <fperez@colorado.edu>
1509
1520
1510 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1521 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1511 install was really requested (so setup.py can be used for other
1522 install was really requested (so setup.py can be used for other
1512 things under Windows).
1523 things under Windows).
1513
1524
1514 2004-06-10 Fernando Perez <fperez@colorado.edu>
1525 2004-06-10 Fernando Perez <fperez@colorado.edu>
1515
1526
1516 * IPython/Logger.py (Logger.create_log): Manually remove any old
1527 * IPython/Logger.py (Logger.create_log): Manually remove any old
1517 backup, since os.remove may fail under Windows. Fixes bug
1528 backup, since os.remove may fail under Windows. Fixes bug
1518 reported by Thorsten.
1529 reported by Thorsten.
1519
1530
1520 2004-06-09 Fernando Perez <fperez@colorado.edu>
1531 2004-06-09 Fernando Perez <fperez@colorado.edu>
1521
1532
1522 * examples/example-embed.py: fixed all references to %n (replaced
1533 * examples/example-embed.py: fixed all references to %n (replaced
1523 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1534 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1524 for all examples and the manual as well.
1535 for all examples and the manual as well.
1525
1536
1526 2004-06-08 Fernando Perez <fperez@colorado.edu>
1537 2004-06-08 Fernando Perez <fperez@colorado.edu>
1527
1538
1528 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1539 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1529 alignment and color management. All 3 prompt subsystems now
1540 alignment and color management. All 3 prompt subsystems now
1530 inherit from BasePrompt.
1541 inherit from BasePrompt.
1531
1542
1532 * tools/release: updates for windows installer build and tag rpms
1543 * tools/release: updates for windows installer build and tag rpms
1533 with python version (since paths are fixed).
1544 with python version (since paths are fixed).
1534
1545
1535 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1546 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1536 which will become eventually obsolete. Also fixed the default
1547 which will become eventually obsolete. Also fixed the default
1537 prompt_in2 to use \D, so at least new users start with the correct
1548 prompt_in2 to use \D, so at least new users start with the correct
1538 defaults.
1549 defaults.
1539 WARNING: Users with existing ipythonrc files will need to apply
1550 WARNING: Users with existing ipythonrc files will need to apply
1540 this fix manually!
1551 this fix manually!
1541
1552
1542 * setup.py: make windows installer (.exe). This is finally the
1553 * setup.py: make windows installer (.exe). This is finally the
1543 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1554 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1544 which I hadn't included because it required Python 2.3 (or recent
1555 which I hadn't included because it required Python 2.3 (or recent
1545 distutils).
1556 distutils).
1546
1557
1547 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1558 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1548 usage of new '\D' escape.
1559 usage of new '\D' escape.
1549
1560
1550 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1561 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1551 lacks os.getuid())
1562 lacks os.getuid())
1552 (CachedOutput.set_colors): Added the ability to turn coloring
1563 (CachedOutput.set_colors): Added the ability to turn coloring
1553 on/off with @colors even for manually defined prompt colors. It
1564 on/off with @colors even for manually defined prompt colors. It
1554 uses a nasty global, but it works safely and via the generic color
1565 uses a nasty global, but it works safely and via the generic color
1555 handling mechanism.
1566 handling mechanism.
1556 (Prompt2.__init__): Introduced new escape '\D' for continuation
1567 (Prompt2.__init__): Introduced new escape '\D' for continuation
1557 prompts. It represents the counter ('\#') as dots.
1568 prompts. It represents the counter ('\#') as dots.
1558 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1569 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1559 need to update their ipythonrc files and replace '%n' with '\D' in
1570 need to update their ipythonrc files and replace '%n' with '\D' in
1560 their prompt_in2 settings everywhere. Sorry, but there's
1571 their prompt_in2 settings everywhere. Sorry, but there's
1561 otherwise no clean way to get all prompts to properly align. The
1572 otherwise no clean way to get all prompts to properly align. The
1562 ipythonrc shipped with IPython has been updated.
1573 ipythonrc shipped with IPython has been updated.
1563
1574
1564 2004-06-07 Fernando Perez <fperez@colorado.edu>
1575 2004-06-07 Fernando Perez <fperez@colorado.edu>
1565
1576
1566 * setup.py (isfile): Pass local_icons option to latex2html, so the
1577 * setup.py (isfile): Pass local_icons option to latex2html, so the
1567 resulting HTML file is self-contained. Thanks to
1578 resulting HTML file is self-contained. Thanks to
1568 dryice-AT-liu.com.cn for the tip.
1579 dryice-AT-liu.com.cn for the tip.
1569
1580
1570 * pysh.py: I created a new profile 'shell', which implements a
1581 * pysh.py: I created a new profile 'shell', which implements a
1571 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1582 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1572 system shell, nor will it become one anytime soon. It's mainly
1583 system shell, nor will it become one anytime soon. It's mainly
1573 meant to illustrate the use of the new flexible bash-like prompts.
1584 meant to illustrate the use of the new flexible bash-like prompts.
1574 I guess it could be used by hardy souls for true shell management,
1585 I guess it could be used by hardy souls for true shell management,
1575 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1586 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1576 profile. This uses the InterpreterExec extension provided by
1587 profile. This uses the InterpreterExec extension provided by
1577 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1588 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1578
1589
1579 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1590 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1580 auto-align itself with the length of the previous input prompt
1591 auto-align itself with the length of the previous input prompt
1581 (taking into account the invisible color escapes).
1592 (taking into account the invisible color escapes).
1582 (CachedOutput.__init__): Large restructuring of this class. Now
1593 (CachedOutput.__init__): Large restructuring of this class. Now
1583 all three prompts (primary1, primary2, output) are proper objects,
1594 all three prompts (primary1, primary2, output) are proper objects,
1584 managed by the 'parent' CachedOutput class. The code is still a
1595 managed by the 'parent' CachedOutput class. The code is still a
1585 bit hackish (all prompts share state via a pointer to the cache),
1596 bit hackish (all prompts share state via a pointer to the cache),
1586 but it's overall far cleaner than before.
1597 but it's overall far cleaner than before.
1587
1598
1588 * IPython/genutils.py (getoutputerror): modified to add verbose,
1599 * IPython/genutils.py (getoutputerror): modified to add verbose,
1589 debug and header options. This makes the interface of all getout*
1600 debug and header options. This makes the interface of all getout*
1590 functions uniform.
1601 functions uniform.
1591 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1602 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1592
1603
1593 * IPython/Magic.py (Magic.default_option): added a function to
1604 * IPython/Magic.py (Magic.default_option): added a function to
1594 allow registering default options for any magic command. This
1605 allow registering default options for any magic command. This
1595 makes it easy to have profiles which customize the magics globally
1606 makes it easy to have profiles which customize the magics globally
1596 for a certain use. The values set through this function are
1607 for a certain use. The values set through this function are
1597 picked up by the parse_options() method, which all magics should
1608 picked up by the parse_options() method, which all magics should
1598 use to parse their options.
1609 use to parse their options.
1599
1610
1600 * IPython/genutils.py (warn): modified the warnings framework to
1611 * IPython/genutils.py (warn): modified the warnings framework to
1601 use the Term I/O class. I'm trying to slowly unify all of
1612 use the Term I/O class. I'm trying to slowly unify all of
1602 IPython's I/O operations to pass through Term.
1613 IPython's I/O operations to pass through Term.
1603
1614
1604 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1615 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1605 the secondary prompt to correctly match the length of the primary
1616 the secondary prompt to correctly match the length of the primary
1606 one for any prompt. Now multi-line code will properly line up
1617 one for any prompt. Now multi-line code will properly line up
1607 even for path dependent prompts, such as the new ones available
1618 even for path dependent prompts, such as the new ones available
1608 via the prompt_specials.
1619 via the prompt_specials.
1609
1620
1610 2004-06-06 Fernando Perez <fperez@colorado.edu>
1621 2004-06-06 Fernando Perez <fperez@colorado.edu>
1611
1622
1612 * IPython/Prompts.py (prompt_specials): Added the ability to have
1623 * IPython/Prompts.py (prompt_specials): Added the ability to have
1613 bash-like special sequences in the prompts, which get
1624 bash-like special sequences in the prompts, which get
1614 automatically expanded. Things like hostname, current working
1625 automatically expanded. Things like hostname, current working
1615 directory and username are implemented already, but it's easy to
1626 directory and username are implemented already, but it's easy to
1616 add more in the future. Thanks to a patch by W.J. van der Laan
1627 add more in the future. Thanks to a patch by W.J. van der Laan
1617 <gnufnork-AT-hetdigitalegat.nl>
1628 <gnufnork-AT-hetdigitalegat.nl>
1618 (prompt_specials): Added color support for prompt strings, so
1629 (prompt_specials): Added color support for prompt strings, so
1619 users can define arbitrary color setups for their prompts.
1630 users can define arbitrary color setups for their prompts.
1620
1631
1621 2004-06-05 Fernando Perez <fperez@colorado.edu>
1632 2004-06-05 Fernando Perez <fperez@colorado.edu>
1622
1633
1623 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
1634 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
1624 code to load Gary Bishop's readline and configure it
1635 code to load Gary Bishop's readline and configure it
1625 automatically. Thanks to Gary for help on this.
1636 automatically. Thanks to Gary for help on this.
1626
1637
1627 2004-06-01 Fernando Perez <fperez@colorado.edu>
1638 2004-06-01 Fernando Perez <fperez@colorado.edu>
1628
1639
1629 * IPython/Logger.py (Logger.create_log): fix bug for logging
1640 * IPython/Logger.py (Logger.create_log): fix bug for logging
1630 with no filename (previous fix was incomplete).
1641 with no filename (previous fix was incomplete).
1631
1642
1632 2004-05-25 Fernando Perez <fperez@colorado.edu>
1643 2004-05-25 Fernando Perez <fperez@colorado.edu>
1633
1644
1634 * IPython/Magic.py (Magic.parse_options): fix bug where naked
1645 * IPython/Magic.py (Magic.parse_options): fix bug where naked
1635 parens would get passed to the shell.
1646 parens would get passed to the shell.
1636
1647
1637 2004-05-20 Fernando Perez <fperez@colorado.edu>
1648 2004-05-20 Fernando Perez <fperez@colorado.edu>
1638
1649
1639 * IPython/Magic.py (Magic.magic_prun): changed default profile
1650 * IPython/Magic.py (Magic.magic_prun): changed default profile
1640 sort order to 'time' (the more common profiling need).
1651 sort order to 'time' (the more common profiling need).
1641
1652
1642 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
1653 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
1643 so that source code shown is guaranteed in sync with the file on
1654 so that source code shown is guaranteed in sync with the file on
1644 disk (also changed in psource). Similar fix to the one for
1655 disk (also changed in psource). Similar fix to the one for
1645 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
1656 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
1646 <yann.ledu-AT-noos.fr>.
1657 <yann.ledu-AT-noos.fr>.
1647
1658
1648 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
1659 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
1649 with a single option would not be correctly parsed. Closes
1660 with a single option would not be correctly parsed. Closes
1650 http://www.scipy.net/roundup/ipython/issue14. This bug had been
1661 http://www.scipy.net/roundup/ipython/issue14. This bug had been
1651 introduced in 0.6.0 (on 2004-05-06).
1662 introduced in 0.6.0 (on 2004-05-06).
1652
1663
1653 2004-05-13 *** Released version 0.6.0
1664 2004-05-13 *** Released version 0.6.0
1654
1665
1655 2004-05-13 Fernando Perez <fperez@colorado.edu>
1666 2004-05-13 Fernando Perez <fperez@colorado.edu>
1656
1667
1657 * debian/: Added debian/ directory to CVS, so that debian support
1668 * debian/: Added debian/ directory to CVS, so that debian support
1658 is publicly accessible. The debian package is maintained by Jack
1669 is publicly accessible. The debian package is maintained by Jack
1659 Moffit <jack-AT-xiph.org>.
1670 Moffit <jack-AT-xiph.org>.
1660
1671
1661 * Documentation: included the notes about an ipython-based system
1672 * Documentation: included the notes about an ipython-based system
1662 shell (the hypothetical 'pysh') into the new_design.pdf document,
1673 shell (the hypothetical 'pysh') into the new_design.pdf document,
1663 so that these ideas get distributed to users along with the
1674 so that these ideas get distributed to users along with the
1664 official documentation.
1675 official documentation.
1665
1676
1666 2004-05-10 Fernando Perez <fperez@colorado.edu>
1677 2004-05-10 Fernando Perez <fperez@colorado.edu>
1667
1678
1668 * IPython/Logger.py (Logger.create_log): fix recently introduced
1679 * IPython/Logger.py (Logger.create_log): fix recently introduced
1669 bug (misindented line) where logstart would fail when not given an
1680 bug (misindented line) where logstart would fail when not given an
1670 explicit filename.
1681 explicit filename.
1671
1682
1672 2004-05-09 Fernando Perez <fperez@colorado.edu>
1683 2004-05-09 Fernando Perez <fperez@colorado.edu>
1673
1684
1674 * IPython/Magic.py (Magic.parse_options): skip system call when
1685 * IPython/Magic.py (Magic.parse_options): skip system call when
1675 there are no options to look for. Faster, cleaner for the common
1686 there are no options to look for. Faster, cleaner for the common
1676 case.
1687 case.
1677
1688
1678 * Documentation: many updates to the manual: describing Windows
1689 * Documentation: many updates to the manual: describing Windows
1679 support better, Gnuplot updates, credits, misc small stuff. Also
1690 support better, Gnuplot updates, credits, misc small stuff. Also
1680 updated the new_design doc a bit.
1691 updated the new_design doc a bit.
1681
1692
1682 2004-05-06 *** Released version 0.6.0.rc1
1693 2004-05-06 *** Released version 0.6.0.rc1
1683
1694
1684 2004-05-06 Fernando Perez <fperez@colorado.edu>
1695 2004-05-06 Fernando Perez <fperez@colorado.edu>
1685
1696
1686 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
1697 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
1687 operations to use the vastly more efficient list/''.join() method.
1698 operations to use the vastly more efficient list/''.join() method.
1688 (FormattedTB.text): Fix
1699 (FormattedTB.text): Fix
1689 http://www.scipy.net/roundup/ipython/issue12 - exception source
1700 http://www.scipy.net/roundup/ipython/issue12 - exception source
1690 extract not updated after reload. Thanks to Mike Salib
1701 extract not updated after reload. Thanks to Mike Salib
1691 <msalib-AT-mit.edu> for pinning the source of the problem.
1702 <msalib-AT-mit.edu> for pinning the source of the problem.
1692 Fortunately, the solution works inside ipython and doesn't require
1703 Fortunately, the solution works inside ipython and doesn't require
1693 any changes to python proper.
1704 any changes to python proper.
1694
1705
1695 * IPython/Magic.py (Magic.parse_options): Improved to process the
1706 * IPython/Magic.py (Magic.parse_options): Improved to process the
1696 argument list as a true shell would (by actually using the
1707 argument list as a true shell would (by actually using the
1697 underlying system shell). This way, all @magics automatically get
1708 underlying system shell). This way, all @magics automatically get
1698 shell expansion for variables. Thanks to a comment by Alex
1709 shell expansion for variables. Thanks to a comment by Alex
1699 Schmolck.
1710 Schmolck.
1700
1711
1701 2004-04-04 Fernando Perez <fperez@colorado.edu>
1712 2004-04-04 Fernando Perez <fperez@colorado.edu>
1702
1713
1703 * IPython/iplib.py (InteractiveShell.interact): Added a special
1714 * IPython/iplib.py (InteractiveShell.interact): Added a special
1704 trap for a debugger quit exception, which is basically impossible
1715 trap for a debugger quit exception, which is basically impossible
1705 to handle by normal mechanisms, given what pdb does to the stack.
1716 to handle by normal mechanisms, given what pdb does to the stack.
1706 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
1717 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
1707
1718
1708 2004-04-03 Fernando Perez <fperez@colorado.edu>
1719 2004-04-03 Fernando Perez <fperez@colorado.edu>
1709
1720
1710 * IPython/genutils.py (Term): Standardized the names of the Term
1721 * IPython/genutils.py (Term): Standardized the names of the Term
1711 class streams to cin/cout/cerr, following C++ naming conventions
1722 class streams to cin/cout/cerr, following C++ naming conventions
1712 (I can't use in/out/err because 'in' is not a valid attribute
1723 (I can't use in/out/err because 'in' is not a valid attribute
1713 name).
1724 name).
1714
1725
1715 * IPython/iplib.py (InteractiveShell.interact): don't increment
1726 * IPython/iplib.py (InteractiveShell.interact): don't increment
1716 the prompt if there's no user input. By Daniel 'Dang' Griffith
1727 the prompt if there's no user input. By Daniel 'Dang' Griffith
1717 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
1728 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
1718 Francois Pinard.
1729 Francois Pinard.
1719
1730
1720 2004-04-02 Fernando Perez <fperez@colorado.edu>
1731 2004-04-02 Fernando Perez <fperez@colorado.edu>
1721
1732
1722 * IPython/genutils.py (Stream.__init__): Modified to survive at
1733 * IPython/genutils.py (Stream.__init__): Modified to survive at
1723 least importing in contexts where stdin/out/err aren't true file
1734 least importing in contexts where stdin/out/err aren't true file
1724 objects, such as PyCrust (they lack fileno() and mode). However,
1735 objects, such as PyCrust (they lack fileno() and mode). However,
1725 the recovery facilities which rely on these things existing will
1736 the recovery facilities which rely on these things existing will
1726 not work.
1737 not work.
1727
1738
1728 2004-04-01 Fernando Perez <fperez@colorado.edu>
1739 2004-04-01 Fernando Perez <fperez@colorado.edu>
1729
1740
1730 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
1741 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
1731 use the new getoutputerror() function, so it properly
1742 use the new getoutputerror() function, so it properly
1732 distinguishes stdout/err.
1743 distinguishes stdout/err.
1733
1744
1734 * IPython/genutils.py (getoutputerror): added a function to
1745 * IPython/genutils.py (getoutputerror): added a function to
1735 capture separately the standard output and error of a command.
1746 capture separately the standard output and error of a command.
1736 After a comment from dang on the mailing lists. This code is
1747 After a comment from dang on the mailing lists. This code is
1737 basically a modified version of commands.getstatusoutput(), from
1748 basically a modified version of commands.getstatusoutput(), from
1738 the standard library.
1749 the standard library.
1739
1750
1740 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
1751 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
1741 '!!' as a special syntax (shorthand) to access @sx.
1752 '!!' as a special syntax (shorthand) to access @sx.
1742
1753
1743 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
1754 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
1744 command and return its output as a list split on '\n'.
1755 command and return its output as a list split on '\n'.
1745
1756
1746 2004-03-31 Fernando Perez <fperez@colorado.edu>
1757 2004-03-31 Fernando Perez <fperez@colorado.edu>
1747
1758
1748 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
1759 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
1749 method to dictionaries used as FakeModule instances if they lack
1760 method to dictionaries used as FakeModule instances if they lack
1750 it. At least pydoc in python2.3 breaks for runtime-defined
1761 it. At least pydoc in python2.3 breaks for runtime-defined
1751 functions without this hack. At some point I need to _really_
1762 functions without this hack. At some point I need to _really_
1752 understand what FakeModule is doing, because it's a gross hack.
1763 understand what FakeModule is doing, because it's a gross hack.
1753 But it solves Arnd's problem for now...
1764 But it solves Arnd's problem for now...
1754
1765
1755 2004-02-27 Fernando Perez <fperez@colorado.edu>
1766 2004-02-27 Fernando Perez <fperez@colorado.edu>
1756
1767
1757 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
1768 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
1758 mode would behave erratically. Also increased the number of
1769 mode would behave erratically. Also increased the number of
1759 possible logs in rotate mod to 999. Thanks to Rod Holland
1770 possible logs in rotate mod to 999. Thanks to Rod Holland
1760 <rhh@StructureLABS.com> for the report and fixes.
1771 <rhh@StructureLABS.com> for the report and fixes.
1761
1772
1762 2004-02-26 Fernando Perez <fperez@colorado.edu>
1773 2004-02-26 Fernando Perez <fperez@colorado.edu>
1763
1774
1764 * IPython/genutils.py (page): Check that the curses module really
1775 * IPython/genutils.py (page): Check that the curses module really
1765 has the initscr attribute before trying to use it. For some
1776 has the initscr attribute before trying to use it. For some
1766 reason, the Solaris curses module is missing this. I think this
1777 reason, the Solaris curses module is missing this. I think this
1767 should be considered a Solaris python bug, but I'm not sure.
1778 should be considered a Solaris python bug, but I'm not sure.
1768
1779
1769 2004-01-17 Fernando Perez <fperez@colorado.edu>
1780 2004-01-17 Fernando Perez <fperez@colorado.edu>
1770
1781
1771 * IPython/genutils.py (Stream.__init__): Changes to try to make
1782 * IPython/genutils.py (Stream.__init__): Changes to try to make
1772 ipython robust against stdin/out/err being closed by the user.
1783 ipython robust against stdin/out/err being closed by the user.
1773 This is 'user error' (and blocks a normal python session, at least
1784 This is 'user error' (and blocks a normal python session, at least
1774 the stdout case). However, Ipython should be able to survive such
1785 the stdout case). However, Ipython should be able to survive such
1775 instances of abuse as gracefully as possible. To simplify the
1786 instances of abuse as gracefully as possible. To simplify the
1776 coding and maintain compatibility with Gary Bishop's Term
1787 coding and maintain compatibility with Gary Bishop's Term
1777 contributions, I've made use of classmethods for this. I think
1788 contributions, I've made use of classmethods for this. I think
1778 this introduces a dependency on python 2.2.
1789 this introduces a dependency on python 2.2.
1779
1790
1780 2004-01-13 Fernando Perez <fperez@colorado.edu>
1791 2004-01-13 Fernando Perez <fperez@colorado.edu>
1781
1792
1782 * IPython/numutils.py (exp_safe): simplified the code a bit and
1793 * IPython/numutils.py (exp_safe): simplified the code a bit and
1783 removed the need for importing the kinds module altogether.
1794 removed the need for importing the kinds module altogether.
1784
1795
1785 2004-01-06 Fernando Perez <fperez@colorado.edu>
1796 2004-01-06 Fernando Perez <fperez@colorado.edu>
1786
1797
1787 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
1798 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
1788 a magic function instead, after some community feedback. No
1799 a magic function instead, after some community feedback. No
1789 special syntax will exist for it, but its name is deliberately
1800 special syntax will exist for it, but its name is deliberately
1790 very short.
1801 very short.
1791
1802
1792 2003-12-20 Fernando Perez <fperez@colorado.edu>
1803 2003-12-20 Fernando Perez <fperez@colorado.edu>
1793
1804
1794 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
1805 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
1795 new functionality, to automagically assign the result of a shell
1806 new functionality, to automagically assign the result of a shell
1796 command to a variable. I'll solicit some community feedback on
1807 command to a variable. I'll solicit some community feedback on
1797 this before making it permanent.
1808 this before making it permanent.
1798
1809
1799 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
1810 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
1800 requested about callables for which inspect couldn't obtain a
1811 requested about callables for which inspect couldn't obtain a
1801 proper argspec. Thanks to a crash report sent by Etienne
1812 proper argspec. Thanks to a crash report sent by Etienne
1802 Posthumus <etienne-AT-apple01.cs.vu.nl>.
1813 Posthumus <etienne-AT-apple01.cs.vu.nl>.
1803
1814
1804 2003-12-09 Fernando Perez <fperez@colorado.edu>
1815 2003-12-09 Fernando Perez <fperez@colorado.edu>
1805
1816
1806 * IPython/genutils.py (page): patch for the pager to work across
1817 * IPython/genutils.py (page): patch for the pager to work across
1807 various versions of Windows. By Gary Bishop.
1818 various versions of Windows. By Gary Bishop.
1808
1819
1809 2003-12-04 Fernando Perez <fperez@colorado.edu>
1820 2003-12-04 Fernando Perez <fperez@colorado.edu>
1810
1821
1811 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
1822 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
1812 Gnuplot.py version 1.7, whose internal names changed quite a bit.
1823 Gnuplot.py version 1.7, whose internal names changed quite a bit.
1813 While I tested this and it looks ok, there may still be corner
1824 While I tested this and it looks ok, there may still be corner
1814 cases I've missed.
1825 cases I've missed.
1815
1826
1816 2003-12-01 Fernando Perez <fperez@colorado.edu>
1827 2003-12-01 Fernando Perez <fperez@colorado.edu>
1817
1828
1818 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
1829 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
1819 where a line like 'p,q=1,2' would fail because the automagic
1830 where a line like 'p,q=1,2' would fail because the automagic
1820 system would be triggered for @p.
1831 system would be triggered for @p.
1821
1832
1822 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
1833 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
1823 cleanups, code unmodified.
1834 cleanups, code unmodified.
1824
1835
1825 * IPython/genutils.py (Term): added a class for IPython to handle
1836 * IPython/genutils.py (Term): added a class for IPython to handle
1826 output. In most cases it will just be a proxy for stdout/err, but
1837 output. In most cases it will just be a proxy for stdout/err, but
1827 having this allows modifications to be made for some platforms,
1838 having this allows modifications to be made for some platforms,
1828 such as handling color escapes under Windows. All of this code
1839 such as handling color escapes under Windows. All of this code
1829 was contributed by Gary Bishop, with minor modifications by me.
1840 was contributed by Gary Bishop, with minor modifications by me.
1830 The actual changes affect many files.
1841 The actual changes affect many files.
1831
1842
1832 2003-11-30 Fernando Perez <fperez@colorado.edu>
1843 2003-11-30 Fernando Perez <fperez@colorado.edu>
1833
1844
1834 * IPython/iplib.py (file_matches): new completion code, courtesy
1845 * IPython/iplib.py (file_matches): new completion code, courtesy
1835 of Jeff Collins. This enables filename completion again under
1846 of Jeff Collins. This enables filename completion again under
1836 python 2.3, which disabled it at the C level.
1847 python 2.3, which disabled it at the C level.
1837
1848
1838 2003-11-11 Fernando Perez <fperez@colorado.edu>
1849 2003-11-11 Fernando Perez <fperez@colorado.edu>
1839
1850
1840 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
1851 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
1841 for Numeric.array(map(...)), but often convenient.
1852 for Numeric.array(map(...)), but often convenient.
1842
1853
1843 2003-11-05 Fernando Perez <fperez@colorado.edu>
1854 2003-11-05 Fernando Perez <fperez@colorado.edu>
1844
1855
1845 * IPython/numutils.py (frange): Changed a call from int() to
1856 * IPython/numutils.py (frange): Changed a call from int() to
1846 int(round()) to prevent a problem reported with arange() in the
1857 int(round()) to prevent a problem reported with arange() in the
1847 numpy list.
1858 numpy list.
1848
1859
1849 2003-10-06 Fernando Perez <fperez@colorado.edu>
1860 2003-10-06 Fernando Perez <fperez@colorado.edu>
1850
1861
1851 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
1862 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
1852 prevent crashes if sys lacks an argv attribute (it happens with
1863 prevent crashes if sys lacks an argv attribute (it happens with
1853 embedded interpreters which build a bare-bones sys module).
1864 embedded interpreters which build a bare-bones sys module).
1854 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
1865 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
1855
1866
1856 2003-09-24 Fernando Perez <fperez@colorado.edu>
1867 2003-09-24 Fernando Perez <fperez@colorado.edu>
1857
1868
1858 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
1869 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
1859 to protect against poorly written user objects where __getattr__
1870 to protect against poorly written user objects where __getattr__
1860 raises exceptions other than AttributeError. Thanks to a bug
1871 raises exceptions other than AttributeError. Thanks to a bug
1861 report by Oliver Sander <osander-AT-gmx.de>.
1872 report by Oliver Sander <osander-AT-gmx.de>.
1862
1873
1863 * IPython/FakeModule.py (FakeModule.__repr__): this method was
1874 * IPython/FakeModule.py (FakeModule.__repr__): this method was
1864 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
1875 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
1865
1876
1866 2003-09-09 Fernando Perez <fperez@colorado.edu>
1877 2003-09-09 Fernando Perez <fperez@colorado.edu>
1867
1878
1868 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1879 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1869 unpacking a list whith a callable as first element would
1880 unpacking a list whith a callable as first element would
1870 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
1881 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
1871 Collins.
1882 Collins.
1872
1883
1873 2003-08-25 *** Released version 0.5.0
1884 2003-08-25 *** Released version 0.5.0
1874
1885
1875 2003-08-22 Fernando Perez <fperez@colorado.edu>
1886 2003-08-22 Fernando Perez <fperez@colorado.edu>
1876
1887
1877 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
1888 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
1878 improperly defined user exceptions. Thanks to feedback from Mark
1889 improperly defined user exceptions. Thanks to feedback from Mark
1879 Russell <mrussell-AT-verio.net>.
1890 Russell <mrussell-AT-verio.net>.
1880
1891
1881 2003-08-20 Fernando Perez <fperez@colorado.edu>
1892 2003-08-20 Fernando Perez <fperez@colorado.edu>
1882
1893
1883 * IPython/OInspect.py (Inspector.pinfo): changed String Form
1894 * IPython/OInspect.py (Inspector.pinfo): changed String Form
1884 printing so that it would print multi-line string forms starting
1895 printing so that it would print multi-line string forms starting
1885 with a new line. This way the formatting is better respected for
1896 with a new line. This way the formatting is better respected for
1886 objects which work hard to make nice string forms.
1897 objects which work hard to make nice string forms.
1887
1898
1888 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
1899 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
1889 autocall would overtake data access for objects with both
1900 autocall would overtake data access for objects with both
1890 __getitem__ and __call__.
1901 __getitem__ and __call__.
1891
1902
1892 2003-08-19 *** Released version 0.5.0-rc1
1903 2003-08-19 *** Released version 0.5.0-rc1
1893
1904
1894 2003-08-19 Fernando Perez <fperez@colorado.edu>
1905 2003-08-19 Fernando Perez <fperez@colorado.edu>
1895
1906
1896 * IPython/deep_reload.py (load_tail): single tiny change here
1907 * IPython/deep_reload.py (load_tail): single tiny change here
1897 seems to fix the long-standing bug of dreload() failing to work
1908 seems to fix the long-standing bug of dreload() failing to work
1898 for dotted names. But this module is pretty tricky, so I may have
1909 for dotted names. But this module is pretty tricky, so I may have
1899 missed some subtlety. Needs more testing!.
1910 missed some subtlety. Needs more testing!.
1900
1911
1901 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
1912 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
1902 exceptions which have badly implemented __str__ methods.
1913 exceptions which have badly implemented __str__ methods.
1903 (VerboseTB.text): harden against inspect.getinnerframes crashing,
1914 (VerboseTB.text): harden against inspect.getinnerframes crashing,
1904 which I've been getting reports about from Python 2.3 users. I
1915 which I've been getting reports about from Python 2.3 users. I
1905 wish I had a simple test case to reproduce the problem, so I could
1916 wish I had a simple test case to reproduce the problem, so I could
1906 either write a cleaner workaround or file a bug report if
1917 either write a cleaner workaround or file a bug report if
1907 necessary.
1918 necessary.
1908
1919
1909 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
1920 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
1910 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
1921 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
1911 a bug report by Tjabo Kloppenburg.
1922 a bug report by Tjabo Kloppenburg.
1912
1923
1913 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
1924 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
1914 crashes. Wrapped the pdb call in a blanket try/except, since pdb
1925 crashes. Wrapped the pdb call in a blanket try/except, since pdb
1915 seems rather unstable. Thanks to a bug report by Tjabo
1926 seems rather unstable. Thanks to a bug report by Tjabo
1916 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
1927 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
1917
1928
1918 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
1929 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
1919 this out soon because of the critical fixes in the inner loop for
1930 this out soon because of the critical fixes in the inner loop for
1920 generators.
1931 generators.
1921
1932
1922 * IPython/Magic.py (Magic.getargspec): removed. This (and
1933 * IPython/Magic.py (Magic.getargspec): removed. This (and
1923 _get_def) have been obsoleted by OInspect for a long time, I
1934 _get_def) have been obsoleted by OInspect for a long time, I
1924 hadn't noticed that they were dead code.
1935 hadn't noticed that they were dead code.
1925 (Magic._ofind): restored _ofind functionality for a few literals
1936 (Magic._ofind): restored _ofind functionality for a few literals
1926 (those in ["''",'""','[]','{}','()']). But it won't work anymore
1937 (those in ["''",'""','[]','{}','()']). But it won't work anymore
1927 for things like "hello".capitalize?, since that would require a
1938 for things like "hello".capitalize?, since that would require a
1928 potentially dangerous eval() again.
1939 potentially dangerous eval() again.
1929
1940
1930 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
1941 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
1931 logic a bit more to clean up the escapes handling and minimize the
1942 logic a bit more to clean up the escapes handling and minimize the
1932 use of _ofind to only necessary cases. The interactive 'feel' of
1943 use of _ofind to only necessary cases. The interactive 'feel' of
1933 IPython should have improved quite a bit with the changes in
1944 IPython should have improved quite a bit with the changes in
1934 _prefilter and _ofind (besides being far safer than before).
1945 _prefilter and _ofind (besides being far safer than before).
1935
1946
1936 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
1947 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
1937 obscure, never reported). Edit would fail to find the object to
1948 obscure, never reported). Edit would fail to find the object to
1938 edit under some circumstances.
1949 edit under some circumstances.
1939 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
1950 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
1940 which were causing double-calling of generators. Those eval calls
1951 which were causing double-calling of generators. Those eval calls
1941 were _very_ dangerous, since code with side effects could be
1952 were _very_ dangerous, since code with side effects could be
1942 triggered. As they say, 'eval is evil'... These were the
1953 triggered. As they say, 'eval is evil'... These were the
1943 nastiest evals in IPython. Besides, _ofind is now far simpler,
1954 nastiest evals in IPython. Besides, _ofind is now far simpler,
1944 and it should also be quite a bit faster. Its use of inspect is
1955 and it should also be quite a bit faster. Its use of inspect is
1945 also safer, so perhaps some of the inspect-related crashes I've
1956 also safer, so perhaps some of the inspect-related crashes I've
1946 seen lately with Python 2.3 might be taken care of. That will
1957 seen lately with Python 2.3 might be taken care of. That will
1947 need more testing.
1958 need more testing.
1948
1959
1949 2003-08-17 Fernando Perez <fperez@colorado.edu>
1960 2003-08-17 Fernando Perez <fperez@colorado.edu>
1950
1961
1951 * IPython/iplib.py (InteractiveShell._prefilter): significant
1962 * IPython/iplib.py (InteractiveShell._prefilter): significant
1952 simplifications to the logic for handling user escapes. Faster
1963 simplifications to the logic for handling user escapes. Faster
1953 and simpler code.
1964 and simpler code.
1954
1965
1955 2003-08-14 Fernando Perez <fperez@colorado.edu>
1966 2003-08-14 Fernando Perez <fperez@colorado.edu>
1956
1967
1957 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
1968 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
1958 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
1969 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
1959 but it should be quite a bit faster. And the recursive version
1970 but it should be quite a bit faster. And the recursive version
1960 generated O(log N) intermediate storage for all rank>1 arrays,
1971 generated O(log N) intermediate storage for all rank>1 arrays,
1961 even if they were contiguous.
1972 even if they were contiguous.
1962 (l1norm): Added this function.
1973 (l1norm): Added this function.
1963 (norm): Added this function for arbitrary norms (including
1974 (norm): Added this function for arbitrary norms (including
1964 l-infinity). l1 and l2 are still special cases for convenience
1975 l-infinity). l1 and l2 are still special cases for convenience
1965 and speed.
1976 and speed.
1966
1977
1967 2003-08-03 Fernando Perez <fperez@colorado.edu>
1978 2003-08-03 Fernando Perez <fperez@colorado.edu>
1968
1979
1969 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
1980 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
1970 exceptions, which now raise PendingDeprecationWarnings in Python
1981 exceptions, which now raise PendingDeprecationWarnings in Python
1971 2.3. There were some in Magic and some in Gnuplot2.
1982 2.3. There were some in Magic and some in Gnuplot2.
1972
1983
1973 2003-06-30 Fernando Perez <fperez@colorado.edu>
1984 2003-06-30 Fernando Perez <fperez@colorado.edu>
1974
1985
1975 * IPython/genutils.py (page): modified to call curses only for
1986 * IPython/genutils.py (page): modified to call curses only for
1976 terminals where TERM=='xterm'. After problems under many other
1987 terminals where TERM=='xterm'. After problems under many other
1977 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
1988 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
1978
1989
1979 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
1990 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
1980 would be triggered when readline was absent. This was just an old
1991 would be triggered when readline was absent. This was just an old
1981 debugging statement I'd forgotten to take out.
1992 debugging statement I'd forgotten to take out.
1982
1993
1983 2003-06-20 Fernando Perez <fperez@colorado.edu>
1994 2003-06-20 Fernando Perez <fperez@colorado.edu>
1984
1995
1985 * IPython/genutils.py (clock): modified to return only user time
1996 * IPython/genutils.py (clock): modified to return only user time
1986 (not counting system time), after a discussion on scipy. While
1997 (not counting system time), after a discussion on scipy. While
1987 system time may be a useful quantity occasionally, it may much
1998 system time may be a useful quantity occasionally, it may much
1988 more easily be skewed by occasional swapping or other similar
1999 more easily be skewed by occasional swapping or other similar
1989 activity.
2000 activity.
1990
2001
1991 2003-06-05 Fernando Perez <fperez@colorado.edu>
2002 2003-06-05 Fernando Perez <fperez@colorado.edu>
1992
2003
1993 * IPython/numutils.py (identity): new function, for building
2004 * IPython/numutils.py (identity): new function, for building
1994 arbitrary rank Kronecker deltas (mostly backwards compatible with
2005 arbitrary rank Kronecker deltas (mostly backwards compatible with
1995 Numeric.identity)
2006 Numeric.identity)
1996
2007
1997 2003-06-03 Fernando Perez <fperez@colorado.edu>
2008 2003-06-03 Fernando Perez <fperez@colorado.edu>
1998
2009
1999 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2010 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2000 arguments passed to magics with spaces, to allow trailing '\' to
2011 arguments passed to magics with spaces, to allow trailing '\' to
2001 work normally (mainly for Windows users).
2012 work normally (mainly for Windows users).
2002
2013
2003 2003-05-29 Fernando Perez <fperez@colorado.edu>
2014 2003-05-29 Fernando Perez <fperez@colorado.edu>
2004
2015
2005 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2016 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2006 instead of pydoc.help. This fixes a bizarre behavior where
2017 instead of pydoc.help. This fixes a bizarre behavior where
2007 printing '%s' % locals() would trigger the help system. Now
2018 printing '%s' % locals() would trigger the help system. Now
2008 ipython behaves like normal python does.
2019 ipython behaves like normal python does.
2009
2020
2010 Note that if one does 'from pydoc import help', the bizarre
2021 Note that if one does 'from pydoc import help', the bizarre
2011 behavior returns, but this will also happen in normal python, so
2022 behavior returns, but this will also happen in normal python, so
2012 it's not an ipython bug anymore (it has to do with how pydoc.help
2023 it's not an ipython bug anymore (it has to do with how pydoc.help
2013 is implemented).
2024 is implemented).
2014
2025
2015 2003-05-22 Fernando Perez <fperez@colorado.edu>
2026 2003-05-22 Fernando Perez <fperez@colorado.edu>
2016
2027
2017 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2028 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2018 return [] instead of None when nothing matches, also match to end
2029 return [] instead of None when nothing matches, also match to end
2019 of line. Patch by Gary Bishop.
2030 of line. Patch by Gary Bishop.
2020
2031
2021 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2032 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2022 protection as before, for files passed on the command line. This
2033 protection as before, for files passed on the command line. This
2023 prevents the CrashHandler from kicking in if user files call into
2034 prevents the CrashHandler from kicking in if user files call into
2024 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2035 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2025 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2036 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2026
2037
2027 2003-05-20 *** Released version 0.4.0
2038 2003-05-20 *** Released version 0.4.0
2028
2039
2029 2003-05-20 Fernando Perez <fperez@colorado.edu>
2040 2003-05-20 Fernando Perez <fperez@colorado.edu>
2030
2041
2031 * setup.py: added support for manpages. It's a bit hackish b/c of
2042 * setup.py: added support for manpages. It's a bit hackish b/c of
2032 a bug in the way the bdist_rpm distutils target handles gzipped
2043 a bug in the way the bdist_rpm distutils target handles gzipped
2033 manpages, but it works. After a patch by Jack.
2044 manpages, but it works. After a patch by Jack.
2034
2045
2035 2003-05-19 Fernando Perez <fperez@colorado.edu>
2046 2003-05-19 Fernando Perez <fperez@colorado.edu>
2036
2047
2037 * IPython/numutils.py: added a mockup of the kinds module, since
2048 * IPython/numutils.py: added a mockup of the kinds module, since
2038 it was recently removed from Numeric. This way, numutils will
2049 it was recently removed from Numeric. This way, numutils will
2039 work for all users even if they are missing kinds.
2050 work for all users even if they are missing kinds.
2040
2051
2041 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2052 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2042 failure, which can occur with SWIG-wrapped extensions. After a
2053 failure, which can occur with SWIG-wrapped extensions. After a
2043 crash report from Prabhu.
2054 crash report from Prabhu.
2044
2055
2045 2003-05-16 Fernando Perez <fperez@colorado.edu>
2056 2003-05-16 Fernando Perez <fperez@colorado.edu>
2046
2057
2047 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2058 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2048 protect ipython from user code which may call directly
2059 protect ipython from user code which may call directly
2049 sys.excepthook (this looks like an ipython crash to the user, even
2060 sys.excepthook (this looks like an ipython crash to the user, even
2050 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2061 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2051 This is especially important to help users of WxWindows, but may
2062 This is especially important to help users of WxWindows, but may
2052 also be useful in other cases.
2063 also be useful in other cases.
2053
2064
2054 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2065 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2055 an optional tb_offset to be specified, and to preserve exception
2066 an optional tb_offset to be specified, and to preserve exception
2056 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2067 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2057
2068
2058 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2069 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2059
2070
2060 2003-05-15 Fernando Perez <fperez@colorado.edu>
2071 2003-05-15 Fernando Perez <fperez@colorado.edu>
2061
2072
2062 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2073 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2063 installing for a new user under Windows.
2074 installing for a new user under Windows.
2064
2075
2065 2003-05-12 Fernando Perez <fperez@colorado.edu>
2076 2003-05-12 Fernando Perez <fperez@colorado.edu>
2066
2077
2067 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2078 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2068 handler for Emacs comint-based lines. Currently it doesn't do
2079 handler for Emacs comint-based lines. Currently it doesn't do
2069 much (but importantly, it doesn't update the history cache). In
2080 much (but importantly, it doesn't update the history cache). In
2070 the future it may be expanded if Alex needs more functionality
2081 the future it may be expanded if Alex needs more functionality
2071 there.
2082 there.
2072
2083
2073 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2084 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2074 info to crash reports.
2085 info to crash reports.
2075
2086
2076 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2087 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2077 just like Python's -c. Also fixed crash with invalid -color
2088 just like Python's -c. Also fixed crash with invalid -color
2078 option value at startup. Thanks to Will French
2089 option value at startup. Thanks to Will French
2079 <wfrench-AT-bestweb.net> for the bug report.
2090 <wfrench-AT-bestweb.net> for the bug report.
2080
2091
2081 2003-05-09 Fernando Perez <fperez@colorado.edu>
2092 2003-05-09 Fernando Perez <fperez@colorado.edu>
2082
2093
2083 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2094 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2084 to EvalDict (it's a mapping, after all) and simplified its code
2095 to EvalDict (it's a mapping, after all) and simplified its code
2085 quite a bit, after a nice discussion on c.l.py where Gustavo
2096 quite a bit, after a nice discussion on c.l.py where Gustavo
2086 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
2097 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
2087
2098
2088 2003-04-30 Fernando Perez <fperez@colorado.edu>
2099 2003-04-30 Fernando Perez <fperez@colorado.edu>
2089
2100
2090 * IPython/genutils.py (timings_out): modified it to reduce its
2101 * IPython/genutils.py (timings_out): modified it to reduce its
2091 overhead in the common reps==1 case.
2102 overhead in the common reps==1 case.
2092
2103
2093 2003-04-29 Fernando Perez <fperez@colorado.edu>
2104 2003-04-29 Fernando Perez <fperez@colorado.edu>
2094
2105
2095 * IPython/genutils.py (timings_out): Modified to use the resource
2106 * IPython/genutils.py (timings_out): Modified to use the resource
2096 module, which avoids the wraparound problems of time.clock().
2107 module, which avoids the wraparound problems of time.clock().
2097
2108
2098 2003-04-17 *** Released version 0.2.15pre4
2109 2003-04-17 *** Released version 0.2.15pre4
2099
2110
2100 2003-04-17 Fernando Perez <fperez@colorado.edu>
2111 2003-04-17 Fernando Perez <fperez@colorado.edu>
2101
2112
2102 * setup.py (scriptfiles): Split windows-specific stuff over to a
2113 * setup.py (scriptfiles): Split windows-specific stuff over to a
2103 separate file, in an attempt to have a Windows GUI installer.
2114 separate file, in an attempt to have a Windows GUI installer.
2104 That didn't work, but part of the groundwork is done.
2115 That didn't work, but part of the groundwork is done.
2105
2116
2106 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2117 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2107 indent/unindent with 4 spaces. Particularly useful in combination
2118 indent/unindent with 4 spaces. Particularly useful in combination
2108 with the new auto-indent option.
2119 with the new auto-indent option.
2109
2120
2110 2003-04-16 Fernando Perez <fperez@colorado.edu>
2121 2003-04-16 Fernando Perez <fperez@colorado.edu>
2111
2122
2112 * IPython/Magic.py: various replacements of self.rc for
2123 * IPython/Magic.py: various replacements of self.rc for
2113 self.shell.rc. A lot more remains to be done to fully disentangle
2124 self.shell.rc. A lot more remains to be done to fully disentangle
2114 this class from the main Shell class.
2125 this class from the main Shell class.
2115
2126
2116 * IPython/GnuplotRuntime.py: added checks for mouse support so
2127 * IPython/GnuplotRuntime.py: added checks for mouse support so
2117 that we don't try to enable it if the current gnuplot doesn't
2128 that we don't try to enable it if the current gnuplot doesn't
2118 really support it. Also added checks so that we don't try to
2129 really support it. Also added checks so that we don't try to
2119 enable persist under Windows (where Gnuplot doesn't recognize the
2130 enable persist under Windows (where Gnuplot doesn't recognize the
2120 option).
2131 option).
2121
2132
2122 * IPython/iplib.py (InteractiveShell.interact): Added optional
2133 * IPython/iplib.py (InteractiveShell.interact): Added optional
2123 auto-indenting code, after a patch by King C. Shu
2134 auto-indenting code, after a patch by King C. Shu
2124 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2135 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2125 get along well with pasting indented code. If I ever figure out
2136 get along well with pasting indented code. If I ever figure out
2126 how to make that part go well, it will become on by default.
2137 how to make that part go well, it will become on by default.
2127
2138
2128 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2139 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2129 crash ipython if there was an unmatched '%' in the user's prompt
2140 crash ipython if there was an unmatched '%' in the user's prompt
2130 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2141 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2131
2142
2132 * IPython/iplib.py (InteractiveShell.interact): removed the
2143 * IPython/iplib.py (InteractiveShell.interact): removed the
2133 ability to ask the user whether he wants to crash or not at the
2144 ability to ask the user whether he wants to crash or not at the
2134 'last line' exception handler. Calling functions at that point
2145 'last line' exception handler. Calling functions at that point
2135 changes the stack, and the error reports would have incorrect
2146 changes the stack, and the error reports would have incorrect
2136 tracebacks.
2147 tracebacks.
2137
2148
2138 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2149 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2139 pass through a peger a pretty-printed form of any object. After a
2150 pass through a peger a pretty-printed form of any object. After a
2140 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2151 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2141
2152
2142 2003-04-14 Fernando Perez <fperez@colorado.edu>
2153 2003-04-14 Fernando Perez <fperez@colorado.edu>
2143
2154
2144 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2155 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2145 all files in ~ would be modified at first install (instead of
2156 all files in ~ would be modified at first install (instead of
2146 ~/.ipython). This could be potentially disastrous, as the
2157 ~/.ipython). This could be potentially disastrous, as the
2147 modification (make line-endings native) could damage binary files.
2158 modification (make line-endings native) could damage binary files.
2148
2159
2149 2003-04-10 Fernando Perez <fperez@colorado.edu>
2160 2003-04-10 Fernando Perez <fperez@colorado.edu>
2150
2161
2151 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2162 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2152 handle only lines which are invalid python. This now means that
2163 handle only lines which are invalid python. This now means that
2153 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2164 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2154 for the bug report.
2165 for the bug report.
2155
2166
2156 2003-04-01 Fernando Perez <fperez@colorado.edu>
2167 2003-04-01 Fernando Perez <fperez@colorado.edu>
2157
2168
2158 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2169 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2159 where failing to set sys.last_traceback would crash pdb.pm().
2170 where failing to set sys.last_traceback would crash pdb.pm().
2160 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2171 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2161 report.
2172 report.
2162
2173
2163 2003-03-25 Fernando Perez <fperez@colorado.edu>
2174 2003-03-25 Fernando Perez <fperez@colorado.edu>
2164
2175
2165 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2176 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2166 before printing it (it had a lot of spurious blank lines at the
2177 before printing it (it had a lot of spurious blank lines at the
2167 end).
2178 end).
2168
2179
2169 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2180 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2170 output would be sent 21 times! Obviously people don't use this
2181 output would be sent 21 times! Obviously people don't use this
2171 too often, or I would have heard about it.
2182 too often, or I would have heard about it.
2172
2183
2173 2003-03-24 Fernando Perez <fperez@colorado.edu>
2184 2003-03-24 Fernando Perez <fperez@colorado.edu>
2174
2185
2175 * setup.py (scriptfiles): renamed the data_files parameter from
2186 * setup.py (scriptfiles): renamed the data_files parameter from
2176 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2187 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2177 for the patch.
2188 for the patch.
2178
2189
2179 2003-03-20 Fernando Perez <fperez@colorado.edu>
2190 2003-03-20 Fernando Perez <fperez@colorado.edu>
2180
2191
2181 * IPython/genutils.py (error): added error() and fatal()
2192 * IPython/genutils.py (error): added error() and fatal()
2182 functions.
2193 functions.
2183
2194
2184 2003-03-18 *** Released version 0.2.15pre3
2195 2003-03-18 *** Released version 0.2.15pre3
2185
2196
2186 2003-03-18 Fernando Perez <fperez@colorado.edu>
2197 2003-03-18 Fernando Perez <fperez@colorado.edu>
2187
2198
2188 * setupext/install_data_ext.py
2199 * setupext/install_data_ext.py
2189 (install_data_ext.initialize_options): Class contributed by Jack
2200 (install_data_ext.initialize_options): Class contributed by Jack
2190 Moffit for fixing the old distutils hack. He is sending this to
2201 Moffit for fixing the old distutils hack. He is sending this to
2191 the distutils folks so in the future we may not need it as a
2202 the distutils folks so in the future we may not need it as a
2192 private fix.
2203 private fix.
2193
2204
2194 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2205 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2195 changes for Debian packaging. See his patch for full details.
2206 changes for Debian packaging. See his patch for full details.
2196 The old distutils hack of making the ipythonrc* files carry a
2207 The old distutils hack of making the ipythonrc* files carry a
2197 bogus .py extension is gone, at last. Examples were moved to a
2208 bogus .py extension is gone, at last. Examples were moved to a
2198 separate subdir under doc/, and the separate executable scripts
2209 separate subdir under doc/, and the separate executable scripts
2199 now live in their own directory. Overall a great cleanup. The
2210 now live in their own directory. Overall a great cleanup. The
2200 manual was updated to use the new files, and setup.py has been
2211 manual was updated to use the new files, and setup.py has been
2201 fixed for this setup.
2212 fixed for this setup.
2202
2213
2203 * IPython/PyColorize.py (Parser.usage): made non-executable and
2214 * IPython/PyColorize.py (Parser.usage): made non-executable and
2204 created a pycolor wrapper around it to be included as a script.
2215 created a pycolor wrapper around it to be included as a script.
2205
2216
2206 2003-03-12 *** Released version 0.2.15pre2
2217 2003-03-12 *** Released version 0.2.15pre2
2207
2218
2208 2003-03-12 Fernando Perez <fperez@colorado.edu>
2219 2003-03-12 Fernando Perez <fperez@colorado.edu>
2209
2220
2210 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2221 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2211 long-standing problem with garbage characters in some terminals.
2222 long-standing problem with garbage characters in some terminals.
2212 The issue was really that the \001 and \002 escapes must _only_ be
2223 The issue was really that the \001 and \002 escapes must _only_ be
2213 passed to input prompts (which call readline), but _never_ to
2224 passed to input prompts (which call readline), but _never_ to
2214 normal text to be printed on screen. I changed ColorANSI to have
2225 normal text to be printed on screen. I changed ColorANSI to have
2215 two classes: TermColors and InputTermColors, each with the
2226 two classes: TermColors and InputTermColors, each with the
2216 appropriate escapes for input prompts or normal text. The code in
2227 appropriate escapes for input prompts or normal text. The code in
2217 Prompts.py got slightly more complicated, but this very old and
2228 Prompts.py got slightly more complicated, but this very old and
2218 annoying bug is finally fixed.
2229 annoying bug is finally fixed.
2219
2230
2220 All the credit for nailing down the real origin of this problem
2231 All the credit for nailing down the real origin of this problem
2221 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2232 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2222 *Many* thanks to him for spending quite a bit of effort on this.
2233 *Many* thanks to him for spending quite a bit of effort on this.
2223
2234
2224 2003-03-05 *** Released version 0.2.15pre1
2235 2003-03-05 *** Released version 0.2.15pre1
2225
2236
2226 2003-03-03 Fernando Perez <fperez@colorado.edu>
2237 2003-03-03 Fernando Perez <fperez@colorado.edu>
2227
2238
2228 * IPython/FakeModule.py: Moved the former _FakeModule to a
2239 * IPython/FakeModule.py: Moved the former _FakeModule to a
2229 separate file, because it's also needed by Magic (to fix a similar
2240 separate file, because it's also needed by Magic (to fix a similar
2230 pickle-related issue in @run).
2241 pickle-related issue in @run).
2231
2242
2232 2003-03-02 Fernando Perez <fperez@colorado.edu>
2243 2003-03-02 Fernando Perez <fperez@colorado.edu>
2233
2244
2234 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2245 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2235 the autocall option at runtime.
2246 the autocall option at runtime.
2236 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2247 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2237 across Magic.py to start separating Magic from InteractiveShell.
2248 across Magic.py to start separating Magic from InteractiveShell.
2238 (Magic._ofind): Fixed to return proper namespace for dotted
2249 (Magic._ofind): Fixed to return proper namespace for dotted
2239 names. Before, a dotted name would always return 'not currently
2250 names. Before, a dotted name would always return 'not currently
2240 defined', because it would find the 'parent'. s.x would be found,
2251 defined', because it would find the 'parent'. s.x would be found,
2241 but since 'x' isn't defined by itself, it would get confused.
2252 but since 'x' isn't defined by itself, it would get confused.
2242 (Magic.magic_run): Fixed pickling problems reported by Ralf
2253 (Magic.magic_run): Fixed pickling problems reported by Ralf
2243 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2254 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2244 that I'd used when Mike Heeter reported similar issues at the
2255 that I'd used when Mike Heeter reported similar issues at the
2245 top-level, but now for @run. It boils down to injecting the
2256 top-level, but now for @run. It boils down to injecting the
2246 namespace where code is being executed with something that looks
2257 namespace where code is being executed with something that looks
2247 enough like a module to fool pickle.dump(). Since a pickle stores
2258 enough like a module to fool pickle.dump(). Since a pickle stores
2248 a named reference to the importing module, we need this for
2259 a named reference to the importing module, we need this for
2249 pickles to save something sensible.
2260 pickles to save something sensible.
2250
2261
2251 * IPython/ipmaker.py (make_IPython): added an autocall option.
2262 * IPython/ipmaker.py (make_IPython): added an autocall option.
2252
2263
2253 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2264 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2254 the auto-eval code. Now autocalling is an option, and the code is
2265 the auto-eval code. Now autocalling is an option, and the code is
2255 also vastly safer. There is no more eval() involved at all.
2266 also vastly safer. There is no more eval() involved at all.
2256
2267
2257 2003-03-01 Fernando Perez <fperez@colorado.edu>
2268 2003-03-01 Fernando Perez <fperez@colorado.edu>
2258
2269
2259 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2270 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2260 dict with named keys instead of a tuple.
2271 dict with named keys instead of a tuple.
2261
2272
2262 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2273 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2263
2274
2264 * setup.py (make_shortcut): Fixed message about directories
2275 * setup.py (make_shortcut): Fixed message about directories
2265 created during Windows installation (the directories were ok, just
2276 created during Windows installation (the directories were ok, just
2266 the printed message was misleading). Thanks to Chris Liechti
2277 the printed message was misleading). Thanks to Chris Liechti
2267 <cliechti-AT-gmx.net> for the heads up.
2278 <cliechti-AT-gmx.net> for the heads up.
2268
2279
2269 2003-02-21 Fernando Perez <fperez@colorado.edu>
2280 2003-02-21 Fernando Perez <fperez@colorado.edu>
2270
2281
2271 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2282 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2272 of ValueError exception when checking for auto-execution. This
2283 of ValueError exception when checking for auto-execution. This
2273 one is raised by things like Numeric arrays arr.flat when the
2284 one is raised by things like Numeric arrays arr.flat when the
2274 array is non-contiguous.
2285 array is non-contiguous.
2275
2286
2276 2003-01-31 Fernando Perez <fperez@colorado.edu>
2287 2003-01-31 Fernando Perez <fperez@colorado.edu>
2277
2288
2278 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2289 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2279 not return any value at all (even though the command would get
2290 not return any value at all (even though the command would get
2280 executed).
2291 executed).
2281 (xsys): Flush stdout right after printing the command to ensure
2292 (xsys): Flush stdout right after printing the command to ensure
2282 proper ordering of commands and command output in the total
2293 proper ordering of commands and command output in the total
2283 output.
2294 output.
2284 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2295 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2285 system/getoutput as defaults. The old ones are kept for
2296 system/getoutput as defaults. The old ones are kept for
2286 compatibility reasons, so no code which uses this library needs
2297 compatibility reasons, so no code which uses this library needs
2287 changing.
2298 changing.
2288
2299
2289 2003-01-27 *** Released version 0.2.14
2300 2003-01-27 *** Released version 0.2.14
2290
2301
2291 2003-01-25 Fernando Perez <fperez@colorado.edu>
2302 2003-01-25 Fernando Perez <fperez@colorado.edu>
2292
2303
2293 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2304 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2294 functions defined in previous edit sessions could not be re-edited
2305 functions defined in previous edit sessions could not be re-edited
2295 (because the temp files were immediately removed). Now temp files
2306 (because the temp files were immediately removed). Now temp files
2296 are removed only at IPython's exit.
2307 are removed only at IPython's exit.
2297 (Magic.magic_run): Improved @run to perform shell-like expansions
2308 (Magic.magic_run): Improved @run to perform shell-like expansions
2298 on its arguments (~users and $VARS). With this, @run becomes more
2309 on its arguments (~users and $VARS). With this, @run becomes more
2299 like a normal command-line.
2310 like a normal command-line.
2300
2311
2301 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2312 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2302 bugs related to embedding and cleaned up that code. A fairly
2313 bugs related to embedding and cleaned up that code. A fairly
2303 important one was the impossibility to access the global namespace
2314 important one was the impossibility to access the global namespace
2304 through the embedded IPython (only local variables were visible).
2315 through the embedded IPython (only local variables were visible).
2305
2316
2306 2003-01-14 Fernando Perez <fperez@colorado.edu>
2317 2003-01-14 Fernando Perez <fperez@colorado.edu>
2307
2318
2308 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2319 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2309 auto-calling to be a bit more conservative. Now it doesn't get
2320 auto-calling to be a bit more conservative. Now it doesn't get
2310 triggered if any of '!=()<>' are in the rest of the input line, to
2321 triggered if any of '!=()<>' are in the rest of the input line, to
2311 allow comparing callables. Thanks to Alex for the heads up.
2322 allow comparing callables. Thanks to Alex for the heads up.
2312
2323
2313 2003-01-07 Fernando Perez <fperez@colorado.edu>
2324 2003-01-07 Fernando Perez <fperez@colorado.edu>
2314
2325
2315 * IPython/genutils.py (page): fixed estimation of the number of
2326 * IPython/genutils.py (page): fixed estimation of the number of
2316 lines in a string to be paged to simply count newlines. This
2327 lines in a string to be paged to simply count newlines. This
2317 prevents over-guessing due to embedded escape sequences. A better
2328 prevents over-guessing due to embedded escape sequences. A better
2318 long-term solution would involve stripping out the control chars
2329 long-term solution would involve stripping out the control chars
2319 for the count, but it's potentially so expensive I just don't
2330 for the count, but it's potentially so expensive I just don't
2320 think it's worth doing.
2331 think it's worth doing.
2321
2332
2322 2002-12-19 *** Released version 0.2.14pre50
2333 2002-12-19 *** Released version 0.2.14pre50
2323
2334
2324 2002-12-19 Fernando Perez <fperez@colorado.edu>
2335 2002-12-19 Fernando Perez <fperez@colorado.edu>
2325
2336
2326 * tools/release (version): Changed release scripts to inform
2337 * tools/release (version): Changed release scripts to inform
2327 Andrea and build a NEWS file with a list of recent changes.
2338 Andrea and build a NEWS file with a list of recent changes.
2328
2339
2329 * IPython/ColorANSI.py (__all__): changed terminal detection
2340 * IPython/ColorANSI.py (__all__): changed terminal detection
2330 code. Seems to work better for xterms without breaking
2341 code. Seems to work better for xterms without breaking
2331 konsole. Will need more testing to determine if WinXP and Mac OSX
2342 konsole. Will need more testing to determine if WinXP and Mac OSX
2332 also work ok.
2343 also work ok.
2333
2344
2334 2002-12-18 *** Released version 0.2.14pre49
2345 2002-12-18 *** Released version 0.2.14pre49
2335
2346
2336 2002-12-18 Fernando Perez <fperez@colorado.edu>
2347 2002-12-18 Fernando Perez <fperez@colorado.edu>
2337
2348
2338 * Docs: added new info about Mac OSX, from Andrea.
2349 * Docs: added new info about Mac OSX, from Andrea.
2339
2350
2340 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2351 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2341 allow direct plotting of python strings whose format is the same
2352 allow direct plotting of python strings whose format is the same
2342 of gnuplot data files.
2353 of gnuplot data files.
2343
2354
2344 2002-12-16 Fernando Perez <fperez@colorado.edu>
2355 2002-12-16 Fernando Perez <fperez@colorado.edu>
2345
2356
2346 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2357 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2347 value of exit question to be acknowledged.
2358 value of exit question to be acknowledged.
2348
2359
2349 2002-12-03 Fernando Perez <fperez@colorado.edu>
2360 2002-12-03 Fernando Perez <fperez@colorado.edu>
2350
2361
2351 * IPython/ipmaker.py: removed generators, which had been added
2362 * IPython/ipmaker.py: removed generators, which had been added
2352 by mistake in an earlier debugging run. This was causing trouble
2363 by mistake in an earlier debugging run. This was causing trouble
2353 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2364 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2354 for pointing this out.
2365 for pointing this out.
2355
2366
2356 2002-11-17 Fernando Perez <fperez@colorado.edu>
2367 2002-11-17 Fernando Perez <fperez@colorado.edu>
2357
2368
2358 * Manual: updated the Gnuplot section.
2369 * Manual: updated the Gnuplot section.
2359
2370
2360 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2371 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2361 a much better split of what goes in Runtime and what goes in
2372 a much better split of what goes in Runtime and what goes in
2362 Interactive.
2373 Interactive.
2363
2374
2364 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2375 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2365 being imported from iplib.
2376 being imported from iplib.
2366
2377
2367 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2378 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2368 for command-passing. Now the global Gnuplot instance is called
2379 for command-passing. Now the global Gnuplot instance is called
2369 'gp' instead of 'g', which was really a far too fragile and
2380 'gp' instead of 'g', which was really a far too fragile and
2370 common name.
2381 common name.
2371
2382
2372 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2383 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2373 bounding boxes generated by Gnuplot for square plots.
2384 bounding boxes generated by Gnuplot for square plots.
2374
2385
2375 * IPython/genutils.py (popkey): new function added. I should
2386 * IPython/genutils.py (popkey): new function added. I should
2376 suggest this on c.l.py as a dict method, it seems useful.
2387 suggest this on c.l.py as a dict method, it seems useful.
2377
2388
2378 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2389 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2379 to transparently handle PostScript generation. MUCH better than
2390 to transparently handle PostScript generation. MUCH better than
2380 the previous plot_eps/replot_eps (which I removed now). The code
2391 the previous plot_eps/replot_eps (which I removed now). The code
2381 is also fairly clean and well documented now (including
2392 is also fairly clean and well documented now (including
2382 docstrings).
2393 docstrings).
2383
2394
2384 2002-11-13 Fernando Perez <fperez@colorado.edu>
2395 2002-11-13 Fernando Perez <fperez@colorado.edu>
2385
2396
2386 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2397 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2387 (inconsistent with options).
2398 (inconsistent with options).
2388
2399
2389 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2400 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2390 manually disabled, I don't know why. Fixed it.
2401 manually disabled, I don't know why. Fixed it.
2391 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2402 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2392 eps output.
2403 eps output.
2393
2404
2394 2002-11-12 Fernando Perez <fperez@colorado.edu>
2405 2002-11-12 Fernando Perez <fperez@colorado.edu>
2395
2406
2396 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2407 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2397 don't propagate up to caller. Fixes crash reported by François
2408 don't propagate up to caller. Fixes crash reported by François
2398 Pinard.
2409 Pinard.
2399
2410
2400 2002-11-09 Fernando Perez <fperez@colorado.edu>
2411 2002-11-09 Fernando Perez <fperez@colorado.edu>
2401
2412
2402 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2413 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2403 history file for new users.
2414 history file for new users.
2404 (make_IPython): fixed bug where initial install would leave the
2415 (make_IPython): fixed bug where initial install would leave the
2405 user running in the .ipython dir.
2416 user running in the .ipython dir.
2406 (make_IPython): fixed bug where config dir .ipython would be
2417 (make_IPython): fixed bug where config dir .ipython would be
2407 created regardless of the given -ipythondir option. Thanks to Cory
2418 created regardless of the given -ipythondir option. Thanks to Cory
2408 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2419 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2409
2420
2410 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2421 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2411 type confirmations. Will need to use it in all of IPython's code
2422 type confirmations. Will need to use it in all of IPython's code
2412 consistently.
2423 consistently.
2413
2424
2414 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2425 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2415 context to print 31 lines instead of the default 5. This will make
2426 context to print 31 lines instead of the default 5. This will make
2416 the crash reports extremely detailed in case the problem is in
2427 the crash reports extremely detailed in case the problem is in
2417 libraries I don't have access to.
2428 libraries I don't have access to.
2418
2429
2419 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2430 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2420 line of defense' code to still crash, but giving users fair
2431 line of defense' code to still crash, but giving users fair
2421 warning. I don't want internal errors to go unreported: if there's
2432 warning. I don't want internal errors to go unreported: if there's
2422 an internal problem, IPython should crash and generate a full
2433 an internal problem, IPython should crash and generate a full
2423 report.
2434 report.
2424
2435
2425 2002-11-08 Fernando Perez <fperez@colorado.edu>
2436 2002-11-08 Fernando Perez <fperez@colorado.edu>
2426
2437
2427 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2438 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2428 otherwise uncaught exceptions which can appear if people set
2439 otherwise uncaught exceptions which can appear if people set
2429 sys.stdout to something badly broken. Thanks to a crash report
2440 sys.stdout to something badly broken. Thanks to a crash report
2430 from henni-AT-mail.brainbot.com.
2441 from henni-AT-mail.brainbot.com.
2431
2442
2432 2002-11-04 Fernando Perez <fperez@colorado.edu>
2443 2002-11-04 Fernando Perez <fperez@colorado.edu>
2433
2444
2434 * IPython/iplib.py (InteractiveShell.interact): added
2445 * IPython/iplib.py (InteractiveShell.interact): added
2435 __IPYTHON__active to the builtins. It's a flag which goes on when
2446 __IPYTHON__active to the builtins. It's a flag which goes on when
2436 the interaction starts and goes off again when it stops. This
2447 the interaction starts and goes off again when it stops. This
2437 allows embedding code to detect being inside IPython. Before this
2448 allows embedding code to detect being inside IPython. Before this
2438 was done via __IPYTHON__, but that only shows that an IPython
2449 was done via __IPYTHON__, but that only shows that an IPython
2439 instance has been created.
2450 instance has been created.
2440
2451
2441 * IPython/Magic.py (Magic.magic_env): I realized that in a
2452 * IPython/Magic.py (Magic.magic_env): I realized that in a
2442 UserDict, instance.data holds the data as a normal dict. So I
2453 UserDict, instance.data holds the data as a normal dict. So I
2443 modified @env to return os.environ.data instead of rebuilding a
2454 modified @env to return os.environ.data instead of rebuilding a
2444 dict by hand.
2455 dict by hand.
2445
2456
2446 2002-11-02 Fernando Perez <fperez@colorado.edu>
2457 2002-11-02 Fernando Perez <fperez@colorado.edu>
2447
2458
2448 * IPython/genutils.py (warn): changed so that level 1 prints no
2459 * IPython/genutils.py (warn): changed so that level 1 prints no
2449 header. Level 2 is now the default (with 'WARNING' header, as
2460 header. Level 2 is now the default (with 'WARNING' header, as
2450 before). I think I tracked all places where changes were needed in
2461 before). I think I tracked all places where changes were needed in
2451 IPython, but outside code using the old level numbering may have
2462 IPython, but outside code using the old level numbering may have
2452 broken.
2463 broken.
2453
2464
2454 * IPython/iplib.py (InteractiveShell.runcode): added this to
2465 * IPython/iplib.py (InteractiveShell.runcode): added this to
2455 handle the tracebacks in SystemExit traps correctly. The previous
2466 handle the tracebacks in SystemExit traps correctly. The previous
2456 code (through interact) was printing more of the stack than
2467 code (through interact) was printing more of the stack than
2457 necessary, showing IPython internal code to the user.
2468 necessary, showing IPython internal code to the user.
2458
2469
2459 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2470 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2460 default. Now that the default at the confirmation prompt is yes,
2471 default. Now that the default at the confirmation prompt is yes,
2461 it's not so intrusive. François' argument that ipython sessions
2472 it's not so intrusive. François' argument that ipython sessions
2462 tend to be complex enough not to lose them from an accidental C-d,
2473 tend to be complex enough not to lose them from an accidental C-d,
2463 is a valid one.
2474 is a valid one.
2464
2475
2465 * IPython/iplib.py (InteractiveShell.interact): added a
2476 * IPython/iplib.py (InteractiveShell.interact): added a
2466 showtraceback() call to the SystemExit trap, and modified the exit
2477 showtraceback() call to the SystemExit trap, and modified the exit
2467 confirmation to have yes as the default.
2478 confirmation to have yes as the default.
2468
2479
2469 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2480 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2470 this file. It's been gone from the code for a long time, this was
2481 this file. It's been gone from the code for a long time, this was
2471 simply leftover junk.
2482 simply leftover junk.
2472
2483
2473 2002-11-01 Fernando Perez <fperez@colorado.edu>
2484 2002-11-01 Fernando Perez <fperez@colorado.edu>
2474
2485
2475 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2486 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2476 added. If set, IPython now traps EOF and asks for
2487 added. If set, IPython now traps EOF and asks for
2477 confirmation. After a request by François Pinard.
2488 confirmation. After a request by François Pinard.
2478
2489
2479 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2490 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2480 of @abort, and with a new (better) mechanism for handling the
2491 of @abort, and with a new (better) mechanism for handling the
2481 exceptions.
2492 exceptions.
2482
2493
2483 2002-10-27 Fernando Perez <fperez@colorado.edu>
2494 2002-10-27 Fernando Perez <fperez@colorado.edu>
2484
2495
2485 * IPython/usage.py (__doc__): updated the --help information and
2496 * IPython/usage.py (__doc__): updated the --help information and
2486 the ipythonrc file to indicate that -log generates
2497 the ipythonrc file to indicate that -log generates
2487 ./ipython.log. Also fixed the corresponding info in @logstart.
2498 ./ipython.log. Also fixed the corresponding info in @logstart.
2488 This and several other fixes in the manuals thanks to reports by
2499 This and several other fixes in the manuals thanks to reports by
2489 François Pinard <pinard-AT-iro.umontreal.ca>.
2500 François Pinard <pinard-AT-iro.umontreal.ca>.
2490
2501
2491 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2502 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2492 refer to @logstart (instead of @log, which doesn't exist).
2503 refer to @logstart (instead of @log, which doesn't exist).
2493
2504
2494 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2505 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2495 AttributeError crash. Thanks to Christopher Armstrong
2506 AttributeError crash. Thanks to Christopher Armstrong
2496 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2507 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2497 introduced recently (in 0.2.14pre37) with the fix to the eval
2508 introduced recently (in 0.2.14pre37) with the fix to the eval
2498 problem mentioned below.
2509 problem mentioned below.
2499
2510
2500 2002-10-17 Fernando Perez <fperez@colorado.edu>
2511 2002-10-17 Fernando Perez <fperez@colorado.edu>
2501
2512
2502 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2513 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2503 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2514 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2504
2515
2505 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2516 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2506 this function to fix a problem reported by Alex Schmolck. He saw
2517 this function to fix a problem reported by Alex Schmolck. He saw
2507 it with list comprehensions and generators, which were getting
2518 it with list comprehensions and generators, which were getting
2508 called twice. The real problem was an 'eval' call in testing for
2519 called twice. The real problem was an 'eval' call in testing for
2509 automagic which was evaluating the input line silently.
2520 automagic which was evaluating the input line silently.
2510
2521
2511 This is a potentially very nasty bug, if the input has side
2522 This is a potentially very nasty bug, if the input has side
2512 effects which must not be repeated. The code is much cleaner now,
2523 effects which must not be repeated. The code is much cleaner now,
2513 without any blanket 'except' left and with a regexp test for
2524 without any blanket 'except' left and with a regexp test for
2514 actual function names.
2525 actual function names.
2515
2526
2516 But an eval remains, which I'm not fully comfortable with. I just
2527 But an eval remains, which I'm not fully comfortable with. I just
2517 don't know how to find out if an expression could be a callable in
2528 don't know how to find out if an expression could be a callable in
2518 the user's namespace without doing an eval on the string. However
2529 the user's namespace without doing an eval on the string. However
2519 that string is now much more strictly checked so that no code
2530 that string is now much more strictly checked so that no code
2520 slips by, so the eval should only happen for things that can
2531 slips by, so the eval should only happen for things that can
2521 really be only function/method names.
2532 really be only function/method names.
2522
2533
2523 2002-10-15 Fernando Perez <fperez@colorado.edu>
2534 2002-10-15 Fernando Perez <fperez@colorado.edu>
2524
2535
2525 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2536 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2526 OSX information to main manual, removed README_Mac_OSX file from
2537 OSX information to main manual, removed README_Mac_OSX file from
2527 distribution. Also updated credits for recent additions.
2538 distribution. Also updated credits for recent additions.
2528
2539
2529 2002-10-10 Fernando Perez <fperez@colorado.edu>
2540 2002-10-10 Fernando Perez <fperez@colorado.edu>
2530
2541
2531 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2542 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2532 terminal-related issues. Many thanks to Andrea Riciputi
2543 terminal-related issues. Many thanks to Andrea Riciputi
2533 <andrea.riciputi-AT-libero.it> for writing it.
2544 <andrea.riciputi-AT-libero.it> for writing it.
2534
2545
2535 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2546 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2536 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2547 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2537
2548
2538 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2549 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2539 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2550 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2540 <syver-en-AT-online.no> who both submitted patches for this problem.
2551 <syver-en-AT-online.no> who both submitted patches for this problem.
2541
2552
2542 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2553 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2543 global embedding to make sure that things don't overwrite user
2554 global embedding to make sure that things don't overwrite user
2544 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2555 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2545
2556
2546 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2557 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2547 compatibility. Thanks to Hayden Callow
2558 compatibility. Thanks to Hayden Callow
2548 <h.callow-AT-elec.canterbury.ac.nz>
2559 <h.callow-AT-elec.canterbury.ac.nz>
2549
2560
2550 2002-10-04 Fernando Perez <fperez@colorado.edu>
2561 2002-10-04 Fernando Perez <fperez@colorado.edu>
2551
2562
2552 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2563 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2553 Gnuplot.File objects.
2564 Gnuplot.File objects.
2554
2565
2555 2002-07-23 Fernando Perez <fperez@colorado.edu>
2566 2002-07-23 Fernando Perez <fperez@colorado.edu>
2556
2567
2557 * IPython/genutils.py (timing): Added timings() and timing() for
2568 * IPython/genutils.py (timing): Added timings() and timing() for
2558 quick access to the most commonly needed data, the execution
2569 quick access to the most commonly needed data, the execution
2559 times. Old timing() renamed to timings_out().
2570 times. Old timing() renamed to timings_out().
2560
2571
2561 2002-07-18 Fernando Perez <fperez@colorado.edu>
2572 2002-07-18 Fernando Perez <fperez@colorado.edu>
2562
2573
2563 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2574 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2564 bug with nested instances disrupting the parent's tab completion.
2575 bug with nested instances disrupting the parent's tab completion.
2565
2576
2566 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2577 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2567 all_completions code to begin the emacs integration.
2578 all_completions code to begin the emacs integration.
2568
2579
2569 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2580 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2570 argument to allow titling individual arrays when plotting.
2581 argument to allow titling individual arrays when plotting.
2571
2582
2572 2002-07-15 Fernando Perez <fperez@colorado.edu>
2583 2002-07-15 Fernando Perez <fperez@colorado.edu>
2573
2584
2574 * setup.py (make_shortcut): changed to retrieve the value of
2585 * setup.py (make_shortcut): changed to retrieve the value of
2575 'Program Files' directory from the registry (this value changes in
2586 'Program Files' directory from the registry (this value changes in
2576 non-english versions of Windows). Thanks to Thomas Fanslau
2587 non-english versions of Windows). Thanks to Thomas Fanslau
2577 <tfanslau-AT-gmx.de> for the report.
2588 <tfanslau-AT-gmx.de> for the report.
2578
2589
2579 2002-07-10 Fernando Perez <fperez@colorado.edu>
2590 2002-07-10 Fernando Perez <fperez@colorado.edu>
2580
2591
2581 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2592 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2582 a bug in pdb, which crashes if a line with only whitespace is
2593 a bug in pdb, which crashes if a line with only whitespace is
2583 entered. Bug report submitted to sourceforge.
2594 entered. Bug report submitted to sourceforge.
2584
2595
2585 2002-07-09 Fernando Perez <fperez@colorado.edu>
2596 2002-07-09 Fernando Perez <fperez@colorado.edu>
2586
2597
2587 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2598 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2588 reporting exceptions (it's a bug in inspect.py, I just set a
2599 reporting exceptions (it's a bug in inspect.py, I just set a
2589 workaround).
2600 workaround).
2590
2601
2591 2002-07-08 Fernando Perez <fperez@colorado.edu>
2602 2002-07-08 Fernando Perez <fperez@colorado.edu>
2592
2603
2593 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2604 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2594 __IPYTHON__ in __builtins__ to show up in user_ns.
2605 __IPYTHON__ in __builtins__ to show up in user_ns.
2595
2606
2596 2002-07-03 Fernando Perez <fperez@colorado.edu>
2607 2002-07-03 Fernando Perez <fperez@colorado.edu>
2597
2608
2598 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2609 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2599 name from @gp_set_instance to @gp_set_default.
2610 name from @gp_set_instance to @gp_set_default.
2600
2611
2601 * IPython/ipmaker.py (make_IPython): default editor value set to
2612 * IPython/ipmaker.py (make_IPython): default editor value set to
2602 '0' (a string), to match the rc file. Otherwise will crash when
2613 '0' (a string), to match the rc file. Otherwise will crash when
2603 .strip() is called on it.
2614 .strip() is called on it.
2604
2615
2605
2616
2606 2002-06-28 Fernando Perez <fperez@colorado.edu>
2617 2002-06-28 Fernando Perez <fperez@colorado.edu>
2607
2618
2608 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2619 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2609 of files in current directory when a file is executed via
2620 of files in current directory when a file is executed via
2610 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2621 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2611
2622
2612 * setup.py (manfiles): fix for rpm builds, submitted by RA
2623 * setup.py (manfiles): fix for rpm builds, submitted by RA
2613 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2624 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2614
2625
2615 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2626 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2616 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2627 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2617 string!). A. Schmolck caught this one.
2628 string!). A. Schmolck caught this one.
2618
2629
2619 2002-06-27 Fernando Perez <fperez@colorado.edu>
2630 2002-06-27 Fernando Perez <fperez@colorado.edu>
2620
2631
2621 * IPython/ipmaker.py (make_IPython): fixed bug when running user
2632 * IPython/ipmaker.py (make_IPython): fixed bug when running user
2622 defined files at the cmd line. __name__ wasn't being set to
2633 defined files at the cmd line. __name__ wasn't being set to
2623 __main__.
2634 __main__.
2624
2635
2625 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
2636 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
2626 regular lists and tuples besides Numeric arrays.
2637 regular lists and tuples besides Numeric arrays.
2627
2638
2628 * IPython/Prompts.py (CachedOutput.__call__): Added output
2639 * IPython/Prompts.py (CachedOutput.__call__): Added output
2629 supression for input ending with ';'. Similar to Mathematica and
2640 supression for input ending with ';'. Similar to Mathematica and
2630 Matlab. The _* vars and Out[] list are still updated, just like
2641 Matlab. The _* vars and Out[] list are still updated, just like
2631 Mathematica behaves.
2642 Mathematica behaves.
2632
2643
2633 2002-06-25 Fernando Perez <fperez@colorado.edu>
2644 2002-06-25 Fernando Perez <fperez@colorado.edu>
2634
2645
2635 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
2646 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
2636 .ini extensions for profiels under Windows.
2647 .ini extensions for profiels under Windows.
2637
2648
2638 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
2649 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
2639 string form. Fix contributed by Alexander Schmolck
2650 string form. Fix contributed by Alexander Schmolck
2640 <a.schmolck-AT-gmx.net>
2651 <a.schmolck-AT-gmx.net>
2641
2652
2642 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
2653 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
2643 pre-configured Gnuplot instance.
2654 pre-configured Gnuplot instance.
2644
2655
2645 2002-06-21 Fernando Perez <fperez@colorado.edu>
2656 2002-06-21 Fernando Perez <fperez@colorado.edu>
2646
2657
2647 * IPython/numutils.py (exp_safe): new function, works around the
2658 * IPython/numutils.py (exp_safe): new function, works around the
2648 underflow problems in Numeric.
2659 underflow problems in Numeric.
2649 (log2): New fn. Safe log in base 2: returns exact integer answer
2660 (log2): New fn. Safe log in base 2: returns exact integer answer
2650 for exact integer powers of 2.
2661 for exact integer powers of 2.
2651
2662
2652 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
2663 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
2653 properly.
2664 properly.
2654
2665
2655 2002-06-20 Fernando Perez <fperez@colorado.edu>
2666 2002-06-20 Fernando Perez <fperez@colorado.edu>
2656
2667
2657 * IPython/genutils.py (timing): new function like
2668 * IPython/genutils.py (timing): new function like
2658 Mathematica's. Similar to time_test, but returns more info.
2669 Mathematica's. Similar to time_test, but returns more info.
2659
2670
2660 2002-06-18 Fernando Perez <fperez@colorado.edu>
2671 2002-06-18 Fernando Perez <fperez@colorado.edu>
2661
2672
2662 * IPython/Magic.py (Magic.magic_save): modified @save and @r
2673 * IPython/Magic.py (Magic.magic_save): modified @save and @r
2663 according to Mike Heeter's suggestions.
2674 according to Mike Heeter's suggestions.
2664
2675
2665 2002-06-16 Fernando Perez <fperez@colorado.edu>
2676 2002-06-16 Fernando Perez <fperez@colorado.edu>
2666
2677
2667 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
2678 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
2668 system. GnuplotMagic is gone as a user-directory option. New files
2679 system. GnuplotMagic is gone as a user-directory option. New files
2669 make it easier to use all the gnuplot stuff both from external
2680 make it easier to use all the gnuplot stuff both from external
2670 programs as well as from IPython. Had to rewrite part of
2681 programs as well as from IPython. Had to rewrite part of
2671 hardcopy() b/c of a strange bug: often the ps files simply don't
2682 hardcopy() b/c of a strange bug: often the ps files simply don't
2672 get created, and require a repeat of the command (often several
2683 get created, and require a repeat of the command (often several
2673 times).
2684 times).
2674
2685
2675 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
2686 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
2676 resolve output channel at call time, so that if sys.stderr has
2687 resolve output channel at call time, so that if sys.stderr has
2677 been redirected by user this gets honored.
2688 been redirected by user this gets honored.
2678
2689
2679 2002-06-13 Fernando Perez <fperez@colorado.edu>
2690 2002-06-13 Fernando Perez <fperez@colorado.edu>
2680
2691
2681 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
2692 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
2682 IPShell. Kept a copy with the old names to avoid breaking people's
2693 IPShell. Kept a copy with the old names to avoid breaking people's
2683 embedded code.
2694 embedded code.
2684
2695
2685 * IPython/ipython: simplified it to the bare minimum after
2696 * IPython/ipython: simplified it to the bare minimum after
2686 Holger's suggestions. Added info about how to use it in
2697 Holger's suggestions. Added info about how to use it in
2687 PYTHONSTARTUP.
2698 PYTHONSTARTUP.
2688
2699
2689 * IPython/Shell.py (IPythonShell): changed the options passing
2700 * IPython/Shell.py (IPythonShell): changed the options passing
2690 from a string with funky %s replacements to a straight list. Maybe
2701 from a string with funky %s replacements to a straight list. Maybe
2691 a bit more typing, but it follows sys.argv conventions, so there's
2702 a bit more typing, but it follows sys.argv conventions, so there's
2692 less special-casing to remember.
2703 less special-casing to remember.
2693
2704
2694 2002-06-12 Fernando Perez <fperez@colorado.edu>
2705 2002-06-12 Fernando Perez <fperez@colorado.edu>
2695
2706
2696 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
2707 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
2697 command. Thanks to a suggestion by Mike Heeter.
2708 command. Thanks to a suggestion by Mike Heeter.
2698 (Magic.magic_pfile): added behavior to look at filenames if given
2709 (Magic.magic_pfile): added behavior to look at filenames if given
2699 arg is not a defined object.
2710 arg is not a defined object.
2700 (Magic.magic_save): New @save function to save code snippets. Also
2711 (Magic.magic_save): New @save function to save code snippets. Also
2701 a Mike Heeter idea.
2712 a Mike Heeter idea.
2702
2713
2703 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
2714 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
2704 plot() and replot(). Much more convenient now, especially for
2715 plot() and replot(). Much more convenient now, especially for
2705 interactive use.
2716 interactive use.
2706
2717
2707 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
2718 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
2708 filenames.
2719 filenames.
2709
2720
2710 2002-06-02 Fernando Perez <fperez@colorado.edu>
2721 2002-06-02 Fernando Perez <fperez@colorado.edu>
2711
2722
2712 * IPython/Struct.py (Struct.__init__): modified to admit
2723 * IPython/Struct.py (Struct.__init__): modified to admit
2713 initialization via another struct.
2724 initialization via another struct.
2714
2725
2715 * IPython/genutils.py (SystemExec.__init__): New stateful
2726 * IPython/genutils.py (SystemExec.__init__): New stateful
2716 interface to xsys and bq. Useful for writing system scripts.
2727 interface to xsys and bq. Useful for writing system scripts.
2717
2728
2718 2002-05-30 Fernando Perez <fperez@colorado.edu>
2729 2002-05-30 Fernando Perez <fperez@colorado.edu>
2719
2730
2720 * MANIFEST.in: Changed docfile selection to exclude all the lyx
2731 * MANIFEST.in: Changed docfile selection to exclude all the lyx
2721 documents. This will make the user download smaller (it's getting
2732 documents. This will make the user download smaller (it's getting
2722 too big).
2733 too big).
2723
2734
2724 2002-05-29 Fernando Perez <fperez@colorado.edu>
2735 2002-05-29 Fernando Perez <fperez@colorado.edu>
2725
2736
2726 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
2737 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
2727 fix problems with shelve and pickle. Seems to work, but I don't
2738 fix problems with shelve and pickle. Seems to work, but I don't
2728 know if corner cases break it. Thanks to Mike Heeter
2739 know if corner cases break it. Thanks to Mike Heeter
2729 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
2740 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
2730
2741
2731 2002-05-24 Fernando Perez <fperez@colorado.edu>
2742 2002-05-24 Fernando Perez <fperez@colorado.edu>
2732
2743
2733 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
2744 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
2734 macros having broken.
2745 macros having broken.
2735
2746
2736 2002-05-21 Fernando Perez <fperez@colorado.edu>
2747 2002-05-21 Fernando Perez <fperez@colorado.edu>
2737
2748
2738 * IPython/Magic.py (Magic.magic_logstart): fixed recently
2749 * IPython/Magic.py (Magic.magic_logstart): fixed recently
2739 introduced logging bug: all history before logging started was
2750 introduced logging bug: all history before logging started was
2740 being written one character per line! This came from the redesign
2751 being written one character per line! This came from the redesign
2741 of the input history as a special list which slices to strings,
2752 of the input history as a special list which slices to strings,
2742 not to lists.
2753 not to lists.
2743
2754
2744 2002-05-20 Fernando Perez <fperez@colorado.edu>
2755 2002-05-20 Fernando Perez <fperez@colorado.edu>
2745
2756
2746 * IPython/Prompts.py (CachedOutput.__init__): made the color table
2757 * IPython/Prompts.py (CachedOutput.__init__): made the color table
2747 be an attribute of all classes in this module. The design of these
2758 be an attribute of all classes in this module. The design of these
2748 classes needs some serious overhauling.
2759 classes needs some serious overhauling.
2749
2760
2750 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
2761 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
2751 which was ignoring '_' in option names.
2762 which was ignoring '_' in option names.
2752
2763
2753 * IPython/ultraTB.py (FormattedTB.__init__): Changed
2764 * IPython/ultraTB.py (FormattedTB.__init__): Changed
2754 'Verbose_novars' to 'Context' and made it the new default. It's a
2765 'Verbose_novars' to 'Context' and made it the new default. It's a
2755 bit more readable and also safer than verbose.
2766 bit more readable and also safer than verbose.
2756
2767
2757 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
2768 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
2758 triple-quoted strings.
2769 triple-quoted strings.
2759
2770
2760 * IPython/OInspect.py (__all__): new module exposing the object
2771 * IPython/OInspect.py (__all__): new module exposing the object
2761 introspection facilities. Now the corresponding magics are dummy
2772 introspection facilities. Now the corresponding magics are dummy
2762 wrappers around this. Having this module will make it much easier
2773 wrappers around this. Having this module will make it much easier
2763 to put these functions into our modified pdb.
2774 to put these functions into our modified pdb.
2764 This new object inspector system uses the new colorizing module,
2775 This new object inspector system uses the new colorizing module,
2765 so source code and other things are nicely syntax highlighted.
2776 so source code and other things are nicely syntax highlighted.
2766
2777
2767 2002-05-18 Fernando Perez <fperez@colorado.edu>
2778 2002-05-18 Fernando Perez <fperez@colorado.edu>
2768
2779
2769 * IPython/ColorANSI.py: Split the coloring tools into a separate
2780 * IPython/ColorANSI.py: Split the coloring tools into a separate
2770 module so I can use them in other code easier (they were part of
2781 module so I can use them in other code easier (they were part of
2771 ultraTB).
2782 ultraTB).
2772
2783
2773 2002-05-17 Fernando Perez <fperez@colorado.edu>
2784 2002-05-17 Fernando Perez <fperez@colorado.edu>
2774
2785
2775 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
2786 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
2776 fixed it to set the global 'g' also to the called instance, as
2787 fixed it to set the global 'g' also to the called instance, as
2777 long as 'g' was still a gnuplot instance (so it doesn't overwrite
2788 long as 'g' was still a gnuplot instance (so it doesn't overwrite
2778 user's 'g' variables).
2789 user's 'g' variables).
2779
2790
2780 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
2791 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
2781 global variables (aliases to _ih,_oh) so that users which expect
2792 global variables (aliases to _ih,_oh) so that users which expect
2782 In[5] or Out[7] to work aren't unpleasantly surprised.
2793 In[5] or Out[7] to work aren't unpleasantly surprised.
2783 (InputList.__getslice__): new class to allow executing slices of
2794 (InputList.__getslice__): new class to allow executing slices of
2784 input history directly. Very simple class, complements the use of
2795 input history directly. Very simple class, complements the use of
2785 macros.
2796 macros.
2786
2797
2787 2002-05-16 Fernando Perez <fperez@colorado.edu>
2798 2002-05-16 Fernando Perez <fperez@colorado.edu>
2788
2799
2789 * setup.py (docdirbase): make doc directory be just doc/IPython
2800 * setup.py (docdirbase): make doc directory be just doc/IPython
2790 without version numbers, it will reduce clutter for users.
2801 without version numbers, it will reduce clutter for users.
2791
2802
2792 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
2803 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
2793 execfile call to prevent possible memory leak. See for details:
2804 execfile call to prevent possible memory leak. See for details:
2794 http://mail.python.org/pipermail/python-list/2002-February/088476.html
2805 http://mail.python.org/pipermail/python-list/2002-February/088476.html
2795
2806
2796 2002-05-15 Fernando Perez <fperez@colorado.edu>
2807 2002-05-15 Fernando Perez <fperez@colorado.edu>
2797
2808
2798 * IPython/Magic.py (Magic.magic_psource): made the object
2809 * IPython/Magic.py (Magic.magic_psource): made the object
2799 introspection names be more standard: pdoc, pdef, pfile and
2810 introspection names be more standard: pdoc, pdef, pfile and
2800 psource. They all print/page their output, and it makes
2811 psource. They all print/page their output, and it makes
2801 remembering them easier. Kept old names for compatibility as
2812 remembering them easier. Kept old names for compatibility as
2802 aliases.
2813 aliases.
2803
2814
2804 2002-05-14 Fernando Perez <fperez@colorado.edu>
2815 2002-05-14 Fernando Perez <fperez@colorado.edu>
2805
2816
2806 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
2817 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
2807 what the mouse problem was. The trick is to use gnuplot with temp
2818 what the mouse problem was. The trick is to use gnuplot with temp
2808 files and NOT with pipes (for data communication), because having
2819 files and NOT with pipes (for data communication), because having
2809 both pipes and the mouse on is bad news.
2820 both pipes and the mouse on is bad news.
2810
2821
2811 2002-05-13 Fernando Perez <fperez@colorado.edu>
2822 2002-05-13 Fernando Perez <fperez@colorado.edu>
2812
2823
2813 * IPython/Magic.py (Magic._ofind): fixed namespace order search
2824 * IPython/Magic.py (Magic._ofind): fixed namespace order search
2814 bug. Information would be reported about builtins even when
2825 bug. Information would be reported about builtins even when
2815 user-defined functions overrode them.
2826 user-defined functions overrode them.
2816
2827
2817 2002-05-11 Fernando Perez <fperez@colorado.edu>
2828 2002-05-11 Fernando Perez <fperez@colorado.edu>
2818
2829
2819 * IPython/__init__.py (__all__): removed FlexCompleter from
2830 * IPython/__init__.py (__all__): removed FlexCompleter from
2820 __all__ so that things don't fail in platforms without readline.
2831 __all__ so that things don't fail in platforms without readline.
2821
2832
2822 2002-05-10 Fernando Perez <fperez@colorado.edu>
2833 2002-05-10 Fernando Perez <fperez@colorado.edu>
2823
2834
2824 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
2835 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
2825 it requires Numeric, effectively making Numeric a dependency for
2836 it requires Numeric, effectively making Numeric a dependency for
2826 IPython.
2837 IPython.
2827
2838
2828 * Released 0.2.13
2839 * Released 0.2.13
2829
2840
2830 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
2841 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
2831 profiler interface. Now all the major options from the profiler
2842 profiler interface. Now all the major options from the profiler
2832 module are directly supported in IPython, both for single
2843 module are directly supported in IPython, both for single
2833 expressions (@prun) and for full programs (@run -p).
2844 expressions (@prun) and for full programs (@run -p).
2834
2845
2835 2002-05-09 Fernando Perez <fperez@colorado.edu>
2846 2002-05-09 Fernando Perez <fperez@colorado.edu>
2836
2847
2837 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
2848 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
2838 magic properly formatted for screen.
2849 magic properly formatted for screen.
2839
2850
2840 * setup.py (make_shortcut): Changed things to put pdf version in
2851 * setup.py (make_shortcut): Changed things to put pdf version in
2841 doc/ instead of doc/manual (had to change lyxport a bit).
2852 doc/ instead of doc/manual (had to change lyxport a bit).
2842
2853
2843 * IPython/Magic.py (Profile.string_stats): made profile runs go
2854 * IPython/Magic.py (Profile.string_stats): made profile runs go
2844 through pager (they are long and a pager allows searching, saving,
2855 through pager (they are long and a pager allows searching, saving,
2845 etc.)
2856 etc.)
2846
2857
2847 2002-05-08 Fernando Perez <fperez@colorado.edu>
2858 2002-05-08 Fernando Perez <fperez@colorado.edu>
2848
2859
2849 * Released 0.2.12
2860 * Released 0.2.12
2850
2861
2851 2002-05-06 Fernando Perez <fperez@colorado.edu>
2862 2002-05-06 Fernando Perez <fperez@colorado.edu>
2852
2863
2853 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
2864 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
2854 introduced); 'hist n1 n2' was broken.
2865 introduced); 'hist n1 n2' was broken.
2855 (Magic.magic_pdb): added optional on/off arguments to @pdb
2866 (Magic.magic_pdb): added optional on/off arguments to @pdb
2856 (Magic.magic_run): added option -i to @run, which executes code in
2867 (Magic.magic_run): added option -i to @run, which executes code in
2857 the IPython namespace instead of a clean one. Also added @irun as
2868 the IPython namespace instead of a clean one. Also added @irun as
2858 an alias to @run -i.
2869 an alias to @run -i.
2859
2870
2860 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
2871 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
2861 fixed (it didn't really do anything, the namespaces were wrong).
2872 fixed (it didn't really do anything, the namespaces were wrong).
2862
2873
2863 * IPython/Debugger.py (__init__): Added workaround for python 2.1
2874 * IPython/Debugger.py (__init__): Added workaround for python 2.1
2864
2875
2865 * IPython/__init__.py (__all__): Fixed package namespace, now
2876 * IPython/__init__.py (__all__): Fixed package namespace, now
2866 'import IPython' does give access to IPython.<all> as
2877 'import IPython' does give access to IPython.<all> as
2867 expected. Also renamed __release__ to Release.
2878 expected. Also renamed __release__ to Release.
2868
2879
2869 * IPython/Debugger.py (__license__): created new Pdb class which
2880 * IPython/Debugger.py (__license__): created new Pdb class which
2870 functions like a drop-in for the normal pdb.Pdb but does NOT
2881 functions like a drop-in for the normal pdb.Pdb but does NOT
2871 import readline by default. This way it doesn't muck up IPython's
2882 import readline by default. This way it doesn't muck up IPython's
2872 readline handling, and now tab-completion finally works in the
2883 readline handling, and now tab-completion finally works in the
2873 debugger -- sort of. It completes things globally visible, but the
2884 debugger -- sort of. It completes things globally visible, but the
2874 completer doesn't track the stack as pdb walks it. That's a bit
2885 completer doesn't track the stack as pdb walks it. That's a bit
2875 tricky, and I'll have to implement it later.
2886 tricky, and I'll have to implement it later.
2876
2887
2877 2002-05-05 Fernando Perez <fperez@colorado.edu>
2888 2002-05-05 Fernando Perez <fperez@colorado.edu>
2878
2889
2879 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
2890 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
2880 magic docstrings when printed via ? (explicit \'s were being
2891 magic docstrings when printed via ? (explicit \'s were being
2881 printed).
2892 printed).
2882
2893
2883 * IPython/ipmaker.py (make_IPython): fixed namespace
2894 * IPython/ipmaker.py (make_IPython): fixed namespace
2884 identification bug. Now variables loaded via logs or command-line
2895 identification bug. Now variables loaded via logs or command-line
2885 files are recognized in the interactive namespace by @who.
2896 files are recognized in the interactive namespace by @who.
2886
2897
2887 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
2898 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
2888 log replay system stemming from the string form of Structs.
2899 log replay system stemming from the string form of Structs.
2889
2900
2890 * IPython/Magic.py (Macro.__init__): improved macros to properly
2901 * IPython/Magic.py (Macro.__init__): improved macros to properly
2891 handle magic commands in them.
2902 handle magic commands in them.
2892 (Magic.magic_logstart): usernames are now expanded so 'logstart
2903 (Magic.magic_logstart): usernames are now expanded so 'logstart
2893 ~/mylog' now works.
2904 ~/mylog' now works.
2894
2905
2895 * IPython/iplib.py (complete): fixed bug where paths starting with
2906 * IPython/iplib.py (complete): fixed bug where paths starting with
2896 '/' would be completed as magic names.
2907 '/' would be completed as magic names.
2897
2908
2898 2002-05-04 Fernando Perez <fperez@colorado.edu>
2909 2002-05-04 Fernando Perez <fperez@colorado.edu>
2899
2910
2900 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
2911 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
2901 allow running full programs under the profiler's control.
2912 allow running full programs under the profiler's control.
2902
2913
2903 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
2914 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
2904 mode to report exceptions verbosely but without formatting
2915 mode to report exceptions verbosely but without formatting
2905 variables. This addresses the issue of ipython 'freezing' (it's
2916 variables. This addresses the issue of ipython 'freezing' (it's
2906 not frozen, but caught in an expensive formatting loop) when huge
2917 not frozen, but caught in an expensive formatting loop) when huge
2907 variables are in the context of an exception.
2918 variables are in the context of an exception.
2908 (VerboseTB.text): Added '--->' markers at line where exception was
2919 (VerboseTB.text): Added '--->' markers at line where exception was
2909 triggered. Much clearer to read, especially in NoColor modes.
2920 triggered. Much clearer to read, especially in NoColor modes.
2910
2921
2911 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
2922 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
2912 implemented in reverse when changing to the new parse_options().
2923 implemented in reverse when changing to the new parse_options().
2913
2924
2914 2002-05-03 Fernando Perez <fperez@colorado.edu>
2925 2002-05-03 Fernando Perez <fperez@colorado.edu>
2915
2926
2916 * IPython/Magic.py (Magic.parse_options): new function so that
2927 * IPython/Magic.py (Magic.parse_options): new function so that
2917 magics can parse options easier.
2928 magics can parse options easier.
2918 (Magic.magic_prun): new function similar to profile.run(),
2929 (Magic.magic_prun): new function similar to profile.run(),
2919 suggested by Chris Hart.
2930 suggested by Chris Hart.
2920 (Magic.magic_cd): fixed behavior so that it only changes if
2931 (Magic.magic_cd): fixed behavior so that it only changes if
2921 directory actually is in history.
2932 directory actually is in history.
2922
2933
2923 * IPython/usage.py (__doc__): added information about potential
2934 * IPython/usage.py (__doc__): added information about potential
2924 slowness of Verbose exception mode when there are huge data
2935 slowness of Verbose exception mode when there are huge data
2925 structures to be formatted (thanks to Archie Paulson).
2936 structures to be formatted (thanks to Archie Paulson).
2926
2937
2927 * IPython/ipmaker.py (make_IPython): Changed default logging
2938 * IPython/ipmaker.py (make_IPython): Changed default logging
2928 (when simply called with -log) to use curr_dir/ipython.log in
2939 (when simply called with -log) to use curr_dir/ipython.log in
2929 rotate mode. Fixed crash which was occuring with -log before
2940 rotate mode. Fixed crash which was occuring with -log before
2930 (thanks to Jim Boyle).
2941 (thanks to Jim Boyle).
2931
2942
2932 2002-05-01 Fernando Perez <fperez@colorado.edu>
2943 2002-05-01 Fernando Perez <fperez@colorado.edu>
2933
2944
2934 * Released 0.2.11 for these fixes (mainly the ultraTB one which
2945 * Released 0.2.11 for these fixes (mainly the ultraTB one which
2935 was nasty -- though somewhat of a corner case).
2946 was nasty -- though somewhat of a corner case).
2936
2947
2937 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
2948 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
2938 text (was a bug).
2949 text (was a bug).
2939
2950
2940 2002-04-30 Fernando Perez <fperez@colorado.edu>
2951 2002-04-30 Fernando Perez <fperez@colorado.edu>
2941
2952
2942 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
2953 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
2943 a print after ^D or ^C from the user so that the In[] prompt
2954 a print after ^D or ^C from the user so that the In[] prompt
2944 doesn't over-run the gnuplot one.
2955 doesn't over-run the gnuplot one.
2945
2956
2946 2002-04-29 Fernando Perez <fperez@colorado.edu>
2957 2002-04-29 Fernando Perez <fperez@colorado.edu>
2947
2958
2948 * Released 0.2.10
2959 * Released 0.2.10
2949
2960
2950 * IPython/__release__.py (version): get date dynamically.
2961 * IPython/__release__.py (version): get date dynamically.
2951
2962
2952 * Misc. documentation updates thanks to Arnd's comments. Also ran
2963 * Misc. documentation updates thanks to Arnd's comments. Also ran
2953 a full spellcheck on the manual (hadn't been done in a while).
2964 a full spellcheck on the manual (hadn't been done in a while).
2954
2965
2955 2002-04-27 Fernando Perez <fperez@colorado.edu>
2966 2002-04-27 Fernando Perez <fperez@colorado.edu>
2956
2967
2957 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
2968 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
2958 starting a log in mid-session would reset the input history list.
2969 starting a log in mid-session would reset the input history list.
2959
2970
2960 2002-04-26 Fernando Perez <fperez@colorado.edu>
2971 2002-04-26 Fernando Perez <fperez@colorado.edu>
2961
2972
2962 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
2973 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
2963 all files were being included in an update. Now anything in
2974 all files were being included in an update. Now anything in
2964 UserConfig that matches [A-Za-z]*.py will go (this excludes
2975 UserConfig that matches [A-Za-z]*.py will go (this excludes
2965 __init__.py)
2976 __init__.py)
2966
2977
2967 2002-04-25 Fernando Perez <fperez@colorado.edu>
2978 2002-04-25 Fernando Perez <fperez@colorado.edu>
2968
2979
2969 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
2980 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
2970 to __builtins__ so that any form of embedded or imported code can
2981 to __builtins__ so that any form of embedded or imported code can
2971 test for being inside IPython.
2982 test for being inside IPython.
2972
2983
2973 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
2984 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
2974 changed to GnuplotMagic because it's now an importable module,
2985 changed to GnuplotMagic because it's now an importable module,
2975 this makes the name follow that of the standard Gnuplot module.
2986 this makes the name follow that of the standard Gnuplot module.
2976 GnuplotMagic can now be loaded at any time in mid-session.
2987 GnuplotMagic can now be loaded at any time in mid-session.
2977
2988
2978 2002-04-24 Fernando Perez <fperez@colorado.edu>
2989 2002-04-24 Fernando Perez <fperez@colorado.edu>
2979
2990
2980 * IPython/numutils.py: removed SIUnits. It doesn't properly set
2991 * IPython/numutils.py: removed SIUnits. It doesn't properly set
2981 the globals (IPython has its own namespace) and the
2992 the globals (IPython has its own namespace) and the
2982 PhysicalQuantity stuff is much better anyway.
2993 PhysicalQuantity stuff is much better anyway.
2983
2994
2984 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
2995 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
2985 embedding example to standard user directory for
2996 embedding example to standard user directory for
2986 distribution. Also put it in the manual.
2997 distribution. Also put it in the manual.
2987
2998
2988 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
2999 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
2989 instance as first argument (so it doesn't rely on some obscure
3000 instance as first argument (so it doesn't rely on some obscure
2990 hidden global).
3001 hidden global).
2991
3002
2992 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3003 * IPython/UserConfig/ipythonrc.py: put () back in accepted
2993 delimiters. While it prevents ().TAB from working, it allows
3004 delimiters. While it prevents ().TAB from working, it allows
2994 completions in open (... expressions. This is by far a more common
3005 completions in open (... expressions. This is by far a more common
2995 case.
3006 case.
2996
3007
2997 2002-04-23 Fernando Perez <fperez@colorado.edu>
3008 2002-04-23 Fernando Perez <fperez@colorado.edu>
2998
3009
2999 * IPython/Extensions/InterpreterPasteInput.py: new
3010 * IPython/Extensions/InterpreterPasteInput.py: new
3000 syntax-processing module for pasting lines with >>> or ... at the
3011 syntax-processing module for pasting lines with >>> or ... at the
3001 start.
3012 start.
3002
3013
3003 * IPython/Extensions/PhysicalQ_Interactive.py
3014 * IPython/Extensions/PhysicalQ_Interactive.py
3004 (PhysicalQuantityInteractive.__int__): fixed to work with either
3015 (PhysicalQuantityInteractive.__int__): fixed to work with either
3005 Numeric or math.
3016 Numeric or math.
3006
3017
3007 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3018 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3008 provided profiles. Now we have:
3019 provided profiles. Now we have:
3009 -math -> math module as * and cmath with its own namespace.
3020 -math -> math module as * and cmath with its own namespace.
3010 -numeric -> Numeric as *, plus gnuplot & grace
3021 -numeric -> Numeric as *, plus gnuplot & grace
3011 -physics -> same as before
3022 -physics -> same as before
3012
3023
3013 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3024 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3014 user-defined magics wouldn't be found by @magic if they were
3025 user-defined magics wouldn't be found by @magic if they were
3015 defined as class methods. Also cleaned up the namespace search
3026 defined as class methods. Also cleaned up the namespace search
3016 logic and the string building (to use %s instead of many repeated
3027 logic and the string building (to use %s instead of many repeated
3017 string adds).
3028 string adds).
3018
3029
3019 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3030 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3020 of user-defined magics to operate with class methods (cleaner, in
3031 of user-defined magics to operate with class methods (cleaner, in
3021 line with the gnuplot code).
3032 line with the gnuplot code).
3022
3033
3023 2002-04-22 Fernando Perez <fperez@colorado.edu>
3034 2002-04-22 Fernando Perez <fperez@colorado.edu>
3024
3035
3025 * setup.py: updated dependency list so that manual is updated when
3036 * setup.py: updated dependency list so that manual is updated when
3026 all included files change.
3037 all included files change.
3027
3038
3028 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3039 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3029 the delimiter removal option (the fix is ugly right now).
3040 the delimiter removal option (the fix is ugly right now).
3030
3041
3031 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3042 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3032 all of the math profile (quicker loading, no conflict between
3043 all of the math profile (quicker loading, no conflict between
3033 g-9.8 and g-gnuplot).
3044 g-9.8 and g-gnuplot).
3034
3045
3035 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3046 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3036 name of post-mortem files to IPython_crash_report.txt.
3047 name of post-mortem files to IPython_crash_report.txt.
3037
3048
3038 * Cleanup/update of the docs. Added all the new readline info and
3049 * Cleanup/update of the docs. Added all the new readline info and
3039 formatted all lists as 'real lists'.
3050 formatted all lists as 'real lists'.
3040
3051
3041 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3052 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3042 tab-completion options, since the full readline parse_and_bind is
3053 tab-completion options, since the full readline parse_and_bind is
3043 now accessible.
3054 now accessible.
3044
3055
3045 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3056 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3046 handling of readline options. Now users can specify any string to
3057 handling of readline options. Now users can specify any string to
3047 be passed to parse_and_bind(), as well as the delimiters to be
3058 be passed to parse_and_bind(), as well as the delimiters to be
3048 removed.
3059 removed.
3049 (InteractiveShell.__init__): Added __name__ to the global
3060 (InteractiveShell.__init__): Added __name__ to the global
3050 namespace so that things like Itpl which rely on its existence
3061 namespace so that things like Itpl which rely on its existence
3051 don't crash.
3062 don't crash.
3052 (InteractiveShell._prefilter): Defined the default with a _ so
3063 (InteractiveShell._prefilter): Defined the default with a _ so
3053 that prefilter() is easier to override, while the default one
3064 that prefilter() is easier to override, while the default one
3054 remains available.
3065 remains available.
3055
3066
3056 2002-04-18 Fernando Perez <fperez@colorado.edu>
3067 2002-04-18 Fernando Perez <fperez@colorado.edu>
3057
3068
3058 * Added information about pdb in the docs.
3069 * Added information about pdb in the docs.
3059
3070
3060 2002-04-17 Fernando Perez <fperez@colorado.edu>
3071 2002-04-17 Fernando Perez <fperez@colorado.edu>
3061
3072
3062 * IPython/ipmaker.py (make_IPython): added rc_override option to
3073 * IPython/ipmaker.py (make_IPython): added rc_override option to
3063 allow passing config options at creation time which may override
3074 allow passing config options at creation time which may override
3064 anything set in the config files or command line. This is
3075 anything set in the config files or command line. This is
3065 particularly useful for configuring embedded instances.
3076 particularly useful for configuring embedded instances.
3066
3077
3067 2002-04-15 Fernando Perez <fperez@colorado.edu>
3078 2002-04-15 Fernando Perez <fperez@colorado.edu>
3068
3079
3069 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3080 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3070 crash embedded instances because of the input cache falling out of
3081 crash embedded instances because of the input cache falling out of
3071 sync with the output counter.
3082 sync with the output counter.
3072
3083
3073 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3084 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3074 mode which calls pdb after an uncaught exception in IPython itself.
3085 mode which calls pdb after an uncaught exception in IPython itself.
3075
3086
3076 2002-04-14 Fernando Perez <fperez@colorado.edu>
3087 2002-04-14 Fernando Perez <fperez@colorado.edu>
3077
3088
3078 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3089 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3079 readline, fix it back after each call.
3090 readline, fix it back after each call.
3080
3091
3081 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3092 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3082 method to force all access via __call__(), which guarantees that
3093 method to force all access via __call__(), which guarantees that
3083 traceback references are properly deleted.
3094 traceback references are properly deleted.
3084
3095
3085 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3096 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3086 improve printing when pprint is in use.
3097 improve printing when pprint is in use.
3087
3098
3088 2002-04-13 Fernando Perez <fperez@colorado.edu>
3099 2002-04-13 Fernando Perez <fperez@colorado.edu>
3089
3100
3090 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3101 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3091 exceptions aren't caught anymore. If the user triggers one, he
3102 exceptions aren't caught anymore. If the user triggers one, he
3092 should know why he's doing it and it should go all the way up,
3103 should know why he's doing it and it should go all the way up,
3093 just like any other exception. So now @abort will fully kill the
3104 just like any other exception. So now @abort will fully kill the
3094 embedded interpreter and the embedding code (unless that happens
3105 embedded interpreter and the embedding code (unless that happens
3095 to catch SystemExit).
3106 to catch SystemExit).
3096
3107
3097 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3108 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3098 and a debugger() method to invoke the interactive pdb debugger
3109 and a debugger() method to invoke the interactive pdb debugger
3099 after printing exception information. Also added the corresponding
3110 after printing exception information. Also added the corresponding
3100 -pdb option and @pdb magic to control this feature, and updated
3111 -pdb option and @pdb magic to control this feature, and updated
3101 the docs. After a suggestion from Christopher Hart
3112 the docs. After a suggestion from Christopher Hart
3102 (hart-AT-caltech.edu).
3113 (hart-AT-caltech.edu).
3103
3114
3104 2002-04-12 Fernando Perez <fperez@colorado.edu>
3115 2002-04-12 Fernando Perez <fperez@colorado.edu>
3105
3116
3106 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3117 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3107 the exception handlers defined by the user (not the CrashHandler)
3118 the exception handlers defined by the user (not the CrashHandler)
3108 so that user exceptions don't trigger an ipython bug report.
3119 so that user exceptions don't trigger an ipython bug report.
3109
3120
3110 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3121 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3111 configurable (it should have always been so).
3122 configurable (it should have always been so).
3112
3123
3113 2002-03-26 Fernando Perez <fperez@colorado.edu>
3124 2002-03-26 Fernando Perez <fperez@colorado.edu>
3114
3125
3115 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3126 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3116 and there to fix embedding namespace issues. This should all be
3127 and there to fix embedding namespace issues. This should all be
3117 done in a more elegant way.
3128 done in a more elegant way.
3118
3129
3119 2002-03-25 Fernando Perez <fperez@colorado.edu>
3130 2002-03-25 Fernando Perez <fperez@colorado.edu>
3120
3131
3121 * IPython/genutils.py (get_home_dir): Try to make it work under
3132 * IPython/genutils.py (get_home_dir): Try to make it work under
3122 win9x also.
3133 win9x also.
3123
3134
3124 2002-03-20 Fernando Perez <fperez@colorado.edu>
3135 2002-03-20 Fernando Perez <fperez@colorado.edu>
3125
3136
3126 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3137 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3127 sys.displayhook untouched upon __init__.
3138 sys.displayhook untouched upon __init__.
3128
3139
3129 2002-03-19 Fernando Perez <fperez@colorado.edu>
3140 2002-03-19 Fernando Perez <fperez@colorado.edu>
3130
3141
3131 * Released 0.2.9 (for embedding bug, basically).
3142 * Released 0.2.9 (for embedding bug, basically).
3132
3143
3133 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3144 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3134 exceptions so that enclosing shell's state can be restored.
3145 exceptions so that enclosing shell's state can be restored.
3135
3146
3136 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3147 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3137 naming conventions in the .ipython/ dir.
3148 naming conventions in the .ipython/ dir.
3138
3149
3139 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3150 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3140 from delimiters list so filenames with - in them get expanded.
3151 from delimiters list so filenames with - in them get expanded.
3141
3152
3142 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3153 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3143 sys.displayhook not being properly restored after an embedded call.
3154 sys.displayhook not being properly restored after an embedded call.
3144
3155
3145 2002-03-18 Fernando Perez <fperez@colorado.edu>
3156 2002-03-18 Fernando Perez <fperez@colorado.edu>
3146
3157
3147 * Released 0.2.8
3158 * Released 0.2.8
3148
3159
3149 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3160 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3150 some files weren't being included in a -upgrade.
3161 some files weren't being included in a -upgrade.
3151 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3162 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3152 on' so that the first tab completes.
3163 on' so that the first tab completes.
3153 (InteractiveShell.handle_magic): fixed bug with spaces around
3164 (InteractiveShell.handle_magic): fixed bug with spaces around
3154 quotes breaking many magic commands.
3165 quotes breaking many magic commands.
3155
3166
3156 * setup.py: added note about ignoring the syntax error messages at
3167 * setup.py: added note about ignoring the syntax error messages at
3157 installation.
3168 installation.
3158
3169
3159 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3170 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3160 streamlining the gnuplot interface, now there's only one magic @gp.
3171 streamlining the gnuplot interface, now there's only one magic @gp.
3161
3172
3162 2002-03-17 Fernando Perez <fperez@colorado.edu>
3173 2002-03-17 Fernando Perez <fperez@colorado.edu>
3163
3174
3164 * IPython/UserConfig/magic_gnuplot.py: new name for the
3175 * IPython/UserConfig/magic_gnuplot.py: new name for the
3165 example-magic_pm.py file. Much enhanced system, now with a shell
3176 example-magic_pm.py file. Much enhanced system, now with a shell
3166 for communicating directly with gnuplot, one command at a time.
3177 for communicating directly with gnuplot, one command at a time.
3167
3178
3168 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3179 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3169 setting __name__=='__main__'.
3180 setting __name__=='__main__'.
3170
3181
3171 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3182 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3172 mini-shell for accessing gnuplot from inside ipython. Should
3183 mini-shell for accessing gnuplot from inside ipython. Should
3173 extend it later for grace access too. Inspired by Arnd's
3184 extend it later for grace access too. Inspired by Arnd's
3174 suggestion.
3185 suggestion.
3175
3186
3176 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3187 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3177 calling magic functions with () in their arguments. Thanks to Arnd
3188 calling magic functions with () in their arguments. Thanks to Arnd
3178 Baecker for pointing this to me.
3189 Baecker for pointing this to me.
3179
3190
3180 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3191 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3181 infinitely for integer or complex arrays (only worked with floats).
3192 infinitely for integer or complex arrays (only worked with floats).
3182
3193
3183 2002-03-16 Fernando Perez <fperez@colorado.edu>
3194 2002-03-16 Fernando Perez <fperez@colorado.edu>
3184
3195
3185 * setup.py: Merged setup and setup_windows into a single script
3196 * setup.py: Merged setup and setup_windows into a single script
3186 which properly handles things for windows users.
3197 which properly handles things for windows users.
3187
3198
3188 2002-03-15 Fernando Perez <fperez@colorado.edu>
3199 2002-03-15 Fernando Perez <fperez@colorado.edu>
3189
3200
3190 * Big change to the manual: now the magics are all automatically
3201 * Big change to the manual: now the magics are all automatically
3191 documented. This information is generated from their docstrings
3202 documented. This information is generated from their docstrings
3192 and put in a latex file included by the manual lyx file. This way
3203 and put in a latex file included by the manual lyx file. This way
3193 we get always up to date information for the magics. The manual
3204 we get always up to date information for the magics. The manual
3194 now also has proper version information, also auto-synced.
3205 now also has proper version information, also auto-synced.
3195
3206
3196 For this to work, an undocumented --magic_docstrings option was added.
3207 For this to work, an undocumented --magic_docstrings option was added.
3197
3208
3198 2002-03-13 Fernando Perez <fperez@colorado.edu>
3209 2002-03-13 Fernando Perez <fperez@colorado.edu>
3199
3210
3200 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3211 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3201 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3212 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3202
3213
3203 2002-03-12 Fernando Perez <fperez@colorado.edu>
3214 2002-03-12 Fernando Perez <fperez@colorado.edu>
3204
3215
3205 * IPython/ultraTB.py (TermColors): changed color escapes again to
3216 * IPython/ultraTB.py (TermColors): changed color escapes again to
3206 fix the (old, reintroduced) line-wrapping bug. Basically, if
3217 fix the (old, reintroduced) line-wrapping bug. Basically, if
3207 \001..\002 aren't given in the color escapes, lines get wrapped
3218 \001..\002 aren't given in the color escapes, lines get wrapped
3208 weirdly. But giving those screws up old xterms and emacs terms. So
3219 weirdly. But giving those screws up old xterms and emacs terms. So
3209 I added some logic for emacs terms to be ok, but I can't identify old
3220 I added some logic for emacs terms to be ok, but I can't identify old
3210 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3221 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3211
3222
3212 2002-03-10 Fernando Perez <fperez@colorado.edu>
3223 2002-03-10 Fernando Perez <fperez@colorado.edu>
3213
3224
3214 * IPython/usage.py (__doc__): Various documentation cleanups and
3225 * IPython/usage.py (__doc__): Various documentation cleanups and
3215 updates, both in usage docstrings and in the manual.
3226 updates, both in usage docstrings and in the manual.
3216
3227
3217 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3228 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3218 handling of caching. Set minimum acceptabe value for having a
3229 handling of caching. Set minimum acceptabe value for having a
3219 cache at 20 values.
3230 cache at 20 values.
3220
3231
3221 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3232 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3222 install_first_time function to a method, renamed it and added an
3233 install_first_time function to a method, renamed it and added an
3223 'upgrade' mode. Now people can update their config directory with
3234 'upgrade' mode. Now people can update their config directory with
3224 a simple command line switch (-upgrade, also new).
3235 a simple command line switch (-upgrade, also new).
3225
3236
3226 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3237 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3227 @file (convenient for automagic users under Python >= 2.2).
3238 @file (convenient for automagic users under Python >= 2.2).
3228 Removed @files (it seemed more like a plural than an abbrev. of
3239 Removed @files (it seemed more like a plural than an abbrev. of
3229 'file show').
3240 'file show').
3230
3241
3231 * IPython/iplib.py (install_first_time): Fixed crash if there were
3242 * IPython/iplib.py (install_first_time): Fixed crash if there were
3232 backup files ('~') in .ipython/ install directory.
3243 backup files ('~') in .ipython/ install directory.
3233
3244
3234 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3245 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3235 system. Things look fine, but these changes are fairly
3246 system. Things look fine, but these changes are fairly
3236 intrusive. Test them for a few days.
3247 intrusive. Test them for a few days.
3237
3248
3238 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3249 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3239 the prompts system. Now all in/out prompt strings are user
3250 the prompts system. Now all in/out prompt strings are user
3240 controllable. This is particularly useful for embedding, as one
3251 controllable. This is particularly useful for embedding, as one
3241 can tag embedded instances with particular prompts.
3252 can tag embedded instances with particular prompts.
3242
3253
3243 Also removed global use of sys.ps1/2, which now allows nested
3254 Also removed global use of sys.ps1/2, which now allows nested
3244 embeddings without any problems. Added command-line options for
3255 embeddings without any problems. Added command-line options for
3245 the prompt strings.
3256 the prompt strings.
3246
3257
3247 2002-03-08 Fernando Perez <fperez@colorado.edu>
3258 2002-03-08 Fernando Perez <fperez@colorado.edu>
3248
3259
3249 * IPython/UserConfig/example-embed-short.py (ipshell): added
3260 * IPython/UserConfig/example-embed-short.py (ipshell): added
3250 example file with the bare minimum code for embedding.
3261 example file with the bare minimum code for embedding.
3251
3262
3252 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3263 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3253 functionality for the embeddable shell to be activated/deactivated
3264 functionality for the embeddable shell to be activated/deactivated
3254 either globally or at each call.
3265 either globally or at each call.
3255
3266
3256 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3267 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3257 rewriting the prompt with '--->' for auto-inputs with proper
3268 rewriting the prompt with '--->' for auto-inputs with proper
3258 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3269 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3259 this is handled by the prompts class itself, as it should.
3270 this is handled by the prompts class itself, as it should.
3260
3271
3261 2002-03-05 Fernando Perez <fperez@colorado.edu>
3272 2002-03-05 Fernando Perez <fperez@colorado.edu>
3262
3273
3263 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3274 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3264 @logstart to avoid name clashes with the math log function.
3275 @logstart to avoid name clashes with the math log function.
3265
3276
3266 * Big updates to X/Emacs section of the manual.
3277 * Big updates to X/Emacs section of the manual.
3267
3278
3268 * Removed ipython_emacs. Milan explained to me how to pass
3279 * Removed ipython_emacs. Milan explained to me how to pass
3269 arguments to ipython through Emacs. Some day I'm going to end up
3280 arguments to ipython through Emacs. Some day I'm going to end up
3270 learning some lisp...
3281 learning some lisp...
3271
3282
3272 2002-03-04 Fernando Perez <fperez@colorado.edu>
3283 2002-03-04 Fernando Perez <fperez@colorado.edu>
3273
3284
3274 * IPython/ipython_emacs: Created script to be used as the
3285 * IPython/ipython_emacs: Created script to be used as the
3275 py-python-command Emacs variable so we can pass IPython
3286 py-python-command Emacs variable so we can pass IPython
3276 parameters. I can't figure out how to tell Emacs directly to pass
3287 parameters. I can't figure out how to tell Emacs directly to pass
3277 parameters to IPython, so a dummy shell script will do it.
3288 parameters to IPython, so a dummy shell script will do it.
3278
3289
3279 Other enhancements made for things to work better under Emacs'
3290 Other enhancements made for things to work better under Emacs'
3280 various types of terminals. Many thanks to Milan Zamazal
3291 various types of terminals. Many thanks to Milan Zamazal
3281 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3292 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3282
3293
3283 2002-03-01 Fernando Perez <fperez@colorado.edu>
3294 2002-03-01 Fernando Perez <fperez@colorado.edu>
3284
3295
3285 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3296 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3286 that loading of readline is now optional. This gives better
3297 that loading of readline is now optional. This gives better
3287 control to emacs users.
3298 control to emacs users.
3288
3299
3289 * IPython/ultraTB.py (__date__): Modified color escape sequences
3300 * IPython/ultraTB.py (__date__): Modified color escape sequences
3290 and now things work fine under xterm and in Emacs' term buffers
3301 and now things work fine under xterm and in Emacs' term buffers
3291 (though not shell ones). Well, in emacs you get colors, but all
3302 (though not shell ones). Well, in emacs you get colors, but all
3292 seem to be 'light' colors (no difference between dark and light
3303 seem to be 'light' colors (no difference between dark and light
3293 ones). But the garbage chars are gone, and also in xterms. It
3304 ones). But the garbage chars are gone, and also in xterms. It
3294 seems that now I'm using 'cleaner' ansi sequences.
3305 seems that now I'm using 'cleaner' ansi sequences.
3295
3306
3296 2002-02-21 Fernando Perez <fperez@colorado.edu>
3307 2002-02-21 Fernando Perez <fperez@colorado.edu>
3297
3308
3298 * Released 0.2.7 (mainly to publish the scoping fix).
3309 * Released 0.2.7 (mainly to publish the scoping fix).
3299
3310
3300 * IPython/Logger.py (Logger.logstate): added. A corresponding
3311 * IPython/Logger.py (Logger.logstate): added. A corresponding
3301 @logstate magic was created.
3312 @logstate magic was created.
3302
3313
3303 * IPython/Magic.py: fixed nested scoping problem under Python
3314 * IPython/Magic.py: fixed nested scoping problem under Python
3304 2.1.x (automagic wasn't working).
3315 2.1.x (automagic wasn't working).
3305
3316
3306 2002-02-20 Fernando Perez <fperez@colorado.edu>
3317 2002-02-20 Fernando Perez <fperez@colorado.edu>
3307
3318
3308 * Released 0.2.6.
3319 * Released 0.2.6.
3309
3320
3310 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3321 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3311 option so that logs can come out without any headers at all.
3322 option so that logs can come out without any headers at all.
3312
3323
3313 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3324 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3314 SciPy.
3325 SciPy.
3315
3326
3316 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3327 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3317 that embedded IPython calls don't require vars() to be explicitly
3328 that embedded IPython calls don't require vars() to be explicitly
3318 passed. Now they are extracted from the caller's frame (code
3329 passed. Now they are extracted from the caller's frame (code
3319 snatched from Eric Jones' weave). Added better documentation to
3330 snatched from Eric Jones' weave). Added better documentation to
3320 the section on embedding and the example file.
3331 the section on embedding and the example file.
3321
3332
3322 * IPython/genutils.py (page): Changed so that under emacs, it just
3333 * IPython/genutils.py (page): Changed so that under emacs, it just
3323 prints the string. You can then page up and down in the emacs
3334 prints the string. You can then page up and down in the emacs
3324 buffer itself. This is how the builtin help() works.
3335 buffer itself. This is how the builtin help() works.
3325
3336
3326 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3337 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3327 macro scoping: macros need to be executed in the user's namespace
3338 macro scoping: macros need to be executed in the user's namespace
3328 to work as if they had been typed by the user.
3339 to work as if they had been typed by the user.
3329
3340
3330 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3341 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3331 execute automatically (no need to type 'exec...'). They then
3342 execute automatically (no need to type 'exec...'). They then
3332 behave like 'true macros'. The printing system was also modified
3343 behave like 'true macros'. The printing system was also modified
3333 for this to work.
3344 for this to work.
3334
3345
3335 2002-02-19 Fernando Perez <fperez@colorado.edu>
3346 2002-02-19 Fernando Perez <fperez@colorado.edu>
3336
3347
3337 * IPython/genutils.py (page_file): new function for paging files
3348 * IPython/genutils.py (page_file): new function for paging files
3338 in an OS-independent way. Also necessary for file viewing to work
3349 in an OS-independent way. Also necessary for file viewing to work
3339 well inside Emacs buffers.
3350 well inside Emacs buffers.
3340 (page): Added checks for being in an emacs buffer.
3351 (page): Added checks for being in an emacs buffer.
3341 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3352 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3342 same bug in iplib.
3353 same bug in iplib.
3343
3354
3344 2002-02-18 Fernando Perez <fperez@colorado.edu>
3355 2002-02-18 Fernando Perez <fperez@colorado.edu>
3345
3356
3346 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3357 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3347 of readline so that IPython can work inside an Emacs buffer.
3358 of readline so that IPython can work inside an Emacs buffer.
3348
3359
3349 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3360 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3350 method signatures (they weren't really bugs, but it looks cleaner
3361 method signatures (they weren't really bugs, but it looks cleaner
3351 and keeps PyChecker happy).
3362 and keeps PyChecker happy).
3352
3363
3353 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3364 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3354 for implementing various user-defined hooks. Currently only
3365 for implementing various user-defined hooks. Currently only
3355 display is done.
3366 display is done.
3356
3367
3357 * IPython/Prompts.py (CachedOutput._display): changed display
3368 * IPython/Prompts.py (CachedOutput._display): changed display
3358 functions so that they can be dynamically changed by users easily.
3369 functions so that they can be dynamically changed by users easily.
3359
3370
3360 * IPython/Extensions/numeric_formats.py (num_display): added an
3371 * IPython/Extensions/numeric_formats.py (num_display): added an
3361 extension for printing NumPy arrays in flexible manners. It
3372 extension for printing NumPy arrays in flexible manners. It
3362 doesn't do anything yet, but all the structure is in
3373 doesn't do anything yet, but all the structure is in
3363 place. Ultimately the plan is to implement output format control
3374 place. Ultimately the plan is to implement output format control
3364 like in Octave.
3375 like in Octave.
3365
3376
3366 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3377 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3367 methods are found at run-time by all the automatic machinery.
3378 methods are found at run-time by all the automatic machinery.
3368
3379
3369 2002-02-17 Fernando Perez <fperez@colorado.edu>
3380 2002-02-17 Fernando Perez <fperez@colorado.edu>
3370
3381
3371 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3382 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3372 whole file a little.
3383 whole file a little.
3373
3384
3374 * ToDo: closed this document. Now there's a new_design.lyx
3385 * ToDo: closed this document. Now there's a new_design.lyx
3375 document for all new ideas. Added making a pdf of it for the
3386 document for all new ideas. Added making a pdf of it for the
3376 end-user distro.
3387 end-user distro.
3377
3388
3378 * IPython/Logger.py (Logger.switch_log): Created this to replace
3389 * IPython/Logger.py (Logger.switch_log): Created this to replace
3379 logon() and logoff(). It also fixes a nasty crash reported by
3390 logon() and logoff(). It also fixes a nasty crash reported by
3380 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3391 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3381
3392
3382 * IPython/iplib.py (complete): got auto-completion to work with
3393 * IPython/iplib.py (complete): got auto-completion to work with
3383 automagic (I had wanted this for a long time).
3394 automagic (I had wanted this for a long time).
3384
3395
3385 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3396 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3386 to @file, since file() is now a builtin and clashes with automagic
3397 to @file, since file() is now a builtin and clashes with automagic
3387 for @file.
3398 for @file.
3388
3399
3389 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3400 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3390 of this was previously in iplib, which had grown to more than 2000
3401 of this was previously in iplib, which had grown to more than 2000
3391 lines, way too long. No new functionality, but it makes managing
3402 lines, way too long. No new functionality, but it makes managing
3392 the code a bit easier.
3403 the code a bit easier.
3393
3404
3394 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3405 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3395 information to crash reports.
3406 information to crash reports.
3396
3407
3397 2002-02-12 Fernando Perez <fperez@colorado.edu>
3408 2002-02-12 Fernando Perez <fperez@colorado.edu>
3398
3409
3399 * Released 0.2.5.
3410 * Released 0.2.5.
3400
3411
3401 2002-02-11 Fernando Perez <fperez@colorado.edu>
3412 2002-02-11 Fernando Perez <fperez@colorado.edu>
3402
3413
3403 * Wrote a relatively complete Windows installer. It puts
3414 * Wrote a relatively complete Windows installer. It puts
3404 everything in place, creates Start Menu entries and fixes the
3415 everything in place, creates Start Menu entries and fixes the
3405 color issues. Nothing fancy, but it works.
3416 color issues. Nothing fancy, but it works.
3406
3417
3407 2002-02-10 Fernando Perez <fperez@colorado.edu>
3418 2002-02-10 Fernando Perez <fperez@colorado.edu>
3408
3419
3409 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3420 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3410 os.path.expanduser() call so that we can type @run ~/myfile.py and
3421 os.path.expanduser() call so that we can type @run ~/myfile.py and
3411 have thigs work as expected.
3422 have thigs work as expected.
3412
3423
3413 * IPython/genutils.py (page): fixed exception handling so things
3424 * IPython/genutils.py (page): fixed exception handling so things
3414 work both in Unix and Windows correctly. Quitting a pager triggers
3425 work both in Unix and Windows correctly. Quitting a pager triggers
3415 an IOError/broken pipe in Unix, and in windows not finding a pager
3426 an IOError/broken pipe in Unix, and in windows not finding a pager
3416 is also an IOError, so I had to actually look at the return value
3427 is also an IOError, so I had to actually look at the return value
3417 of the exception, not just the exception itself. Should be ok now.
3428 of the exception, not just the exception itself. Should be ok now.
3418
3429
3419 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3430 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3420 modified to allow case-insensitive color scheme changes.
3431 modified to allow case-insensitive color scheme changes.
3421
3432
3422 2002-02-09 Fernando Perez <fperez@colorado.edu>
3433 2002-02-09 Fernando Perez <fperez@colorado.edu>
3423
3434
3424 * IPython/genutils.py (native_line_ends): new function to leave
3435 * IPython/genutils.py (native_line_ends): new function to leave
3425 user config files with os-native line-endings.
3436 user config files with os-native line-endings.
3426
3437
3427 * README and manual updates.
3438 * README and manual updates.
3428
3439
3429 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3440 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3430 instead of StringType to catch Unicode strings.
3441 instead of StringType to catch Unicode strings.
3431
3442
3432 * IPython/genutils.py (filefind): fixed bug for paths with
3443 * IPython/genutils.py (filefind): fixed bug for paths with
3433 embedded spaces (very common in Windows).
3444 embedded spaces (very common in Windows).
3434
3445
3435 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3446 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3436 files under Windows, so that they get automatically associated
3447 files under Windows, so that they get automatically associated
3437 with a text editor. Windows makes it a pain to handle
3448 with a text editor. Windows makes it a pain to handle
3438 extension-less files.
3449 extension-less files.
3439
3450
3440 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3451 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3441 warning about readline only occur for Posix. In Windows there's no
3452 warning about readline only occur for Posix. In Windows there's no
3442 way to get readline, so why bother with the warning.
3453 way to get readline, so why bother with the warning.
3443
3454
3444 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3455 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3445 for __str__ instead of dir(self), since dir() changed in 2.2.
3456 for __str__ instead of dir(self), since dir() changed in 2.2.
3446
3457
3447 * Ported to Windows! Tested on XP, I suspect it should work fine
3458 * Ported to Windows! Tested on XP, I suspect it should work fine
3448 on NT/2000, but I don't think it will work on 98 et al. That
3459 on NT/2000, but I don't think it will work on 98 et al. That
3449 series of Windows is such a piece of junk anyway that I won't try
3460 series of Windows is such a piece of junk anyway that I won't try
3450 porting it there. The XP port was straightforward, showed a few
3461 porting it there. The XP port was straightforward, showed a few
3451 bugs here and there (fixed all), in particular some string
3462 bugs here and there (fixed all), in particular some string
3452 handling stuff which required considering Unicode strings (which
3463 handling stuff which required considering Unicode strings (which
3453 Windows uses). This is good, but hasn't been too tested :) No
3464 Windows uses). This is good, but hasn't been too tested :) No
3454 fancy installer yet, I'll put a note in the manual so people at
3465 fancy installer yet, I'll put a note in the manual so people at
3455 least make manually a shortcut.
3466 least make manually a shortcut.
3456
3467
3457 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3468 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3458 into a single one, "colors". This now controls both prompt and
3469 into a single one, "colors". This now controls both prompt and
3459 exception color schemes, and can be changed both at startup
3470 exception color schemes, and can be changed both at startup
3460 (either via command-line switches or via ipythonrc files) and at
3471 (either via command-line switches or via ipythonrc files) and at
3461 runtime, with @colors.
3472 runtime, with @colors.
3462 (Magic.magic_run): renamed @prun to @run and removed the old
3473 (Magic.magic_run): renamed @prun to @run and removed the old
3463 @run. The two were too similar to warrant keeping both.
3474 @run. The two were too similar to warrant keeping both.
3464
3475
3465 2002-02-03 Fernando Perez <fperez@colorado.edu>
3476 2002-02-03 Fernando Perez <fperez@colorado.edu>
3466
3477
3467 * IPython/iplib.py (install_first_time): Added comment on how to
3478 * IPython/iplib.py (install_first_time): Added comment on how to
3468 configure the color options for first-time users. Put a <return>
3479 configure the color options for first-time users. Put a <return>
3469 request at the end so that small-terminal users get a chance to
3480 request at the end so that small-terminal users get a chance to
3470 read the startup info.
3481 read the startup info.
3471
3482
3472 2002-01-23 Fernando Perez <fperez@colorado.edu>
3483 2002-01-23 Fernando Perez <fperez@colorado.edu>
3473
3484
3474 * IPython/iplib.py (CachedOutput.update): Changed output memory
3485 * IPython/iplib.py (CachedOutput.update): Changed output memory
3475 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3486 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3476 input history we still use _i. Did this b/c these variable are
3487 input history we still use _i. Did this b/c these variable are
3477 very commonly used in interactive work, so the less we need to
3488 very commonly used in interactive work, so the less we need to
3478 type the better off we are.
3489 type the better off we are.
3479 (Magic.magic_prun): updated @prun to better handle the namespaces
3490 (Magic.magic_prun): updated @prun to better handle the namespaces
3480 the file will run in, including a fix for __name__ not being set
3491 the file will run in, including a fix for __name__ not being set
3481 before.
3492 before.
3482
3493
3483 2002-01-20 Fernando Perez <fperez@colorado.edu>
3494 2002-01-20 Fernando Perez <fperez@colorado.edu>
3484
3495
3485 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3496 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3486 extra garbage for Python 2.2. Need to look more carefully into
3497 extra garbage for Python 2.2. Need to look more carefully into
3487 this later.
3498 this later.
3488
3499
3489 2002-01-19 Fernando Perez <fperez@colorado.edu>
3500 2002-01-19 Fernando Perez <fperez@colorado.edu>
3490
3501
3491 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3502 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3492 display SyntaxError exceptions properly formatted when they occur
3503 display SyntaxError exceptions properly formatted when they occur
3493 (they can be triggered by imported code).
3504 (they can be triggered by imported code).
3494
3505
3495 2002-01-18 Fernando Perez <fperez@colorado.edu>
3506 2002-01-18 Fernando Perez <fperez@colorado.edu>
3496
3507
3497 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3508 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3498 SyntaxError exceptions are reported nicely formatted, instead of
3509 SyntaxError exceptions are reported nicely formatted, instead of
3499 spitting out only offset information as before.
3510 spitting out only offset information as before.
3500 (Magic.magic_prun): Added the @prun function for executing
3511 (Magic.magic_prun): Added the @prun function for executing
3501 programs with command line args inside IPython.
3512 programs with command line args inside IPython.
3502
3513
3503 2002-01-16 Fernando Perez <fperez@colorado.edu>
3514 2002-01-16 Fernando Perez <fperez@colorado.edu>
3504
3515
3505 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3516 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3506 to *not* include the last item given in a range. This brings their
3517 to *not* include the last item given in a range. This brings their
3507 behavior in line with Python's slicing:
3518 behavior in line with Python's slicing:
3508 a[n1:n2] -> a[n1]...a[n2-1]
3519 a[n1:n2] -> a[n1]...a[n2-1]
3509 It may be a bit less convenient, but I prefer to stick to Python's
3520 It may be a bit less convenient, but I prefer to stick to Python's
3510 conventions *everywhere*, so users never have to wonder.
3521 conventions *everywhere*, so users never have to wonder.
3511 (Magic.magic_macro): Added @macro function to ease the creation of
3522 (Magic.magic_macro): Added @macro function to ease the creation of
3512 macros.
3523 macros.
3513
3524
3514 2002-01-05 Fernando Perez <fperez@colorado.edu>
3525 2002-01-05 Fernando Perez <fperez@colorado.edu>
3515
3526
3516 * Released 0.2.4.
3527 * Released 0.2.4.
3517
3528
3518 * IPython/iplib.py (Magic.magic_pdef):
3529 * IPython/iplib.py (Magic.magic_pdef):
3519 (InteractiveShell.safe_execfile): report magic lines and error
3530 (InteractiveShell.safe_execfile): report magic lines and error
3520 lines without line numbers so one can easily copy/paste them for
3531 lines without line numbers so one can easily copy/paste them for
3521 re-execution.
3532 re-execution.
3522
3533
3523 * Updated manual with recent changes.
3534 * Updated manual with recent changes.
3524
3535
3525 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3536 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3526 docstring printing when class? is called. Very handy for knowing
3537 docstring printing when class? is called. Very handy for knowing
3527 how to create class instances (as long as __init__ is well
3538 how to create class instances (as long as __init__ is well
3528 documented, of course :)
3539 documented, of course :)
3529 (Magic.magic_doc): print both class and constructor docstrings.
3540 (Magic.magic_doc): print both class and constructor docstrings.
3530 (Magic.magic_pdef): give constructor info if passed a class and
3541 (Magic.magic_pdef): give constructor info if passed a class and
3531 __call__ info for callable object instances.
3542 __call__ info for callable object instances.
3532
3543
3533 2002-01-04 Fernando Perez <fperez@colorado.edu>
3544 2002-01-04 Fernando Perez <fperez@colorado.edu>
3534
3545
3535 * Made deep_reload() off by default. It doesn't always work
3546 * Made deep_reload() off by default. It doesn't always work
3536 exactly as intended, so it's probably safer to have it off. It's
3547 exactly as intended, so it's probably safer to have it off. It's
3537 still available as dreload() anyway, so nothing is lost.
3548 still available as dreload() anyway, so nothing is lost.
3538
3549
3539 2002-01-02 Fernando Perez <fperez@colorado.edu>
3550 2002-01-02 Fernando Perez <fperez@colorado.edu>
3540
3551
3541 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3552 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3542 so I wanted an updated release).
3553 so I wanted an updated release).
3543
3554
3544 2001-12-27 Fernando Perez <fperez@colorado.edu>
3555 2001-12-27 Fernando Perez <fperez@colorado.edu>
3545
3556
3546 * IPython/iplib.py (InteractiveShell.interact): Added the original
3557 * IPython/iplib.py (InteractiveShell.interact): Added the original
3547 code from 'code.py' for this module in order to change the
3558 code from 'code.py' for this module in order to change the
3548 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3559 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3549 the history cache would break when the user hit Ctrl-C, and
3560 the history cache would break when the user hit Ctrl-C, and
3550 interact() offers no way to add any hooks to it.
3561 interact() offers no way to add any hooks to it.
3551
3562
3552 2001-12-23 Fernando Perez <fperez@colorado.edu>
3563 2001-12-23 Fernando Perez <fperez@colorado.edu>
3553
3564
3554 * setup.py: added check for 'MANIFEST' before trying to remove
3565 * setup.py: added check for 'MANIFEST' before trying to remove
3555 it. Thanks to Sean Reifschneider.
3566 it. Thanks to Sean Reifschneider.
3556
3567
3557 2001-12-22 Fernando Perez <fperez@colorado.edu>
3568 2001-12-22 Fernando Perez <fperez@colorado.edu>
3558
3569
3559 * Released 0.2.2.
3570 * Released 0.2.2.
3560
3571
3561 * Finished (reasonably) writing the manual. Later will add the
3572 * Finished (reasonably) writing the manual. Later will add the
3562 python-standard navigation stylesheets, but for the time being
3573 python-standard navigation stylesheets, but for the time being
3563 it's fairly complete. Distribution will include html and pdf
3574 it's fairly complete. Distribution will include html and pdf
3564 versions.
3575 versions.
3565
3576
3566 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3577 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3567 (MayaVi author).
3578 (MayaVi author).
3568
3579
3569 2001-12-21 Fernando Perez <fperez@colorado.edu>
3580 2001-12-21 Fernando Perez <fperez@colorado.edu>
3570
3581
3571 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3582 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3572 good public release, I think (with the manual and the distutils
3583 good public release, I think (with the manual and the distutils
3573 installer). The manual can use some work, but that can go
3584 installer). The manual can use some work, but that can go
3574 slowly. Otherwise I think it's quite nice for end users. Next
3585 slowly. Otherwise I think it's quite nice for end users. Next
3575 summer, rewrite the guts of it...
3586 summer, rewrite the guts of it...
3576
3587
3577 * Changed format of ipythonrc files to use whitespace as the
3588 * Changed format of ipythonrc files to use whitespace as the
3578 separator instead of an explicit '='. Cleaner.
3589 separator instead of an explicit '='. Cleaner.
3579
3590
3580 2001-12-20 Fernando Perez <fperez@colorado.edu>
3591 2001-12-20 Fernando Perez <fperez@colorado.edu>
3581
3592
3582 * Started a manual in LyX. For now it's just a quick merge of the
3593 * Started a manual in LyX. For now it's just a quick merge of the
3583 various internal docstrings and READMEs. Later it may grow into a
3594 various internal docstrings and READMEs. Later it may grow into a
3584 nice, full-blown manual.
3595 nice, full-blown manual.
3585
3596
3586 * Set up a distutils based installer. Installation should now be
3597 * Set up a distutils based installer. Installation should now be
3587 trivially simple for end-users.
3598 trivially simple for end-users.
3588
3599
3589 2001-12-11 Fernando Perez <fperez@colorado.edu>
3600 2001-12-11 Fernando Perez <fperez@colorado.edu>
3590
3601
3591 * Released 0.2.0. First public release, announced it at
3602 * Released 0.2.0. First public release, announced it at
3592 comp.lang.python. From now on, just bugfixes...
3603 comp.lang.python. From now on, just bugfixes...
3593
3604
3594 * Went through all the files, set copyright/license notices and
3605 * Went through all the files, set copyright/license notices and
3595 cleaned up things. Ready for release.
3606 cleaned up things. Ready for release.
3596
3607
3597 2001-12-10 Fernando Perez <fperez@colorado.edu>
3608 2001-12-10 Fernando Perez <fperez@colorado.edu>
3598
3609
3599 * Changed the first-time installer not to use tarfiles. It's more
3610 * Changed the first-time installer not to use tarfiles. It's more
3600 robust now and less unix-dependent. Also makes it easier for
3611 robust now and less unix-dependent. Also makes it easier for
3601 people to later upgrade versions.
3612 people to later upgrade versions.
3602
3613
3603 * Changed @exit to @abort to reflect the fact that it's pretty
3614 * Changed @exit to @abort to reflect the fact that it's pretty
3604 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3615 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3605 becomes significant only when IPyhton is embedded: in that case,
3616 becomes significant only when IPyhton is embedded: in that case,
3606 C-D closes IPython only, but @abort kills the enclosing program
3617 C-D closes IPython only, but @abort kills the enclosing program
3607 too (unless it had called IPython inside a try catching
3618 too (unless it had called IPython inside a try catching
3608 SystemExit).
3619 SystemExit).
3609
3620
3610 * Created Shell module which exposes the actuall IPython Shell
3621 * Created Shell module which exposes the actuall IPython Shell
3611 classes, currently the normal and the embeddable one. This at
3622 classes, currently the normal and the embeddable one. This at
3612 least offers a stable interface we won't need to change when
3623 least offers a stable interface we won't need to change when
3613 (later) the internals are rewritten. That rewrite will be confined
3624 (later) the internals are rewritten. That rewrite will be confined
3614 to iplib and ipmaker, but the Shell interface should remain as is.
3625 to iplib and ipmaker, but the Shell interface should remain as is.
3615
3626
3616 * Added embed module which offers an embeddable IPShell object,
3627 * Added embed module which offers an embeddable IPShell object,
3617 useful to fire up IPython *inside* a running program. Great for
3628 useful to fire up IPython *inside* a running program. Great for
3618 debugging or dynamical data analysis.
3629 debugging or dynamical data analysis.
3619
3630
3620 2001-12-08 Fernando Perez <fperez@colorado.edu>
3631 2001-12-08 Fernando Perez <fperez@colorado.edu>
3621
3632
3622 * Fixed small bug preventing seeing info from methods of defined
3633 * Fixed small bug preventing seeing info from methods of defined
3623 objects (incorrect namespace in _ofind()).
3634 objects (incorrect namespace in _ofind()).
3624
3635
3625 * Documentation cleanup. Moved the main usage docstrings to a
3636 * Documentation cleanup. Moved the main usage docstrings to a
3626 separate file, usage.py (cleaner to maintain, and hopefully in the
3637 separate file, usage.py (cleaner to maintain, and hopefully in the
3627 future some perlpod-like way of producing interactive, man and
3638 future some perlpod-like way of producing interactive, man and
3628 html docs out of it will be found).
3639 html docs out of it will be found).
3629
3640
3630 * Added @profile to see your profile at any time.
3641 * Added @profile to see your profile at any time.
3631
3642
3632 * Added @p as an alias for 'print'. It's especially convenient if
3643 * Added @p as an alias for 'print'. It's especially convenient if
3633 using automagic ('p x' prints x).
3644 using automagic ('p x' prints x).
3634
3645
3635 * Small cleanups and fixes after a pychecker run.
3646 * Small cleanups and fixes after a pychecker run.
3636
3647
3637 * Changed the @cd command to handle @cd - and @cd -<n> for
3648 * Changed the @cd command to handle @cd - and @cd -<n> for
3638 visiting any directory in _dh.
3649 visiting any directory in _dh.
3639
3650
3640 * Introduced _dh, a history of visited directories. @dhist prints
3651 * Introduced _dh, a history of visited directories. @dhist prints
3641 it out with numbers.
3652 it out with numbers.
3642
3653
3643 2001-12-07 Fernando Perez <fperez@colorado.edu>
3654 2001-12-07 Fernando Perez <fperez@colorado.edu>
3644
3655
3645 * Released 0.1.22
3656 * Released 0.1.22
3646
3657
3647 * Made initialization a bit more robust against invalid color
3658 * Made initialization a bit more robust against invalid color
3648 options in user input (exit, not traceback-crash).
3659 options in user input (exit, not traceback-crash).
3649
3660
3650 * Changed the bug crash reporter to write the report only in the
3661 * Changed the bug crash reporter to write the report only in the
3651 user's .ipython directory. That way IPython won't litter people's
3662 user's .ipython directory. That way IPython won't litter people's
3652 hard disks with crash files all over the place. Also print on
3663 hard disks with crash files all over the place. Also print on
3653 screen the necessary mail command.
3664 screen the necessary mail command.
3654
3665
3655 * With the new ultraTB, implemented LightBG color scheme for light
3666 * With the new ultraTB, implemented LightBG color scheme for light
3656 background terminals. A lot of people like white backgrounds, so I
3667 background terminals. A lot of people like white backgrounds, so I
3657 guess we should at least give them something readable.
3668 guess we should at least give them something readable.
3658
3669
3659 2001-12-06 Fernando Perez <fperez@colorado.edu>
3670 2001-12-06 Fernando Perez <fperez@colorado.edu>
3660
3671
3661 * Modified the structure of ultraTB. Now there's a proper class
3672 * Modified the structure of ultraTB. Now there's a proper class
3662 for tables of color schemes which allow adding schemes easily and
3673 for tables of color schemes which allow adding schemes easily and
3663 switching the active scheme without creating a new instance every
3674 switching the active scheme without creating a new instance every
3664 time (which was ridiculous). The syntax for creating new schemes
3675 time (which was ridiculous). The syntax for creating new schemes
3665 is also cleaner. I think ultraTB is finally done, with a clean
3676 is also cleaner. I think ultraTB is finally done, with a clean
3666 class structure. Names are also much cleaner (now there's proper
3677 class structure. Names are also much cleaner (now there's proper
3667 color tables, no need for every variable to also have 'color' in
3678 color tables, no need for every variable to also have 'color' in
3668 its name).
3679 its name).
3669
3680
3670 * Broke down genutils into separate files. Now genutils only
3681 * Broke down genutils into separate files. Now genutils only
3671 contains utility functions, and classes have been moved to their
3682 contains utility functions, and classes have been moved to their
3672 own files (they had enough independent functionality to warrant
3683 own files (they had enough independent functionality to warrant
3673 it): ConfigLoader, OutputTrap, Struct.
3684 it): ConfigLoader, OutputTrap, Struct.
3674
3685
3675 2001-12-05 Fernando Perez <fperez@colorado.edu>
3686 2001-12-05 Fernando Perez <fperez@colorado.edu>
3676
3687
3677 * IPython turns 21! Released version 0.1.21, as a candidate for
3688 * IPython turns 21! Released version 0.1.21, as a candidate for
3678 public consumption. If all goes well, release in a few days.
3689 public consumption. If all goes well, release in a few days.
3679
3690
3680 * Fixed path bug (files in Extensions/ directory wouldn't be found
3691 * Fixed path bug (files in Extensions/ directory wouldn't be found
3681 unless IPython/ was explicitly in sys.path).
3692 unless IPython/ was explicitly in sys.path).
3682
3693
3683 * Extended the FlexCompleter class as MagicCompleter to allow
3694 * Extended the FlexCompleter class as MagicCompleter to allow
3684 completion of @-starting lines.
3695 completion of @-starting lines.
3685
3696
3686 * Created __release__.py file as a central repository for release
3697 * Created __release__.py file as a central repository for release
3687 info that other files can read from.
3698 info that other files can read from.
3688
3699
3689 * Fixed small bug in logging: when logging was turned on in
3700 * Fixed small bug in logging: when logging was turned on in
3690 mid-session, old lines with special meanings (!@?) were being
3701 mid-session, old lines with special meanings (!@?) were being
3691 logged without the prepended comment, which is necessary since
3702 logged without the prepended comment, which is necessary since
3692 they are not truly valid python syntax. This should make session
3703 they are not truly valid python syntax. This should make session
3693 restores produce less errors.
3704 restores produce less errors.
3694
3705
3695 * The namespace cleanup forced me to make a FlexCompleter class
3706 * The namespace cleanup forced me to make a FlexCompleter class
3696 which is nothing but a ripoff of rlcompleter, but with selectable
3707 which is nothing but a ripoff of rlcompleter, but with selectable
3697 namespace (rlcompleter only works in __main__.__dict__). I'll try
3708 namespace (rlcompleter only works in __main__.__dict__). I'll try
3698 to submit a note to the authors to see if this change can be
3709 to submit a note to the authors to see if this change can be
3699 incorporated in future rlcompleter releases (Dec.6: done)
3710 incorporated in future rlcompleter releases (Dec.6: done)
3700
3711
3701 * More fixes to namespace handling. It was a mess! Now all
3712 * More fixes to namespace handling. It was a mess! Now all
3702 explicit references to __main__.__dict__ are gone (except when
3713 explicit references to __main__.__dict__ are gone (except when
3703 really needed) and everything is handled through the namespace
3714 really needed) and everything is handled through the namespace
3704 dicts in the IPython instance. We seem to be getting somewhere
3715 dicts in the IPython instance. We seem to be getting somewhere
3705 with this, finally...
3716 with this, finally...
3706
3717
3707 * Small documentation updates.
3718 * Small documentation updates.
3708
3719
3709 * Created the Extensions directory under IPython (with an
3720 * Created the Extensions directory under IPython (with an
3710 __init__.py). Put the PhysicalQ stuff there. This directory should
3721 __init__.py). Put the PhysicalQ stuff there. This directory should
3711 be used for all special-purpose extensions.
3722 be used for all special-purpose extensions.
3712
3723
3713 * File renaming:
3724 * File renaming:
3714 ipythonlib --> ipmaker
3725 ipythonlib --> ipmaker
3715 ipplib --> iplib
3726 ipplib --> iplib
3716 This makes a bit more sense in terms of what these files actually do.
3727 This makes a bit more sense in terms of what these files actually do.
3717
3728
3718 * Moved all the classes and functions in ipythonlib to ipplib, so
3729 * Moved all the classes and functions in ipythonlib to ipplib, so
3719 now ipythonlib only has make_IPython(). This will ease up its
3730 now ipythonlib only has make_IPython(). This will ease up its
3720 splitting in smaller functional chunks later.
3731 splitting in smaller functional chunks later.
3721
3732
3722 * Cleaned up (done, I think) output of @whos. Better column
3733 * Cleaned up (done, I think) output of @whos. Better column
3723 formatting, and now shows str(var) for as much as it can, which is
3734 formatting, and now shows str(var) for as much as it can, which is
3724 typically what one gets with a 'print var'.
3735 typically what one gets with a 'print var'.
3725
3736
3726 2001-12-04 Fernando Perez <fperez@colorado.edu>
3737 2001-12-04 Fernando Perez <fperez@colorado.edu>
3727
3738
3728 * Fixed namespace problems. Now builtin/IPyhton/user names get
3739 * Fixed namespace problems. Now builtin/IPyhton/user names get
3729 properly reported in their namespace. Internal namespace handling
3740 properly reported in their namespace. Internal namespace handling
3730 is finally getting decent (not perfect yet, but much better than
3741 is finally getting decent (not perfect yet, but much better than
3731 the ad-hoc mess we had).
3742 the ad-hoc mess we had).
3732
3743
3733 * Removed -exit option. If people just want to run a python
3744 * Removed -exit option. If people just want to run a python
3734 script, that's what the normal interpreter is for. Less
3745 script, that's what the normal interpreter is for. Less
3735 unnecessary options, less chances for bugs.
3746 unnecessary options, less chances for bugs.
3736
3747
3737 * Added a crash handler which generates a complete post-mortem if
3748 * Added a crash handler which generates a complete post-mortem if
3738 IPython crashes. This will help a lot in tracking bugs down the
3749 IPython crashes. This will help a lot in tracking bugs down the
3739 road.
3750 road.
3740
3751
3741 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
3752 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
3742 which were boud to functions being reassigned would bypass the
3753 which were boud to functions being reassigned would bypass the
3743 logger, breaking the sync of _il with the prompt counter. This
3754 logger, breaking the sync of _il with the prompt counter. This
3744 would then crash IPython later when a new line was logged.
3755 would then crash IPython later when a new line was logged.
3745
3756
3746 2001-12-02 Fernando Perez <fperez@colorado.edu>
3757 2001-12-02 Fernando Perez <fperez@colorado.edu>
3747
3758
3748 * Made IPython a package. This means people don't have to clutter
3759 * Made IPython a package. This means people don't have to clutter
3749 their sys.path with yet another directory. Changed the INSTALL
3760 their sys.path with yet another directory. Changed the INSTALL
3750 file accordingly.
3761 file accordingly.
3751
3762
3752 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
3763 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
3753 sorts its output (so @who shows it sorted) and @whos formats the
3764 sorts its output (so @who shows it sorted) and @whos formats the
3754 table according to the width of the first column. Nicer, easier to
3765 table according to the width of the first column. Nicer, easier to
3755 read. Todo: write a generic table_format() which takes a list of
3766 read. Todo: write a generic table_format() which takes a list of
3756 lists and prints it nicely formatted, with optional row/column
3767 lists and prints it nicely formatted, with optional row/column
3757 separators and proper padding and justification.
3768 separators and proper padding and justification.
3758
3769
3759 * Released 0.1.20
3770 * Released 0.1.20
3760
3771
3761 * Fixed bug in @log which would reverse the inputcache list (a
3772 * Fixed bug in @log which would reverse the inputcache list (a
3762 copy operation was missing).
3773 copy operation was missing).
3763
3774
3764 * Code cleanup. @config was changed to use page(). Better, since
3775 * Code cleanup. @config was changed to use page(). Better, since
3765 its output is always quite long.
3776 its output is always quite long.
3766
3777
3767 * Itpl is back as a dependency. I was having too many problems
3778 * Itpl is back as a dependency. I was having too many problems
3768 getting the parametric aliases to work reliably, and it's just
3779 getting the parametric aliases to work reliably, and it's just
3769 easier to code weird string operations with it than playing %()s
3780 easier to code weird string operations with it than playing %()s
3770 games. It's only ~6k, so I don't think it's too big a deal.
3781 games. It's only ~6k, so I don't think it's too big a deal.
3771
3782
3772 * Found (and fixed) a very nasty bug with history. !lines weren't
3783 * Found (and fixed) a very nasty bug with history. !lines weren't
3773 getting cached, and the out of sync caches would crash
3784 getting cached, and the out of sync caches would crash
3774 IPython. Fixed it by reorganizing the prefilter/handlers/logger
3785 IPython. Fixed it by reorganizing the prefilter/handlers/logger
3775 division of labor a bit better. Bug fixed, cleaner structure.
3786 division of labor a bit better. Bug fixed, cleaner structure.
3776
3787
3777 2001-12-01 Fernando Perez <fperez@colorado.edu>
3788 2001-12-01 Fernando Perez <fperez@colorado.edu>
3778
3789
3779 * Released 0.1.19
3790 * Released 0.1.19
3780
3791
3781 * Added option -n to @hist to prevent line number printing. Much
3792 * Added option -n to @hist to prevent line number printing. Much
3782 easier to copy/paste code this way.
3793 easier to copy/paste code this way.
3783
3794
3784 * Created global _il to hold the input list. Allows easy
3795 * Created global _il to hold the input list. Allows easy
3785 re-execution of blocks of code by slicing it (inspired by Janko's
3796 re-execution of blocks of code by slicing it (inspired by Janko's
3786 comment on 'macros').
3797 comment on 'macros').
3787
3798
3788 * Small fixes and doc updates.
3799 * Small fixes and doc updates.
3789
3800
3790 * Rewrote @history function (was @h). Renamed it to @hist, @h is
3801 * Rewrote @history function (was @h). Renamed it to @hist, @h is
3791 much too fragile with automagic. Handles properly multi-line
3802 much too fragile with automagic. Handles properly multi-line
3792 statements and takes parameters.
3803 statements and takes parameters.
3793
3804
3794 2001-11-30 Fernando Perez <fperez@colorado.edu>
3805 2001-11-30 Fernando Perez <fperez@colorado.edu>
3795
3806
3796 * Version 0.1.18 released.
3807 * Version 0.1.18 released.
3797
3808
3798 * Fixed nasty namespace bug in initial module imports.
3809 * Fixed nasty namespace bug in initial module imports.
3799
3810
3800 * Added copyright/license notes to all code files (except
3811 * Added copyright/license notes to all code files (except
3801 DPyGetOpt). For the time being, LGPL. That could change.
3812 DPyGetOpt). For the time being, LGPL. That could change.
3802
3813
3803 * Rewrote a much nicer README, updated INSTALL, cleaned up
3814 * Rewrote a much nicer README, updated INSTALL, cleaned up
3804 ipythonrc-* samples.
3815 ipythonrc-* samples.
3805
3816
3806 * Overall code/documentation cleanup. Basically ready for
3817 * Overall code/documentation cleanup. Basically ready for
3807 release. Only remaining thing: licence decision (LGPL?).
3818 release. Only remaining thing: licence decision (LGPL?).
3808
3819
3809 * Converted load_config to a class, ConfigLoader. Now recursion
3820 * Converted load_config to a class, ConfigLoader. Now recursion
3810 control is better organized. Doesn't include the same file twice.
3821 control is better organized. Doesn't include the same file twice.
3811
3822
3812 2001-11-29 Fernando Perez <fperez@colorado.edu>
3823 2001-11-29 Fernando Perez <fperez@colorado.edu>
3813
3824
3814 * Got input history working. Changed output history variables from
3825 * Got input history working. Changed output history variables from
3815 _p to _o so that _i is for input and _o for output. Just cleaner
3826 _p to _o so that _i is for input and _o for output. Just cleaner
3816 convention.
3827 convention.
3817
3828
3818 * Implemented parametric aliases. This pretty much allows the
3829 * Implemented parametric aliases. This pretty much allows the
3819 alias system to offer full-blown shell convenience, I think.
3830 alias system to offer full-blown shell convenience, I think.
3820
3831
3821 * Version 0.1.17 released, 0.1.18 opened.
3832 * Version 0.1.17 released, 0.1.18 opened.
3822
3833
3823 * dot_ipython/ipythonrc (alias): added documentation.
3834 * dot_ipython/ipythonrc (alias): added documentation.
3824 (xcolor): Fixed small bug (xcolors -> xcolor)
3835 (xcolor): Fixed small bug (xcolors -> xcolor)
3825
3836
3826 * Changed the alias system. Now alias is a magic command to define
3837 * Changed the alias system. Now alias is a magic command to define
3827 aliases just like the shell. Rationale: the builtin magics should
3838 aliases just like the shell. Rationale: the builtin magics should
3828 be there for things deeply connected to IPython's
3839 be there for things deeply connected to IPython's
3829 architecture. And this is a much lighter system for what I think
3840 architecture. And this is a much lighter system for what I think
3830 is the really important feature: allowing users to define quickly
3841 is the really important feature: allowing users to define quickly
3831 magics that will do shell things for them, so they can customize
3842 magics that will do shell things for them, so they can customize
3832 IPython easily to match their work habits. If someone is really
3843 IPython easily to match their work habits. If someone is really
3833 desperate to have another name for a builtin alias, they can
3844 desperate to have another name for a builtin alias, they can
3834 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
3845 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
3835 works.
3846 works.
3836
3847
3837 2001-11-28 Fernando Perez <fperez@colorado.edu>
3848 2001-11-28 Fernando Perez <fperez@colorado.edu>
3838
3849
3839 * Changed @file so that it opens the source file at the proper
3850 * Changed @file so that it opens the source file at the proper
3840 line. Since it uses less, if your EDITOR environment is
3851 line. Since it uses less, if your EDITOR environment is
3841 configured, typing v will immediately open your editor of choice
3852 configured, typing v will immediately open your editor of choice
3842 right at the line where the object is defined. Not as quick as
3853 right at the line where the object is defined. Not as quick as
3843 having a direct @edit command, but for all intents and purposes it
3854 having a direct @edit command, but for all intents and purposes it
3844 works. And I don't have to worry about writing @edit to deal with
3855 works. And I don't have to worry about writing @edit to deal with
3845 all the editors, less does that.
3856 all the editors, less does that.
3846
3857
3847 * Version 0.1.16 released, 0.1.17 opened.
3858 * Version 0.1.16 released, 0.1.17 opened.
3848
3859
3849 * Fixed some nasty bugs in the page/page_dumb combo that could
3860 * Fixed some nasty bugs in the page/page_dumb combo that could
3850 crash IPython.
3861 crash IPython.
3851
3862
3852 2001-11-27 Fernando Perez <fperez@colorado.edu>
3863 2001-11-27 Fernando Perez <fperez@colorado.edu>
3853
3864
3854 * Version 0.1.15 released, 0.1.16 opened.
3865 * Version 0.1.15 released, 0.1.16 opened.
3855
3866
3856 * Finally got ? and ?? to work for undefined things: now it's
3867 * Finally got ? and ?? to work for undefined things: now it's
3857 possible to type {}.get? and get information about the get method
3868 possible to type {}.get? and get information about the get method
3858 of dicts, or os.path? even if only os is defined (so technically
3869 of dicts, or os.path? even if only os is defined (so technically
3859 os.path isn't). Works at any level. For example, after import os,
3870 os.path isn't). Works at any level. For example, after import os,
3860 os?, os.path?, os.path.abspath? all work. This is great, took some
3871 os?, os.path?, os.path.abspath? all work. This is great, took some
3861 work in _ofind.
3872 work in _ofind.
3862
3873
3863 * Fixed more bugs with logging. The sanest way to do it was to add
3874 * Fixed more bugs with logging. The sanest way to do it was to add
3864 to @log a 'mode' parameter. Killed two in one shot (this mode
3875 to @log a 'mode' parameter. Killed two in one shot (this mode
3865 option was a request of Janko's). I think it's finally clean
3876 option was a request of Janko's). I think it's finally clean
3866 (famous last words).
3877 (famous last words).
3867
3878
3868 * Added a page_dumb() pager which does a decent job of paging on
3879 * Added a page_dumb() pager which does a decent job of paging on
3869 screen, if better things (like less) aren't available. One less
3880 screen, if better things (like less) aren't available. One less
3870 unix dependency (someday maybe somebody will port this to
3881 unix dependency (someday maybe somebody will port this to
3871 windows).
3882 windows).
3872
3883
3873 * Fixed problem in magic_log: would lock of logging out if log
3884 * Fixed problem in magic_log: would lock of logging out if log
3874 creation failed (because it would still think it had succeeded).
3885 creation failed (because it would still think it had succeeded).
3875
3886
3876 * Improved the page() function using curses to auto-detect screen
3887 * Improved the page() function using curses to auto-detect screen
3877 size. Now it can make a much better decision on whether to print
3888 size. Now it can make a much better decision on whether to print
3878 or page a string. Option screen_length was modified: a value 0
3889 or page a string. Option screen_length was modified: a value 0
3879 means auto-detect, and that's the default now.
3890 means auto-detect, and that's the default now.
3880
3891
3881 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
3892 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
3882 go out. I'll test it for a few days, then talk to Janko about
3893 go out. I'll test it for a few days, then talk to Janko about
3883 licences and announce it.
3894 licences and announce it.
3884
3895
3885 * Fixed the length of the auto-generated ---> prompt which appears
3896 * Fixed the length of the auto-generated ---> prompt which appears
3886 for auto-parens and auto-quotes. Getting this right isn't trivial,
3897 for auto-parens and auto-quotes. Getting this right isn't trivial,
3887 with all the color escapes, different prompt types and optional
3898 with all the color escapes, different prompt types and optional
3888 separators. But it seems to be working in all the combinations.
3899 separators. But it seems to be working in all the combinations.
3889
3900
3890 2001-11-26 Fernando Perez <fperez@colorado.edu>
3901 2001-11-26 Fernando Perez <fperez@colorado.edu>
3891
3902
3892 * Wrote a regexp filter to get option types from the option names
3903 * Wrote a regexp filter to get option types from the option names
3893 string. This eliminates the need to manually keep two duplicate
3904 string. This eliminates the need to manually keep two duplicate
3894 lists.
3905 lists.
3895
3906
3896 * Removed the unneeded check_option_names. Now options are handled
3907 * Removed the unneeded check_option_names. Now options are handled
3897 in a much saner manner and it's easy to visually check that things
3908 in a much saner manner and it's easy to visually check that things
3898 are ok.
3909 are ok.
3899
3910
3900 * Updated version numbers on all files I modified to carry a
3911 * Updated version numbers on all files I modified to carry a
3901 notice so Janko and Nathan have clear version markers.
3912 notice so Janko and Nathan have clear version markers.
3902
3913
3903 * Updated docstring for ultraTB with my changes. I should send
3914 * Updated docstring for ultraTB with my changes. I should send
3904 this to Nathan.
3915 this to Nathan.
3905
3916
3906 * Lots of small fixes. Ran everything through pychecker again.
3917 * Lots of small fixes. Ran everything through pychecker again.
3907
3918
3908 * Made loading of deep_reload an cmd line option. If it's not too
3919 * Made loading of deep_reload an cmd line option. If it's not too
3909 kosher, now people can just disable it. With -nodeep_reload it's
3920 kosher, now people can just disable it. With -nodeep_reload it's
3910 still available as dreload(), it just won't overwrite reload().
3921 still available as dreload(), it just won't overwrite reload().
3911
3922
3912 * Moved many options to the no| form (-opt and -noopt
3923 * Moved many options to the no| form (-opt and -noopt
3913 accepted). Cleaner.
3924 accepted). Cleaner.
3914
3925
3915 * Changed magic_log so that if called with no parameters, it uses
3926 * Changed magic_log so that if called with no parameters, it uses
3916 'rotate' mode. That way auto-generated logs aren't automatically
3927 'rotate' mode. That way auto-generated logs aren't automatically
3917 over-written. For normal logs, now a backup is made if it exists
3928 over-written. For normal logs, now a backup is made if it exists
3918 (only 1 level of backups). A new 'backup' mode was added to the
3929 (only 1 level of backups). A new 'backup' mode was added to the
3919 Logger class to support this. This was a request by Janko.
3930 Logger class to support this. This was a request by Janko.
3920
3931
3921 * Added @logoff/@logon to stop/restart an active log.
3932 * Added @logoff/@logon to stop/restart an active log.
3922
3933
3923 * Fixed a lot of bugs in log saving/replay. It was pretty
3934 * Fixed a lot of bugs in log saving/replay. It was pretty
3924 broken. Now special lines (!@,/) appear properly in the command
3935 broken. Now special lines (!@,/) appear properly in the command
3925 history after a log replay.
3936 history after a log replay.
3926
3937
3927 * Tried and failed to implement full session saving via pickle. My
3938 * Tried and failed to implement full session saving via pickle. My
3928 idea was to pickle __main__.__dict__, but modules can't be
3939 idea was to pickle __main__.__dict__, but modules can't be
3929 pickled. This would be a better alternative to replaying logs, but
3940 pickled. This would be a better alternative to replaying logs, but
3930 seems quite tricky to get to work. Changed -session to be called
3941 seems quite tricky to get to work. Changed -session to be called
3931 -logplay, which more accurately reflects what it does. And if we
3942 -logplay, which more accurately reflects what it does. And if we
3932 ever get real session saving working, -session is now available.
3943 ever get real session saving working, -session is now available.
3933
3944
3934 * Implemented color schemes for prompts also. As for tracebacks,
3945 * Implemented color schemes for prompts also. As for tracebacks,
3935 currently only NoColor and Linux are supported. But now the
3946 currently only NoColor and Linux are supported. But now the
3936 infrastructure is in place, based on a generic ColorScheme
3947 infrastructure is in place, based on a generic ColorScheme
3937 class. So writing and activating new schemes both for the prompts
3948 class. So writing and activating new schemes both for the prompts
3938 and the tracebacks should be straightforward.
3949 and the tracebacks should be straightforward.
3939
3950
3940 * Version 0.1.13 released, 0.1.14 opened.
3951 * Version 0.1.13 released, 0.1.14 opened.
3941
3952
3942 * Changed handling of options for output cache. Now counter is
3953 * Changed handling of options for output cache. Now counter is
3943 hardwired starting at 1 and one specifies the maximum number of
3954 hardwired starting at 1 and one specifies the maximum number of
3944 entries *in the outcache* (not the max prompt counter). This is
3955 entries *in the outcache* (not the max prompt counter). This is
3945 much better, since many statements won't increase the cache
3956 much better, since many statements won't increase the cache
3946 count. It also eliminated some confusing options, now there's only
3957 count. It also eliminated some confusing options, now there's only
3947 one: cache_size.
3958 one: cache_size.
3948
3959
3949 * Added 'alias' magic function and magic_alias option in the
3960 * Added 'alias' magic function and magic_alias option in the
3950 ipythonrc file. Now the user can easily define whatever names he
3961 ipythonrc file. Now the user can easily define whatever names he
3951 wants for the magic functions without having to play weird
3962 wants for the magic functions without having to play weird
3952 namespace games. This gives IPython a real shell-like feel.
3963 namespace games. This gives IPython a real shell-like feel.
3953
3964
3954 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
3965 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
3955 @ or not).
3966 @ or not).
3956
3967
3957 This was one of the last remaining 'visible' bugs (that I know
3968 This was one of the last remaining 'visible' bugs (that I know
3958 of). I think if I can clean up the session loading so it works
3969 of). I think if I can clean up the session loading so it works
3959 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
3970 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
3960 about licensing).
3971 about licensing).
3961
3972
3962 2001-11-25 Fernando Perez <fperez@colorado.edu>
3973 2001-11-25 Fernando Perez <fperez@colorado.edu>
3963
3974
3964 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
3975 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
3965 there's a cleaner distinction between what ? and ?? show.
3976 there's a cleaner distinction between what ? and ?? show.
3966
3977
3967 * Added screen_length option. Now the user can define his own
3978 * Added screen_length option. Now the user can define his own
3968 screen size for page() operations.
3979 screen size for page() operations.
3969
3980
3970 * Implemented magic shell-like functions with automatic code
3981 * Implemented magic shell-like functions with automatic code
3971 generation. Now adding another function is just a matter of adding
3982 generation. Now adding another function is just a matter of adding
3972 an entry to a dict, and the function is dynamically generated at
3983 an entry to a dict, and the function is dynamically generated at
3973 run-time. Python has some really cool features!
3984 run-time. Python has some really cool features!
3974
3985
3975 * Renamed many options to cleanup conventions a little. Now all
3986 * Renamed many options to cleanup conventions a little. Now all
3976 are lowercase, and only underscores where needed. Also in the code
3987 are lowercase, and only underscores where needed. Also in the code
3977 option name tables are clearer.
3988 option name tables are clearer.
3978
3989
3979 * Changed prompts a little. Now input is 'In [n]:' instead of
3990 * Changed prompts a little. Now input is 'In [n]:' instead of
3980 'In[n]:='. This allows it the numbers to be aligned with the
3991 'In[n]:='. This allows it the numbers to be aligned with the
3981 Out[n] numbers, and removes usage of ':=' which doesn't exist in
3992 Out[n] numbers, and removes usage of ':=' which doesn't exist in
3982 Python (it was a Mathematica thing). The '...' continuation prompt
3993 Python (it was a Mathematica thing). The '...' continuation prompt
3983 was also changed a little to align better.
3994 was also changed a little to align better.
3984
3995
3985 * Fixed bug when flushing output cache. Not all _p<n> variables
3996 * Fixed bug when flushing output cache. Not all _p<n> variables
3986 exist, so their deletion needs to be wrapped in a try:
3997 exist, so their deletion needs to be wrapped in a try:
3987
3998
3988 * Figured out how to properly use inspect.formatargspec() (it
3999 * Figured out how to properly use inspect.formatargspec() (it
3989 requires the args preceded by *). So I removed all the code from
4000 requires the args preceded by *). So I removed all the code from
3990 _get_pdef in Magic, which was just replicating that.
4001 _get_pdef in Magic, which was just replicating that.
3991
4002
3992 * Added test to prefilter to allow redefining magic function names
4003 * Added test to prefilter to allow redefining magic function names
3993 as variables. This is ok, since the @ form is always available,
4004 as variables. This is ok, since the @ form is always available,
3994 but whe should allow the user to define a variable called 'ls' if
4005 but whe should allow the user to define a variable called 'ls' if
3995 he needs it.
4006 he needs it.
3996
4007
3997 * Moved the ToDo information from README into a separate ToDo.
4008 * Moved the ToDo information from README into a separate ToDo.
3998
4009
3999 * General code cleanup and small bugfixes. I think it's close to a
4010 * General code cleanup and small bugfixes. I think it's close to a
4000 state where it can be released, obviously with a big 'beta'
4011 state where it can be released, obviously with a big 'beta'
4001 warning on it.
4012 warning on it.
4002
4013
4003 * Got the magic function split to work. Now all magics are defined
4014 * Got the magic function split to work. Now all magics are defined
4004 in a separate class. It just organizes things a bit, and now
4015 in a separate class. It just organizes things a bit, and now
4005 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4016 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4006 was too long).
4017 was too long).
4007
4018
4008 * Changed @clear to @reset to avoid potential confusions with
4019 * Changed @clear to @reset to avoid potential confusions with
4009 the shell command clear. Also renamed @cl to @clear, which does
4020 the shell command clear. Also renamed @cl to @clear, which does
4010 exactly what people expect it to from their shell experience.
4021 exactly what people expect it to from their shell experience.
4011
4022
4012 Added a check to the @reset command (since it's so
4023 Added a check to the @reset command (since it's so
4013 destructive, it's probably a good idea to ask for confirmation).
4024 destructive, it's probably a good idea to ask for confirmation).
4014 But now reset only works for full namespace resetting. Since the
4025 But now reset only works for full namespace resetting. Since the
4015 del keyword is already there for deleting a few specific
4026 del keyword is already there for deleting a few specific
4016 variables, I don't see the point of having a redundant magic
4027 variables, I don't see the point of having a redundant magic
4017 function for the same task.
4028 function for the same task.
4018
4029
4019 2001-11-24 Fernando Perez <fperez@colorado.edu>
4030 2001-11-24 Fernando Perez <fperez@colorado.edu>
4020
4031
4021 * Updated the builtin docs (esp. the ? ones).
4032 * Updated the builtin docs (esp. the ? ones).
4022
4033
4023 * Ran all the code through pychecker. Not terribly impressed with
4034 * Ran all the code through pychecker. Not terribly impressed with
4024 it: lots of spurious warnings and didn't really find anything of
4035 it: lots of spurious warnings and didn't really find anything of
4025 substance (just a few modules being imported and not used).
4036 substance (just a few modules being imported and not used).
4026
4037
4027 * Implemented the new ultraTB functionality into IPython. New
4038 * Implemented the new ultraTB functionality into IPython. New
4028 option: xcolors. This chooses color scheme. xmode now only selects
4039 option: xcolors. This chooses color scheme. xmode now only selects
4029 between Plain and Verbose. Better orthogonality.
4040 between Plain and Verbose. Better orthogonality.
4030
4041
4031 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4042 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4032 mode and color scheme for the exception handlers. Now it's
4043 mode and color scheme for the exception handlers. Now it's
4033 possible to have the verbose traceback with no coloring.
4044 possible to have the verbose traceback with no coloring.
4034
4045
4035 2001-11-23 Fernando Perez <fperez@colorado.edu>
4046 2001-11-23 Fernando Perez <fperez@colorado.edu>
4036
4047
4037 * Version 0.1.12 released, 0.1.13 opened.
4048 * Version 0.1.12 released, 0.1.13 opened.
4038
4049
4039 * Removed option to set auto-quote and auto-paren escapes by
4050 * Removed option to set auto-quote and auto-paren escapes by
4040 user. The chances of breaking valid syntax are just too high. If
4051 user. The chances of breaking valid syntax are just too high. If
4041 someone *really* wants, they can always dig into the code.
4052 someone *really* wants, they can always dig into the code.
4042
4053
4043 * Made prompt separators configurable.
4054 * Made prompt separators configurable.
4044
4055
4045 2001-11-22 Fernando Perez <fperez@colorado.edu>
4056 2001-11-22 Fernando Perez <fperez@colorado.edu>
4046
4057
4047 * Small bugfixes in many places.
4058 * Small bugfixes in many places.
4048
4059
4049 * Removed the MyCompleter class from ipplib. It seemed redundant
4060 * Removed the MyCompleter class from ipplib. It seemed redundant
4050 with the C-p,C-n history search functionality. Less code to
4061 with the C-p,C-n history search functionality. Less code to
4051 maintain.
4062 maintain.
4052
4063
4053 * Moved all the original ipython.py code into ipythonlib.py. Right
4064 * Moved all the original ipython.py code into ipythonlib.py. Right
4054 now it's just one big dump into a function called make_IPython, so
4065 now it's just one big dump into a function called make_IPython, so
4055 no real modularity has been gained. But at least it makes the
4066 no real modularity has been gained. But at least it makes the
4056 wrapper script tiny, and since ipythonlib is a module, it gets
4067 wrapper script tiny, and since ipythonlib is a module, it gets
4057 compiled and startup is much faster.
4068 compiled and startup is much faster.
4058
4069
4059 This is a reasobably 'deep' change, so we should test it for a
4070 This is a reasobably 'deep' change, so we should test it for a
4060 while without messing too much more with the code.
4071 while without messing too much more with the code.
4061
4072
4062 2001-11-21 Fernando Perez <fperez@colorado.edu>
4073 2001-11-21 Fernando Perez <fperez@colorado.edu>
4063
4074
4064 * Version 0.1.11 released, 0.1.12 opened for further work.
4075 * Version 0.1.11 released, 0.1.12 opened for further work.
4065
4076
4066 * Removed dependency on Itpl. It was only needed in one place. It
4077 * Removed dependency on Itpl. It was only needed in one place. It
4067 would be nice if this became part of python, though. It makes life
4078 would be nice if this became part of python, though. It makes life
4068 *a lot* easier in some cases.
4079 *a lot* easier in some cases.
4069
4080
4070 * Simplified the prefilter code a bit. Now all handlers are
4081 * Simplified the prefilter code a bit. Now all handlers are
4071 expected to explicitly return a value (at least a blank string).
4082 expected to explicitly return a value (at least a blank string).
4072
4083
4073 * Heavy edits in ipplib. Removed the help system altogether. Now
4084 * Heavy edits in ipplib. Removed the help system altogether. Now
4074 obj?/?? is used for inspecting objects, a magic @doc prints
4085 obj?/?? is used for inspecting objects, a magic @doc prints
4075 docstrings, and full-blown Python help is accessed via the 'help'
4086 docstrings, and full-blown Python help is accessed via the 'help'
4076 keyword. This cleans up a lot of code (less to maintain) and does
4087 keyword. This cleans up a lot of code (less to maintain) and does
4077 the job. Since 'help' is now a standard Python component, might as
4088 the job. Since 'help' is now a standard Python component, might as
4078 well use it and remove duplicate functionality.
4089 well use it and remove duplicate functionality.
4079
4090
4080 Also removed the option to use ipplib as a standalone program. By
4091 Also removed the option to use ipplib as a standalone program. By
4081 now it's too dependent on other parts of IPython to function alone.
4092 now it's too dependent on other parts of IPython to function alone.
4082
4093
4083 * Fixed bug in genutils.pager. It would crash if the pager was
4094 * Fixed bug in genutils.pager. It would crash if the pager was
4084 exited immediately after opening (broken pipe).
4095 exited immediately after opening (broken pipe).
4085
4096
4086 * Trimmed down the VerboseTB reporting a little. The header is
4097 * Trimmed down the VerboseTB reporting a little. The header is
4087 much shorter now and the repeated exception arguments at the end
4098 much shorter now and the repeated exception arguments at the end
4088 have been removed. For interactive use the old header seemed a bit
4099 have been removed. For interactive use the old header seemed a bit
4089 excessive.
4100 excessive.
4090
4101
4091 * Fixed small bug in output of @whos for variables with multi-word
4102 * Fixed small bug in output of @whos for variables with multi-word
4092 types (only first word was displayed).
4103 types (only first word was displayed).
4093
4104
4094 2001-11-17 Fernando Perez <fperez@colorado.edu>
4105 2001-11-17 Fernando Perez <fperez@colorado.edu>
4095
4106
4096 * Version 0.1.10 released, 0.1.11 opened for further work.
4107 * Version 0.1.10 released, 0.1.11 opened for further work.
4097
4108
4098 * Modified dirs and friends. dirs now *returns* the stack (not
4109 * Modified dirs and friends. dirs now *returns* the stack (not
4099 prints), so one can manipulate it as a variable. Convenient to
4110 prints), so one can manipulate it as a variable. Convenient to
4100 travel along many directories.
4111 travel along many directories.
4101
4112
4102 * Fixed bug in magic_pdef: would only work with functions with
4113 * Fixed bug in magic_pdef: would only work with functions with
4103 arguments with default values.
4114 arguments with default values.
4104
4115
4105 2001-11-14 Fernando Perez <fperez@colorado.edu>
4116 2001-11-14 Fernando Perez <fperez@colorado.edu>
4106
4117
4107 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4118 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4108 example with IPython. Various other minor fixes and cleanups.
4119 example with IPython. Various other minor fixes and cleanups.
4109
4120
4110 * Version 0.1.9 released, 0.1.10 opened for further work.
4121 * Version 0.1.9 released, 0.1.10 opened for further work.
4111
4122
4112 * Added sys.path to the list of directories searched in the
4123 * Added sys.path to the list of directories searched in the
4113 execfile= option. It used to be the current directory and the
4124 execfile= option. It used to be the current directory and the
4114 user's IPYTHONDIR only.
4125 user's IPYTHONDIR only.
4115
4126
4116 2001-11-13 Fernando Perez <fperez@colorado.edu>
4127 2001-11-13 Fernando Perez <fperez@colorado.edu>
4117
4128
4118 * Reinstated the raw_input/prefilter separation that Janko had
4129 * Reinstated the raw_input/prefilter separation that Janko had
4119 initially. This gives a more convenient setup for extending the
4130 initially. This gives a more convenient setup for extending the
4120 pre-processor from the outside: raw_input always gets a string,
4131 pre-processor from the outside: raw_input always gets a string,
4121 and prefilter has to process it. We can then redefine prefilter
4132 and prefilter has to process it. We can then redefine prefilter
4122 from the outside and implement extensions for special
4133 from the outside and implement extensions for special
4123 purposes.
4134 purposes.
4124
4135
4125 Today I got one for inputting PhysicalQuantity objects
4136 Today I got one for inputting PhysicalQuantity objects
4126 (from Scientific) without needing any function calls at
4137 (from Scientific) without needing any function calls at
4127 all. Extremely convenient, and it's all done as a user-level
4138 all. Extremely convenient, and it's all done as a user-level
4128 extension (no IPython code was touched). Now instead of:
4139 extension (no IPython code was touched). Now instead of:
4129 a = PhysicalQuantity(4.2,'m/s**2')
4140 a = PhysicalQuantity(4.2,'m/s**2')
4130 one can simply say
4141 one can simply say
4131 a = 4.2 m/s**2
4142 a = 4.2 m/s**2
4132 or even
4143 or even
4133 a = 4.2 m/s^2
4144 a = 4.2 m/s^2
4134
4145
4135 I use this, but it's also a proof of concept: IPython really is
4146 I use this, but it's also a proof of concept: IPython really is
4136 fully user-extensible, even at the level of the parsing of the
4147 fully user-extensible, even at the level of the parsing of the
4137 command line. It's not trivial, but it's perfectly doable.
4148 command line. It's not trivial, but it's perfectly doable.
4138
4149
4139 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4150 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4140 the problem of modules being loaded in the inverse order in which
4151 the problem of modules being loaded in the inverse order in which
4141 they were defined in
4152 they were defined in
4142
4153
4143 * Version 0.1.8 released, 0.1.9 opened for further work.
4154 * Version 0.1.8 released, 0.1.9 opened for further work.
4144
4155
4145 * Added magics pdef, source and file. They respectively show the
4156 * Added magics pdef, source and file. They respectively show the
4146 definition line ('prototype' in C), source code and full python
4157 definition line ('prototype' in C), source code and full python
4147 file for any callable object. The object inspector oinfo uses
4158 file for any callable object. The object inspector oinfo uses
4148 these to show the same information.
4159 these to show the same information.
4149
4160
4150 * Version 0.1.7 released, 0.1.8 opened for further work.
4161 * Version 0.1.7 released, 0.1.8 opened for further work.
4151
4162
4152 * Separated all the magic functions into a class called Magic. The
4163 * Separated all the magic functions into a class called Magic. The
4153 InteractiveShell class was becoming too big for Xemacs to handle
4164 InteractiveShell class was becoming too big for Xemacs to handle
4154 (de-indenting a line would lock it up for 10 seconds while it
4165 (de-indenting a line would lock it up for 10 seconds while it
4155 backtracked on the whole class!)
4166 backtracked on the whole class!)
4156
4167
4157 FIXME: didn't work. It can be done, but right now namespaces are
4168 FIXME: didn't work. It can be done, but right now namespaces are
4158 all messed up. Do it later (reverted it for now, so at least
4169 all messed up. Do it later (reverted it for now, so at least
4159 everything works as before).
4170 everything works as before).
4160
4171
4161 * Got the object introspection system (magic_oinfo) working! I
4172 * Got the object introspection system (magic_oinfo) working! I
4162 think this is pretty much ready for release to Janko, so he can
4173 think this is pretty much ready for release to Janko, so he can
4163 test it for a while and then announce it. Pretty much 100% of what
4174 test it for a while and then announce it. Pretty much 100% of what
4164 I wanted for the 'phase 1' release is ready. Happy, tired.
4175 I wanted for the 'phase 1' release is ready. Happy, tired.
4165
4176
4166 2001-11-12 Fernando Perez <fperez@colorado.edu>
4177 2001-11-12 Fernando Perez <fperez@colorado.edu>
4167
4178
4168 * Version 0.1.6 released, 0.1.7 opened for further work.
4179 * Version 0.1.6 released, 0.1.7 opened for further work.
4169
4180
4170 * Fixed bug in printing: it used to test for truth before
4181 * Fixed bug in printing: it used to test for truth before
4171 printing, so 0 wouldn't print. Now checks for None.
4182 printing, so 0 wouldn't print. Now checks for None.
4172
4183
4173 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4184 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4174 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4185 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4175 reaches by hand into the outputcache. Think of a better way to do
4186 reaches by hand into the outputcache. Think of a better way to do
4176 this later.
4187 this later.
4177
4188
4178 * Various small fixes thanks to Nathan's comments.
4189 * Various small fixes thanks to Nathan's comments.
4179
4190
4180 * Changed magic_pprint to magic_Pprint. This way it doesn't
4191 * Changed magic_pprint to magic_Pprint. This way it doesn't
4181 collide with pprint() and the name is consistent with the command
4192 collide with pprint() and the name is consistent with the command
4182 line option.
4193 line option.
4183
4194
4184 * Changed prompt counter behavior to be fully like
4195 * Changed prompt counter behavior to be fully like
4185 Mathematica's. That is, even input that doesn't return a result
4196 Mathematica's. That is, even input that doesn't return a result
4186 raises the prompt counter. The old behavior was kind of confusing
4197 raises the prompt counter. The old behavior was kind of confusing
4187 (getting the same prompt number several times if the operation
4198 (getting the same prompt number several times if the operation
4188 didn't return a result).
4199 didn't return a result).
4189
4200
4190 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4201 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4191
4202
4192 * Fixed -Classic mode (wasn't working anymore).
4203 * Fixed -Classic mode (wasn't working anymore).
4193
4204
4194 * Added colored prompts using Nathan's new code. Colors are
4205 * Added colored prompts using Nathan's new code. Colors are
4195 currently hardwired, they can be user-configurable. For
4206 currently hardwired, they can be user-configurable. For
4196 developers, they can be chosen in file ipythonlib.py, at the
4207 developers, they can be chosen in file ipythonlib.py, at the
4197 beginning of the CachedOutput class def.
4208 beginning of the CachedOutput class def.
4198
4209
4199 2001-11-11 Fernando Perez <fperez@colorado.edu>
4210 2001-11-11 Fernando Perez <fperez@colorado.edu>
4200
4211
4201 * Version 0.1.5 released, 0.1.6 opened for further work.
4212 * Version 0.1.5 released, 0.1.6 opened for further work.
4202
4213
4203 * Changed magic_env to *return* the environment as a dict (not to
4214 * Changed magic_env to *return* the environment as a dict (not to
4204 print it). This way it prints, but it can also be processed.
4215 print it). This way it prints, but it can also be processed.
4205
4216
4206 * Added Verbose exception reporting to interactive
4217 * Added Verbose exception reporting to interactive
4207 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4218 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4208 traceback. Had to make some changes to the ultraTB file. This is
4219 traceback. Had to make some changes to the ultraTB file. This is
4209 probably the last 'big' thing in my mental todo list. This ties
4220 probably the last 'big' thing in my mental todo list. This ties
4210 in with the next entry:
4221 in with the next entry:
4211
4222
4212 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4223 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4213 has to specify is Plain, Color or Verbose for all exception
4224 has to specify is Plain, Color or Verbose for all exception
4214 handling.
4225 handling.
4215
4226
4216 * Removed ShellServices option. All this can really be done via
4227 * Removed ShellServices option. All this can really be done via
4217 the magic system. It's easier to extend, cleaner and has automatic
4228 the magic system. It's easier to extend, cleaner and has automatic
4218 namespace protection and documentation.
4229 namespace protection and documentation.
4219
4230
4220 2001-11-09 Fernando Perez <fperez@colorado.edu>
4231 2001-11-09 Fernando Perez <fperez@colorado.edu>
4221
4232
4222 * Fixed bug in output cache flushing (missing parameter to
4233 * Fixed bug in output cache flushing (missing parameter to
4223 __init__). Other small bugs fixed (found using pychecker).
4234 __init__). Other small bugs fixed (found using pychecker).
4224
4235
4225 * Version 0.1.4 opened for bugfixing.
4236 * Version 0.1.4 opened for bugfixing.
4226
4237
4227 2001-11-07 Fernando Perez <fperez@colorado.edu>
4238 2001-11-07 Fernando Perez <fperez@colorado.edu>
4228
4239
4229 * Version 0.1.3 released, mainly because of the raw_input bug.
4240 * Version 0.1.3 released, mainly because of the raw_input bug.
4230
4241
4231 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4242 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4232 and when testing for whether things were callable, a call could
4243 and when testing for whether things were callable, a call could
4233 actually be made to certain functions. They would get called again
4244 actually be made to certain functions. They would get called again
4234 once 'really' executed, with a resulting double call. A disaster
4245 once 'really' executed, with a resulting double call. A disaster
4235 in many cases (list.reverse() would never work!).
4246 in many cases (list.reverse() would never work!).
4236
4247
4237 * Removed prefilter() function, moved its code to raw_input (which
4248 * Removed prefilter() function, moved its code to raw_input (which
4238 after all was just a near-empty caller for prefilter). This saves
4249 after all was just a near-empty caller for prefilter). This saves
4239 a function call on every prompt, and simplifies the class a tiny bit.
4250 a function call on every prompt, and simplifies the class a tiny bit.
4240
4251
4241 * Fix _ip to __ip name in magic example file.
4252 * Fix _ip to __ip name in magic example file.
4242
4253
4243 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4254 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4244 work with non-gnu versions of tar.
4255 work with non-gnu versions of tar.
4245
4256
4246 2001-11-06 Fernando Perez <fperez@colorado.edu>
4257 2001-11-06 Fernando Perez <fperez@colorado.edu>
4247
4258
4248 * Version 0.1.2. Just to keep track of the recent changes.
4259 * Version 0.1.2. Just to keep track of the recent changes.
4249
4260
4250 * Fixed nasty bug in output prompt routine. It used to check 'if
4261 * Fixed nasty bug in output prompt routine. It used to check 'if
4251 arg != None...'. Problem is, this fails if arg implements a
4262 arg != None...'. Problem is, this fails if arg implements a
4252 special comparison (__cmp__) which disallows comparing to
4263 special comparison (__cmp__) which disallows comparing to
4253 None. Found it when trying to use the PhysicalQuantity module from
4264 None. Found it when trying to use the PhysicalQuantity module from
4254 ScientificPython.
4265 ScientificPython.
4255
4266
4256 2001-11-05 Fernando Perez <fperez@colorado.edu>
4267 2001-11-05 Fernando Perez <fperez@colorado.edu>
4257
4268
4258 * Also added dirs. Now the pushd/popd/dirs family functions
4269 * Also added dirs. Now the pushd/popd/dirs family functions
4259 basically like the shell, with the added convenience of going home
4270 basically like the shell, with the added convenience of going home
4260 when called with no args.
4271 when called with no args.
4261
4272
4262 * pushd/popd slightly modified to mimic shell behavior more
4273 * pushd/popd slightly modified to mimic shell behavior more
4263 closely.
4274 closely.
4264
4275
4265 * Added env,pushd,popd from ShellServices as magic functions. I
4276 * Added env,pushd,popd from ShellServices as magic functions. I
4266 think the cleanest will be to port all desired functions from
4277 think the cleanest will be to port all desired functions from
4267 ShellServices as magics and remove ShellServices altogether. This
4278 ShellServices as magics and remove ShellServices altogether. This
4268 will provide a single, clean way of adding functionality
4279 will provide a single, clean way of adding functionality
4269 (shell-type or otherwise) to IP.
4280 (shell-type or otherwise) to IP.
4270
4281
4271 2001-11-04 Fernando Perez <fperez@colorado.edu>
4282 2001-11-04 Fernando Perez <fperez@colorado.edu>
4272
4283
4273 * Added .ipython/ directory to sys.path. This way users can keep
4284 * Added .ipython/ directory to sys.path. This way users can keep
4274 customizations there and access them via import.
4285 customizations there and access them via import.
4275
4286
4276 2001-11-03 Fernando Perez <fperez@colorado.edu>
4287 2001-11-03 Fernando Perez <fperez@colorado.edu>
4277
4288
4278 * Opened version 0.1.1 for new changes.
4289 * Opened version 0.1.1 for new changes.
4279
4290
4280 * Changed version number to 0.1.0: first 'public' release, sent to
4291 * Changed version number to 0.1.0: first 'public' release, sent to
4281 Nathan and Janko.
4292 Nathan and Janko.
4282
4293
4283 * Lots of small fixes and tweaks.
4294 * Lots of small fixes and tweaks.
4284
4295
4285 * Minor changes to whos format. Now strings are shown, snipped if
4296 * Minor changes to whos format. Now strings are shown, snipped if
4286 too long.
4297 too long.
4287
4298
4288 * Changed ShellServices to work on __main__ so they show up in @who
4299 * Changed ShellServices to work on __main__ so they show up in @who
4289
4300
4290 * Help also works with ? at the end of a line:
4301 * Help also works with ? at the end of a line:
4291 ?sin and sin?
4302 ?sin and sin?
4292 both produce the same effect. This is nice, as often I use the
4303 both produce the same effect. This is nice, as often I use the
4293 tab-complete to find the name of a method, but I used to then have
4304 tab-complete to find the name of a method, but I used to then have
4294 to go to the beginning of the line to put a ? if I wanted more
4305 to go to the beginning of the line to put a ? if I wanted more
4295 info. Now I can just add the ? and hit return. Convenient.
4306 info. Now I can just add the ? and hit return. Convenient.
4296
4307
4297 2001-11-02 Fernando Perez <fperez@colorado.edu>
4308 2001-11-02 Fernando Perez <fperez@colorado.edu>
4298
4309
4299 * Python version check (>=2.1) added.
4310 * Python version check (>=2.1) added.
4300
4311
4301 * Added LazyPython documentation. At this point the docs are quite
4312 * Added LazyPython documentation. At this point the docs are quite
4302 a mess. A cleanup is in order.
4313 a mess. A cleanup is in order.
4303
4314
4304 * Auto-installer created. For some bizarre reason, the zipfiles
4315 * Auto-installer created. For some bizarre reason, the zipfiles
4305 module isn't working on my system. So I made a tar version
4316 module isn't working on my system. So I made a tar version
4306 (hopefully the command line options in various systems won't kill
4317 (hopefully the command line options in various systems won't kill
4307 me).
4318 me).
4308
4319
4309 * Fixes to Struct in genutils. Now all dictionary-like methods are
4320 * Fixes to Struct in genutils. Now all dictionary-like methods are
4310 protected (reasonably).
4321 protected (reasonably).
4311
4322
4312 * Added pager function to genutils and changed ? to print usage
4323 * Added pager function to genutils and changed ? to print usage
4313 note through it (it was too long).
4324 note through it (it was too long).
4314
4325
4315 * Added the LazyPython functionality. Works great! I changed the
4326 * Added the LazyPython functionality. Works great! I changed the
4316 auto-quote escape to ';', it's on home row and next to '. But
4327 auto-quote escape to ';', it's on home row and next to '. But
4317 both auto-quote and auto-paren (still /) escapes are command-line
4328 both auto-quote and auto-paren (still /) escapes are command-line
4318 parameters.
4329 parameters.
4319
4330
4320
4331
4321 2001-11-01 Fernando Perez <fperez@colorado.edu>
4332 2001-11-01 Fernando Perez <fperez@colorado.edu>
4322
4333
4323 * Version changed to 0.0.7. Fairly large change: configuration now
4334 * Version changed to 0.0.7. Fairly large change: configuration now
4324 is all stored in a directory, by default .ipython. There, all
4335 is all stored in a directory, by default .ipython. There, all
4325 config files have normal looking names (not .names)
4336 config files have normal looking names (not .names)
4326
4337
4327 * Version 0.0.6 Released first to Lucas and Archie as a test
4338 * Version 0.0.6 Released first to Lucas and Archie as a test
4328 run. Since it's the first 'semi-public' release, change version to
4339 run. Since it's the first 'semi-public' release, change version to
4329 > 0.0.6 for any changes now.
4340 > 0.0.6 for any changes now.
4330
4341
4331 * Stuff I had put in the ipplib.py changelog:
4342 * Stuff I had put in the ipplib.py changelog:
4332
4343
4333 Changes to InteractiveShell:
4344 Changes to InteractiveShell:
4334
4345
4335 - Made the usage message a parameter.
4346 - Made the usage message a parameter.
4336
4347
4337 - Require the name of the shell variable to be given. It's a bit
4348 - Require the name of the shell variable to be given. It's a bit
4338 of a hack, but allows the name 'shell' not to be hardwire in the
4349 of a hack, but allows the name 'shell' not to be hardwire in the
4339 magic (@) handler, which is problematic b/c it requires
4350 magic (@) handler, which is problematic b/c it requires
4340 polluting the global namespace with 'shell'. This in turn is
4351 polluting the global namespace with 'shell'. This in turn is
4341 fragile: if a user redefines a variable called shell, things
4352 fragile: if a user redefines a variable called shell, things
4342 break.
4353 break.
4343
4354
4344 - magic @: all functions available through @ need to be defined
4355 - magic @: all functions available through @ need to be defined
4345 as magic_<name>, even though they can be called simply as
4356 as magic_<name>, even though they can be called simply as
4346 @<name>. This allows the special command @magic to gather
4357 @<name>. This allows the special command @magic to gather
4347 information automatically about all existing magic functions,
4358 information automatically about all existing magic functions,
4348 even if they are run-time user extensions, by parsing the shell
4359 even if they are run-time user extensions, by parsing the shell
4349 instance __dict__ looking for special magic_ names.
4360 instance __dict__ looking for special magic_ names.
4350
4361
4351 - mainloop: added *two* local namespace parameters. This allows
4362 - mainloop: added *two* local namespace parameters. This allows
4352 the class to differentiate between parameters which were there
4363 the class to differentiate between parameters which were there
4353 before and after command line initialization was processed. This
4364 before and after command line initialization was processed. This
4354 way, later @who can show things loaded at startup by the
4365 way, later @who can show things loaded at startup by the
4355 user. This trick was necessary to make session saving/reloading
4366 user. This trick was necessary to make session saving/reloading
4356 really work: ideally after saving/exiting/reloading a session,
4367 really work: ideally after saving/exiting/reloading a session,
4357 *everythin* should look the same, including the output of @who. I
4368 *everythin* should look the same, including the output of @who. I
4358 was only able to make this work with this double namespace
4369 was only able to make this work with this double namespace
4359 trick.
4370 trick.
4360
4371
4361 - added a header to the logfile which allows (almost) full
4372 - added a header to the logfile which allows (almost) full
4362 session restoring.
4373 session restoring.
4363
4374
4364 - prepend lines beginning with @ or !, with a and log
4375 - prepend lines beginning with @ or !, with a and log
4365 them. Why? !lines: may be useful to know what you did @lines:
4376 them. Why? !lines: may be useful to know what you did @lines:
4366 they may affect session state. So when restoring a session, at
4377 they may affect session state. So when restoring a session, at
4367 least inform the user of their presence. I couldn't quite get
4378 least inform the user of their presence. I couldn't quite get
4368 them to properly re-execute, but at least the user is warned.
4379 them to properly re-execute, but at least the user is warned.
4369
4380
4370 * Started ChangeLog.
4381 * Started ChangeLog.
General Comments 0
You need to be logged in to leave comments. Login now