##// END OF EJS Templates
- Cleanup [1786], which went in with unfinished stuff by accident....
fperez -
Show More
@@ -1,363 +1,315 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Pdb debugger class.
3 Pdb debugger class.
4
4
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 the command line completion of other programs which include this isn't
6 the command line completion of other programs which include this isn't
7 damaged.
7 damaged.
8
8
9 In the future, this class will be expanded with improvements over the standard
9 In the future, this class will be expanded with improvements over the standard
10 pdb.
10 pdb.
11
11
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 changes. Licensing should therefore be under the standard Python terms. For
13 changes. Licensing should therefore be under the standard Python terms. For
14 details on the PSF (Python Software Foundation) standard license, see:
14 details on the PSF (Python Software Foundation) standard license, see:
15
15
16 http://www.python.org/2.2.3/license.html
16 http://www.python.org/2.2.3/license.html
17
17
18 $Id: Debugger.py 1786 2006-09-27 05:47:28Z fperez $"""
18 $Id: Debugger.py 1787 2006-09-27 06:56:29Z fperez $"""
19
19
20 #*****************************************************************************
20 #*****************************************************************************
21 #
21 #
22 # Since this file is essentially a modified copy of the pdb module which is
22 # Since this file is essentially a modified copy of the pdb module which is
23 # part of the standard Python distribution, I assume that the proper procedure
23 # part of the standard Python distribution, I assume that the proper procedure
24 # is to maintain its copyright as belonging to the Python Software Foundation
24 # is to maintain its copyright as belonging to the Python Software Foundation
25 # (in addition to my own, for all new code).
25 # (in addition to my own, for all new code).
26 #
26 #
27 # Copyright (C) 2001 Python Software Foundation, www.python.org
27 # Copyright (C) 2001 Python Software Foundation, www.python.org
28 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
28 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
29 #
29 #
30 # Distributed under the terms of the BSD License. The full license is in
30 # Distributed under the terms of the BSD License. The full license is in
31 # the file COPYING, distributed as part of this software.
31 # the file COPYING, distributed as part of this software.
32 #
32 #
33 #*****************************************************************************
33 #*****************************************************************************
34
34
35 from IPython import Release
35 from IPython import Release
36 __author__ = '%s <%s>' % Release.authors['Fernando']
36 __author__ = '%s <%s>' % Release.authors['Fernando']
37 __license__ = 'Python'
37 __license__ = 'Python'
38
38
39 import bdb
39 import bdb
40 import cmd
40 import cmd
41 import linecache
41 import linecache
42 import os
42 import os
43 import pdb
43 import pdb
44 import sys
44 import sys
45
45
46 from IPython import PyColorize, ColorANSI
46 from IPython import PyColorize, ColorANSI
47 from IPython.genutils import Term
47 from IPython.genutils import Term
48 from IPython.excolors import ExceptionColors
48 from IPython.excolors import ExceptionColors
49
49
50 def _file_lines(fname):
50 def _file_lines(fname):
51 """Return the contents of a named file as a list of lines.
51 """Return the contents of a named file as a list of lines.
52
52
53 This function never raises an IOError exception: if the file can't be
53 This function never raises an IOError exception: if the file can't be
54 read, it simply returns an empty list."""
54 read, it simply returns an empty list."""
55
55
56 try:
56 try:
57 outfile = open(fname)
57 outfile = open(fname)
58 except IOError:
58 except IOError:
59 return []
59 return []
60 else:
60 else:
61 out = outfile.readlines()
61 out = outfile.readlines()
62 outfile.close()
62 outfile.close()
63 return out
63 return out
64
64
65 class Pdb(pdb.Pdb):
65 class Pdb(pdb.Pdb):
66 """Modified Pdb class, does not load readline."""
66 """Modified Pdb class, does not load readline."""
67
67
68 # Ugly hack: we can't call the parent constructor, because it binds
68 if sys.version[:3] >= '2.5':
69 # readline and breaks tab-completion. This means we have to COPY the
70 # constructor here, and that requires tracking various python versions.
71
72 if sys.version[:3] == '2.5':
73 def __init__(self,color_scheme='NoColor',completekey=None,
69 def __init__(self,color_scheme='NoColor',completekey=None,
74 stdin=None, stdout=None):
70 stdin=None, stdout=None):
75 bdb.Bdb.__init__(self)
76
77 # IPython change
78 # don't load readline
79 cmd.Cmd.__init__(self,completekey,stdin,stdout)
80 #cmd.Cmd.__init__(self, completekey, stdin, stdout)
81 # /IPython change
82
83 if stdout:
84 self.use_rawinput = 0
85 self.prompt = '(Pdb) '
86 self.aliases = {}
87 self.mainpyfile = ''
88 self._wait_for_mainpyfile = 0
89 # Try to load readline if it exists
90 try:
91 import readline
92 except ImportError:
93 pass
94
95 # Read $HOME/.pdbrc and ./.pdbrc
96 self.rcLines = []
97 if 'HOME' in os.environ:
98 envHome = os.environ['HOME']
99 try:
100 rcFile = open(os.path.join(envHome, ".pdbrc"))
101 except IOError:
102 pass
103 else:
104 for line in rcFile.readlines():
105 self.rcLines.append(line)
106 rcFile.close()
107 try:
108 rcFile = open(".pdbrc")
109 except IOError:
110 pass
111 else:
112 for line in rcFile.readlines():
113 self.rcLines.append(line)
114 rcFile.close()
115
116 self.commands = {} # associates a command list to breakpoint numbers
117 self.commands_doprompt = {} # for each bp num, tells if the prompt must be disp. after execing the cmd list
118 self.commands_silent = {} # for each bp num, tells if the stack trace must be disp. after execing the cmd list
119 self.commands_defining = False # True while in the process of defining a command list
120 self.commands_bnum = None # The breakpoint number for which we are defining a list
121
122
71
72 # Parent constructor:
73 pdb.Pdb.__init__(self,completekey,stdin,stdout)
74
123 # IPython changes...
75 # IPython changes...
124
125 self.prompt = 'ipdb> ' # The default prompt is '(Pdb)'
76 self.prompt = 'ipdb> ' # The default prompt is '(Pdb)'
126 self.aliases = {}
77 self.aliases = {}
127
78
128 # Create color table: we copy the default one from the traceback
79 # Create color table: we copy the default one from the traceback
129 # module and add a few attributes needed for debugging
80 # module and add a few attributes needed for debugging
130 self.color_scheme_table = ExceptionColors.copy()
81 self.color_scheme_table = ExceptionColors.copy()
131
82
132 # shorthands
83 # shorthands
133 C = ColorANSI.TermColors
84 C = ColorANSI.TermColors
134 cst = self.color_scheme_table
85 cst = self.color_scheme_table
135
86
136 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
87 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
137 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
88 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
138
89
139 cst['Linux'].colors.breakpoint_enabled = C.LightRed
90 cst['Linux'].colors.breakpoint_enabled = C.LightRed
140 cst['Linux'].colors.breakpoint_disabled = C.Red
91 cst['Linux'].colors.breakpoint_disabled = C.Red
141
92
142 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
93 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
143 cst['LightBG'].colors.breakpoint_disabled = C.Red
94 cst['LightBG'].colors.breakpoint_disabled = C.Red
144
95
145 self.set_colors(color_scheme)
96 self.set_colors(color_scheme)
146
147
97
148 else:
98 else:
149
99 # Ugly hack: for Python 2.3-2.4, we can't call the parent constructor,
100 # because it binds readline and breaks tab-completion. This means we
101 # have to COPY the constructor here.
150 def __init__(self,color_scheme='NoColor'):
102 def __init__(self,color_scheme='NoColor'):
151 bdb.Bdb.__init__(self)
103 bdb.Bdb.__init__(self)
152 cmd.Cmd.__init__(self,completekey=None) # don't load readline
104 cmd.Cmd.__init__(self,completekey=None) # don't load readline
153 self.prompt = 'ipdb> ' # The default prompt is '(Pdb)'
105 self.prompt = 'ipdb> ' # The default prompt is '(Pdb)'
154 self.aliases = {}
106 self.aliases = {}
155
107
156 # These two lines are part of the py2.4 constructor, let's put them
108 # These two lines are part of the py2.4 constructor, let's put them
157 # unconditionally here as they won't cause any problems in 2.3.
109 # unconditionally here as they won't cause any problems in 2.3.
158 self.mainpyfile = ''
110 self.mainpyfile = ''
159 self._wait_for_mainpyfile = 0
111 self._wait_for_mainpyfile = 0
160
112
161 # Read $HOME/.pdbrc and ./.pdbrc
113 # Read $HOME/.pdbrc and ./.pdbrc
162 try:
114 try:
163 self.rcLines = _file_lines(os.path.join(os.environ['HOME'],
115 self.rcLines = _file_lines(os.path.join(os.environ['HOME'],
164 ".pdbrc"))
116 ".pdbrc"))
165 except KeyError:
117 except KeyError:
166 self.rcLines = []
118 self.rcLines = []
167 self.rcLines.extend(_file_lines(".pdbrc"))
119 self.rcLines.extend(_file_lines(".pdbrc"))
168
120
169 # Create color table: we copy the default one from the traceback
121 # Create color table: we copy the default one from the traceback
170 # module and add a few attributes needed for debugging
122 # module and add a few attributes needed for debugging
171 self.color_scheme_table = ExceptionColors.copy()
123 self.color_scheme_table = ExceptionColors.copy()
172
124
173 # shorthands
125 # shorthands
174 C = ColorANSI.TermColors
126 C = ColorANSI.TermColors
175 cst = self.color_scheme_table
127 cst = self.color_scheme_table
176
128
177 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
129 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
178 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
130 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
179
131
180 cst['Linux'].colors.breakpoint_enabled = C.LightRed
132 cst['Linux'].colors.breakpoint_enabled = C.LightRed
181 cst['Linux'].colors.breakpoint_disabled = C.Red
133 cst['Linux'].colors.breakpoint_disabled = C.Red
182
134
183 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
135 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
184 cst['LightBG'].colors.breakpoint_disabled = C.Red
136 cst['LightBG'].colors.breakpoint_disabled = C.Red
185
137
186 self.set_colors(color_scheme)
138 self.set_colors(color_scheme)
187
139
188 def set_colors(self, scheme):
140 def set_colors(self, scheme):
189 """Shorthand access to the color table scheme selector method."""
141 """Shorthand access to the color table scheme selector method."""
190 self.color_scheme_table.set_active_scheme(scheme)
142 self.color_scheme_table.set_active_scheme(scheme)
191
143
192 def interaction(self, frame, traceback):
144 def interaction(self, frame, traceback):
193 __IPYTHON__.set_completer_frame(frame)
145 __IPYTHON__.set_completer_frame(frame)
194 pdb.Pdb.interaction(self, frame, traceback)
146 pdb.Pdb.interaction(self, frame, traceback)
195
147
196 def do_up(self, arg):
148 def do_up(self, arg):
197 pdb.Pdb.do_up(self, arg)
149 pdb.Pdb.do_up(self, arg)
198 __IPYTHON__.set_completer_frame(self.curframe)
150 __IPYTHON__.set_completer_frame(self.curframe)
199 do_u = do_up
151 do_u = do_up
200
152
201 def do_down(self, arg):
153 def do_down(self, arg):
202 pdb.Pdb.do_down(self, arg)
154 pdb.Pdb.do_down(self, arg)
203 __IPYTHON__.set_completer_frame(self.curframe)
155 __IPYTHON__.set_completer_frame(self.curframe)
204 do_d = do_down
156 do_d = do_down
205
157
206 def postloop(self):
158 def postloop(self):
207 __IPYTHON__.set_completer_frame(None)
159 __IPYTHON__.set_completer_frame(None)
208
160
209 def print_stack_trace(self):
161 def print_stack_trace(self):
210 try:
162 try:
211 for frame_lineno in self.stack:
163 for frame_lineno in self.stack:
212 self.print_stack_entry(frame_lineno, context = 5)
164 self.print_stack_entry(frame_lineno, context = 5)
213 except KeyboardInterrupt:
165 except KeyboardInterrupt:
214 pass
166 pass
215
167
216 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
168 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
217 context = 3):
169 context = 3):
218 frame, lineno = frame_lineno
170 frame, lineno = frame_lineno
219 print >>Term.cout, self.format_stack_entry(frame_lineno, '', context)
171 print >>Term.cout, self.format_stack_entry(frame_lineno, '', context)
220
172
221 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
173 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
222 import linecache, repr
174 import linecache, repr
223
175
224 ret = []
176 ret = []
225
177
226 Colors = self.color_scheme_table.active_colors
178 Colors = self.color_scheme_table.active_colors
227 ColorsNormal = Colors.Normal
179 ColorsNormal = Colors.Normal
228 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
180 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
229 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
181 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
230 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
182 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
231 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
183 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
232 ColorsNormal)
184 ColorsNormal)
233
185
234 frame, lineno = frame_lineno
186 frame, lineno = frame_lineno
235
187
236 return_value = ''
188 return_value = ''
237 if '__return__' in frame.f_locals:
189 if '__return__' in frame.f_locals:
238 rv = frame.f_locals['__return__']
190 rv = frame.f_locals['__return__']
239 #return_value += '->'
191 #return_value += '->'
240 return_value += repr.repr(rv) + '\n'
192 return_value += repr.repr(rv) + '\n'
241 ret.append(return_value)
193 ret.append(return_value)
242
194
243 #s = filename + '(' + `lineno` + ')'
195 #s = filename + '(' + `lineno` + ')'
244 filename = self.canonic(frame.f_code.co_filename)
196 filename = self.canonic(frame.f_code.co_filename)
245 link = tpl_link % filename
197 link = tpl_link % filename
246
198
247 if frame.f_code.co_name:
199 if frame.f_code.co_name:
248 func = frame.f_code.co_name
200 func = frame.f_code.co_name
249 else:
201 else:
250 func = "<lambda>"
202 func = "<lambda>"
251
203
252 call = ''
204 call = ''
253 if func != '?':
205 if func != '?':
254 if '__args__' in frame.f_locals:
206 if '__args__' in frame.f_locals:
255 args = repr.repr(frame.f_locals['__args__'])
207 args = repr.repr(frame.f_locals['__args__'])
256 else:
208 else:
257 args = '()'
209 args = '()'
258 call = tpl_call % (func, args)
210 call = tpl_call % (func, args)
259
211
260 # The level info should be generated in the same format pdb uses, to
212 # The level info should be generated in the same format pdb uses, to
261 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
213 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
262 ret.append('> %s(%s)%s\n' % (link,lineno,call))
214 ret.append('> %s(%s)%s\n' % (link,lineno,call))
263
215
264 start = lineno - 1 - context//2
216 start = lineno - 1 - context//2
265 lines = linecache.getlines(filename)
217 lines = linecache.getlines(filename)
266 start = max(start, 0)
218 start = max(start, 0)
267 start = min(start, len(lines) - context)
219 start = min(start, len(lines) - context)
268 lines = lines[start : start + context]
220 lines = lines[start : start + context]
269
221
270 for i,line in enumerate(lines):
222 for i,line in enumerate(lines):
271 show_arrow = (start + 1 + i == lineno)
223 show_arrow = (start + 1 + i == lineno)
272 ret.append(self.__format_line(tpl_line_em, filename,
224 ret.append(self.__format_line(tpl_line_em, filename,
273 start + 1 + i, line,
225 start + 1 + i, line,
274 arrow = show_arrow) )
226 arrow = show_arrow) )
275
227
276 return ''.join(ret)
228 return ''.join(ret)
277
229
278 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
230 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
279 bp_mark = ""
231 bp_mark = ""
280 bp_mark_color = ""
232 bp_mark_color = ""
281
233
282 bp = None
234 bp = None
283 if lineno in self.get_file_breaks(filename):
235 if lineno in self.get_file_breaks(filename):
284 bps = self.get_breaks(filename, lineno)
236 bps = self.get_breaks(filename, lineno)
285 bp = bps[-1]
237 bp = bps[-1]
286
238
287 if bp:
239 if bp:
288 Colors = self.color_scheme_table.active_colors
240 Colors = self.color_scheme_table.active_colors
289 bp_mark = str(bp.number)
241 bp_mark = str(bp.number)
290 bp_mark_color = Colors.breakpoint_enabled
242 bp_mark_color = Colors.breakpoint_enabled
291 if not bp.enabled:
243 if not bp.enabled:
292 bp_mark_color = Colors.breakpoint_disabled
244 bp_mark_color = Colors.breakpoint_disabled
293
245
294 numbers_width = 7
246 numbers_width = 7
295 if arrow:
247 if arrow:
296 # This is the line with the error
248 # This is the line with the error
297 pad = numbers_width - len(str(lineno)) - len(bp_mark)
249 pad = numbers_width - len(str(lineno)) - len(bp_mark)
298 if pad >= 3:
250 if pad >= 3:
299 marker = '-'*(pad-3) + '-> '
251 marker = '-'*(pad-3) + '-> '
300 elif pad == 2:
252 elif pad == 2:
301 marker = '> '
253 marker = '> '
302 elif pad == 1:
254 elif pad == 1:
303 marker = '>'
255 marker = '>'
304 else:
256 else:
305 marker = ''
257 marker = ''
306 num = '%s%s' % (marker, str(lineno))
258 num = '%s%s' % (marker, str(lineno))
307 line = tpl_line % (bp_mark_color + bp_mark, num, line)
259 line = tpl_line % (bp_mark_color + bp_mark, num, line)
308 else:
260 else:
309 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
261 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
310 line = tpl_line % (bp_mark_color + bp_mark, num, line)
262 line = tpl_line % (bp_mark_color + bp_mark, num, line)
311
263
312 return line
264 return line
313
265
314 def do_list(self, arg):
266 def do_list(self, arg):
315 self.lastcmd = 'list'
267 self.lastcmd = 'list'
316 last = None
268 last = None
317 if arg:
269 if arg:
318 try:
270 try:
319 x = eval(arg, {}, {})
271 x = eval(arg, {}, {})
320 if type(x) == type(()):
272 if type(x) == type(()):
321 first, last = x
273 first, last = x
322 first = int(first)
274 first = int(first)
323 last = int(last)
275 last = int(last)
324 if last < first:
276 if last < first:
325 # Assume it's a count
277 # Assume it's a count
326 last = first + last
278 last = first + last
327 else:
279 else:
328 first = max(1, int(x) - 5)
280 first = max(1, int(x) - 5)
329 except:
281 except:
330 print '*** Error in argument:', `arg`
282 print '*** Error in argument:', `arg`
331 return
283 return
332 elif self.lineno is None:
284 elif self.lineno is None:
333 first = max(1, self.curframe.f_lineno - 5)
285 first = max(1, self.curframe.f_lineno - 5)
334 else:
286 else:
335 first = self.lineno + 1
287 first = self.lineno + 1
336 if last is None:
288 if last is None:
337 last = first + 10
289 last = first + 10
338 filename = self.curframe.f_code.co_filename
290 filename = self.curframe.f_code.co_filename
339 try:
291 try:
340 Colors = self.color_scheme_table.active_colors
292 Colors = self.color_scheme_table.active_colors
341 ColorsNormal = Colors.Normal
293 ColorsNormal = Colors.Normal
342 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
294 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
343 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
295 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
344 src = []
296 src = []
345 for lineno in range(first, last+1):
297 for lineno in range(first, last+1):
346 line = linecache.getline(filename, lineno)
298 line = linecache.getline(filename, lineno)
347 if not line:
299 if not line:
348 break
300 break
349
301
350 if lineno == self.curframe.f_lineno:
302 if lineno == self.curframe.f_lineno:
351 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
303 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
352 else:
304 else:
353 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
305 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
354
306
355 src.append(line)
307 src.append(line)
356 self.lineno = lineno
308 self.lineno = lineno
357
309
358 print >>Term.cout, ''.join(src)
310 print >>Term.cout, ''.join(src)
359
311
360 except KeyboardInterrupt:
312 except KeyboardInterrupt:
361 pass
313 pass
362
314
363 do_l = do_list
315 do_l = do_list
@@ -1,2990 +1,2991 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3
3
4 $Id: Magic.py 1386 2006-07-08 09:32:30Z vivainio $"""
4 $Id: Magic.py 1787 2006-09-27 06:56:29Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import shlex
29 import shlex
30 import sys
30 import sys
31 import re
31 import re
32 import tempfile
32 import tempfile
33 import time
33 import time
34 import cPickle as pickle
34 import cPickle as pickle
35 import textwrap
35 import textwrap
36 from cStringIO import StringIO
36 from cStringIO import StringIO
37 from getopt import getopt,GetoptError
37 from getopt import getopt,GetoptError
38 from pprint import pprint, pformat
38 from pprint import pprint, pformat
39
39
40 # profile isn't bundled by default in Debian for license reasons
40 # profile isn't bundled by default in Debian for license reasons
41 try:
41 try:
42 import profile,pstats
42 import profile,pstats
43 except ImportError:
43 except ImportError:
44 profile = pstats = None
44 profile = pstats = None
45
45
46 # Homebrewed
46 # Homebrewed
47 import IPython
47 import IPython
48 from IPython import Debugger, OInspect, wildcard
48 from IPython import Debugger, OInspect, wildcard
49 from IPython.FakeModule import FakeModule
49 from IPython.FakeModule import FakeModule
50 from IPython.Itpl import Itpl, itpl, printpl,itplns
50 from IPython.Itpl import Itpl, itpl, printpl,itplns
51 from IPython.PyColorize import Parser
51 from IPython.PyColorize import Parser
52 from IPython.ipstruct import Struct
52 from IPython.ipstruct import Struct
53 from IPython.macro import Macro
53 from IPython.macro import Macro
54 from IPython.genutils import *
54 from IPython.genutils import *
55 from IPython import platutils
55 from IPython import platutils
56
56
57 #***************************************************************************
57 #***************************************************************************
58 # Utility functions
58 # Utility functions
59 def on_off(tag):
59 def on_off(tag):
60 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
60 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
61 return ['OFF','ON'][tag]
61 return ['OFF','ON'][tag]
62
62
63 class Bunch: pass
63 class Bunch: pass
64
64
65 #***************************************************************************
65 #***************************************************************************
66 # Main class implementing Magic functionality
66 # Main class implementing Magic functionality
67 class Magic:
67 class Magic:
68 """Magic functions for InteractiveShell.
68 """Magic functions for InteractiveShell.
69
69
70 Shell functions which can be reached as %function_name. All magic
70 Shell functions which can be reached as %function_name. All magic
71 functions should accept a string, which they can parse for their own
71 functions should accept a string, which they can parse for their own
72 needs. This can make some functions easier to type, eg `%cd ../`
72 needs. This can make some functions easier to type, eg `%cd ../`
73 vs. `%cd("../")`
73 vs. `%cd("../")`
74
74
75 ALL definitions MUST begin with the prefix magic_. The user won't need it
75 ALL definitions MUST begin with the prefix magic_. The user won't need it
76 at the command line, but it is is needed in the definition. """
76 at the command line, but it is is needed in the definition. """
77
77
78 # class globals
78 # class globals
79 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
79 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
80 'Automagic is ON, % prefix NOT needed for magic functions.']
80 'Automagic is ON, % prefix NOT needed for magic functions.']
81
81
82 #......................................................................
82 #......................................................................
83 # some utility functions
83 # some utility functions
84
84
85 def __init__(self,shell):
85 def __init__(self,shell):
86
86
87 self.options_table = {}
87 self.options_table = {}
88 if profile is None:
88 if profile is None:
89 self.magic_prun = self.profile_missing_notice
89 self.magic_prun = self.profile_missing_notice
90 self.shell = shell
90 self.shell = shell
91
91
92 # namespace for holding state we may need
92 # namespace for holding state we may need
93 self._magic_state = Bunch()
93 self._magic_state = Bunch()
94
94
95 def profile_missing_notice(self, *args, **kwargs):
95 def profile_missing_notice(self, *args, **kwargs):
96 error("""\
96 error("""\
97 The profile module could not be found. If you are a Debian user,
97 The profile module could not be found. If you are a Debian user,
98 it has been removed from the standard Debian package because of its non-free
98 it has been removed from the standard Debian package because of its non-free
99 license. To use profiling, please install"python2.3-profiler" from non-free.""")
99 license. To use profiling, please install"python2.3-profiler" from non-free.""")
100
100
101 def default_option(self,fn,optstr):
101 def default_option(self,fn,optstr):
102 """Make an entry in the options_table for fn, with value optstr"""
102 """Make an entry in the options_table for fn, with value optstr"""
103
103
104 if fn not in self.lsmagic():
104 if fn not in self.lsmagic():
105 error("%s is not a magic function" % fn)
105 error("%s is not a magic function" % fn)
106 self.options_table[fn] = optstr
106 self.options_table[fn] = optstr
107
107
108 def lsmagic(self):
108 def lsmagic(self):
109 """Return a list of currently available magic functions.
109 """Return a list of currently available magic functions.
110
110
111 Gives a list of the bare names after mangling (['ls','cd', ...], not
111 Gives a list of the bare names after mangling (['ls','cd', ...], not
112 ['magic_ls','magic_cd',...]"""
112 ['magic_ls','magic_cd',...]"""
113
113
114 # FIXME. This needs a cleanup, in the way the magics list is built.
114 # FIXME. This needs a cleanup, in the way the magics list is built.
115
115
116 # magics in class definition
116 # magics in class definition
117 class_magic = lambda fn: fn.startswith('magic_') and \
117 class_magic = lambda fn: fn.startswith('magic_') and \
118 callable(Magic.__dict__[fn])
118 callable(Magic.__dict__[fn])
119 # in instance namespace (run-time user additions)
119 # in instance namespace (run-time user additions)
120 inst_magic = lambda fn: fn.startswith('magic_') and \
120 inst_magic = lambda fn: fn.startswith('magic_') and \
121 callable(self.__dict__[fn])
121 callable(self.__dict__[fn])
122 # and bound magics by user (so they can access self):
122 # and bound magics by user (so they can access self):
123 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
123 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
124 callable(self.__class__.__dict__[fn])
124 callable(self.__class__.__dict__[fn])
125 magics = filter(class_magic,Magic.__dict__.keys()) + \
125 magics = filter(class_magic,Magic.__dict__.keys()) + \
126 filter(inst_magic,self.__dict__.keys()) + \
126 filter(inst_magic,self.__dict__.keys()) + \
127 filter(inst_bound_magic,self.__class__.__dict__.keys())
127 filter(inst_bound_magic,self.__class__.__dict__.keys())
128 out = []
128 out = []
129 for fn in magics:
129 for fn in magics:
130 out.append(fn.replace('magic_','',1))
130 out.append(fn.replace('magic_','',1))
131 out.sort()
131 out.sort()
132 return out
132 return out
133
133
134 def extract_input_slices(self,slices,raw=False):
134 def extract_input_slices(self,slices,raw=False):
135 """Return as a string a set of input history slices.
135 """Return as a string a set of input history slices.
136
136
137 Inputs:
137 Inputs:
138
138
139 - slices: the set of slices is given as a list of strings (like
139 - slices: the set of slices is given as a list of strings (like
140 ['1','4:8','9'], since this function is for use by magic functions
140 ['1','4:8','9'], since this function is for use by magic functions
141 which get their arguments as strings.
141 which get their arguments as strings.
142
142
143 Optional inputs:
143 Optional inputs:
144
144
145 - raw(False): by default, the processed input is used. If this is
145 - raw(False): by default, the processed input is used. If this is
146 true, the raw input history is used instead.
146 true, the raw input history is used instead.
147
147
148 Note that slices can be called with two notations:
148 Note that slices can be called with two notations:
149
149
150 N:M -> standard python form, means including items N...(M-1).
150 N:M -> standard python form, means including items N...(M-1).
151
151
152 N-M -> include items N..M (closed endpoint)."""
152 N-M -> include items N..M (closed endpoint)."""
153
153
154 if raw:
154 if raw:
155 hist = self.shell.input_hist_raw
155 hist = self.shell.input_hist_raw
156 else:
156 else:
157 hist = self.shell.input_hist
157 hist = self.shell.input_hist
158
158
159 cmds = []
159 cmds = []
160 for chunk in slices:
160 for chunk in slices:
161 if ':' in chunk:
161 if ':' in chunk:
162 ini,fin = map(int,chunk.split(':'))
162 ini,fin = map(int,chunk.split(':'))
163 elif '-' in chunk:
163 elif '-' in chunk:
164 ini,fin = map(int,chunk.split('-'))
164 ini,fin = map(int,chunk.split('-'))
165 fin += 1
165 fin += 1
166 else:
166 else:
167 ini = int(chunk)
167 ini = int(chunk)
168 fin = ini+1
168 fin = ini+1
169 cmds.append(hist[ini:fin])
169 cmds.append(hist[ini:fin])
170 return cmds
170 return cmds
171
171
172 def _ofind(self,oname):
172 def _ofind(self,oname):
173 """Find an object in the available namespaces.
173 """Find an object in the available namespaces.
174
174
175 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
175 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
176
176
177 Has special code to detect magic functions.
177 Has special code to detect magic functions.
178 """
178 """
179
179
180 oname = oname.strip()
180 oname = oname.strip()
181
181
182 # Namespaces to search in:
182 # Namespaces to search in:
183 user_ns = self.shell.user_ns
183 user_ns = self.shell.user_ns
184 internal_ns = self.shell.internal_ns
184 internal_ns = self.shell.internal_ns
185 builtin_ns = __builtin__.__dict__
185 builtin_ns = __builtin__.__dict__
186 alias_ns = self.shell.alias_table
186 alias_ns = self.shell.alias_table
187
187
188 # Put them in a list. The order is important so that we find things in
188 # Put them in a list. The order is important so that we find things in
189 # the same order that Python finds them.
189 # the same order that Python finds them.
190 namespaces = [ ('Interactive',user_ns),
190 namespaces = [ ('Interactive',user_ns),
191 ('IPython internal',internal_ns),
191 ('IPython internal',internal_ns),
192 ('Python builtin',builtin_ns),
192 ('Python builtin',builtin_ns),
193 ('Alias',alias_ns),
193 ('Alias',alias_ns),
194 ]
194 ]
195
195
196 # initialize results to 'null'
196 # initialize results to 'null'
197 found = 0; obj = None; ospace = None; ds = None;
197 found = 0; obj = None; ospace = None; ds = None;
198 ismagic = 0; isalias = 0; parent = None
198 ismagic = 0; isalias = 0; parent = None
199
199
200 # Look for the given name by splitting it in parts. If the head is
200 # Look for the given name by splitting it in parts. If the head is
201 # found, then we look for all the remaining parts as members, and only
201 # found, then we look for all the remaining parts as members, and only
202 # declare success if we can find them all.
202 # declare success if we can find them all.
203 oname_parts = oname.split('.')
203 oname_parts = oname.split('.')
204 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
204 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
205 for nsname,ns in namespaces:
205 for nsname,ns in namespaces:
206 try:
206 try:
207 obj = ns[oname_head]
207 obj = ns[oname_head]
208 except KeyError:
208 except KeyError:
209 continue
209 continue
210 else:
210 else:
211 for part in oname_rest:
211 for part in oname_rest:
212 try:
212 try:
213 parent = obj
213 parent = obj
214 obj = getattr(obj,part)
214 obj = getattr(obj,part)
215 except:
215 except:
216 # Blanket except b/c some badly implemented objects
216 # Blanket except b/c some badly implemented objects
217 # allow __getattr__ to raise exceptions other than
217 # allow __getattr__ to raise exceptions other than
218 # AttributeError, which then crashes IPython.
218 # AttributeError, which then crashes IPython.
219 break
219 break
220 else:
220 else:
221 # If we finish the for loop (no break), we got all members
221 # If we finish the for loop (no break), we got all members
222 found = 1
222 found = 1
223 ospace = nsname
223 ospace = nsname
224 if ns == alias_ns:
224 if ns == alias_ns:
225 isalias = 1
225 isalias = 1
226 break # namespace loop
226 break # namespace loop
227
227
228 # Try to see if it's magic
228 # Try to see if it's magic
229 if not found:
229 if not found:
230 if oname.startswith(self.shell.ESC_MAGIC):
230 if oname.startswith(self.shell.ESC_MAGIC):
231 oname = oname[1:]
231 oname = oname[1:]
232 obj = getattr(self,'magic_'+oname,None)
232 obj = getattr(self,'magic_'+oname,None)
233 if obj is not None:
233 if obj is not None:
234 found = 1
234 found = 1
235 ospace = 'IPython internal'
235 ospace = 'IPython internal'
236 ismagic = 1
236 ismagic = 1
237
237
238 # Last try: special-case some literals like '', [], {}, etc:
238 # Last try: special-case some literals like '', [], {}, etc:
239 if not found and oname_head in ["''",'""','[]','{}','()']:
239 if not found and oname_head in ["''",'""','[]','{}','()']:
240 obj = eval(oname_head)
240 obj = eval(oname_head)
241 found = 1
241 found = 1
242 ospace = 'Interactive'
242 ospace = 'Interactive'
243
243
244 return {'found':found, 'obj':obj, 'namespace':ospace,
244 return {'found':found, 'obj':obj, 'namespace':ospace,
245 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
245 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
246
246
247 def arg_err(self,func):
247 def arg_err(self,func):
248 """Print docstring if incorrect arguments were passed"""
248 """Print docstring if incorrect arguments were passed"""
249 print 'Error in arguments:'
249 print 'Error in arguments:'
250 print OInspect.getdoc(func)
250 print OInspect.getdoc(func)
251
251
252 def format_latex(self,strng):
252 def format_latex(self,strng):
253 """Format a string for latex inclusion."""
253 """Format a string for latex inclusion."""
254
254
255 # Characters that need to be escaped for latex:
255 # Characters that need to be escaped for latex:
256 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
256 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
257 # Magic command names as headers:
257 # Magic command names as headers:
258 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
258 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
259 re.MULTILINE)
259 re.MULTILINE)
260 # Magic commands
260 # Magic commands
261 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
261 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
262 re.MULTILINE)
262 re.MULTILINE)
263 # Paragraph continue
263 # Paragraph continue
264 par_re = re.compile(r'\\$',re.MULTILINE)
264 par_re = re.compile(r'\\$',re.MULTILINE)
265
265
266 # The "\n" symbol
266 # The "\n" symbol
267 newline_re = re.compile(r'\\n')
267 newline_re = re.compile(r'\\n')
268
268
269 # Now build the string for output:
269 # Now build the string for output:
270 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
270 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
271 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
271 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
272 strng)
272 strng)
273 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
273 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
274 strng = par_re.sub(r'\\\\',strng)
274 strng = par_re.sub(r'\\\\',strng)
275 strng = escape_re.sub(r'\\\1',strng)
275 strng = escape_re.sub(r'\\\1',strng)
276 strng = newline_re.sub(r'\\textbackslash{}n',strng)
276 strng = newline_re.sub(r'\\textbackslash{}n',strng)
277 return strng
277 return strng
278
278
279 def format_screen(self,strng):
279 def format_screen(self,strng):
280 """Format a string for screen printing.
280 """Format a string for screen printing.
281
281
282 This removes some latex-type format codes."""
282 This removes some latex-type format codes."""
283 # Paragraph continue
283 # Paragraph continue
284 par_re = re.compile(r'\\$',re.MULTILINE)
284 par_re = re.compile(r'\\$',re.MULTILINE)
285 strng = par_re.sub('',strng)
285 strng = par_re.sub('',strng)
286 return strng
286 return strng
287
287
288 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
288 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
289 """Parse options passed to an argument string.
289 """Parse options passed to an argument string.
290
290
291 The interface is similar to that of getopt(), but it returns back a
291 The interface is similar to that of getopt(), but it returns back a
292 Struct with the options as keys and the stripped argument string still
292 Struct with the options as keys and the stripped argument string still
293 as a string.
293 as a string.
294
294
295 arg_str is quoted as a true sys.argv vector by using shlex.split.
295 arg_str is quoted as a true sys.argv vector by using shlex.split.
296 This allows us to easily expand variables, glob files, quote
296 This allows us to easily expand variables, glob files, quote
297 arguments, etc.
297 arguments, etc.
298
298
299 Options:
299 Options:
300 -mode: default 'string'. If given as 'list', the argument string is
300 -mode: default 'string'. If given as 'list', the argument string is
301 returned as a list (split on whitespace) instead of a string.
301 returned as a list (split on whitespace) instead of a string.
302
302
303 -list_all: put all option values in lists. Normally only options
303 -list_all: put all option values in lists. Normally only options
304 appearing more than once are put in a list."""
304 appearing more than once are put in a list."""
305
305
306 # inject default options at the beginning of the input line
306 # inject default options at the beginning of the input line
307 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
307 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
308 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
308 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
309
309
310 mode = kw.get('mode','string')
310 mode = kw.get('mode','string')
311 if mode not in ['string','list']:
311 if mode not in ['string','list']:
312 raise ValueError,'incorrect mode given: %s' % mode
312 raise ValueError,'incorrect mode given: %s' % mode
313 # Get options
313 # Get options
314 list_all = kw.get('list_all',0)
314 list_all = kw.get('list_all',0)
315
315
316 # Check if we have more than one argument to warrant extra processing:
316 # Check if we have more than one argument to warrant extra processing:
317 odict = {} # Dictionary with options
317 odict = {} # Dictionary with options
318 args = arg_str.split()
318 args = arg_str.split()
319 if len(args) >= 1:
319 if len(args) >= 1:
320 # If the list of inputs only has 0 or 1 thing in it, there's no
320 # If the list of inputs only has 0 or 1 thing in it, there's no
321 # need to look for options
321 # need to look for options
322 argv = shlex.split(arg_str)
322 argv = shlex.split(arg_str)
323 # Do regular option processing
323 # Do regular option processing
324 try:
324 try:
325 opts,args = getopt(argv,opt_str,*long_opts)
325 opts,args = getopt(argv,opt_str,*long_opts)
326 except GetoptError,e:
326 except GetoptError,e:
327 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
327 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
328 " ".join(long_opts)))
328 " ".join(long_opts)))
329 for o,a in opts:
329 for o,a in opts:
330 if o.startswith('--'):
330 if o.startswith('--'):
331 o = o[2:]
331 o = o[2:]
332 else:
332 else:
333 o = o[1:]
333 o = o[1:]
334 try:
334 try:
335 odict[o].append(a)
335 odict[o].append(a)
336 except AttributeError:
336 except AttributeError:
337 odict[o] = [odict[o],a]
337 odict[o] = [odict[o],a]
338 except KeyError:
338 except KeyError:
339 if list_all:
339 if list_all:
340 odict[o] = [a]
340 odict[o] = [a]
341 else:
341 else:
342 odict[o] = a
342 odict[o] = a
343
343
344 # Prepare opts,args for return
344 # Prepare opts,args for return
345 opts = Struct(odict)
345 opts = Struct(odict)
346 if mode == 'string':
346 if mode == 'string':
347 args = ' '.join(args)
347 args = ' '.join(args)
348
348
349 return opts,args
349 return opts,args
350
350
351 #......................................................................
351 #......................................................................
352 # And now the actual magic functions
352 # And now the actual magic functions
353
353
354 # Functions for IPython shell work (vars,funcs, config, etc)
354 # Functions for IPython shell work (vars,funcs, config, etc)
355 def magic_lsmagic(self, parameter_s = ''):
355 def magic_lsmagic(self, parameter_s = ''):
356 """List currently available magic functions."""
356 """List currently available magic functions."""
357 mesc = self.shell.ESC_MAGIC
357 mesc = self.shell.ESC_MAGIC
358 print 'Available magic functions:\n'+mesc+\
358 print 'Available magic functions:\n'+mesc+\
359 (' '+mesc).join(self.lsmagic())
359 (' '+mesc).join(self.lsmagic())
360 print '\n' + Magic.auto_status[self.shell.rc.automagic]
360 print '\n' + Magic.auto_status[self.shell.rc.automagic]
361 return None
361 return None
362
362
363 def magic_magic(self, parameter_s = ''):
363 def magic_magic(self, parameter_s = ''):
364 """Print information about the magic function system."""
364 """Print information about the magic function system."""
365
365
366 mode = ''
366 mode = ''
367 try:
367 try:
368 if parameter_s.split()[0] == '-latex':
368 if parameter_s.split()[0] == '-latex':
369 mode = 'latex'
369 mode = 'latex'
370 if parameter_s.split()[0] == '-brief':
370 if parameter_s.split()[0] == '-brief':
371 mode = 'brief'
371 mode = 'brief'
372 except:
372 except:
373 pass
373 pass
374
374
375 magic_docs = []
375 magic_docs = []
376 for fname in self.lsmagic():
376 for fname in self.lsmagic():
377 mname = 'magic_' + fname
377 mname = 'magic_' + fname
378 for space in (Magic,self,self.__class__):
378 for space in (Magic,self,self.__class__):
379 try:
379 try:
380 fn = space.__dict__[mname]
380 fn = space.__dict__[mname]
381 except KeyError:
381 except KeyError:
382 pass
382 pass
383 else:
383 else:
384 break
384 break
385 if mode == 'brief':
385 if mode == 'brief':
386 # only first line
386 # only first line
387 fndoc = fn.__doc__.split('\n',1)[0]
387 fndoc = fn.__doc__.split('\n',1)[0]
388 else:
388 else:
389 fndoc = fn.__doc__
389 fndoc = fn.__doc__
390
390
391 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
391 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
392 fname,fndoc))
392 fname,fndoc))
393 magic_docs = ''.join(magic_docs)
393 magic_docs = ''.join(magic_docs)
394
394
395 if mode == 'latex':
395 if mode == 'latex':
396 print self.format_latex(magic_docs)
396 print self.format_latex(magic_docs)
397 return
397 return
398 else:
398 else:
399 magic_docs = self.format_screen(magic_docs)
399 magic_docs = self.format_screen(magic_docs)
400 if mode == 'brief':
400 if mode == 'brief':
401 return magic_docs
401 return magic_docs
402
402
403 outmsg = """
403 outmsg = """
404 IPython's 'magic' functions
404 IPython's 'magic' functions
405 ===========================
405 ===========================
406
406
407 The magic function system provides a series of functions which allow you to
407 The magic function system provides a series of functions which allow you to
408 control the behavior of IPython itself, plus a lot of system-type
408 control the behavior of IPython itself, plus a lot of system-type
409 features. All these functions are prefixed with a % character, but parameters
409 features. All these functions are prefixed with a % character, but parameters
410 are given without parentheses or quotes.
410 are given without parentheses or quotes.
411
411
412 NOTE: If you have 'automagic' enabled (via the command line option or with the
412 NOTE: If you have 'automagic' enabled (via the command line option or with the
413 %automagic function), you don't need to type in the % explicitly. By default,
413 %automagic function), you don't need to type in the % explicitly. By default,
414 IPython ships with automagic on, so you should only rarely need the % escape.
414 IPython ships with automagic on, so you should only rarely need the % escape.
415
415
416 Example: typing '%cd mydir' (without the quotes) changes you working directory
416 Example: typing '%cd mydir' (without the quotes) changes you working directory
417 to 'mydir', if it exists.
417 to 'mydir', if it exists.
418
418
419 You can define your own magic functions to extend the system. See the supplied
419 You can define your own magic functions to extend the system. See the supplied
420 ipythonrc and example-magic.py files for details (in your ipython
420 ipythonrc and example-magic.py files for details (in your ipython
421 configuration directory, typically $HOME/.ipython/).
421 configuration directory, typically $HOME/.ipython/).
422
422
423 You can also define your own aliased names for magic functions. In your
423 You can also define your own aliased names for magic functions. In your
424 ipythonrc file, placing a line like:
424 ipythonrc file, placing a line like:
425
425
426 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
426 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
427
427
428 will define %pf as a new name for %profile.
428 will define %pf as a new name for %profile.
429
429
430 You can also call magics in code using the ipmagic() function, which IPython
430 You can also call magics in code using the ipmagic() function, which IPython
431 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
431 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
432
432
433 For a list of the available magic functions, use %lsmagic. For a description
433 For a list of the available magic functions, use %lsmagic. For a description
434 of any of them, type %magic_name?, e.g. '%cd?'.
434 of any of them, type %magic_name?, e.g. '%cd?'.
435
435
436 Currently the magic system has the following functions:\n"""
436 Currently the magic system has the following functions:\n"""
437
437
438 mesc = self.shell.ESC_MAGIC
438 mesc = self.shell.ESC_MAGIC
439 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
439 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
440 "\n\n%s%s\n\n%s" % (outmsg,
440 "\n\n%s%s\n\n%s" % (outmsg,
441 magic_docs,mesc,mesc,
441 magic_docs,mesc,mesc,
442 (' '+mesc).join(self.lsmagic()),
442 (' '+mesc).join(self.lsmagic()),
443 Magic.auto_status[self.shell.rc.automagic] ) )
443 Magic.auto_status[self.shell.rc.automagic] ) )
444
444
445 page(outmsg,screen_lines=self.shell.rc.screen_length)
445 page(outmsg,screen_lines=self.shell.rc.screen_length)
446
446
447 def magic_automagic(self, parameter_s = ''):
447 def magic_automagic(self, parameter_s = ''):
448 """Make magic functions callable without having to type the initial %.
448 """Make magic functions callable without having to type the initial %.
449
449
450 Toggles on/off (when off, you must call it as %automagic, of
450 Toggles on/off (when off, you must call it as %automagic, of
451 course). Note that magic functions have lowest priority, so if there's
451 course). Note that magic functions have lowest priority, so if there's
452 a variable whose name collides with that of a magic fn, automagic
452 a variable whose name collides with that of a magic fn, automagic
453 won't work for that function (you get the variable instead). However,
453 won't work for that function (you get the variable instead). However,
454 if you delete the variable (del var), the previously shadowed magic
454 if you delete the variable (del var), the previously shadowed magic
455 function becomes visible to automagic again."""
455 function becomes visible to automagic again."""
456
456
457 rc = self.shell.rc
457 rc = self.shell.rc
458 rc.automagic = not rc.automagic
458 rc.automagic = not rc.automagic
459 print '\n' + Magic.auto_status[rc.automagic]
459 print '\n' + Magic.auto_status[rc.automagic]
460
460
461 def magic_autocall(self, parameter_s = ''):
461 def magic_autocall(self, parameter_s = ''):
462 """Make functions callable without having to type parentheses.
462 """Make functions callable without having to type parentheses.
463
463
464 Usage:
464 Usage:
465
465
466 %autocall [mode]
466 %autocall [mode]
467
467
468 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
468 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
469 value is toggled on and off (remembering the previous state)."""
469 value is toggled on and off (remembering the previous state)."""
470
470
471 rc = self.shell.rc
471 rc = self.shell.rc
472
472
473 if parameter_s:
473 if parameter_s:
474 arg = int(parameter_s)
474 arg = int(parameter_s)
475 else:
475 else:
476 arg = 'toggle'
476 arg = 'toggle'
477
477
478 if not arg in (0,1,2,'toggle'):
478 if not arg in (0,1,2,'toggle'):
479 error('Valid modes: (0->Off, 1->Smart, 2->Full')
479 error('Valid modes: (0->Off, 1->Smart, 2->Full')
480 return
480 return
481
481
482 if arg in (0,1,2):
482 if arg in (0,1,2):
483 rc.autocall = arg
483 rc.autocall = arg
484 else: # toggle
484 else: # toggle
485 if rc.autocall:
485 if rc.autocall:
486 self._magic_state.autocall_save = rc.autocall
486 self._magic_state.autocall_save = rc.autocall
487 rc.autocall = 0
487 rc.autocall = 0
488 else:
488 else:
489 try:
489 try:
490 rc.autocall = self._magic_state.autocall_save
490 rc.autocall = self._magic_state.autocall_save
491 except AttributeError:
491 except AttributeError:
492 rc.autocall = self._magic_state.autocall_save = 1
492 rc.autocall = self._magic_state.autocall_save = 1
493
493
494 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
494 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
495
495
496 def magic_autoindent(self, parameter_s = ''):
496 def magic_autoindent(self, parameter_s = ''):
497 """Toggle autoindent on/off (if available)."""
497 """Toggle autoindent on/off (if available)."""
498
498
499 self.shell.set_autoindent()
499 self.shell.set_autoindent()
500 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
500 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
501
501
502 def magic_system_verbose(self, parameter_s = ''):
502 def magic_system_verbose(self, parameter_s = ''):
503 """Toggle verbose printing of system calls on/off."""
503 """Toggle verbose printing of system calls on/off."""
504
504
505 self.shell.rc_set_toggle('system_verbose')
505 self.shell.rc_set_toggle('system_verbose')
506 print "System verbose printing is:",\
506 print "System verbose printing is:",\
507 ['OFF','ON'][self.shell.rc.system_verbose]
507 ['OFF','ON'][self.shell.rc.system_verbose]
508
508
509 def magic_history(self, parameter_s = ''):
509 def magic_history(self, parameter_s = ''):
510 """Print input history (_i<n> variables), with most recent last.
510 """Print input history (_i<n> variables), with most recent last.
511
511
512 %history -> print at most 40 inputs (some may be multi-line)\\
512 %history -> print at most 40 inputs (some may be multi-line)\\
513 %history n -> print at most n inputs\\
513 %history n -> print at most n inputs\\
514 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
514 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
515
515
516 Each input's number <n> is shown, and is accessible as the
516 Each input's number <n> is shown, and is accessible as the
517 automatically generated variable _i<n>. Multi-line statements are
517 automatically generated variable _i<n>. Multi-line statements are
518 printed starting at a new line for easy copy/paste.
518 printed starting at a new line for easy copy/paste.
519
519
520
520
521 Options:
521 Options:
522
522
523 -n: do NOT print line numbers. This is useful if you want to get a
523 -n: do NOT print line numbers. This is useful if you want to get a
524 printout of many lines which can be directly pasted into a text
524 printout of many lines which can be directly pasted into a text
525 editor.
525 editor.
526
526
527 This feature is only available if numbered prompts are in use.
527 This feature is only available if numbered prompts are in use.
528
528
529 -r: print the 'raw' history. IPython filters your input and
529 -r: print the 'raw' history. IPython filters your input and
530 converts it all into valid Python source before executing it (things
530 converts it all into valid Python source before executing it (things
531 like magics or aliases are turned into function calls, for
531 like magics or aliases are turned into function calls, for
532 example). With this option, you'll see the unfiltered history
532 example). With this option, you'll see the unfiltered history
533 instead of the filtered version: '%cd /' will be seen as '%cd /'
533 instead of the filtered version: '%cd /' will be seen as '%cd /'
534 instead of '_ip.magic("%cd /")'.
534 instead of '_ip.magic("%cd /")'.
535 """
535 """
536
536
537 shell = self.shell
537 shell = self.shell
538 if not shell.outputcache.do_full_cache:
538 if not shell.outputcache.do_full_cache:
539 print 'This feature is only available if numbered prompts are in use.'
539 print 'This feature is only available if numbered prompts are in use.'
540 return
540 return
541 opts,args = self.parse_options(parameter_s,'nr',mode='list')
541 opts,args = self.parse_options(parameter_s,'nr',mode='list')
542
542
543 if opts.has_key('r'):
543 if opts.has_key('r'):
544 input_hist = shell.input_hist_raw
544 input_hist = shell.input_hist_raw
545 else:
545 else:
546 input_hist = shell.input_hist
546 input_hist = shell.input_hist
547
547
548 default_length = 40
548 default_length = 40
549 if len(args) == 0:
549 if len(args) == 0:
550 final = len(input_hist)
550 final = len(input_hist)
551 init = max(1,final-default_length)
551 init = max(1,final-default_length)
552 elif len(args) == 1:
552 elif len(args) == 1:
553 final = len(input_hist)
553 final = len(input_hist)
554 init = max(1,final-int(args[0]))
554 init = max(1,final-int(args[0]))
555 elif len(args) == 2:
555 elif len(args) == 2:
556 init,final = map(int,args)
556 init,final = map(int,args)
557 else:
557 else:
558 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
558 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
559 print self.magic_hist.__doc__
559 print self.magic_hist.__doc__
560 return
560 return
561 width = len(str(final))
561 width = len(str(final))
562 line_sep = ['','\n']
562 line_sep = ['','\n']
563 print_nums = not opts.has_key('n')
563 print_nums = not opts.has_key('n')
564 for in_num in range(init,final):
564 for in_num in range(init,final):
565 inline = input_hist[in_num]
565 inline = input_hist[in_num]
566 multiline = int(inline.count('\n') > 1)
566 multiline = int(inline.count('\n') > 1)
567 if print_nums:
567 if print_nums:
568 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
568 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
569 print inline,
569 print inline,
570
570
571 def magic_hist(self, parameter_s=''):
571 def magic_hist(self, parameter_s=''):
572 """Alternate name for %history."""
572 """Alternate name for %history."""
573 return self.magic_history(parameter_s)
573 return self.magic_history(parameter_s)
574
574
575 def magic_p(self, parameter_s=''):
575 def magic_p(self, parameter_s=''):
576 """Just a short alias for Python's 'print'."""
576 """Just a short alias for Python's 'print'."""
577 exec 'print ' + parameter_s in self.shell.user_ns
577 exec 'print ' + parameter_s in self.shell.user_ns
578
578
579 def magic_r(self, parameter_s=''):
579 def magic_r(self, parameter_s=''):
580 """Repeat previous input.
580 """Repeat previous input.
581
581
582 If given an argument, repeats the previous command which starts with
582 If given an argument, repeats the previous command which starts with
583 the same string, otherwise it just repeats the previous input.
583 the same string, otherwise it just repeats the previous input.
584
584
585 Shell escaped commands (with ! as first character) are not recognized
585 Shell escaped commands (with ! as first character) are not recognized
586 by this system, only pure python code and magic commands.
586 by this system, only pure python code and magic commands.
587 """
587 """
588
588
589 start = parameter_s.strip()
589 start = parameter_s.strip()
590 esc_magic = self.shell.ESC_MAGIC
590 esc_magic = self.shell.ESC_MAGIC
591 # Identify magic commands even if automagic is on (which means
591 # Identify magic commands even if automagic is on (which means
592 # the in-memory version is different from that typed by the user).
592 # the in-memory version is different from that typed by the user).
593 if self.shell.rc.automagic:
593 if self.shell.rc.automagic:
594 start_magic = esc_magic+start
594 start_magic = esc_magic+start
595 else:
595 else:
596 start_magic = start
596 start_magic = start
597 # Look through the input history in reverse
597 # Look through the input history in reverse
598 for n in range(len(self.shell.input_hist)-2,0,-1):
598 for n in range(len(self.shell.input_hist)-2,0,-1):
599 input = self.shell.input_hist[n]
599 input = self.shell.input_hist[n]
600 # skip plain 'r' lines so we don't recurse to infinity
600 # skip plain 'r' lines so we don't recurse to infinity
601 if input != '_ip.magic("r")\n' and \
601 if input != '_ip.magic("r")\n' and \
602 (input.startswith(start) or input.startswith(start_magic)):
602 (input.startswith(start) or input.startswith(start_magic)):
603 #print 'match',`input` # dbg
603 #print 'match',`input` # dbg
604 print 'Executing:',input,
604 print 'Executing:',input,
605 self.shell.runlines(input)
605 self.shell.runlines(input)
606 return
606 return
607 print 'No previous input matching `%s` found.' % start
607 print 'No previous input matching `%s` found.' % start
608
608
609 def magic_page(self, parameter_s=''):
609 def magic_page(self, parameter_s=''):
610 """Pretty print the object and display it through a pager.
610 """Pretty print the object and display it through a pager.
611
611
612 If no parameter is given, use _ (last output)."""
612 If no parameter is given, use _ (last output)."""
613 # After a function contributed by Olivier Aubert, slightly modified.
613 # After a function contributed by Olivier Aubert, slightly modified.
614
614
615 oname = parameter_s and parameter_s or '_'
615 oname = parameter_s and parameter_s or '_'
616 info = self._ofind(oname)
616 info = self._ofind(oname)
617 if info['found']:
617 if info['found']:
618 page(pformat(info['obj']))
618 page(pformat(info['obj']))
619 else:
619 else:
620 print 'Object `%s` not found' % oname
620 print 'Object `%s` not found' % oname
621
621
622 def magic_profile(self, parameter_s=''):
622 def magic_profile(self, parameter_s=''):
623 """Print your currently active IPyhton profile."""
623 """Print your currently active IPyhton profile."""
624 if self.shell.rc.profile:
624 if self.shell.rc.profile:
625 printpl('Current IPython profile: $self.shell.rc.profile.')
625 printpl('Current IPython profile: $self.shell.rc.profile.')
626 else:
626 else:
627 print 'No profile active.'
627 print 'No profile active.'
628
628
629 def _inspect(self,meth,oname,**kw):
629 def _inspect(self,meth,oname,**kw):
630 """Generic interface to the inspector system.
630 """Generic interface to the inspector system.
631
631
632 This function is meant to be called by pdef, pdoc & friends."""
632 This function is meant to be called by pdef, pdoc & friends."""
633
633
634 oname = oname.strip()
634 oname = oname.strip()
635 info = Struct(self._ofind(oname))
635 info = Struct(self._ofind(oname))
636
636
637 if info.found:
637 if info.found:
638 # Get the docstring of the class property if it exists.
638 # Get the docstring of the class property if it exists.
639 path = oname.split('.')
639 path = oname.split('.')
640 root = '.'.join(path[:-1])
640 root = '.'.join(path[:-1])
641 if info.parent is not None:
641 if info.parent is not None:
642 try:
642 try:
643 target = getattr(info.parent, '__class__')
643 target = getattr(info.parent, '__class__')
644 # The object belongs to a class instance.
644 # The object belongs to a class instance.
645 try:
645 try:
646 target = getattr(target, path[-1])
646 target = getattr(target, path[-1])
647 # The class defines the object.
647 # The class defines the object.
648 if isinstance(target, property):
648 if isinstance(target, property):
649 oname = root + '.__class__.' + path[-1]
649 oname = root + '.__class__.' + path[-1]
650 info = Struct(self._ofind(oname))
650 info = Struct(self._ofind(oname))
651 except AttributeError: pass
651 except AttributeError: pass
652 except AttributeError: pass
652 except AttributeError: pass
653
653
654 pmethod = getattr(self.shell.inspector,meth)
654 pmethod = getattr(self.shell.inspector,meth)
655 formatter = info.ismagic and self.format_screen or None
655 formatter = info.ismagic and self.format_screen or None
656 if meth == 'pdoc':
656 if meth == 'pdoc':
657 pmethod(info.obj,oname,formatter)
657 pmethod(info.obj,oname,formatter)
658 elif meth == 'pinfo':
658 elif meth == 'pinfo':
659 pmethod(info.obj,oname,formatter,info,**kw)
659 pmethod(info.obj,oname,formatter,info,**kw)
660 else:
660 else:
661 pmethod(info.obj,oname)
661 pmethod(info.obj,oname)
662 else:
662 else:
663 print 'Object `%s` not found.' % oname
663 print 'Object `%s` not found.' % oname
664 return 'not found' # so callers can take other action
664 return 'not found' # so callers can take other action
665
665
666 def magic_pdef(self, parameter_s=''):
666 def magic_pdef(self, parameter_s=''):
667 """Print the definition header for any callable object.
667 """Print the definition header for any callable object.
668
668
669 If the object is a class, print the constructor information."""
669 If the object is a class, print the constructor information."""
670 self._inspect('pdef',parameter_s)
670 self._inspect('pdef',parameter_s)
671
671
672 def magic_pdoc(self, parameter_s=''):
672 def magic_pdoc(self, parameter_s=''):
673 """Print the docstring for an object.
673 """Print the docstring for an object.
674
674
675 If the given object is a class, it will print both the class and the
675 If the given object is a class, it will print both the class and the
676 constructor docstrings."""
676 constructor docstrings."""
677 self._inspect('pdoc',parameter_s)
677 self._inspect('pdoc',parameter_s)
678
678
679 def magic_psource(self, parameter_s=''):
679 def magic_psource(self, parameter_s=''):
680 """Print (or run through pager) the source code for an object."""
680 """Print (or run through pager) the source code for an object."""
681 self._inspect('psource',parameter_s)
681 self._inspect('psource',parameter_s)
682
682
683 def magic_pfile(self, parameter_s=''):
683 def magic_pfile(self, parameter_s=''):
684 """Print (or run through pager) the file where an object is defined.
684 """Print (or run through pager) the file where an object is defined.
685
685
686 The file opens at the line where the object definition begins. IPython
686 The file opens at the line where the object definition begins. IPython
687 will honor the environment variable PAGER if set, and otherwise will
687 will honor the environment variable PAGER if set, and otherwise will
688 do its best to print the file in a convenient form.
688 do its best to print the file in a convenient form.
689
689
690 If the given argument is not an object currently defined, IPython will
690 If the given argument is not an object currently defined, IPython will
691 try to interpret it as a filename (automatically adding a .py extension
691 try to interpret it as a filename (automatically adding a .py extension
692 if needed). You can thus use %pfile as a syntax highlighting code
692 if needed). You can thus use %pfile as a syntax highlighting code
693 viewer."""
693 viewer."""
694
694
695 # first interpret argument as an object name
695 # first interpret argument as an object name
696 out = self._inspect('pfile',parameter_s)
696 out = self._inspect('pfile',parameter_s)
697 # if not, try the input as a filename
697 # if not, try the input as a filename
698 if out == 'not found':
698 if out == 'not found':
699 try:
699 try:
700 filename = get_py_filename(parameter_s)
700 filename = get_py_filename(parameter_s)
701 except IOError,msg:
701 except IOError,msg:
702 print msg
702 print msg
703 return
703 return
704 page(self.shell.inspector.format(file(filename).read()))
704 page(self.shell.inspector.format(file(filename).read()))
705
705
706 def magic_pinfo(self, parameter_s=''):
706 def magic_pinfo(self, parameter_s=''):
707 """Provide detailed information about an object.
707 """Provide detailed information about an object.
708
708
709 '%pinfo object' is just a synonym for object? or ?object."""
709 '%pinfo object' is just a synonym for object? or ?object."""
710
710
711 #print 'pinfo par: <%s>' % parameter_s # dbg
711 #print 'pinfo par: <%s>' % parameter_s # dbg
712
712
713 # detail_level: 0 -> obj? , 1 -> obj??
713 # detail_level: 0 -> obj? , 1 -> obj??
714 detail_level = 0
714 detail_level = 0
715 # We need to detect if we got called as 'pinfo pinfo foo', which can
715 # We need to detect if we got called as 'pinfo pinfo foo', which can
716 # happen if the user types 'pinfo foo?' at the cmd line.
716 # happen if the user types 'pinfo foo?' at the cmd line.
717 pinfo,qmark1,oname,qmark2 = \
717 pinfo,qmark1,oname,qmark2 = \
718 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
718 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
719 if pinfo or qmark1 or qmark2:
719 if pinfo or qmark1 or qmark2:
720 detail_level = 1
720 detail_level = 1
721 if "*" in oname:
721 if "*" in oname:
722 self.magic_psearch(oname)
722 self.magic_psearch(oname)
723 else:
723 else:
724 self._inspect('pinfo',oname,detail_level=detail_level)
724 self._inspect('pinfo',oname,detail_level=detail_level)
725
725
726 def magic_psearch(self, parameter_s=''):
726 def magic_psearch(self, parameter_s=''):
727 """Search for object in namespaces by wildcard.
727 """Search for object in namespaces by wildcard.
728
728
729 %psearch [options] PATTERN [OBJECT TYPE]
729 %psearch [options] PATTERN [OBJECT TYPE]
730
730
731 Note: ? can be used as a synonym for %psearch, at the beginning or at
731 Note: ? can be used as a synonym for %psearch, at the beginning or at
732 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
732 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
733 rest of the command line must be unchanged (options come first), so
733 rest of the command line must be unchanged (options come first), so
734 for example the following forms are equivalent
734 for example the following forms are equivalent
735
735
736 %psearch -i a* function
736 %psearch -i a* function
737 -i a* function?
737 -i a* function?
738 ?-i a* function
738 ?-i a* function
739
739
740 Arguments:
740 Arguments:
741
741
742 PATTERN
742 PATTERN
743
743
744 where PATTERN is a string containing * as a wildcard similar to its
744 where PATTERN is a string containing * as a wildcard similar to its
745 use in a shell. The pattern is matched in all namespaces on the
745 use in a shell. The pattern is matched in all namespaces on the
746 search path. By default objects starting with a single _ are not
746 search path. By default objects starting with a single _ are not
747 matched, many IPython generated objects have a single
747 matched, many IPython generated objects have a single
748 underscore. The default is case insensitive matching. Matching is
748 underscore. The default is case insensitive matching. Matching is
749 also done on the attributes of objects and not only on the objects
749 also done on the attributes of objects and not only on the objects
750 in a module.
750 in a module.
751
751
752 [OBJECT TYPE]
752 [OBJECT TYPE]
753
753
754 Is the name of a python type from the types module. The name is
754 Is the name of a python type from the types module. The name is
755 given in lowercase without the ending type, ex. StringType is
755 given in lowercase without the ending type, ex. StringType is
756 written string. By adding a type here only objects matching the
756 written string. By adding a type here only objects matching the
757 given type are matched. Using all here makes the pattern match all
757 given type are matched. Using all here makes the pattern match all
758 types (this is the default).
758 types (this is the default).
759
759
760 Options:
760 Options:
761
761
762 -a: makes the pattern match even objects whose names start with a
762 -a: makes the pattern match even objects whose names start with a
763 single underscore. These names are normally ommitted from the
763 single underscore. These names are normally ommitted from the
764 search.
764 search.
765
765
766 -i/-c: make the pattern case insensitive/sensitive. If neither of
766 -i/-c: make the pattern case insensitive/sensitive. If neither of
767 these options is given, the default is read from your ipythonrc
767 these options is given, the default is read from your ipythonrc
768 file. The option name which sets this value is
768 file. The option name which sets this value is
769 'wildcards_case_sensitive'. If this option is not specified in your
769 'wildcards_case_sensitive'. If this option is not specified in your
770 ipythonrc file, IPython's internal default is to do a case sensitive
770 ipythonrc file, IPython's internal default is to do a case sensitive
771 search.
771 search.
772
772
773 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
773 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
774 specifiy can be searched in any of the following namespaces:
774 specifiy can be searched in any of the following namespaces:
775 'builtin', 'user', 'user_global','internal', 'alias', where
775 'builtin', 'user', 'user_global','internal', 'alias', where
776 'builtin' and 'user' are the search defaults. Note that you should
776 'builtin' and 'user' are the search defaults. Note that you should
777 not use quotes when specifying namespaces.
777 not use quotes when specifying namespaces.
778
778
779 'Builtin' contains the python module builtin, 'user' contains all
779 'Builtin' contains the python module builtin, 'user' contains all
780 user data, 'alias' only contain the shell aliases and no python
780 user data, 'alias' only contain the shell aliases and no python
781 objects, 'internal' contains objects used by IPython. The
781 objects, 'internal' contains objects used by IPython. The
782 'user_global' namespace is only used by embedded IPython instances,
782 'user_global' namespace is only used by embedded IPython instances,
783 and it contains module-level globals. You can add namespaces to the
783 and it contains module-level globals. You can add namespaces to the
784 search with -s or exclude them with -e (these options can be given
784 search with -s or exclude them with -e (these options can be given
785 more than once).
785 more than once).
786
786
787 Examples:
787 Examples:
788
788
789 %psearch a* -> objects beginning with an a
789 %psearch a* -> objects beginning with an a
790 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
790 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
791 %psearch a* function -> all functions beginning with an a
791 %psearch a* function -> all functions beginning with an a
792 %psearch re.e* -> objects beginning with an e in module re
792 %psearch re.e* -> objects beginning with an e in module re
793 %psearch r*.e* -> objects that start with e in modules starting in r
793 %psearch r*.e* -> objects that start with e in modules starting in r
794 %psearch r*.* string -> all strings in modules beginning with r
794 %psearch r*.* string -> all strings in modules beginning with r
795
795
796 Case sensitve search:
796 Case sensitve search:
797
797
798 %psearch -c a* list all object beginning with lower case a
798 %psearch -c a* list all object beginning with lower case a
799
799
800 Show objects beginning with a single _:
800 Show objects beginning with a single _:
801
801
802 %psearch -a _* list objects beginning with a single underscore"""
802 %psearch -a _* list objects beginning with a single underscore"""
803
803
804 # default namespaces to be searched
804 # default namespaces to be searched
805 def_search = ['user','builtin']
805 def_search = ['user','builtin']
806
806
807 # Process options/args
807 # Process options/args
808 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
808 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
809 opt = opts.get
809 opt = opts.get
810 shell = self.shell
810 shell = self.shell
811 psearch = shell.inspector.psearch
811 psearch = shell.inspector.psearch
812
812
813 # select case options
813 # select case options
814 if opts.has_key('i'):
814 if opts.has_key('i'):
815 ignore_case = True
815 ignore_case = True
816 elif opts.has_key('c'):
816 elif opts.has_key('c'):
817 ignore_case = False
817 ignore_case = False
818 else:
818 else:
819 ignore_case = not shell.rc.wildcards_case_sensitive
819 ignore_case = not shell.rc.wildcards_case_sensitive
820
820
821 # Build list of namespaces to search from user options
821 # Build list of namespaces to search from user options
822 def_search.extend(opt('s',[]))
822 def_search.extend(opt('s',[]))
823 ns_exclude = ns_exclude=opt('e',[])
823 ns_exclude = ns_exclude=opt('e',[])
824 ns_search = [nm for nm in def_search if nm not in ns_exclude]
824 ns_search = [nm for nm in def_search if nm not in ns_exclude]
825
825
826 # Call the actual search
826 # Call the actual search
827 try:
827 try:
828 psearch(args,shell.ns_table,ns_search,
828 psearch(args,shell.ns_table,ns_search,
829 show_all=opt('a'),ignore_case=ignore_case)
829 show_all=opt('a'),ignore_case=ignore_case)
830 except:
830 except:
831 shell.showtraceback()
831 shell.showtraceback()
832
832
833 def magic_who_ls(self, parameter_s=''):
833 def magic_who_ls(self, parameter_s=''):
834 """Return a sorted list of all interactive variables.
834 """Return a sorted list of all interactive variables.
835
835
836 If arguments are given, only variables of types matching these
836 If arguments are given, only variables of types matching these
837 arguments are returned."""
837 arguments are returned."""
838
838
839 user_ns = self.shell.user_ns
839 user_ns = self.shell.user_ns
840 internal_ns = self.shell.internal_ns
840 internal_ns = self.shell.internal_ns
841 user_config_ns = self.shell.user_config_ns
841 user_config_ns = self.shell.user_config_ns
842 out = []
842 out = []
843 typelist = parameter_s.split()
843 typelist = parameter_s.split()
844
844
845 for i in user_ns:
845 for i in user_ns:
846 if not (i.startswith('_') or i.startswith('_i')) \
846 if not (i.startswith('_') or i.startswith('_i')) \
847 and not (i in internal_ns or i in user_config_ns):
847 and not (i in internal_ns or i in user_config_ns):
848 if typelist:
848 if typelist:
849 if type(user_ns[i]).__name__ in typelist:
849 if type(user_ns[i]).__name__ in typelist:
850 out.append(i)
850 out.append(i)
851 else:
851 else:
852 out.append(i)
852 out.append(i)
853 out.sort()
853 out.sort()
854 return out
854 return out
855
855
856 def magic_who(self, parameter_s=''):
856 def magic_who(self, parameter_s=''):
857 """Print all interactive variables, with some minimal formatting.
857 """Print all interactive variables, with some minimal formatting.
858
858
859 If any arguments are given, only variables whose type matches one of
859 If any arguments are given, only variables whose type matches one of
860 these are printed. For example:
860 these are printed. For example:
861
861
862 %who function str
862 %who function str
863
863
864 will only list functions and strings, excluding all other types of
864 will only list functions and strings, excluding all other types of
865 variables. To find the proper type names, simply use type(var) at a
865 variables. To find the proper type names, simply use type(var) at a
866 command line to see how python prints type names. For example:
866 command line to see how python prints type names. For example:
867
867
868 In [1]: type('hello')\\
868 In [1]: type('hello')\\
869 Out[1]: <type 'str'>
869 Out[1]: <type 'str'>
870
870
871 indicates that the type name for strings is 'str'.
871 indicates that the type name for strings is 'str'.
872
872
873 %who always excludes executed names loaded through your configuration
873 %who always excludes executed names loaded through your configuration
874 file and things which are internal to IPython.
874 file and things which are internal to IPython.
875
875
876 This is deliberate, as typically you may load many modules and the
876 This is deliberate, as typically you may load many modules and the
877 purpose of %who is to show you only what you've manually defined."""
877 purpose of %who is to show you only what you've manually defined."""
878
878
879 varlist = self.magic_who_ls(parameter_s)
879 varlist = self.magic_who_ls(parameter_s)
880 if not varlist:
880 if not varlist:
881 print 'Interactive namespace is empty.'
881 print 'Interactive namespace is empty.'
882 return
882 return
883
883
884 # if we have variables, move on...
884 # if we have variables, move on...
885
885
886 # stupid flushing problem: when prompts have no separators, stdout is
886 # stupid flushing problem: when prompts have no separators, stdout is
887 # getting lost. I'm starting to think this is a python bug. I'm having
887 # getting lost. I'm starting to think this is a python bug. I'm having
888 # to force a flush with a print because even a sys.stdout.flush
888 # to force a flush with a print because even a sys.stdout.flush
889 # doesn't seem to do anything!
889 # doesn't seem to do anything!
890
890
891 count = 0
891 count = 0
892 for i in varlist:
892 for i in varlist:
893 print i+'\t',
893 print i+'\t',
894 count += 1
894 count += 1
895 if count > 8:
895 if count > 8:
896 count = 0
896 count = 0
897 print
897 print
898 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
898 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
899
899
900 print # well, this does force a flush at the expense of an extra \n
900 print # well, this does force a flush at the expense of an extra \n
901
901
902 def magic_whos(self, parameter_s=''):
902 def magic_whos(self, parameter_s=''):
903 """Like %who, but gives some extra information about each variable.
903 """Like %who, but gives some extra information about each variable.
904
904
905 The same type filtering of %who can be applied here.
905 The same type filtering of %who can be applied here.
906
906
907 For all variables, the type is printed. Additionally it prints:
907 For all variables, the type is printed. Additionally it prints:
908
908
909 - For {},[],(): their length.
909 - For {},[],(): their length.
910
910
911 - For Numeric arrays, a summary with shape, number of elements,
911 - For Numeric arrays, a summary with shape, number of elements,
912 typecode and size in memory.
912 typecode and size in memory.
913
913
914 - Everything else: a string representation, snipping their middle if
914 - Everything else: a string representation, snipping their middle if
915 too long."""
915 too long."""
916
916
917 varnames = self.magic_who_ls(parameter_s)
917 varnames = self.magic_who_ls(parameter_s)
918 if not varnames:
918 if not varnames:
919 print 'Interactive namespace is empty.'
919 print 'Interactive namespace is empty.'
920 return
920 return
921
921
922 # if we have variables, move on...
922 # if we have variables, move on...
923
923
924 # for these types, show len() instead of data:
924 # for these types, show len() instead of data:
925 seq_types = [types.DictType,types.ListType,types.TupleType]
925 seq_types = [types.DictType,types.ListType,types.TupleType]
926
926
927 # for Numeric arrays, display summary info
927 # for Numeric arrays, display summary info
928 try:
928 try:
929 import Numeric
929 import Numeric
930 except ImportError:
930 except ImportError:
931 array_type = None
931 array_type = None
932 else:
932 else:
933 array_type = Numeric.ArrayType.__name__
933 array_type = Numeric.ArrayType.__name__
934
934
935 # Find all variable names and types so we can figure out column sizes
935 # Find all variable names and types so we can figure out column sizes
936 get_vars = lambda i: self.shell.user_ns[i]
936 get_vars = lambda i: self.shell.user_ns[i]
937 type_name = lambda v: type(v).__name__
937 type_name = lambda v: type(v).__name__
938 varlist = map(get_vars,varnames)
938 varlist = map(get_vars,varnames)
939
939
940 typelist = []
940 typelist = []
941 for vv in varlist:
941 for vv in varlist:
942 tt = type_name(vv)
942 tt = type_name(vv)
943 if tt=='instance':
943 if tt=='instance':
944 typelist.append(str(vv.__class__))
944 typelist.append(str(vv.__class__))
945 else:
945 else:
946 typelist.append(tt)
946 typelist.append(tt)
947
947
948 # column labels and # of spaces as separator
948 # column labels and # of spaces as separator
949 varlabel = 'Variable'
949 varlabel = 'Variable'
950 typelabel = 'Type'
950 typelabel = 'Type'
951 datalabel = 'Data/Info'
951 datalabel = 'Data/Info'
952 colsep = 3
952 colsep = 3
953 # variable format strings
953 # variable format strings
954 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
954 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
955 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
955 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
956 aformat = "%s: %s elems, type `%s`, %s bytes"
956 aformat = "%s: %s elems, type `%s`, %s bytes"
957 # find the size of the columns to format the output nicely
957 # find the size of the columns to format the output nicely
958 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
958 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
959 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
959 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
960 # table header
960 # table header
961 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
961 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
962 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
962 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
963 # and the table itself
963 # and the table itself
964 kb = 1024
964 kb = 1024
965 Mb = 1048576 # kb**2
965 Mb = 1048576 # kb**2
966 for vname,var,vtype in zip(varnames,varlist,typelist):
966 for vname,var,vtype in zip(varnames,varlist,typelist):
967 print itpl(vformat),
967 print itpl(vformat),
968 if vtype in seq_types:
968 if vtype in seq_types:
969 print len(var)
969 print len(var)
970 elif vtype==array_type:
970 elif vtype==array_type:
971 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
971 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
972 vsize = Numeric.size(var)
972 vsize = Numeric.size(var)
973 vbytes = vsize*var.itemsize()
973 vbytes = vsize*var.itemsize()
974 if vbytes < 100000:
974 if vbytes < 100000:
975 print aformat % (vshape,vsize,var.typecode(),vbytes)
975 print aformat % (vshape,vsize,var.typecode(),vbytes)
976 else:
976 else:
977 print aformat % (vshape,vsize,var.typecode(),vbytes),
977 print aformat % (vshape,vsize,var.typecode(),vbytes),
978 if vbytes < Mb:
978 if vbytes < Mb:
979 print '(%s kb)' % (vbytes/kb,)
979 print '(%s kb)' % (vbytes/kb,)
980 else:
980 else:
981 print '(%s Mb)' % (vbytes/Mb,)
981 print '(%s Mb)' % (vbytes/Mb,)
982 else:
982 else:
983 vstr = str(var).replace('\n','\\n')
983 vstr = str(var).replace('\n','\\n')
984 if len(vstr) < 50:
984 if len(vstr) < 50:
985 print vstr
985 print vstr
986 else:
986 else:
987 printpl(vfmt_short)
987 printpl(vfmt_short)
988
988
989 def magic_reset(self, parameter_s=''):
989 def magic_reset(self, parameter_s=''):
990 """Resets the namespace by removing all names defined by the user.
990 """Resets the namespace by removing all names defined by the user.
991
991
992 Input/Output history are left around in case you need them."""
992 Input/Output history are left around in case you need them."""
993
993
994 ans = self.shell.ask_yes_no(
994 ans = self.shell.ask_yes_no(
995 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
995 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
996 if not ans:
996 if not ans:
997 print 'Nothing done.'
997 print 'Nothing done.'
998 return
998 return
999 user_ns = self.shell.user_ns
999 user_ns = self.shell.user_ns
1000 for i in self.magic_who_ls():
1000 for i in self.magic_who_ls():
1001 del(user_ns[i])
1001 del(user_ns[i])
1002
1002
1003 def magic_config(self,parameter_s=''):
1003 def magic_config(self,parameter_s=''):
1004 """Show IPython's internal configuration."""
1004 """Show IPython's internal configuration."""
1005
1005
1006 page('Current configuration structure:\n'+
1006 page('Current configuration structure:\n'+
1007 pformat(self.shell.rc.dict()))
1007 pformat(self.shell.rc.dict()))
1008
1008
1009 def magic_logstart(self,parameter_s=''):
1009 def magic_logstart(self,parameter_s=''):
1010 """Start logging anywhere in a session.
1010 """Start logging anywhere in a session.
1011
1011
1012 %logstart [-o|-r|-t] [log_name [log_mode]]
1012 %logstart [-o|-r|-t] [log_name [log_mode]]
1013
1013
1014 If no name is given, it defaults to a file named 'ipython_log.py' in your
1014 If no name is given, it defaults to a file named 'ipython_log.py' in your
1015 current directory, in 'rotate' mode (see below).
1015 current directory, in 'rotate' mode (see below).
1016
1016
1017 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1017 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1018 history up to that point and then continues logging.
1018 history up to that point and then continues logging.
1019
1019
1020 %logstart takes a second optional parameter: logging mode. This can be one
1020 %logstart takes a second optional parameter: logging mode. This can be one
1021 of (note that the modes are given unquoted):\\
1021 of (note that the modes are given unquoted):\\
1022 append: well, that says it.\\
1022 append: well, that says it.\\
1023 backup: rename (if exists) to name~ and start name.\\
1023 backup: rename (if exists) to name~ and start name.\\
1024 global: single logfile in your home dir, appended to.\\
1024 global: single logfile in your home dir, appended to.\\
1025 over : overwrite existing log.\\
1025 over : overwrite existing log.\\
1026 rotate: create rotating logs name.1~, name.2~, etc.
1026 rotate: create rotating logs name.1~, name.2~, etc.
1027
1027
1028 Options:
1028 Options:
1029
1029
1030 -o: log also IPython's output. In this mode, all commands which
1030 -o: log also IPython's output. In this mode, all commands which
1031 generate an Out[NN] prompt are recorded to the logfile, right after
1031 generate an Out[NN] prompt are recorded to the logfile, right after
1032 their corresponding input line. The output lines are always
1032 their corresponding input line. The output lines are always
1033 prepended with a '#[Out]# ' marker, so that the log remains valid
1033 prepended with a '#[Out]# ' marker, so that the log remains valid
1034 Python code.
1034 Python code.
1035
1035
1036 Since this marker is always the same, filtering only the output from
1036 Since this marker is always the same, filtering only the output from
1037 a log is very easy, using for example a simple awk call:
1037 a log is very easy, using for example a simple awk call:
1038
1038
1039 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1039 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1040
1040
1041 -r: log 'raw' input. Normally, IPython's logs contain the processed
1041 -r: log 'raw' input. Normally, IPython's logs contain the processed
1042 input, so that user lines are logged in their final form, converted
1042 input, so that user lines are logged in their final form, converted
1043 into valid Python. For example, %Exit is logged as
1043 into valid Python. For example, %Exit is logged as
1044 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1044 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1045 exactly as typed, with no transformations applied.
1045 exactly as typed, with no transformations applied.
1046
1046
1047 -t: put timestamps before each input line logged (these are put in
1047 -t: put timestamps before each input line logged (these are put in
1048 comments)."""
1048 comments)."""
1049
1049
1050 opts,par = self.parse_options(parameter_s,'ort')
1050 opts,par = self.parse_options(parameter_s,'ort')
1051 log_output = 'o' in opts
1051 log_output = 'o' in opts
1052 log_raw_input = 'r' in opts
1052 log_raw_input = 'r' in opts
1053 timestamp = 't' in opts
1053 timestamp = 't' in opts
1054
1054
1055 rc = self.shell.rc
1055 rc = self.shell.rc
1056 logger = self.shell.logger
1056 logger = self.shell.logger
1057
1057
1058 # if no args are given, the defaults set in the logger constructor by
1058 # if no args are given, the defaults set in the logger constructor by
1059 # ipytohn remain valid
1059 # ipytohn remain valid
1060 if par:
1060 if par:
1061 try:
1061 try:
1062 logfname,logmode = par.split()
1062 logfname,logmode = par.split()
1063 except:
1063 except:
1064 logfname = par
1064 logfname = par
1065 logmode = 'backup'
1065 logmode = 'backup'
1066 else:
1066 else:
1067 logfname = logger.logfname
1067 logfname = logger.logfname
1068 logmode = logger.logmode
1068 logmode = logger.logmode
1069 # put logfname into rc struct as if it had been called on the command
1069 # put logfname into rc struct as if it had been called on the command
1070 # line, so it ends up saved in the log header Save it in case we need
1070 # line, so it ends up saved in the log header Save it in case we need
1071 # to restore it...
1071 # to restore it...
1072 old_logfile = rc.opts.get('logfile','')
1072 old_logfile = rc.opts.get('logfile','')
1073 if logfname:
1073 if logfname:
1074 logfname = os.path.expanduser(logfname)
1074 logfname = os.path.expanduser(logfname)
1075 rc.opts.logfile = logfname
1075 rc.opts.logfile = logfname
1076 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1076 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1077 try:
1077 try:
1078 started = logger.logstart(logfname,loghead,logmode,
1078 started = logger.logstart(logfname,loghead,logmode,
1079 log_output,timestamp,log_raw_input)
1079 log_output,timestamp,log_raw_input)
1080 except:
1080 except:
1081 rc.opts.logfile = old_logfile
1081 rc.opts.logfile = old_logfile
1082 warn("Couldn't start log: %s" % sys.exc_info()[1])
1082 warn("Couldn't start log: %s" % sys.exc_info()[1])
1083 else:
1083 else:
1084 # log input history up to this point, optionally interleaving
1084 # log input history up to this point, optionally interleaving
1085 # output if requested
1085 # output if requested
1086
1086
1087 if timestamp:
1087 if timestamp:
1088 # disable timestamping for the previous history, since we've
1088 # disable timestamping for the previous history, since we've
1089 # lost those already (no time machine here).
1089 # lost those already (no time machine here).
1090 logger.timestamp = False
1090 logger.timestamp = False
1091
1091
1092 if log_raw_input:
1092 if log_raw_input:
1093 input_hist = self.shell.input_hist_raw
1093 input_hist = self.shell.input_hist_raw
1094 else:
1094 else:
1095 input_hist = self.shell.input_hist
1095 input_hist = self.shell.input_hist
1096
1096
1097 if log_output:
1097 if log_output:
1098 log_write = logger.log_write
1098 log_write = logger.log_write
1099 output_hist = self.shell.output_hist
1099 output_hist = self.shell.output_hist
1100 for n in range(1,len(input_hist)-1):
1100 for n in range(1,len(input_hist)-1):
1101 log_write(input_hist[n].rstrip())
1101 log_write(input_hist[n].rstrip())
1102 if n in output_hist:
1102 if n in output_hist:
1103 log_write(repr(output_hist[n]),'output')
1103 log_write(repr(output_hist[n]),'output')
1104 else:
1104 else:
1105 logger.log_write(input_hist[1:])
1105 logger.log_write(input_hist[1:])
1106 if timestamp:
1106 if timestamp:
1107 # re-enable timestamping
1107 # re-enable timestamping
1108 logger.timestamp = True
1108 logger.timestamp = True
1109
1109
1110 print ('Activating auto-logging. '
1110 print ('Activating auto-logging. '
1111 'Current session state plus future input saved.')
1111 'Current session state plus future input saved.')
1112 logger.logstate()
1112 logger.logstate()
1113
1113
1114 def magic_logoff(self,parameter_s=''):
1114 def magic_logoff(self,parameter_s=''):
1115 """Temporarily stop logging.
1115 """Temporarily stop logging.
1116
1116
1117 You must have previously started logging."""
1117 You must have previously started logging."""
1118 self.shell.logger.switch_log(0)
1118 self.shell.logger.switch_log(0)
1119
1119
1120 def magic_logon(self,parameter_s=''):
1120 def magic_logon(self,parameter_s=''):
1121 """Restart logging.
1121 """Restart logging.
1122
1122
1123 This function is for restarting logging which you've temporarily
1123 This function is for restarting logging which you've temporarily
1124 stopped with %logoff. For starting logging for the first time, you
1124 stopped with %logoff. For starting logging for the first time, you
1125 must use the %logstart function, which allows you to specify an
1125 must use the %logstart function, which allows you to specify an
1126 optional log filename."""
1126 optional log filename."""
1127
1127
1128 self.shell.logger.switch_log(1)
1128 self.shell.logger.switch_log(1)
1129
1129
1130 def magic_logstate(self,parameter_s=''):
1130 def magic_logstate(self,parameter_s=''):
1131 """Print the status of the logging system."""
1131 """Print the status of the logging system."""
1132
1132
1133 self.shell.logger.logstate()
1133 self.shell.logger.logstate()
1134
1134
1135 def magic_pdb(self, parameter_s=''):
1135 def magic_pdb(self, parameter_s=''):
1136 """Control the calling of the pdb interactive debugger.
1136 """Control the calling of the pdb interactive debugger.
1137
1137
1138 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1138 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1139 argument it works as a toggle.
1139 argument it works as a toggle.
1140
1140
1141 When an exception is triggered, IPython can optionally call the
1141 When an exception is triggered, IPython can optionally call the
1142 interactive pdb debugger after the traceback printout. %pdb toggles
1142 interactive pdb debugger after the traceback printout. %pdb toggles
1143 this feature on and off."""
1143 this feature on and off."""
1144
1144
1145 par = parameter_s.strip().lower()
1145 par = parameter_s.strip().lower()
1146
1146
1147 if par:
1147 if par:
1148 try:
1148 try:
1149 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1149 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1150 except KeyError:
1150 except KeyError:
1151 print ('Incorrect argument. Use on/1, off/0, '
1151 print ('Incorrect argument. Use on/1, off/0, '
1152 'or nothing for a toggle.')
1152 'or nothing for a toggle.')
1153 return
1153 return
1154 else:
1154 else:
1155 # toggle
1155 # toggle
1156 new_pdb = not self.shell.InteractiveTB.call_pdb
1156 new_pdb = not self.shell.InteractiveTB.call_pdb
1157
1157
1158 # set on the shell
1158 # set on the shell
1159 self.shell.call_pdb = new_pdb
1159 self.shell.call_pdb = new_pdb
1160 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1160 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1161
1161
1162 def magic_prun(self, parameter_s ='',user_mode=1,
1162 def magic_prun(self, parameter_s ='',user_mode=1,
1163 opts=None,arg_lst=None,prog_ns=None):
1163 opts=None,arg_lst=None,prog_ns=None):
1164
1164
1165 """Run a statement through the python code profiler.
1165 """Run a statement through the python code profiler.
1166
1166
1167 Usage:\\
1167 Usage:\\
1168 %prun [options] statement
1168 %prun [options] statement
1169
1169
1170 The given statement (which doesn't require quote marks) is run via the
1170 The given statement (which doesn't require quote marks) is run via the
1171 python profiler in a manner similar to the profile.run() function.
1171 python profiler in a manner similar to the profile.run() function.
1172 Namespaces are internally managed to work correctly; profile.run
1172 Namespaces are internally managed to work correctly; profile.run
1173 cannot be used in IPython because it makes certain assumptions about
1173 cannot be used in IPython because it makes certain assumptions about
1174 namespaces which do not hold under IPython.
1174 namespaces which do not hold under IPython.
1175
1175
1176 Options:
1176 Options:
1177
1177
1178 -l <limit>: you can place restrictions on what or how much of the
1178 -l <limit>: you can place restrictions on what or how much of the
1179 profile gets printed. The limit value can be:
1179 profile gets printed. The limit value can be:
1180
1180
1181 * A string: only information for function names containing this string
1181 * A string: only information for function names containing this string
1182 is printed.
1182 is printed.
1183
1183
1184 * An integer: only these many lines are printed.
1184 * An integer: only these many lines are printed.
1185
1185
1186 * A float (between 0 and 1): this fraction of the report is printed
1186 * A float (between 0 and 1): this fraction of the report is printed
1187 (for example, use a limit of 0.4 to see the topmost 40% only).
1187 (for example, use a limit of 0.4 to see the topmost 40% only).
1188
1188
1189 You can combine several limits with repeated use of the option. For
1189 You can combine several limits with repeated use of the option. For
1190 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1190 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1191 information about class constructors.
1191 information about class constructors.
1192
1192
1193 -r: return the pstats.Stats object generated by the profiling. This
1193 -r: return the pstats.Stats object generated by the profiling. This
1194 object has all the information about the profile in it, and you can
1194 object has all the information about the profile in it, and you can
1195 later use it for further analysis or in other functions.
1195 later use it for further analysis or in other functions.
1196
1196
1197 Since magic functions have a particular form of calling which prevents
1197 Since magic functions have a particular form of calling which prevents
1198 you from writing something like:\\
1198 you from writing something like:\\
1199 In [1]: p = %prun -r print 4 # invalid!\\
1199 In [1]: p = %prun -r print 4 # invalid!\\
1200 you must instead use IPython's automatic variables to assign this:\\
1200 you must instead use IPython's automatic variables to assign this:\\
1201 In [1]: %prun -r print 4 \\
1201 In [1]: %prun -r print 4 \\
1202 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1202 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1203 In [2]: stats = _
1203 In [2]: stats = _
1204
1204
1205 If you really need to assign this value via an explicit function call,
1205 If you really need to assign this value via an explicit function call,
1206 you can always tap directly into the true name of the magic function
1206 you can always tap directly into the true name of the magic function
1207 by using the _ip.magic function:\\
1207 by using the _ip.magic function:\\
1208 In [3]: stats = _ip.magic('prun','-r print 4')
1208 In [3]: stats = _ip.magic('prun','-r print 4')
1209
1209
1210 You can type _ip.magic? for more details.
1210 You can type _ip.magic? for more details.
1211
1211
1212 -s <key>: sort profile by given key. You can provide more than one key
1212 -s <key>: sort profile by given key. You can provide more than one key
1213 by using the option several times: '-s key1 -s key2 -s key3...'. The
1213 by using the option several times: '-s key1 -s key2 -s key3...'. The
1214 default sorting key is 'time'.
1214 default sorting key is 'time'.
1215
1215
1216 The following is copied verbatim from the profile documentation
1216 The following is copied verbatim from the profile documentation
1217 referenced below:
1217 referenced below:
1218
1218
1219 When more than one key is provided, additional keys are used as
1219 When more than one key is provided, additional keys are used as
1220 secondary criteria when the there is equality in all keys selected
1220 secondary criteria when the there is equality in all keys selected
1221 before them.
1221 before them.
1222
1222
1223 Abbreviations can be used for any key names, as long as the
1223 Abbreviations can be used for any key names, as long as the
1224 abbreviation is unambiguous. The following are the keys currently
1224 abbreviation is unambiguous. The following are the keys currently
1225 defined:
1225 defined:
1226
1226
1227 Valid Arg Meaning\\
1227 Valid Arg Meaning\\
1228 "calls" call count\\
1228 "calls" call count\\
1229 "cumulative" cumulative time\\
1229 "cumulative" cumulative time\\
1230 "file" file name\\
1230 "file" file name\\
1231 "module" file name\\
1231 "module" file name\\
1232 "pcalls" primitive call count\\
1232 "pcalls" primitive call count\\
1233 "line" line number\\
1233 "line" line number\\
1234 "name" function name\\
1234 "name" function name\\
1235 "nfl" name/file/line\\
1235 "nfl" name/file/line\\
1236 "stdname" standard name\\
1236 "stdname" standard name\\
1237 "time" internal time
1237 "time" internal time
1238
1238
1239 Note that all sorts on statistics are in descending order (placing
1239 Note that all sorts on statistics are in descending order (placing
1240 most time consuming items first), where as name, file, and line number
1240 most time consuming items first), where as name, file, and line number
1241 searches are in ascending order (i.e., alphabetical). The subtle
1241 searches are in ascending order (i.e., alphabetical). The subtle
1242 distinction between "nfl" and "stdname" is that the standard name is a
1242 distinction between "nfl" and "stdname" is that the standard name is a
1243 sort of the name as printed, which means that the embedded line
1243 sort of the name as printed, which means that the embedded line
1244 numbers get compared in an odd way. For example, lines 3, 20, and 40
1244 numbers get compared in an odd way. For example, lines 3, 20, and 40
1245 would (if the file names were the same) appear in the string order
1245 would (if the file names were the same) appear in the string order
1246 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1246 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1247 line numbers. In fact, sort_stats("nfl") is the same as
1247 line numbers. In fact, sort_stats("nfl") is the same as
1248 sort_stats("name", "file", "line").
1248 sort_stats("name", "file", "line").
1249
1249
1250 -T <filename>: save profile results as shown on screen to a text
1250 -T <filename>: save profile results as shown on screen to a text
1251 file. The profile is still shown on screen.
1251 file. The profile is still shown on screen.
1252
1252
1253 -D <filename>: save (via dump_stats) profile statistics to given
1253 -D <filename>: save (via dump_stats) profile statistics to given
1254 filename. This data is in a format understod by the pstats module, and
1254 filename. This data is in a format understod by the pstats module, and
1255 is generated by a call to the dump_stats() method of profile
1255 is generated by a call to the dump_stats() method of profile
1256 objects. The profile is still shown on screen.
1256 objects. The profile is still shown on screen.
1257
1257
1258 If you want to run complete programs under the profiler's control, use
1258 If you want to run complete programs under the profiler's control, use
1259 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1259 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1260 contains profiler specific options as described here.
1260 contains profiler specific options as described here.
1261
1261
1262 You can read the complete documentation for the profile module with:\\
1262 You can read the complete documentation for the profile module with:\\
1263 In [1]: import profile; profile.help() """
1263 In [1]: import profile; profile.help() """
1264
1264
1265 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1265 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1266 # protect user quote marks
1266 # protect user quote marks
1267 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1267 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1268
1268
1269 if user_mode: # regular user call
1269 if user_mode: # regular user call
1270 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1270 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1271 list_all=1)
1271 list_all=1)
1272 namespace = self.shell.user_ns
1272 namespace = self.shell.user_ns
1273 else: # called to run a program by %run -p
1273 else: # called to run a program by %run -p
1274 try:
1274 try:
1275 filename = get_py_filename(arg_lst[0])
1275 filename = get_py_filename(arg_lst[0])
1276 except IOError,msg:
1276 except IOError,msg:
1277 error(msg)
1277 error(msg)
1278 return
1278 return
1279
1279
1280 arg_str = 'execfile(filename,prog_ns)'
1280 arg_str = 'execfile(filename,prog_ns)'
1281 namespace = locals()
1281 namespace = locals()
1282
1282
1283 opts.merge(opts_def)
1283 opts.merge(opts_def)
1284
1284
1285 prof = profile.Profile()
1285 prof = profile.Profile()
1286 try:
1286 try:
1287 prof = prof.runctx(arg_str,namespace,namespace)
1287 prof = prof.runctx(arg_str,namespace,namespace)
1288 sys_exit = ''
1288 sys_exit = ''
1289 except SystemExit:
1289 except SystemExit:
1290 sys_exit = """*** SystemExit exception caught in code being profiled."""
1290 sys_exit = """*** SystemExit exception caught in code being profiled."""
1291
1291
1292 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1292 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1293
1293
1294 lims = opts.l
1294 lims = opts.l
1295 if lims:
1295 if lims:
1296 lims = [] # rebuild lims with ints/floats/strings
1296 lims = [] # rebuild lims with ints/floats/strings
1297 for lim in opts.l:
1297 for lim in opts.l:
1298 try:
1298 try:
1299 lims.append(int(lim))
1299 lims.append(int(lim))
1300 except ValueError:
1300 except ValueError:
1301 try:
1301 try:
1302 lims.append(float(lim))
1302 lims.append(float(lim))
1303 except ValueError:
1303 except ValueError:
1304 lims.append(lim)
1304 lims.append(lim)
1305
1305
1306 # trap output
1306 # trap output
1307 sys_stdout = sys.stdout
1307 sys_stdout = sys.stdout
1308 stdout_trap = StringIO()
1308 stdout_trap = StringIO()
1309 try:
1309 try:
1310 sys.stdout = stdout_trap
1310 sys.stdout = stdout_trap
1311 stats.print_stats(*lims)
1311 stats.print_stats(*lims)
1312 finally:
1312 finally:
1313 sys.stdout = sys_stdout
1313 sys.stdout = sys_stdout
1314 output = stdout_trap.getvalue()
1314 output = stdout_trap.getvalue()
1315 output = output.rstrip()
1315 output = output.rstrip()
1316
1316
1317 page(output,screen_lines=self.shell.rc.screen_length)
1317 page(output,screen_lines=self.shell.rc.screen_length)
1318 print sys_exit,
1318 print sys_exit,
1319
1319
1320 dump_file = opts.D[0]
1320 dump_file = opts.D[0]
1321 text_file = opts.T[0]
1321 text_file = opts.T[0]
1322 if dump_file:
1322 if dump_file:
1323 prof.dump_stats(dump_file)
1323 prof.dump_stats(dump_file)
1324 print '\n*** Profile stats marshalled to file',\
1324 print '\n*** Profile stats marshalled to file',\
1325 `dump_file`+'.',sys_exit
1325 `dump_file`+'.',sys_exit
1326 if text_file:
1326 if text_file:
1327 file(text_file,'w').write(output)
1327 file(text_file,'w').write(output)
1328 print '\n*** Profile printout saved to text file',\
1328 print '\n*** Profile printout saved to text file',\
1329 `text_file`+'.',sys_exit
1329 `text_file`+'.',sys_exit
1330
1330
1331 if opts.has_key('r'):
1331 if opts.has_key('r'):
1332 return stats
1332 return stats
1333 else:
1333 else:
1334 return None
1334 return None
1335
1335
1336 def magic_run(self, parameter_s ='',runner=None):
1336 def magic_run(self, parameter_s ='',runner=None):
1337 """Run the named file inside IPython as a program.
1337 """Run the named file inside IPython as a program.
1338
1338
1339 Usage:\\
1339 Usage:\\
1340 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1340 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1341
1341
1342 Parameters after the filename are passed as command-line arguments to
1342 Parameters after the filename are passed as command-line arguments to
1343 the program (put in sys.argv). Then, control returns to IPython's
1343 the program (put in sys.argv). Then, control returns to IPython's
1344 prompt.
1344 prompt.
1345
1345
1346 This is similar to running at a system prompt:\\
1346 This is similar to running at a system prompt:\\
1347 $ python file args\\
1347 $ python file args\\
1348 but with the advantage of giving you IPython's tracebacks, and of
1348 but with the advantage of giving you IPython's tracebacks, and of
1349 loading all variables into your interactive namespace for further use
1349 loading all variables into your interactive namespace for further use
1350 (unless -p is used, see below).
1350 (unless -p is used, see below).
1351
1351
1352 The file is executed in a namespace initially consisting only of
1352 The file is executed in a namespace initially consisting only of
1353 __name__=='__main__' and sys.argv constructed as indicated. It thus
1353 __name__=='__main__' and sys.argv constructed as indicated. It thus
1354 sees its environment as if it were being run as a stand-alone
1354 sees its environment as if it were being run as a stand-alone
1355 program. But after execution, the IPython interactive namespace gets
1355 program. But after execution, the IPython interactive namespace gets
1356 updated with all variables defined in the program (except for __name__
1356 updated with all variables defined in the program (except for __name__
1357 and sys.argv). This allows for very convenient loading of code for
1357 and sys.argv). This allows for very convenient loading of code for
1358 interactive work, while giving each program a 'clean sheet' to run in.
1358 interactive work, while giving each program a 'clean sheet' to run in.
1359
1359
1360 Options:
1360 Options:
1361
1361
1362 -n: __name__ is NOT set to '__main__', but to the running file's name
1362 -n: __name__ is NOT set to '__main__', but to the running file's name
1363 without extension (as python does under import). This allows running
1363 without extension (as python does under import). This allows running
1364 scripts and reloading the definitions in them without calling code
1364 scripts and reloading the definitions in them without calling code
1365 protected by an ' if __name__ == "__main__" ' clause.
1365 protected by an ' if __name__ == "__main__" ' clause.
1366
1366
1367 -i: run the file in IPython's namespace instead of an empty one. This
1367 -i: run the file in IPython's namespace instead of an empty one. This
1368 is useful if you are experimenting with code written in a text editor
1368 is useful if you are experimenting with code written in a text editor
1369 which depends on variables defined interactively.
1369 which depends on variables defined interactively.
1370
1370
1371 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1371 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1372 being run. This is particularly useful if IPython is being used to
1372 being run. This is particularly useful if IPython is being used to
1373 run unittests, which always exit with a sys.exit() call. In such
1373 run unittests, which always exit with a sys.exit() call. In such
1374 cases you are interested in the output of the test results, not in
1374 cases you are interested in the output of the test results, not in
1375 seeing a traceback of the unittest module.
1375 seeing a traceback of the unittest module.
1376
1376
1377 -t: print timing information at the end of the run. IPython will give
1377 -t: print timing information at the end of the run. IPython will give
1378 you an estimated CPU time consumption for your script, which under
1378 you an estimated CPU time consumption for your script, which under
1379 Unix uses the resource module to avoid the wraparound problems of
1379 Unix uses the resource module to avoid the wraparound problems of
1380 time.clock(). Under Unix, an estimate of time spent on system tasks
1380 time.clock(). Under Unix, an estimate of time spent on system tasks
1381 is also given (for Windows platforms this is reported as 0.0).
1381 is also given (for Windows platforms this is reported as 0.0).
1382
1382
1383 If -t is given, an additional -N<N> option can be given, where <N>
1383 If -t is given, an additional -N<N> option can be given, where <N>
1384 must be an integer indicating how many times you want the script to
1384 must be an integer indicating how many times you want the script to
1385 run. The final timing report will include total and per run results.
1385 run. The final timing report will include total and per run results.
1386
1386
1387 For example (testing the script uniq_stable.py):
1387 For example (testing the script uniq_stable.py):
1388
1388
1389 In [1]: run -t uniq_stable
1389 In [1]: run -t uniq_stable
1390
1390
1391 IPython CPU timings (estimated):\\
1391 IPython CPU timings (estimated):\\
1392 User : 0.19597 s.\\
1392 User : 0.19597 s.\\
1393 System: 0.0 s.\\
1393 System: 0.0 s.\\
1394
1394
1395 In [2]: run -t -N5 uniq_stable
1395 In [2]: run -t -N5 uniq_stable
1396
1396
1397 IPython CPU timings (estimated):\\
1397 IPython CPU timings (estimated):\\
1398 Total runs performed: 5\\
1398 Total runs performed: 5\\
1399 Times : Total Per run\\
1399 Times : Total Per run\\
1400 User : 0.910862 s, 0.1821724 s.\\
1400 User : 0.910862 s, 0.1821724 s.\\
1401 System: 0.0 s, 0.0 s.
1401 System: 0.0 s, 0.0 s.
1402
1402
1403 -d: run your program under the control of pdb, the Python debugger.
1403 -d: run your program under the control of pdb, the Python debugger.
1404 This allows you to execute your program step by step, watch variables,
1404 This allows you to execute your program step by step, watch variables,
1405 etc. Internally, what IPython does is similar to calling:
1405 etc. Internally, what IPython does is similar to calling:
1406
1406
1407 pdb.run('execfile("YOURFILENAME")')
1407 pdb.run('execfile("YOURFILENAME")')
1408
1408
1409 with a breakpoint set on line 1 of your file. You can change the line
1409 with a breakpoint set on line 1 of your file. You can change the line
1410 number for this automatic breakpoint to be <N> by using the -bN option
1410 number for this automatic breakpoint to be <N> by using the -bN option
1411 (where N must be an integer). For example:
1411 (where N must be an integer). For example:
1412
1412
1413 %run -d -b40 myscript
1413 %run -d -b40 myscript
1414
1414
1415 will set the first breakpoint at line 40 in myscript.py. Note that
1415 will set the first breakpoint at line 40 in myscript.py. Note that
1416 the first breakpoint must be set on a line which actually does
1416 the first breakpoint must be set on a line which actually does
1417 something (not a comment or docstring) for it to stop execution.
1417 something (not a comment or docstring) for it to stop execution.
1418
1418
1419 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1419 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1420 first enter 'c' (without qoutes) to start execution up to the first
1420 first enter 'c' (without qoutes) to start execution up to the first
1421 breakpoint.
1421 breakpoint.
1422
1422
1423 Entering 'help' gives information about the use of the debugger. You
1423 Entering 'help' gives information about the use of the debugger. You
1424 can easily see pdb's full documentation with "import pdb;pdb.help()"
1424 can easily see pdb's full documentation with "import pdb;pdb.help()"
1425 at a prompt.
1425 at a prompt.
1426
1426
1427 -p: run program under the control of the Python profiler module (which
1427 -p: run program under the control of the Python profiler module (which
1428 prints a detailed report of execution times, function calls, etc).
1428 prints a detailed report of execution times, function calls, etc).
1429
1429
1430 You can pass other options after -p which affect the behavior of the
1430 You can pass other options after -p which affect the behavior of the
1431 profiler itself. See the docs for %prun for details.
1431 profiler itself. See the docs for %prun for details.
1432
1432
1433 In this mode, the program's variables do NOT propagate back to the
1433 In this mode, the program's variables do NOT propagate back to the
1434 IPython interactive namespace (because they remain in the namespace
1434 IPython interactive namespace (because they remain in the namespace
1435 where the profiler executes them).
1435 where the profiler executes them).
1436
1436
1437 Internally this triggers a call to %prun, see its documentation for
1437 Internally this triggers a call to %prun, see its documentation for
1438 details on the options available specifically for profiling."""
1438 details on the options available specifically for profiling."""
1439
1439
1440 # get arguments and set sys.argv for program to be run.
1440 # get arguments and set sys.argv for program to be run.
1441 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1441 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1442 mode='list',list_all=1)
1442 mode='list',list_all=1)
1443
1443
1444 try:
1444 try:
1445 filename = get_py_filename(arg_lst[0])
1445 filename = get_py_filename(arg_lst[0])
1446 except IndexError:
1446 except IndexError:
1447 warn('you must provide at least a filename.')
1447 warn('you must provide at least a filename.')
1448 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1448 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1449 return
1449 return
1450 except IOError,msg:
1450 except IOError,msg:
1451 error(msg)
1451 error(msg)
1452 return
1452 return
1453
1453
1454 # Control the response to exit() calls made by the script being run
1454 # Control the response to exit() calls made by the script being run
1455 exit_ignore = opts.has_key('e')
1455 exit_ignore = opts.has_key('e')
1456
1456
1457 # Make sure that the running script gets a proper sys.argv as if it
1457 # Make sure that the running script gets a proper sys.argv as if it
1458 # were run from a system shell.
1458 # were run from a system shell.
1459 save_argv = sys.argv # save it for later restoring
1459 save_argv = sys.argv # save it for later restoring
1460 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1460 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1461
1461
1462 if opts.has_key('i'):
1462 if opts.has_key('i'):
1463 prog_ns = self.shell.user_ns
1463 prog_ns = self.shell.user_ns
1464 __name__save = self.shell.user_ns['__name__']
1464 __name__save = self.shell.user_ns['__name__']
1465 prog_ns['__name__'] = '__main__'
1465 prog_ns['__name__'] = '__main__'
1466 else:
1466 else:
1467 if opts.has_key('n'):
1467 if opts.has_key('n'):
1468 name = os.path.splitext(os.path.basename(filename))[0]
1468 name = os.path.splitext(os.path.basename(filename))[0]
1469 else:
1469 else:
1470 name = '__main__'
1470 name = '__main__'
1471 prog_ns = {'__name__':name}
1471 prog_ns = {'__name__':name}
1472
1472
1473 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1473 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1474 # set the __file__ global in the script's namespace
1474 # set the __file__ global in the script's namespace
1475 prog_ns['__file__'] = filename
1475 prog_ns['__file__'] = filename
1476
1476
1477 # pickle fix. See iplib for an explanation. But we need to make sure
1477 # pickle fix. See iplib for an explanation. But we need to make sure
1478 # that, if we overwrite __main__, we replace it at the end
1478 # that, if we overwrite __main__, we replace it at the end
1479 if prog_ns['__name__'] == '__main__':
1479 if prog_ns['__name__'] == '__main__':
1480 restore_main = sys.modules['__main__']
1480 restore_main = sys.modules['__main__']
1481 else:
1481 else:
1482 restore_main = False
1482 restore_main = False
1483
1483
1484 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1484 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1485
1485
1486 stats = None
1486 stats = None
1487 try:
1487 try:
1488 if opts.has_key('p'):
1488 if opts.has_key('p'):
1489 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1489 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1490 else:
1490 else:
1491 if opts.has_key('d'):
1491 if opts.has_key('d'):
1492 deb = Debugger.Pdb(self.shell.rc.colors)
1492 deb = Debugger.Pdb(self.shell.rc.colors)
1493 # reset Breakpoint state, which is moronically kept
1493 # reset Breakpoint state, which is moronically kept
1494 # in a class
1494 # in a class
1495 bdb.Breakpoint.next = 1
1495 bdb.Breakpoint.next = 1
1496 bdb.Breakpoint.bplist = {}
1496 bdb.Breakpoint.bplist = {}
1497 bdb.Breakpoint.bpbynumber = [None]
1497 bdb.Breakpoint.bpbynumber = [None]
1498 # Set an initial breakpoint to stop execution
1498 # Set an initial breakpoint to stop execution
1499 maxtries = 10
1499 maxtries = 10
1500 bp = int(opts.get('b',[1])[0])
1500 bp = int(opts.get('b',[1])[0])
1501 checkline = deb.checkline(filename,bp)
1501 checkline = deb.checkline(filename,bp)
1502 if not checkline:
1502 if not checkline:
1503 for bp in range(bp+1,bp+maxtries+1):
1503 for bp in range(bp+1,bp+maxtries+1):
1504 if deb.checkline(filename,bp):
1504 if deb.checkline(filename,bp):
1505 break
1505 break
1506 else:
1506 else:
1507 msg = ("\nI failed to find a valid line to set "
1507 msg = ("\nI failed to find a valid line to set "
1508 "a breakpoint\n"
1508 "a breakpoint\n"
1509 "after trying up to line: %s.\n"
1509 "after trying up to line: %s.\n"
1510 "Please set a valid breakpoint manually "
1510 "Please set a valid breakpoint manually "
1511 "with the -b option." % bp)
1511 "with the -b option." % bp)
1512 error(msg)
1512 error(msg)
1513 return
1513 return
1514 # if we find a good linenumber, set the breakpoint
1514 # if we find a good linenumber, set the breakpoint
1515 deb.do_break('%s:%s' % (filename,bp))
1515 deb.do_break('%s:%s' % (filename,bp))
1516 # Start file run
1516 # Start file run
1517 print "NOTE: Enter 'c' at the",
1517 print "NOTE: Enter 'c' at the",
1518 print "ipdb> prompt to start your script."
1518 print "ipdb> prompt to start your script."
1519 try:
1519 try:
1520 deb.run('execfile("%s")' % filename,prog_ns)
1520 deb.run('execfile("%s")' % filename,prog_ns)
1521 except:
1521 except:
1522 etype, value, tb = sys.exc_info()
1522 etype, value, tb = sys.exc_info()
1523 # Skip three frames in the traceback: the %run one,
1523 # Skip three frames in the traceback: the %run one,
1524 # one inside bdb.py, and the command-line typed by the
1524 # one inside bdb.py, and the command-line typed by the
1525 # user (run by exec in pdb itself).
1525 # user (run by exec in pdb itself).
1526 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1526 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1527 else:
1527 else:
1528 if runner is None:
1528 if runner is None:
1529 runner = self.shell.safe_execfile
1529 runner = self.shell.safe_execfile
1530 if opts.has_key('t'):
1530 if opts.has_key('t'):
1531 try:
1531 try:
1532 nruns = int(opts['N'][0])
1532 nruns = int(opts['N'][0])
1533 if nruns < 1:
1533 if nruns < 1:
1534 error('Number of runs must be >=1')
1534 error('Number of runs must be >=1')
1535 return
1535 return
1536 except (KeyError):
1536 except (KeyError):
1537 nruns = 1
1537 nruns = 1
1538 if nruns == 1:
1538 if nruns == 1:
1539 t0 = clock2()
1539 t0 = clock2()
1540 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1540 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1541 t1 = clock2()
1541 t1 = clock2()
1542 t_usr = t1[0]-t0[0]
1542 t_usr = t1[0]-t0[0]
1543 t_sys = t1[1]-t1[1]
1543 t_sys = t1[1]-t1[1]
1544 print "\nIPython CPU timings (estimated):"
1544 print "\nIPython CPU timings (estimated):"
1545 print " User : %10s s." % t_usr
1545 print " User : %10s s." % t_usr
1546 print " System: %10s s." % t_sys
1546 print " System: %10s s." % t_sys
1547 else:
1547 else:
1548 runs = range(nruns)
1548 runs = range(nruns)
1549 t0 = clock2()
1549 t0 = clock2()
1550 for nr in runs:
1550 for nr in runs:
1551 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1551 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1552 t1 = clock2()
1552 t1 = clock2()
1553 t_usr = t1[0]-t0[0]
1553 t_usr = t1[0]-t0[0]
1554 t_sys = t1[1]-t1[1]
1554 t_sys = t1[1]-t1[1]
1555 print "\nIPython CPU timings (estimated):"
1555 print "\nIPython CPU timings (estimated):"
1556 print "Total runs performed:",nruns
1556 print "Total runs performed:",nruns
1557 print " Times : %10s %10s" % ('Total','Per run')
1557 print " Times : %10s %10s" % ('Total','Per run')
1558 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1558 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1559 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1559 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1560
1560
1561 else:
1561 else:
1562 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1562 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1563 if opts.has_key('i'):
1563 if opts.has_key('i'):
1564 self.shell.user_ns['__name__'] = __name__save
1564 self.shell.user_ns['__name__'] = __name__save
1565 else:
1565 else:
1566 # update IPython interactive namespace
1566 # update IPython interactive namespace
1567 del prog_ns['__name__']
1567 del prog_ns['__name__']
1568 self.shell.user_ns.update(prog_ns)
1568 self.shell.user_ns.update(prog_ns)
1569 finally:
1569 finally:
1570 sys.argv = save_argv
1570 sys.argv = save_argv
1571 if restore_main:
1571 if restore_main:
1572 sys.modules['__main__'] = restore_main
1572 sys.modules['__main__'] = restore_main
1573 return stats
1573 return stats
1574
1574
1575 def magic_runlog(self, parameter_s =''):
1575 def magic_runlog(self, parameter_s =''):
1576 """Run files as logs.
1576 """Run files as logs.
1577
1577
1578 Usage:\\
1578 Usage:\\
1579 %runlog file1 file2 ...
1579 %runlog file1 file2 ...
1580
1580
1581 Run the named files (treating them as log files) in sequence inside
1581 Run the named files (treating them as log files) in sequence inside
1582 the interpreter, and return to the prompt. This is much slower than
1582 the interpreter, and return to the prompt. This is much slower than
1583 %run because each line is executed in a try/except block, but it
1583 %run because each line is executed in a try/except block, but it
1584 allows running files with syntax errors in them.
1584 allows running files with syntax errors in them.
1585
1585
1586 Normally IPython will guess when a file is one of its own logfiles, so
1586 Normally IPython will guess when a file is one of its own logfiles, so
1587 you can typically use %run even for logs. This shorthand allows you to
1587 you can typically use %run even for logs. This shorthand allows you to
1588 force any file to be treated as a log file."""
1588 force any file to be treated as a log file."""
1589
1589
1590 for f in parameter_s.split():
1590 for f in parameter_s.split():
1591 self.shell.safe_execfile(f,self.shell.user_ns,
1591 self.shell.safe_execfile(f,self.shell.user_ns,
1592 self.shell.user_ns,islog=1)
1592 self.shell.user_ns,islog=1)
1593
1593
1594 def magic_timeit(self, parameter_s =''):
1594 def magic_timeit(self, parameter_s =''):
1595 """Time execution of a Python statement or expression
1595 """Time execution of a Python statement or expression
1596
1596
1597 Usage:\\
1597 Usage:\\
1598 %timeit [-n<N> -r<R> [-t|-c]] statement
1598 %timeit [-n<N> -r<R> [-t|-c]] statement
1599
1599
1600 Time execution of a Python statement or expression using the timeit
1600 Time execution of a Python statement or expression using the timeit
1601 module.
1601 module.
1602
1602
1603 Options:
1603 Options:
1604 -n<N>: execute the given statement <N> times in a loop. If this value
1604 -n<N>: execute the given statement <N> times in a loop. If this value
1605 is not given, a fitting value is chosen.
1605 is not given, a fitting value is chosen.
1606
1606
1607 -r<R>: repeat the loop iteration <R> times and take the best result.
1607 -r<R>: repeat the loop iteration <R> times and take the best result.
1608 Default: 3
1608 Default: 3
1609
1609
1610 -t: use time.time to measure the time, which is the default on Unix.
1610 -t: use time.time to measure the time, which is the default on Unix.
1611 This function measures wall time.
1611 This function measures wall time.
1612
1612
1613 -c: use time.clock to measure the time, which is the default on
1613 -c: use time.clock to measure the time, which is the default on
1614 Windows and measures wall time. On Unix, resource.getrusage is used
1614 Windows and measures wall time. On Unix, resource.getrusage is used
1615 instead and returns the CPU user time.
1615 instead and returns the CPU user time.
1616
1616
1617 -p<P>: use a precision of <P> digits to display the timing result.
1617 -p<P>: use a precision of <P> digits to display the timing result.
1618 Default: 3
1618 Default: 3
1619
1619
1620
1620
1621 Examples:\\
1621 Examples:\\
1622 In [1]: %timeit pass
1622 In [1]: %timeit pass
1623 10000000 loops, best of 3: 53.3 ns per loop
1623 10000000 loops, best of 3: 53.3 ns per loop
1624
1624
1625 In [2]: u = None
1625 In [2]: u = None
1626
1626
1627 In [3]: %timeit u is None
1627 In [3]: %timeit u is None
1628 10000000 loops, best of 3: 184 ns per loop
1628 10000000 loops, best of 3: 184 ns per loop
1629
1629
1630 In [4]: %timeit -r 4 u == None
1630 In [4]: %timeit -r 4 u == None
1631 1000000 loops, best of 4: 242 ns per loop
1631 1000000 loops, best of 4: 242 ns per loop
1632
1632
1633 In [5]: import time
1633 In [5]: import time
1634
1634
1635 In [6]: %timeit -n1 time.sleep(2)
1635 In [6]: %timeit -n1 time.sleep(2)
1636 1 loops, best of 3: 2 s per loop
1636 1 loops, best of 3: 2 s per loop
1637
1637
1638
1638
1639 The times reported by %timeit will be slightly higher than those reported
1639 The times reported by %timeit will be slightly higher than those reported
1640 by the timeit.py script when variables are accessed. This is due to the
1640 by the timeit.py script when variables are accessed. This is due to the
1641 fact that %timeit executes the statement in the namespace of the shell,
1641 fact that %timeit executes the statement in the namespace of the shell,
1642 compared with timeit.py, which uses a single setup statement to import
1642 compared with timeit.py, which uses a single setup statement to import
1643 function or create variables. Generally, the bias does not matter as long
1643 function or create variables. Generally, the bias does not matter as long
1644 as results from timeit.py are not mixed with those from %timeit."""
1644 as results from timeit.py are not mixed with those from %timeit."""
1645 import timeit
1645 import timeit
1646 import math
1646 import math
1647
1647
1648 units = ["s", "ms", "\xc2\xb5s", "ns"]
1648 units = ["s", "ms", "\xc2\xb5s", "ns"]
1649 scaling = [1, 1e3, 1e6, 1e9]
1649 scaling = [1, 1e3, 1e6, 1e9]
1650
1650
1651 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:')
1651 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:')
1652 if stmt == "":
1652 if stmt == "":
1653 return
1653 return
1654 timefunc = timeit.default_timer
1654 timefunc = timeit.default_timer
1655 number = int(getattr(opts, "n", 0))
1655 number = int(getattr(opts, "n", 0))
1656 repeat = int(getattr(opts, "r", timeit.default_repeat))
1656 repeat = int(getattr(opts, "r", timeit.default_repeat))
1657 precision = int(getattr(opts, "p", 3))
1657 precision = int(getattr(opts, "p", 3))
1658 if hasattr(opts, "t"):
1658 if hasattr(opts, "t"):
1659 timefunc = time.time
1659 timefunc = time.time
1660 if hasattr(opts, "c"):
1660 if hasattr(opts, "c"):
1661 timefunc = clock
1661 timefunc = clock
1662
1662
1663 timer = timeit.Timer(timer=timefunc)
1663 timer = timeit.Timer(timer=timefunc)
1664 # this code has tight coupling to the inner workings of timeit.Timer,
1664 # this code has tight coupling to the inner workings of timeit.Timer,
1665 # but is there a better way to achieve that the code stmt has access
1665 # but is there a better way to achieve that the code stmt has access
1666 # to the shell namespace?
1666 # to the shell namespace?
1667
1667
1668 src = timeit.template % {'stmt': timeit.reindent(stmt, 8), 'setup': "pass"}
1668 src = timeit.template % {'stmt': timeit.reindent(stmt, 8), 'setup': "pass"}
1669 code = compile(src, "<magic-timeit>", "exec")
1669 code = compile(src, "<magic-timeit>", "exec")
1670 ns = {}
1670 ns = {}
1671 exec code in self.shell.user_ns, ns
1671 exec code in self.shell.user_ns, ns
1672 timer.inner = ns["inner"]
1672 timer.inner = ns["inner"]
1673
1673
1674 if number == 0:
1674 if number == 0:
1675 # determine number so that 0.2 <= total time < 2.0
1675 # determine number so that 0.2 <= total time < 2.0
1676 number = 1
1676 number = 1
1677 for i in range(1, 10):
1677 for i in range(1, 10):
1678 number *= 10
1678 number *= 10
1679 if timer.timeit(number) >= 0.2:
1679 if timer.timeit(number) >= 0.2:
1680 break
1680 break
1681
1681
1682 best = min(timer.repeat(repeat, number)) / number
1682 best = min(timer.repeat(repeat, number)) / number
1683
1683
1684 if best > 0.0:
1684 if best > 0.0:
1685 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1685 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1686 else:
1686 else:
1687 order = 3
1687 order = 3
1688 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1688 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1689 precision,
1689 precision,
1690 best * scaling[order],
1690 best * scaling[order],
1691 units[order])
1691 units[order])
1692
1692
1693 def magic_time(self,parameter_s = ''):
1693 def magic_time(self,parameter_s = ''):
1694 """Time execution of a Python statement or expression.
1694 """Time execution of a Python statement or expression.
1695
1695
1696 The CPU and wall clock times are printed, and the value of the
1696 The CPU and wall clock times are printed, and the value of the
1697 expression (if any) is returned. Note that under Win32, system time
1697 expression (if any) is returned. Note that under Win32, system time
1698 is always reported as 0, since it can not be measured.
1698 is always reported as 0, since it can not be measured.
1699
1699
1700 This function provides very basic timing functionality. In Python
1700 This function provides very basic timing functionality. In Python
1701 2.3, the timeit module offers more control and sophistication, so this
1701 2.3, the timeit module offers more control and sophistication, so this
1702 could be rewritten to use it (patches welcome).
1702 could be rewritten to use it (patches welcome).
1703
1703
1704 Some examples:
1704 Some examples:
1705
1705
1706 In [1]: time 2**128
1706 In [1]: time 2**128
1707 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1707 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1708 Wall time: 0.00
1708 Wall time: 0.00
1709 Out[1]: 340282366920938463463374607431768211456L
1709 Out[1]: 340282366920938463463374607431768211456L
1710
1710
1711 In [2]: n = 1000000
1711 In [2]: n = 1000000
1712
1712
1713 In [3]: time sum(range(n))
1713 In [3]: time sum(range(n))
1714 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1714 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1715 Wall time: 1.37
1715 Wall time: 1.37
1716 Out[3]: 499999500000L
1716 Out[3]: 499999500000L
1717
1717
1718 In [4]: time print 'hello world'
1718 In [4]: time print 'hello world'
1719 hello world
1719 hello world
1720 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1720 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1721 Wall time: 0.00
1721 Wall time: 0.00
1722 """
1722 """
1723
1723
1724 # fail immediately if the given expression can't be compiled
1724 # fail immediately if the given expression can't be compiled
1725 try:
1725 try:
1726 mode = 'eval'
1726 mode = 'eval'
1727 code = compile(parameter_s,'<timed eval>',mode)
1727 code = compile(parameter_s,'<timed eval>',mode)
1728 except SyntaxError:
1728 except SyntaxError:
1729 mode = 'exec'
1729 mode = 'exec'
1730 code = compile(parameter_s,'<timed exec>',mode)
1730 code = compile(parameter_s,'<timed exec>',mode)
1731 # skew measurement as little as possible
1731 # skew measurement as little as possible
1732 glob = self.shell.user_ns
1732 glob = self.shell.user_ns
1733 clk = clock2
1733 clk = clock2
1734 wtime = time.time
1734 wtime = time.time
1735 # time execution
1735 # time execution
1736 wall_st = wtime()
1736 wall_st = wtime()
1737 if mode=='eval':
1737 if mode=='eval':
1738 st = clk()
1738 st = clk()
1739 out = eval(code,glob)
1739 out = eval(code,glob)
1740 end = clk()
1740 end = clk()
1741 else:
1741 else:
1742 st = clk()
1742 st = clk()
1743 exec code in glob
1743 exec code in glob
1744 end = clk()
1744 end = clk()
1745 out = None
1745 out = None
1746 wall_end = wtime()
1746 wall_end = wtime()
1747 # Compute actual times and report
1747 # Compute actual times and report
1748 wall_time = wall_end-wall_st
1748 wall_time = wall_end-wall_st
1749 cpu_user = end[0]-st[0]
1749 cpu_user = end[0]-st[0]
1750 cpu_sys = end[1]-st[1]
1750 cpu_sys = end[1]-st[1]
1751 cpu_tot = cpu_user+cpu_sys
1751 cpu_tot = cpu_user+cpu_sys
1752 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1752 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1753 (cpu_user,cpu_sys,cpu_tot)
1753 (cpu_user,cpu_sys,cpu_tot)
1754 print "Wall time: %.2f" % wall_time
1754 print "Wall time: %.2f" % wall_time
1755 return out
1755 return out
1756
1756
1757 def magic_macro(self,parameter_s = ''):
1757 def magic_macro(self,parameter_s = ''):
1758 """Define a set of input lines as a macro for future re-execution.
1758 """Define a set of input lines as a macro for future re-execution.
1759
1759
1760 Usage:\\
1760 Usage:\\
1761 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1761 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1762
1762
1763 Options:
1763 Options:
1764
1764
1765 -r: use 'raw' input. By default, the 'processed' history is used,
1765 -r: use 'raw' input. By default, the 'processed' history is used,
1766 so that magics are loaded in their transformed version to valid
1766 so that magics are loaded in their transformed version to valid
1767 Python. If this option is given, the raw input as typed as the
1767 Python. If this option is given, the raw input as typed as the
1768 command line is used instead.
1768 command line is used instead.
1769
1769
1770 This will define a global variable called `name` which is a string
1770 This will define a global variable called `name` which is a string
1771 made of joining the slices and lines you specify (n1,n2,... numbers
1771 made of joining the slices and lines you specify (n1,n2,... numbers
1772 above) from your input history into a single string. This variable
1772 above) from your input history into a single string. This variable
1773 acts like an automatic function which re-executes those lines as if
1773 acts like an automatic function which re-executes those lines as if
1774 you had typed them. You just type 'name' at the prompt and the code
1774 you had typed them. You just type 'name' at the prompt and the code
1775 executes.
1775 executes.
1776
1776
1777 The notation for indicating number ranges is: n1-n2 means 'use line
1777 The notation for indicating number ranges is: n1-n2 means 'use line
1778 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1778 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1779 using the lines numbered 5,6 and 7.
1779 using the lines numbered 5,6 and 7.
1780
1780
1781 Note: as a 'hidden' feature, you can also use traditional python slice
1781 Note: as a 'hidden' feature, you can also use traditional python slice
1782 notation, where N:M means numbers N through M-1.
1782 notation, where N:M means numbers N through M-1.
1783
1783
1784 For example, if your history contains (%hist prints it):
1784 For example, if your history contains (%hist prints it):
1785
1785
1786 44: x=1\\
1786 44: x=1\\
1787 45: y=3\\
1787 45: y=3\\
1788 46: z=x+y\\
1788 46: z=x+y\\
1789 47: print x\\
1789 47: print x\\
1790 48: a=5\\
1790 48: a=5\\
1791 49: print 'x',x,'y',y\\
1791 49: print 'x',x,'y',y\\
1792
1792
1793 you can create a macro with lines 44 through 47 (included) and line 49
1793 you can create a macro with lines 44 through 47 (included) and line 49
1794 called my_macro with:
1794 called my_macro with:
1795
1795
1796 In [51]: %macro my_macro 44-47 49
1796 In [51]: %macro my_macro 44-47 49
1797
1797
1798 Now, typing `my_macro` (without quotes) will re-execute all this code
1798 Now, typing `my_macro` (without quotes) will re-execute all this code
1799 in one pass.
1799 in one pass.
1800
1800
1801 You don't need to give the line-numbers in order, and any given line
1801 You don't need to give the line-numbers in order, and any given line
1802 number can appear multiple times. You can assemble macros with any
1802 number can appear multiple times. You can assemble macros with any
1803 lines from your input history in any order.
1803 lines from your input history in any order.
1804
1804
1805 The macro is a simple object which holds its value in an attribute,
1805 The macro is a simple object which holds its value in an attribute,
1806 but IPython's display system checks for macros and executes them as
1806 but IPython's display system checks for macros and executes them as
1807 code instead of printing them when you type their name.
1807 code instead of printing them when you type their name.
1808
1808
1809 You can view a macro's contents by explicitly printing it with:
1809 You can view a macro's contents by explicitly printing it with:
1810
1810
1811 'print macro_name'.
1811 'print macro_name'.
1812
1812
1813 For one-off cases which DON'T contain magic function calls in them you
1813 For one-off cases which DON'T contain magic function calls in them you
1814 can obtain similar results by explicitly executing slices from your
1814 can obtain similar results by explicitly executing slices from your
1815 input history with:
1815 input history with:
1816
1816
1817 In [60]: exec In[44:48]+In[49]"""
1817 In [60]: exec In[44:48]+In[49]"""
1818
1818
1819 opts,args = self.parse_options(parameter_s,'r',mode='list')
1819 opts,args = self.parse_options(parameter_s,'r',mode='list')
1820 name,ranges = args[0], args[1:]
1820 name,ranges = args[0], args[1:]
1821 #print 'rng',ranges # dbg
1821 #print 'rng',ranges # dbg
1822 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1822 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1823 macro = Macro(lines)
1823 macro = Macro(lines)
1824 self.shell.user_ns.update({name:macro})
1824 self.shell.user_ns.update({name:macro})
1825 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1825 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1826 print 'Macro contents:'
1826 print 'Macro contents:'
1827 print macro,
1827 print macro,
1828
1828
1829 def magic_save(self,parameter_s = ''):
1829 def magic_save(self,parameter_s = ''):
1830 """Save a set of lines to a given filename.
1830 """Save a set of lines to a given filename.
1831
1831
1832 Usage:\\
1832 Usage:\\
1833 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1833 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1834
1834
1835 Options:
1835 Options:
1836
1836
1837 -r: use 'raw' input. By default, the 'processed' history is used,
1837 -r: use 'raw' input. By default, the 'processed' history is used,
1838 so that magics are loaded in their transformed version to valid
1838 so that magics are loaded in their transformed version to valid
1839 Python. If this option is given, the raw input as typed as the
1839 Python. If this option is given, the raw input as typed as the
1840 command line is used instead.
1840 command line is used instead.
1841
1841
1842 This function uses the same syntax as %macro for line extraction, but
1842 This function uses the same syntax as %macro for line extraction, but
1843 instead of creating a macro it saves the resulting string to the
1843 instead of creating a macro it saves the resulting string to the
1844 filename you specify.
1844 filename you specify.
1845
1845
1846 It adds a '.py' extension to the file if you don't do so yourself, and
1846 It adds a '.py' extension to the file if you don't do so yourself, and
1847 it asks for confirmation before overwriting existing files."""
1847 it asks for confirmation before overwriting existing files."""
1848
1848
1849 opts,args = self.parse_options(parameter_s,'r',mode='list')
1849 opts,args = self.parse_options(parameter_s,'r',mode='list')
1850 fname,ranges = args[0], args[1:]
1850 fname,ranges = args[0], args[1:]
1851 if not fname.endswith('.py'):
1851 if not fname.endswith('.py'):
1852 fname += '.py'
1852 fname += '.py'
1853 if os.path.isfile(fname):
1853 if os.path.isfile(fname):
1854 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1854 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1855 if ans.lower() not in ['y','yes']:
1855 if ans.lower() not in ['y','yes']:
1856 print 'Operation cancelled.'
1856 print 'Operation cancelled.'
1857 return
1857 return
1858 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1858 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1859 f = file(fname,'w')
1859 f = file(fname,'w')
1860 f.write(cmds)
1860 f.write(cmds)
1861 f.close()
1861 f.close()
1862 print 'The following commands were written to file `%s`:' % fname
1862 print 'The following commands were written to file `%s`:' % fname
1863 print cmds
1863 print cmds
1864
1864
1865 def _edit_macro(self,mname,macro):
1865 def _edit_macro(self,mname,macro):
1866 """open an editor with the macro data in a file"""
1866 """open an editor with the macro data in a file"""
1867 filename = self.shell.mktempfile(macro.value)
1867 filename = self.shell.mktempfile(macro.value)
1868 self.shell.hooks.editor(filename)
1868 self.shell.hooks.editor(filename)
1869
1869
1870 # and make a new macro object, to replace the old one
1870 # and make a new macro object, to replace the old one
1871 mfile = open(filename)
1871 mfile = open(filename)
1872 mvalue = mfile.read()
1872 mvalue = mfile.read()
1873 mfile.close()
1873 mfile.close()
1874 self.shell.user_ns[mname] = Macro(mvalue)
1874 self.shell.user_ns[mname] = Macro(mvalue)
1875
1875
1876 def magic_ed(self,parameter_s=''):
1876 def magic_ed(self,parameter_s=''):
1877 """Alias to %edit."""
1877 """Alias to %edit."""
1878 return self.magic_edit(parameter_s)
1878 return self.magic_edit(parameter_s)
1879
1879
1880 def magic_edit(self,parameter_s='',last_call=['','']):
1880 def magic_edit(self,parameter_s='',last_call=['','']):
1881 """Bring up an editor and execute the resulting code.
1881 """Bring up an editor and execute the resulting code.
1882
1882
1883 Usage:
1883 Usage:
1884 %edit [options] [args]
1884 %edit [options] [args]
1885
1885
1886 %edit runs IPython's editor hook. The default version of this hook is
1886 %edit runs IPython's editor hook. The default version of this hook is
1887 set to call the __IPYTHON__.rc.editor command. This is read from your
1887 set to call the __IPYTHON__.rc.editor command. This is read from your
1888 environment variable $EDITOR. If this isn't found, it will default to
1888 environment variable $EDITOR. If this isn't found, it will default to
1889 vi under Linux/Unix and to notepad under Windows. See the end of this
1889 vi under Linux/Unix and to notepad under Windows. See the end of this
1890 docstring for how to change the editor hook.
1890 docstring for how to change the editor hook.
1891
1891
1892 You can also set the value of this editor via the command line option
1892 You can also set the value of this editor via the command line option
1893 '-editor' or in your ipythonrc file. This is useful if you wish to use
1893 '-editor' or in your ipythonrc file. This is useful if you wish to use
1894 specifically for IPython an editor different from your typical default
1894 specifically for IPython an editor different from your typical default
1895 (and for Windows users who typically don't set environment variables).
1895 (and for Windows users who typically don't set environment variables).
1896
1896
1897 This command allows you to conveniently edit multi-line code right in
1897 This command allows you to conveniently edit multi-line code right in
1898 your IPython session.
1898 your IPython session.
1899
1899
1900 If called without arguments, %edit opens up an empty editor with a
1900 If called without arguments, %edit opens up an empty editor with a
1901 temporary file and will execute the contents of this file when you
1901 temporary file and will execute the contents of this file when you
1902 close it (don't forget to save it!).
1902 close it (don't forget to save it!).
1903
1903
1904
1904
1905 Options:
1905 Options:
1906
1906
1907 -n <number>: open the editor at a specified line number. By default,
1907 -n <number>: open the editor at a specified line number. By default,
1908 the IPython editor hook uses the unix syntax 'editor +N filename', but
1908 the IPython editor hook uses the unix syntax 'editor +N filename', but
1909 you can configure this by providing your own modified hook if your
1909 you can configure this by providing your own modified hook if your
1910 favorite editor supports line-number specifications with a different
1910 favorite editor supports line-number specifications with a different
1911 syntax.
1911 syntax.
1912
1912
1913 -p: this will call the editor with the same data as the previous time
1913 -p: this will call the editor with the same data as the previous time
1914 it was used, regardless of how long ago (in your current session) it
1914 it was used, regardless of how long ago (in your current session) it
1915 was.
1915 was.
1916
1916
1917 -r: use 'raw' input. This option only applies to input taken from the
1917 -r: use 'raw' input. This option only applies to input taken from the
1918 user's history. By default, the 'processed' history is used, so that
1918 user's history. By default, the 'processed' history is used, so that
1919 magics are loaded in their transformed version to valid Python. If
1919 magics are loaded in their transformed version to valid Python. If
1920 this option is given, the raw input as typed as the command line is
1920 this option is given, the raw input as typed as the command line is
1921 used instead. When you exit the editor, it will be executed by
1921 used instead. When you exit the editor, it will be executed by
1922 IPython's own processor.
1922 IPython's own processor.
1923
1923
1924 -x: do not execute the edited code immediately upon exit. This is
1924 -x: do not execute the edited code immediately upon exit. This is
1925 mainly useful if you are editing programs which need to be called with
1925 mainly useful if you are editing programs which need to be called with
1926 command line arguments, which you can then do using %run.
1926 command line arguments, which you can then do using %run.
1927
1927
1928
1928
1929 Arguments:
1929 Arguments:
1930
1930
1931 If arguments are given, the following possibilites exist:
1931 If arguments are given, the following possibilites exist:
1932
1932
1933 - The arguments are numbers or pairs of colon-separated numbers (like
1933 - The arguments are numbers or pairs of colon-separated numbers (like
1934 1 4:8 9). These are interpreted as lines of previous input to be
1934 1 4:8 9). These are interpreted as lines of previous input to be
1935 loaded into the editor. The syntax is the same of the %macro command.
1935 loaded into the editor. The syntax is the same of the %macro command.
1936
1936
1937 - If the argument doesn't start with a number, it is evaluated as a
1937 - If the argument doesn't start with a number, it is evaluated as a
1938 variable and its contents loaded into the editor. You can thus edit
1938 variable and its contents loaded into the editor. You can thus edit
1939 any string which contains python code (including the result of
1939 any string which contains python code (including the result of
1940 previous edits).
1940 previous edits).
1941
1941
1942 - If the argument is the name of an object (other than a string),
1942 - If the argument is the name of an object (other than a string),
1943 IPython will try to locate the file where it was defined and open the
1943 IPython will try to locate the file where it was defined and open the
1944 editor at the point where it is defined. You can use `%edit function`
1944 editor at the point where it is defined. You can use `%edit function`
1945 to load an editor exactly at the point where 'function' is defined,
1945 to load an editor exactly at the point where 'function' is defined,
1946 edit it and have the file be executed automatically.
1946 edit it and have the file be executed automatically.
1947
1947
1948 If the object is a macro (see %macro for details), this opens up your
1948 If the object is a macro (see %macro for details), this opens up your
1949 specified editor with a temporary file containing the macro's data.
1949 specified editor with a temporary file containing the macro's data.
1950 Upon exit, the macro is reloaded with the contents of the file.
1950 Upon exit, the macro is reloaded with the contents of the file.
1951
1951
1952 Note: opening at an exact line is only supported under Unix, and some
1952 Note: opening at an exact line is only supported under Unix, and some
1953 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1953 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1954 '+NUMBER' parameter necessary for this feature. Good editors like
1954 '+NUMBER' parameter necessary for this feature. Good editors like
1955 (X)Emacs, vi, jed, pico and joe all do.
1955 (X)Emacs, vi, jed, pico and joe all do.
1956
1956
1957 - If the argument is not found as a variable, IPython will look for a
1957 - If the argument is not found as a variable, IPython will look for a
1958 file with that name (adding .py if necessary) and load it into the
1958 file with that name (adding .py if necessary) and load it into the
1959 editor. It will execute its contents with execfile() when you exit,
1959 editor. It will execute its contents with execfile() when you exit,
1960 loading any code in the file into your interactive namespace.
1960 loading any code in the file into your interactive namespace.
1961
1961
1962 After executing your code, %edit will return as output the code you
1962 After executing your code, %edit will return as output the code you
1963 typed in the editor (except when it was an existing file). This way
1963 typed in the editor (except when it was an existing file). This way
1964 you can reload the code in further invocations of %edit as a variable,
1964 you can reload the code in further invocations of %edit as a variable,
1965 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1965 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1966 the output.
1966 the output.
1967
1967
1968 Note that %edit is also available through the alias %ed.
1968 Note that %edit is also available through the alias %ed.
1969
1969
1970 This is an example of creating a simple function inside the editor and
1970 This is an example of creating a simple function inside the editor and
1971 then modifying it. First, start up the editor:
1971 then modifying it. First, start up the editor:
1972
1972
1973 In [1]: ed\\
1973 In [1]: ed\\
1974 Editing... done. Executing edited code...\\
1974 Editing... done. Executing edited code...\\
1975 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1975 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1976
1976
1977 We can then call the function foo():
1977 We can then call the function foo():
1978
1978
1979 In [2]: foo()\\
1979 In [2]: foo()\\
1980 foo() was defined in an editing session
1980 foo() was defined in an editing session
1981
1981
1982 Now we edit foo. IPython automatically loads the editor with the
1982 Now we edit foo. IPython automatically loads the editor with the
1983 (temporary) file where foo() was previously defined:
1983 (temporary) file where foo() was previously defined:
1984
1984
1985 In [3]: ed foo\\
1985 In [3]: ed foo\\
1986 Editing... done. Executing edited code...
1986 Editing... done. Executing edited code...
1987
1987
1988 And if we call foo() again we get the modified version:
1988 And if we call foo() again we get the modified version:
1989
1989
1990 In [4]: foo()\\
1990 In [4]: foo()\\
1991 foo() has now been changed!
1991 foo() has now been changed!
1992
1992
1993 Here is an example of how to edit a code snippet successive
1993 Here is an example of how to edit a code snippet successive
1994 times. First we call the editor:
1994 times. First we call the editor:
1995
1995
1996 In [8]: ed\\
1996 In [8]: ed\\
1997 Editing... done. Executing edited code...\\
1997 Editing... done. Executing edited code...\\
1998 hello\\
1998 hello\\
1999 Out[8]: "print 'hello'\\n"
1999 Out[8]: "print 'hello'\\n"
2000
2000
2001 Now we call it again with the previous output (stored in _):
2001 Now we call it again with the previous output (stored in _):
2002
2002
2003 In [9]: ed _\\
2003 In [9]: ed _\\
2004 Editing... done. Executing edited code...\\
2004 Editing... done. Executing edited code...\\
2005 hello world\\
2005 hello world\\
2006 Out[9]: "print 'hello world'\\n"
2006 Out[9]: "print 'hello world'\\n"
2007
2007
2008 Now we call it with the output #8 (stored in _8, also as Out[8]):
2008 Now we call it with the output #8 (stored in _8, also as Out[8]):
2009
2009
2010 In [10]: ed _8\\
2010 In [10]: ed _8\\
2011 Editing... done. Executing edited code...\\
2011 Editing... done. Executing edited code...\\
2012 hello again\\
2012 hello again\\
2013 Out[10]: "print 'hello again'\\n"
2013 Out[10]: "print 'hello again'\\n"
2014
2014
2015
2015
2016 Changing the default editor hook:
2016 Changing the default editor hook:
2017
2017
2018 If you wish to write your own editor hook, you can put it in a
2018 If you wish to write your own editor hook, you can put it in a
2019 configuration file which you load at startup time. The default hook
2019 configuration file which you load at startup time. The default hook
2020 is defined in the IPython.hooks module, and you can use that as a
2020 is defined in the IPython.hooks module, and you can use that as a
2021 starting example for further modifications. That file also has
2021 starting example for further modifications. That file also has
2022 general instructions on how to set a new hook for use once you've
2022 general instructions on how to set a new hook for use once you've
2023 defined it."""
2023 defined it."""
2024
2024
2025 # FIXME: This function has become a convoluted mess. It needs a
2025 # FIXME: This function has become a convoluted mess. It needs a
2026 # ground-up rewrite with clean, simple logic.
2026 # ground-up rewrite with clean, simple logic.
2027
2027
2028 def make_filename(arg):
2028 def make_filename(arg):
2029 "Make a filename from the given args"
2029 "Make a filename from the given args"
2030 try:
2030 try:
2031 filename = get_py_filename(arg)
2031 filename = get_py_filename(arg)
2032 except IOError:
2032 except IOError:
2033 if args.endswith('.py'):
2033 if args.endswith('.py'):
2034 filename = arg
2034 filename = arg
2035 else:
2035 else:
2036 filename = None
2036 filename = None
2037 return filename
2037 return filename
2038
2038
2039 # custom exceptions
2039 # custom exceptions
2040 class DataIsObject(Exception): pass
2040 class DataIsObject(Exception): pass
2041
2041
2042 opts,args = self.parse_options(parameter_s,'prxn:')
2042 opts,args = self.parse_options(parameter_s,'prxn:')
2043 # Set a few locals from the options for convenience:
2043 # Set a few locals from the options for convenience:
2044 opts_p = opts.has_key('p')
2044 opts_p = opts.has_key('p')
2045 opts_r = opts.has_key('r')
2045 opts_r = opts.has_key('r')
2046
2046
2047 # Default line number value
2047 # Default line number value
2048 lineno = opts.get('n',None)
2048 lineno = opts.get('n',None)
2049
2049
2050 if opts_p:
2050 if opts_p:
2051 args = '_%s' % last_call[0]
2051 args = '_%s' % last_call[0]
2052 if not self.shell.user_ns.has_key(args):
2052 if not self.shell.user_ns.has_key(args):
2053 args = last_call[1]
2053 args = last_call[1]
2054
2054
2055 # use last_call to remember the state of the previous call, but don't
2055 # use last_call to remember the state of the previous call, but don't
2056 # let it be clobbered by successive '-p' calls.
2056 # let it be clobbered by successive '-p' calls.
2057 try:
2057 try:
2058 last_call[0] = self.shell.outputcache.prompt_count
2058 last_call[0] = self.shell.outputcache.prompt_count
2059 if not opts_p:
2059 if not opts_p:
2060 last_call[1] = parameter_s
2060 last_call[1] = parameter_s
2061 except:
2061 except:
2062 pass
2062 pass
2063
2063
2064 # by default this is done with temp files, except when the given
2064 # by default this is done with temp files, except when the given
2065 # arg is a filename
2065 # arg is a filename
2066 use_temp = 1
2066 use_temp = 1
2067
2067
2068 if re.match(r'\d',args):
2068 if re.match(r'\d',args):
2069 # Mode where user specifies ranges of lines, like in %macro.
2069 # Mode where user specifies ranges of lines, like in %macro.
2070 # This means that you can't edit files whose names begin with
2070 # This means that you can't edit files whose names begin with
2071 # numbers this way. Tough.
2071 # numbers this way. Tough.
2072 ranges = args.split()
2072 ranges = args.split()
2073 data = ''.join(self.extract_input_slices(ranges,opts_r))
2073 data = ''.join(self.extract_input_slices(ranges,opts_r))
2074 elif args.endswith('.py'):
2074 elif args.endswith('.py'):
2075 filename = make_filename(args)
2075 filename = make_filename(args)
2076 data = ''
2076 data = ''
2077 use_temp = 0
2077 use_temp = 0
2078 elif args:
2078 elif args:
2079 try:
2079 try:
2080 # Load the parameter given as a variable. If not a string,
2080 # Load the parameter given as a variable. If not a string,
2081 # process it as an object instead (below)
2081 # process it as an object instead (below)
2082
2082
2083 #print '*** args',args,'type',type(args) # dbg
2083 #print '*** args',args,'type',type(args) # dbg
2084 data = eval(args,self.shell.user_ns)
2084 data = eval(args,self.shell.user_ns)
2085 if not type(data) in StringTypes:
2085 if not type(data) in StringTypes:
2086 raise DataIsObject
2086 raise DataIsObject
2087
2087
2088 except (NameError,SyntaxError):
2088 except (NameError,SyntaxError):
2089 # given argument is not a variable, try as a filename
2089 # given argument is not a variable, try as a filename
2090 filename = make_filename(args)
2090 filename = make_filename(args)
2091 if filename is None:
2091 if filename is None:
2092 warn("Argument given (%s) can't be found as a variable "
2092 warn("Argument given (%s) can't be found as a variable "
2093 "or as a filename." % args)
2093 "or as a filename." % args)
2094 return
2094 return
2095
2095
2096 data = ''
2096 data = ''
2097 use_temp = 0
2097 use_temp = 0
2098 except DataIsObject:
2098 except DataIsObject:
2099
2099
2100 # macros have a special edit function
2100 # macros have a special edit function
2101 if isinstance(data,Macro):
2101 if isinstance(data,Macro):
2102 self._edit_macro(args,data)
2102 self._edit_macro(args,data)
2103 return
2103 return
2104
2104
2105 # For objects, try to edit the file where they are defined
2105 # For objects, try to edit the file where they are defined
2106 try:
2106 try:
2107 filename = inspect.getabsfile(data)
2107 filename = inspect.getabsfile(data)
2108 datafile = 1
2108 datafile = 1
2109 except TypeError:
2109 except TypeError:
2110 filename = make_filename(args)
2110 filename = make_filename(args)
2111 datafile = 1
2111 datafile = 1
2112 warn('Could not find file where `%s` is defined.\n'
2112 warn('Could not find file where `%s` is defined.\n'
2113 'Opening a file named `%s`' % (args,filename))
2113 'Opening a file named `%s`' % (args,filename))
2114 # Now, make sure we can actually read the source (if it was in
2114 # Now, make sure we can actually read the source (if it was in
2115 # a temp file it's gone by now).
2115 # a temp file it's gone by now).
2116 if datafile:
2116 if datafile:
2117 try:
2117 try:
2118 if lineno is None:
2118 if lineno is None:
2119 lineno = inspect.getsourcelines(data)[1]
2119 lineno = inspect.getsourcelines(data)[1]
2120 except IOError:
2120 except IOError:
2121 filename = make_filename(args)
2121 filename = make_filename(args)
2122 if filename is None:
2122 if filename is None:
2123 warn('The file `%s` where `%s` was defined cannot '
2123 warn('The file `%s` where `%s` was defined cannot '
2124 'be read.' % (filename,data))
2124 'be read.' % (filename,data))
2125 return
2125 return
2126 use_temp = 0
2126 use_temp = 0
2127 else:
2127 else:
2128 data = ''
2128 data = ''
2129
2129
2130 if use_temp:
2130 if use_temp:
2131 filename = self.shell.mktempfile(data)
2131 filename = self.shell.mktempfile(data)
2132 print 'IPython will make a temporary file named:',filename
2132 print 'IPython will make a temporary file named:',filename
2133
2133
2134 # do actual editing here
2134 # do actual editing here
2135 print 'Editing...',
2135 print 'Editing...',
2136 sys.stdout.flush()
2136 sys.stdout.flush()
2137 self.shell.hooks.editor(filename,lineno)
2137 self.shell.hooks.editor(filename,lineno)
2138 if opts.has_key('x'): # -x prevents actual execution
2138 if opts.has_key('x'): # -x prevents actual execution
2139 print
2139 print
2140 else:
2140 else:
2141 print 'done. Executing edited code...'
2141 print 'done. Executing edited code...'
2142 if opts_r:
2142 if opts_r:
2143 self.shell.runlines(file_read(filename))
2143 self.shell.runlines(file_read(filename))
2144 else:
2144 else:
2145 self.shell.safe_execfile(filename,self.shell.user_ns)
2145 self.shell.safe_execfile(filename,self.shell.user_ns)
2146 if use_temp:
2146 if use_temp:
2147 try:
2147 try:
2148 return open(filename).read()
2148 return open(filename).read()
2149 except IOError,msg:
2149 except IOError,msg:
2150 if msg.filename == filename:
2150 if msg.filename == filename:
2151 warn('File not found. Did you forget to save?')
2151 warn('File not found. Did you forget to save?')
2152 return
2152 return
2153 else:
2153 else:
2154 self.shell.showtraceback()
2154 self.shell.showtraceback()
2155
2155
2156 def magic_xmode(self,parameter_s = ''):
2156 def magic_xmode(self,parameter_s = ''):
2157 """Switch modes for the exception handlers.
2157 """Switch modes for the exception handlers.
2158
2158
2159 Valid modes: Plain, Context and Verbose.
2159 Valid modes: Plain, Context and Verbose.
2160
2160
2161 If called without arguments, acts as a toggle."""
2161 If called without arguments, acts as a toggle."""
2162
2162
2163 def xmode_switch_err(name):
2163 def xmode_switch_err(name):
2164 warn('Error changing %s exception modes.\n%s' %
2164 warn('Error changing %s exception modes.\n%s' %
2165 (name,sys.exc_info()[1]))
2165 (name,sys.exc_info()[1]))
2166
2166
2167 shell = self.shell
2167 shell = self.shell
2168 new_mode = parameter_s.strip().capitalize()
2168 new_mode = parameter_s.strip().capitalize()
2169 try:
2169 try:
2170 shell.InteractiveTB.set_mode(mode=new_mode)
2170 shell.InteractiveTB.set_mode(mode=new_mode)
2171 print 'Exception reporting mode:',shell.InteractiveTB.mode
2171 print 'Exception reporting mode:',shell.InteractiveTB.mode
2172 except:
2172 except:
2173 xmode_switch_err('user')
2173 xmode_switch_err('user')
2174
2174
2175 # threaded shells use a special handler in sys.excepthook
2175 # threaded shells use a special handler in sys.excepthook
2176 if shell.isthreaded:
2176 if shell.isthreaded:
2177 try:
2177 try:
2178 shell.sys_excepthook.set_mode(mode=new_mode)
2178 shell.sys_excepthook.set_mode(mode=new_mode)
2179 except:
2179 except:
2180 xmode_switch_err('threaded')
2180 xmode_switch_err('threaded')
2181
2181
2182 def magic_colors(self,parameter_s = ''):
2182 def magic_colors(self,parameter_s = ''):
2183 """Switch color scheme for prompts, info system and exception handlers.
2183 """Switch color scheme for prompts, info system and exception handlers.
2184
2184
2185 Currently implemented schemes: NoColor, Linux, LightBG.
2185 Currently implemented schemes: NoColor, Linux, LightBG.
2186
2186
2187 Color scheme names are not case-sensitive."""
2187 Color scheme names are not case-sensitive."""
2188
2188
2189 def color_switch_err(name):
2189 def color_switch_err(name):
2190 warn('Error changing %s color schemes.\n%s' %
2190 warn('Error changing %s color schemes.\n%s' %
2191 (name,sys.exc_info()[1]))
2191 (name,sys.exc_info()[1]))
2192
2192
2193
2193
2194 new_scheme = parameter_s.strip()
2194 new_scheme = parameter_s.strip()
2195 if not new_scheme:
2195 if not new_scheme:
2196 print 'You must specify a color scheme.'
2196 print 'You must specify a color scheme.'
2197 return
2197 return
2198 import IPython.rlineimpl as readline
2198 import IPython.rlineimpl as readline
2199 if not readline.have_readline:
2199 if not readline.have_readline:
2200 msg = """\
2200 msg = """\
2201 Proper color support under MS Windows requires Gary Bishop's readline library.
2201 Proper color support under MS Windows requires the pyreadline library.
2202 You can find it at:
2202 You can find it at:
2203 http://sourceforge.net/projects/uncpythontools
2203 http://ipython.scipy.org/moin/PyReadline/Intro
2204 Gary's readline needs the ctypes module, from:
2204 Gary's readline needs the ctypes module, from:
2205 http://starship.python.net/crew/theller/ctypes
2205 http://starship.python.net/crew/theller/ctypes
2206 (Note that ctypes is already part of Python versions 2.5 and newer).
2206
2207
2207 Defaulting color scheme to 'NoColor'"""
2208 Defaulting color scheme to 'NoColor'"""
2208 new_scheme = 'NoColor'
2209 new_scheme = 'NoColor'
2209 warn(msg)
2210 warn(msg)
2210 # local shortcut
2211 # local shortcut
2211 shell = self.shell
2212 shell = self.shell
2212
2213
2213 # Set prompt colors
2214 # Set prompt colors
2214 try:
2215 try:
2215 shell.outputcache.set_colors(new_scheme)
2216 shell.outputcache.set_colors(new_scheme)
2216 except:
2217 except:
2217 color_switch_err('prompt')
2218 color_switch_err('prompt')
2218 else:
2219 else:
2219 shell.rc.colors = \
2220 shell.rc.colors = \
2220 shell.outputcache.color_table.active_scheme_name
2221 shell.outputcache.color_table.active_scheme_name
2221 # Set exception colors
2222 # Set exception colors
2222 try:
2223 try:
2223 shell.InteractiveTB.set_colors(scheme = new_scheme)
2224 shell.InteractiveTB.set_colors(scheme = new_scheme)
2224 shell.SyntaxTB.set_colors(scheme = new_scheme)
2225 shell.SyntaxTB.set_colors(scheme = new_scheme)
2225 except:
2226 except:
2226 color_switch_err('exception')
2227 color_switch_err('exception')
2227
2228
2228 # threaded shells use a verbose traceback in sys.excepthook
2229 # threaded shells use a verbose traceback in sys.excepthook
2229 if shell.isthreaded:
2230 if shell.isthreaded:
2230 try:
2231 try:
2231 shell.sys_excepthook.set_colors(scheme=new_scheme)
2232 shell.sys_excepthook.set_colors(scheme=new_scheme)
2232 except:
2233 except:
2233 color_switch_err('system exception handler')
2234 color_switch_err('system exception handler')
2234
2235
2235 # Set info (for 'object?') colors
2236 # Set info (for 'object?') colors
2236 if shell.rc.color_info:
2237 if shell.rc.color_info:
2237 try:
2238 try:
2238 shell.inspector.set_active_scheme(new_scheme)
2239 shell.inspector.set_active_scheme(new_scheme)
2239 except:
2240 except:
2240 color_switch_err('object inspector')
2241 color_switch_err('object inspector')
2241 else:
2242 else:
2242 shell.inspector.set_active_scheme('NoColor')
2243 shell.inspector.set_active_scheme('NoColor')
2243
2244
2244 def magic_color_info(self,parameter_s = ''):
2245 def magic_color_info(self,parameter_s = ''):
2245 """Toggle color_info.
2246 """Toggle color_info.
2246
2247
2247 The color_info configuration parameter controls whether colors are
2248 The color_info configuration parameter controls whether colors are
2248 used for displaying object details (by things like %psource, %pfile or
2249 used for displaying object details (by things like %psource, %pfile or
2249 the '?' system). This function toggles this value with each call.
2250 the '?' system). This function toggles this value with each call.
2250
2251
2251 Note that unless you have a fairly recent pager (less works better
2252 Note that unless you have a fairly recent pager (less works better
2252 than more) in your system, using colored object information displays
2253 than more) in your system, using colored object information displays
2253 will not work properly. Test it and see."""
2254 will not work properly. Test it and see."""
2254
2255
2255 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2256 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2256 self.magic_colors(self.shell.rc.colors)
2257 self.magic_colors(self.shell.rc.colors)
2257 print 'Object introspection functions have now coloring:',
2258 print 'Object introspection functions have now coloring:',
2258 print ['OFF','ON'][self.shell.rc.color_info]
2259 print ['OFF','ON'][self.shell.rc.color_info]
2259
2260
2260 def magic_Pprint(self, parameter_s=''):
2261 def magic_Pprint(self, parameter_s=''):
2261 """Toggle pretty printing on/off."""
2262 """Toggle pretty printing on/off."""
2262
2263
2263 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2264 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2264 print 'Pretty printing has been turned', \
2265 print 'Pretty printing has been turned', \
2265 ['OFF','ON'][self.shell.rc.pprint]
2266 ['OFF','ON'][self.shell.rc.pprint]
2266
2267
2267 def magic_exit(self, parameter_s=''):
2268 def magic_exit(self, parameter_s=''):
2268 """Exit IPython, confirming if configured to do so.
2269 """Exit IPython, confirming if configured to do so.
2269
2270
2270 You can configure whether IPython asks for confirmation upon exit by
2271 You can configure whether IPython asks for confirmation upon exit by
2271 setting the confirm_exit flag in the ipythonrc file."""
2272 setting the confirm_exit flag in the ipythonrc file."""
2272
2273
2273 self.shell.exit()
2274 self.shell.exit()
2274
2275
2275 def magic_quit(self, parameter_s=''):
2276 def magic_quit(self, parameter_s=''):
2276 """Exit IPython, confirming if configured to do so (like %exit)"""
2277 """Exit IPython, confirming if configured to do so (like %exit)"""
2277
2278
2278 self.shell.exit()
2279 self.shell.exit()
2279
2280
2280 def magic_Exit(self, parameter_s=''):
2281 def magic_Exit(self, parameter_s=''):
2281 """Exit IPython without confirmation."""
2282 """Exit IPython without confirmation."""
2282
2283
2283 self.shell.exit_now = True
2284 self.shell.exit_now = True
2284
2285
2285 def magic_Quit(self, parameter_s=''):
2286 def magic_Quit(self, parameter_s=''):
2286 """Exit IPython without confirmation (like %Exit)."""
2287 """Exit IPython without confirmation (like %Exit)."""
2287
2288
2288 self.shell.exit_now = True
2289 self.shell.exit_now = True
2289
2290
2290 #......................................................................
2291 #......................................................................
2291 # Functions to implement unix shell-type things
2292 # Functions to implement unix shell-type things
2292
2293
2293 def magic_alias(self, parameter_s = ''):
2294 def magic_alias(self, parameter_s = ''):
2294 """Define an alias for a system command.
2295 """Define an alias for a system command.
2295
2296
2296 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2297 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2297
2298
2298 Then, typing 'alias_name params' will execute the system command 'cmd
2299 Then, typing 'alias_name params' will execute the system command 'cmd
2299 params' (from your underlying operating system).
2300 params' (from your underlying operating system).
2300
2301
2301 Aliases have lower precedence than magic functions and Python normal
2302 Aliases have lower precedence than magic functions and Python normal
2302 variables, so if 'foo' is both a Python variable and an alias, the
2303 variables, so if 'foo' is both a Python variable and an alias, the
2303 alias can not be executed until 'del foo' removes the Python variable.
2304 alias can not be executed until 'del foo' removes the Python variable.
2304
2305
2305 You can use the %l specifier in an alias definition to represent the
2306 You can use the %l specifier in an alias definition to represent the
2306 whole line when the alias is called. For example:
2307 whole line when the alias is called. For example:
2307
2308
2308 In [2]: alias all echo "Input in brackets: <%l>"\\
2309 In [2]: alias all echo "Input in brackets: <%l>"\\
2309 In [3]: all hello world\\
2310 In [3]: all hello world\\
2310 Input in brackets: <hello world>
2311 Input in brackets: <hello world>
2311
2312
2312 You can also define aliases with parameters using %s specifiers (one
2313 You can also define aliases with parameters using %s specifiers (one
2313 per parameter):
2314 per parameter):
2314
2315
2315 In [1]: alias parts echo first %s second %s\\
2316 In [1]: alias parts echo first %s second %s\\
2316 In [2]: %parts A B\\
2317 In [2]: %parts A B\\
2317 first A second B\\
2318 first A second B\\
2318 In [3]: %parts A\\
2319 In [3]: %parts A\\
2319 Incorrect number of arguments: 2 expected.\\
2320 Incorrect number of arguments: 2 expected.\\
2320 parts is an alias to: 'echo first %s second %s'
2321 parts is an alias to: 'echo first %s second %s'
2321
2322
2322 Note that %l and %s are mutually exclusive. You can only use one or
2323 Note that %l and %s are mutually exclusive. You can only use one or
2323 the other in your aliases.
2324 the other in your aliases.
2324
2325
2325 Aliases expand Python variables just like system calls using ! or !!
2326 Aliases expand Python variables just like system calls using ! or !!
2326 do: all expressions prefixed with '$' get expanded. For details of
2327 do: all expressions prefixed with '$' get expanded. For details of
2327 the semantic rules, see PEP-215:
2328 the semantic rules, see PEP-215:
2328 http://www.python.org/peps/pep-0215.html. This is the library used by
2329 http://www.python.org/peps/pep-0215.html. This is the library used by
2329 IPython for variable expansion. If you want to access a true shell
2330 IPython for variable expansion. If you want to access a true shell
2330 variable, an extra $ is necessary to prevent its expansion by IPython:
2331 variable, an extra $ is necessary to prevent its expansion by IPython:
2331
2332
2332 In [6]: alias show echo\\
2333 In [6]: alias show echo\\
2333 In [7]: PATH='A Python string'\\
2334 In [7]: PATH='A Python string'\\
2334 In [8]: show $PATH\\
2335 In [8]: show $PATH\\
2335 A Python string\\
2336 A Python string\\
2336 In [9]: show $$PATH\\
2337 In [9]: show $$PATH\\
2337 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2338 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2338
2339
2339 You can use the alias facility to acess all of $PATH. See the %rehash
2340 You can use the alias facility to acess all of $PATH. See the %rehash
2340 and %rehashx functions, which automatically create aliases for the
2341 and %rehashx functions, which automatically create aliases for the
2341 contents of your $PATH.
2342 contents of your $PATH.
2342
2343
2343 If called with no parameters, %alias prints the current alias table."""
2344 If called with no parameters, %alias prints the current alias table."""
2344
2345
2345 par = parameter_s.strip()
2346 par = parameter_s.strip()
2346 if not par:
2347 if not par:
2347 if self.shell.rc.automagic:
2348 if self.shell.rc.automagic:
2348 prechar = ''
2349 prechar = ''
2349 else:
2350 else:
2350 prechar = self.shell.ESC_MAGIC
2351 prechar = self.shell.ESC_MAGIC
2351 #print 'Alias\t\tSystem Command\n'+'-'*30
2352 #print 'Alias\t\tSystem Command\n'+'-'*30
2352 atab = self.shell.alias_table
2353 atab = self.shell.alias_table
2353 aliases = atab.keys()
2354 aliases = atab.keys()
2354 aliases.sort()
2355 aliases.sort()
2355 res = []
2356 res = []
2356 for alias in aliases:
2357 for alias in aliases:
2357 res.append((alias, atab[alias][1]))
2358 res.append((alias, atab[alias][1]))
2358 print "Total number of aliases:",len(aliases)
2359 print "Total number of aliases:",len(aliases)
2359 return res
2360 return res
2360 try:
2361 try:
2361 alias,cmd = par.split(None,1)
2362 alias,cmd = par.split(None,1)
2362 except:
2363 except:
2363 print OInspect.getdoc(self.magic_alias)
2364 print OInspect.getdoc(self.magic_alias)
2364 else:
2365 else:
2365 nargs = cmd.count('%s')
2366 nargs = cmd.count('%s')
2366 if nargs>0 and cmd.find('%l')>=0:
2367 if nargs>0 and cmd.find('%l')>=0:
2367 error('The %s and %l specifiers are mutually exclusive '
2368 error('The %s and %l specifiers are mutually exclusive '
2368 'in alias definitions.')
2369 'in alias definitions.')
2369 else: # all looks OK
2370 else: # all looks OK
2370 self.shell.alias_table[alias] = (nargs,cmd)
2371 self.shell.alias_table[alias] = (nargs,cmd)
2371 self.shell.alias_table_validate(verbose=0)
2372 self.shell.alias_table_validate(verbose=0)
2372 # end magic_alias
2373 # end magic_alias
2373
2374
2374 def magic_unalias(self, parameter_s = ''):
2375 def magic_unalias(self, parameter_s = ''):
2375 """Remove an alias"""
2376 """Remove an alias"""
2376
2377
2377 aname = parameter_s.strip()
2378 aname = parameter_s.strip()
2378 if aname in self.shell.alias_table:
2379 if aname in self.shell.alias_table:
2379 del self.shell.alias_table[aname]
2380 del self.shell.alias_table[aname]
2380
2381
2381 def magic_rehash(self, parameter_s = ''):
2382 def magic_rehash(self, parameter_s = ''):
2382 """Update the alias table with all entries in $PATH.
2383 """Update the alias table with all entries in $PATH.
2383
2384
2384 This version does no checks on execute permissions or whether the
2385 This version does no checks on execute permissions or whether the
2385 contents of $PATH are truly files (instead of directories or something
2386 contents of $PATH are truly files (instead of directories or something
2386 else). For such a safer (but slower) version, use %rehashx."""
2387 else). For such a safer (but slower) version, use %rehashx."""
2387
2388
2388 # This function (and rehashx) manipulate the alias_table directly
2389 # This function (and rehashx) manipulate the alias_table directly
2389 # rather than calling magic_alias, for speed reasons. A rehash on a
2390 # rather than calling magic_alias, for speed reasons. A rehash on a
2390 # typical Linux box involves several thousand entries, so efficiency
2391 # typical Linux box involves several thousand entries, so efficiency
2391 # here is a top concern.
2392 # here is a top concern.
2392
2393
2393 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2394 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2394 alias_table = self.shell.alias_table
2395 alias_table = self.shell.alias_table
2395 for pdir in path:
2396 for pdir in path:
2396 for ff in os.listdir(pdir):
2397 for ff in os.listdir(pdir):
2397 # each entry in the alias table must be (N,name), where
2398 # each entry in the alias table must be (N,name), where
2398 # N is the number of positional arguments of the alias.
2399 # N is the number of positional arguments of the alias.
2399 alias_table[ff] = (0,ff)
2400 alias_table[ff] = (0,ff)
2400 # Make sure the alias table doesn't contain keywords or builtins
2401 # Make sure the alias table doesn't contain keywords or builtins
2401 self.shell.alias_table_validate()
2402 self.shell.alias_table_validate()
2402 # Call again init_auto_alias() so we get 'rm -i' and other modified
2403 # Call again init_auto_alias() so we get 'rm -i' and other modified
2403 # aliases since %rehash will probably clobber them
2404 # aliases since %rehash will probably clobber them
2404 self.shell.init_auto_alias()
2405 self.shell.init_auto_alias()
2405
2406
2406 def magic_rehashx(self, parameter_s = ''):
2407 def magic_rehashx(self, parameter_s = ''):
2407 """Update the alias table with all executable files in $PATH.
2408 """Update the alias table with all executable files in $PATH.
2408
2409
2409 This version explicitly checks that every entry in $PATH is a file
2410 This version explicitly checks that every entry in $PATH is a file
2410 with execute access (os.X_OK), so it is much slower than %rehash.
2411 with execute access (os.X_OK), so it is much slower than %rehash.
2411
2412
2412 Under Windows, it checks executability as a match agains a
2413 Under Windows, it checks executability as a match agains a
2413 '|'-separated string of extensions, stored in the IPython config
2414 '|'-separated string of extensions, stored in the IPython config
2414 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2415 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2415
2416
2416 path = [os.path.abspath(os.path.expanduser(p)) for p in
2417 path = [os.path.abspath(os.path.expanduser(p)) for p in
2417 os.environ['PATH'].split(os.pathsep)]
2418 os.environ['PATH'].split(os.pathsep)]
2418 path = filter(os.path.isdir,path)
2419 path = filter(os.path.isdir,path)
2419
2420
2420 alias_table = self.shell.alias_table
2421 alias_table = self.shell.alias_table
2421 syscmdlist = []
2422 syscmdlist = []
2422 if os.name == 'posix':
2423 if os.name == 'posix':
2423 isexec = lambda fname:os.path.isfile(fname) and \
2424 isexec = lambda fname:os.path.isfile(fname) and \
2424 os.access(fname,os.X_OK)
2425 os.access(fname,os.X_OK)
2425 else:
2426 else:
2426
2427
2427 try:
2428 try:
2428 winext = os.environ['pathext'].replace(';','|').replace('.','')
2429 winext = os.environ['pathext'].replace(';','|').replace('.','')
2429 except KeyError:
2430 except KeyError:
2430 winext = 'exe|com|bat'
2431 winext = 'exe|com|bat'
2431
2432
2432 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2433 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2433 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2434 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2434 savedir = os.getcwd()
2435 savedir = os.getcwd()
2435 try:
2436 try:
2436 # write the whole loop for posix/Windows so we don't have an if in
2437 # write the whole loop for posix/Windows so we don't have an if in
2437 # the innermost part
2438 # the innermost part
2438 if os.name == 'posix':
2439 if os.name == 'posix':
2439 for pdir in path:
2440 for pdir in path:
2440 os.chdir(pdir)
2441 os.chdir(pdir)
2441 for ff in os.listdir(pdir):
2442 for ff in os.listdir(pdir):
2442 if isexec(ff) and ff not in self.shell.no_alias:
2443 if isexec(ff) and ff not in self.shell.no_alias:
2443 # each entry in the alias table must be (N,name),
2444 # each entry in the alias table must be (N,name),
2444 # where N is the number of positional arguments of the
2445 # where N is the number of positional arguments of the
2445 # alias.
2446 # alias.
2446 alias_table[ff] = (0,ff)
2447 alias_table[ff] = (0,ff)
2447 syscmdlist.append(ff)
2448 syscmdlist.append(ff)
2448 else:
2449 else:
2449 for pdir in path:
2450 for pdir in path:
2450 os.chdir(pdir)
2451 os.chdir(pdir)
2451 for ff in os.listdir(pdir):
2452 for ff in os.listdir(pdir):
2452 if isexec(ff) and os.path.splitext(ff)[0] not in self.shell.no_alias:
2453 if isexec(ff) and os.path.splitext(ff)[0] not in self.shell.no_alias:
2453 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2454 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2454 syscmdlist.append(ff)
2455 syscmdlist.append(ff)
2455 # Make sure the alias table doesn't contain keywords or builtins
2456 # Make sure the alias table doesn't contain keywords or builtins
2456 self.shell.alias_table_validate()
2457 self.shell.alias_table_validate()
2457 # Call again init_auto_alias() so we get 'rm -i' and other
2458 # Call again init_auto_alias() so we get 'rm -i' and other
2458 # modified aliases since %rehashx will probably clobber them
2459 # modified aliases since %rehashx will probably clobber them
2459 self.shell.init_auto_alias()
2460 self.shell.init_auto_alias()
2460 db = self.getapi().db
2461 db = self.getapi().db
2461 db['syscmdlist'] = syscmdlist
2462 db['syscmdlist'] = syscmdlist
2462 finally:
2463 finally:
2463 os.chdir(savedir)
2464 os.chdir(savedir)
2464
2465
2465 def magic_pwd(self, parameter_s = ''):
2466 def magic_pwd(self, parameter_s = ''):
2466 """Return the current working directory path."""
2467 """Return the current working directory path."""
2467 return os.getcwd()
2468 return os.getcwd()
2468
2469
2469 def magic_cd(self, parameter_s=''):
2470 def magic_cd(self, parameter_s=''):
2470 """Change the current working directory.
2471 """Change the current working directory.
2471
2472
2472 This command automatically maintains an internal list of directories
2473 This command automatically maintains an internal list of directories
2473 you visit during your IPython session, in the variable _dh. The
2474 you visit during your IPython session, in the variable _dh. The
2474 command %dhist shows this history nicely formatted.
2475 command %dhist shows this history nicely formatted.
2475
2476
2476 Usage:
2477 Usage:
2477
2478
2478 cd 'dir': changes to directory 'dir'.
2479 cd 'dir': changes to directory 'dir'.
2479
2480
2480 cd -: changes to the last visited directory.
2481 cd -: changes to the last visited directory.
2481
2482
2482 cd -<n>: changes to the n-th directory in the directory history.
2483 cd -<n>: changes to the n-th directory in the directory history.
2483
2484
2484 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2485 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2485 (note: cd <bookmark_name> is enough if there is no
2486 (note: cd <bookmark_name> is enough if there is no
2486 directory <bookmark_name>, but a bookmark with the name exists.)
2487 directory <bookmark_name>, but a bookmark with the name exists.)
2487
2488
2488 Options:
2489 Options:
2489
2490
2490 -q: quiet. Do not print the working directory after the cd command is
2491 -q: quiet. Do not print the working directory after the cd command is
2491 executed. By default IPython's cd command does print this directory,
2492 executed. By default IPython's cd command does print this directory,
2492 since the default prompts do not display path information.
2493 since the default prompts do not display path information.
2493
2494
2494 Note that !cd doesn't work for this purpose because the shell where
2495 Note that !cd doesn't work for this purpose because the shell where
2495 !command runs is immediately discarded after executing 'command'."""
2496 !command runs is immediately discarded after executing 'command'."""
2496
2497
2497 parameter_s = parameter_s.strip()
2498 parameter_s = parameter_s.strip()
2498 #bkms = self.shell.persist.get("bookmarks",{})
2499 #bkms = self.shell.persist.get("bookmarks",{})
2499
2500
2500 numcd = re.match(r'(-)(\d+)$',parameter_s)
2501 numcd = re.match(r'(-)(\d+)$',parameter_s)
2501 # jump in directory history by number
2502 # jump in directory history by number
2502 if numcd:
2503 if numcd:
2503 nn = int(numcd.group(2))
2504 nn = int(numcd.group(2))
2504 try:
2505 try:
2505 ps = self.shell.user_ns['_dh'][nn]
2506 ps = self.shell.user_ns['_dh'][nn]
2506 except IndexError:
2507 except IndexError:
2507 print 'The requested directory does not exist in history.'
2508 print 'The requested directory does not exist in history.'
2508 return
2509 return
2509 else:
2510 else:
2510 opts = {}
2511 opts = {}
2511 else:
2512 else:
2512 #turn all non-space-escaping backslashes to slashes,
2513 #turn all non-space-escaping backslashes to slashes,
2513 # for c:\windows\directory\names\
2514 # for c:\windows\directory\names\
2514 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2515 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2515 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2516 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2516 # jump to previous
2517 # jump to previous
2517 if ps == '-':
2518 if ps == '-':
2518 try:
2519 try:
2519 ps = self.shell.user_ns['_dh'][-2]
2520 ps = self.shell.user_ns['_dh'][-2]
2520 except IndexError:
2521 except IndexError:
2521 print 'No previous directory to change to.'
2522 print 'No previous directory to change to.'
2522 return
2523 return
2523 # jump to bookmark if needed
2524 # jump to bookmark if needed
2524 else:
2525 else:
2525 if not os.path.isdir(ps) or opts.has_key('b'):
2526 if not os.path.isdir(ps) or opts.has_key('b'):
2526 bkms = self.db.get('bookmarks', {})
2527 bkms = self.db.get('bookmarks', {})
2527
2528
2528 if bkms.has_key(ps):
2529 if bkms.has_key(ps):
2529 target = bkms[ps]
2530 target = bkms[ps]
2530 print '(bookmark:%s) -> %s' % (ps,target)
2531 print '(bookmark:%s) -> %s' % (ps,target)
2531 ps = target
2532 ps = target
2532 else:
2533 else:
2533 if opts.has_key('b'):
2534 if opts.has_key('b'):
2534 error("Bookmark '%s' not found. "
2535 error("Bookmark '%s' not found. "
2535 "Use '%%bookmark -l' to see your bookmarks." % ps)
2536 "Use '%%bookmark -l' to see your bookmarks." % ps)
2536 return
2537 return
2537
2538
2538 # at this point ps should point to the target dir
2539 # at this point ps should point to the target dir
2539 if ps:
2540 if ps:
2540 try:
2541 try:
2541 os.chdir(os.path.expanduser(ps))
2542 os.chdir(os.path.expanduser(ps))
2542 ttitle = ("IPy:" + (
2543 ttitle = ("IPy:" + (
2543 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2544 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2544 platutils.set_term_title(ttitle)
2545 platutils.set_term_title(ttitle)
2545 except OSError:
2546 except OSError:
2546 print sys.exc_info()[1]
2547 print sys.exc_info()[1]
2547 else:
2548 else:
2548 self.shell.user_ns['_dh'].append(os.getcwd())
2549 self.shell.user_ns['_dh'].append(os.getcwd())
2549 else:
2550 else:
2550 os.chdir(self.shell.home_dir)
2551 os.chdir(self.shell.home_dir)
2551 platutils.set_term_title("IPy:~")
2552 platutils.set_term_title("IPy:~")
2552 self.shell.user_ns['_dh'].append(os.getcwd())
2553 self.shell.user_ns['_dh'].append(os.getcwd())
2553 if not 'q' in opts:
2554 if not 'q' in opts:
2554 print self.shell.user_ns['_dh'][-1]
2555 print self.shell.user_ns['_dh'][-1]
2555
2556
2556 def magic_dhist(self, parameter_s=''):
2557 def magic_dhist(self, parameter_s=''):
2557 """Print your history of visited directories.
2558 """Print your history of visited directories.
2558
2559
2559 %dhist -> print full history\\
2560 %dhist -> print full history\\
2560 %dhist n -> print last n entries only\\
2561 %dhist n -> print last n entries only\\
2561 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2562 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2562
2563
2563 This history is automatically maintained by the %cd command, and
2564 This history is automatically maintained by the %cd command, and
2564 always available as the global list variable _dh. You can use %cd -<n>
2565 always available as the global list variable _dh. You can use %cd -<n>
2565 to go to directory number <n>."""
2566 to go to directory number <n>."""
2566
2567
2567 dh = self.shell.user_ns['_dh']
2568 dh = self.shell.user_ns['_dh']
2568 if parameter_s:
2569 if parameter_s:
2569 try:
2570 try:
2570 args = map(int,parameter_s.split())
2571 args = map(int,parameter_s.split())
2571 except:
2572 except:
2572 self.arg_err(Magic.magic_dhist)
2573 self.arg_err(Magic.magic_dhist)
2573 return
2574 return
2574 if len(args) == 1:
2575 if len(args) == 1:
2575 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2576 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2576 elif len(args) == 2:
2577 elif len(args) == 2:
2577 ini,fin = args
2578 ini,fin = args
2578 else:
2579 else:
2579 self.arg_err(Magic.magic_dhist)
2580 self.arg_err(Magic.magic_dhist)
2580 return
2581 return
2581 else:
2582 else:
2582 ini,fin = 0,len(dh)
2583 ini,fin = 0,len(dh)
2583 nlprint(dh,
2584 nlprint(dh,
2584 header = 'Directory history (kept in _dh)',
2585 header = 'Directory history (kept in _dh)',
2585 start=ini,stop=fin)
2586 start=ini,stop=fin)
2586
2587
2587 def magic_env(self, parameter_s=''):
2588 def magic_env(self, parameter_s=''):
2588 """List environment variables."""
2589 """List environment variables."""
2589
2590
2590 return os.environ.data
2591 return os.environ.data
2591
2592
2592 def magic_pushd(self, parameter_s=''):
2593 def magic_pushd(self, parameter_s=''):
2593 """Place the current dir on stack and change directory.
2594 """Place the current dir on stack and change directory.
2594
2595
2595 Usage:\\
2596 Usage:\\
2596 %pushd ['dirname']
2597 %pushd ['dirname']
2597
2598
2598 %pushd with no arguments does a %pushd to your home directory.
2599 %pushd with no arguments does a %pushd to your home directory.
2599 """
2600 """
2600 if parameter_s == '': parameter_s = '~'
2601 if parameter_s == '': parameter_s = '~'
2601 dir_s = self.shell.dir_stack
2602 dir_s = self.shell.dir_stack
2602 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2603 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2603 os.path.expanduser(self.shell.dir_stack[0]):
2604 os.path.expanduser(self.shell.dir_stack[0]):
2604 try:
2605 try:
2605 self.magic_cd(parameter_s)
2606 self.magic_cd(parameter_s)
2606 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2607 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2607 self.magic_dirs()
2608 self.magic_dirs()
2608 except:
2609 except:
2609 print 'Invalid directory'
2610 print 'Invalid directory'
2610 else:
2611 else:
2611 print 'You are already there!'
2612 print 'You are already there!'
2612
2613
2613 def magic_popd(self, parameter_s=''):
2614 def magic_popd(self, parameter_s=''):
2614 """Change to directory popped off the top of the stack.
2615 """Change to directory popped off the top of the stack.
2615 """
2616 """
2616 if len (self.shell.dir_stack) > 1:
2617 if len (self.shell.dir_stack) > 1:
2617 self.shell.dir_stack.pop(0)
2618 self.shell.dir_stack.pop(0)
2618 self.magic_cd(self.shell.dir_stack[0])
2619 self.magic_cd(self.shell.dir_stack[0])
2619 print self.shell.dir_stack[0]
2620 print self.shell.dir_stack[0]
2620 else:
2621 else:
2621 print "You can't remove the starting directory from the stack:",\
2622 print "You can't remove the starting directory from the stack:",\
2622 self.shell.dir_stack
2623 self.shell.dir_stack
2623
2624
2624 def magic_dirs(self, parameter_s=''):
2625 def magic_dirs(self, parameter_s=''):
2625 """Return the current directory stack."""
2626 """Return the current directory stack."""
2626
2627
2627 return self.shell.dir_stack[:]
2628 return self.shell.dir_stack[:]
2628
2629
2629 def magic_sc(self, parameter_s=''):
2630 def magic_sc(self, parameter_s=''):
2630 """Shell capture - execute a shell command and capture its output.
2631 """Shell capture - execute a shell command and capture its output.
2631
2632
2632 DEPRECATED. Suboptimal, retained for backwards compatibility.
2633 DEPRECATED. Suboptimal, retained for backwards compatibility.
2633
2634
2634 You should use the form 'var = !command' instead. Example:
2635 You should use the form 'var = !command' instead. Example:
2635
2636
2636 "%sc -l myfiles = ls ~" should now be written as
2637 "%sc -l myfiles = ls ~" should now be written as
2637
2638
2638 "myfiles = !ls ~"
2639 "myfiles = !ls ~"
2639
2640
2640 myfiles.s, myfiles.l and myfiles.n still apply as documented
2641 myfiles.s, myfiles.l and myfiles.n still apply as documented
2641 below.
2642 below.
2642
2643
2643 --
2644 --
2644 %sc [options] varname=command
2645 %sc [options] varname=command
2645
2646
2646 IPython will run the given command using commands.getoutput(), and
2647 IPython will run the given command using commands.getoutput(), and
2647 will then update the user's interactive namespace with a variable
2648 will then update the user's interactive namespace with a variable
2648 called varname, containing the value of the call. Your command can
2649 called varname, containing the value of the call. Your command can
2649 contain shell wildcards, pipes, etc.
2650 contain shell wildcards, pipes, etc.
2650
2651
2651 The '=' sign in the syntax is mandatory, and the variable name you
2652 The '=' sign in the syntax is mandatory, and the variable name you
2652 supply must follow Python's standard conventions for valid names.
2653 supply must follow Python's standard conventions for valid names.
2653
2654
2654 (A special format without variable name exists for internal use)
2655 (A special format without variable name exists for internal use)
2655
2656
2656 Options:
2657 Options:
2657
2658
2658 -l: list output. Split the output on newlines into a list before
2659 -l: list output. Split the output on newlines into a list before
2659 assigning it to the given variable. By default the output is stored
2660 assigning it to the given variable. By default the output is stored
2660 as a single string.
2661 as a single string.
2661
2662
2662 -v: verbose. Print the contents of the variable.
2663 -v: verbose. Print the contents of the variable.
2663
2664
2664 In most cases you should not need to split as a list, because the
2665 In most cases you should not need to split as a list, because the
2665 returned value is a special type of string which can automatically
2666 returned value is a special type of string which can automatically
2666 provide its contents either as a list (split on newlines) or as a
2667 provide its contents either as a list (split on newlines) or as a
2667 space-separated string. These are convenient, respectively, either
2668 space-separated string. These are convenient, respectively, either
2668 for sequential processing or to be passed to a shell command.
2669 for sequential processing or to be passed to a shell command.
2669
2670
2670 For example:
2671 For example:
2671
2672
2672 # Capture into variable a
2673 # Capture into variable a
2673 In [9]: sc a=ls *py
2674 In [9]: sc a=ls *py
2674
2675
2675 # a is a string with embedded newlines
2676 # a is a string with embedded newlines
2676 In [10]: a
2677 In [10]: a
2677 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2678 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2678
2679
2679 # which can be seen as a list:
2680 # which can be seen as a list:
2680 In [11]: a.l
2681 In [11]: a.l
2681 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2682 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2682
2683
2683 # or as a whitespace-separated string:
2684 # or as a whitespace-separated string:
2684 In [12]: a.s
2685 In [12]: a.s
2685 Out[12]: 'setup.py win32_manual_post_install.py'
2686 Out[12]: 'setup.py win32_manual_post_install.py'
2686
2687
2687 # a.s is useful to pass as a single command line:
2688 # a.s is useful to pass as a single command line:
2688 In [13]: !wc -l $a.s
2689 In [13]: !wc -l $a.s
2689 146 setup.py
2690 146 setup.py
2690 130 win32_manual_post_install.py
2691 130 win32_manual_post_install.py
2691 276 total
2692 276 total
2692
2693
2693 # while the list form is useful to loop over:
2694 # while the list form is useful to loop over:
2694 In [14]: for f in a.l:
2695 In [14]: for f in a.l:
2695 ....: !wc -l $f
2696 ....: !wc -l $f
2696 ....:
2697 ....:
2697 146 setup.py
2698 146 setup.py
2698 130 win32_manual_post_install.py
2699 130 win32_manual_post_install.py
2699
2700
2700 Similiarly, the lists returned by the -l option are also special, in
2701 Similiarly, the lists returned by the -l option are also special, in
2701 the sense that you can equally invoke the .s attribute on them to
2702 the sense that you can equally invoke the .s attribute on them to
2702 automatically get a whitespace-separated string from their contents:
2703 automatically get a whitespace-separated string from their contents:
2703
2704
2704 In [1]: sc -l b=ls *py
2705 In [1]: sc -l b=ls *py
2705
2706
2706 In [2]: b
2707 In [2]: b
2707 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2708 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2708
2709
2709 In [3]: b.s
2710 In [3]: b.s
2710 Out[3]: 'setup.py win32_manual_post_install.py'
2711 Out[3]: 'setup.py win32_manual_post_install.py'
2711
2712
2712 In summary, both the lists and strings used for ouptut capture have
2713 In summary, both the lists and strings used for ouptut capture have
2713 the following special attributes:
2714 the following special attributes:
2714
2715
2715 .l (or .list) : value as list.
2716 .l (or .list) : value as list.
2716 .n (or .nlstr): value as newline-separated string.
2717 .n (or .nlstr): value as newline-separated string.
2717 .s (or .spstr): value as space-separated string.
2718 .s (or .spstr): value as space-separated string.
2718 """
2719 """
2719
2720
2720 opts,args = self.parse_options(parameter_s,'lv')
2721 opts,args = self.parse_options(parameter_s,'lv')
2721 # Try to get a variable name and command to run
2722 # Try to get a variable name and command to run
2722 try:
2723 try:
2723 # the variable name must be obtained from the parse_options
2724 # the variable name must be obtained from the parse_options
2724 # output, which uses shlex.split to strip options out.
2725 # output, which uses shlex.split to strip options out.
2725 var,_ = args.split('=',1)
2726 var,_ = args.split('=',1)
2726 var = var.strip()
2727 var = var.strip()
2727 # But the the command has to be extracted from the original input
2728 # But the the command has to be extracted from the original input
2728 # parameter_s, not on what parse_options returns, to avoid the
2729 # parameter_s, not on what parse_options returns, to avoid the
2729 # quote stripping which shlex.split performs on it.
2730 # quote stripping which shlex.split performs on it.
2730 _,cmd = parameter_s.split('=',1)
2731 _,cmd = parameter_s.split('=',1)
2731 except ValueError:
2732 except ValueError:
2732 var,cmd = '',''
2733 var,cmd = '',''
2733 # If all looks ok, proceed
2734 # If all looks ok, proceed
2734 out,err = self.shell.getoutputerror(cmd)
2735 out,err = self.shell.getoutputerror(cmd)
2735 if err:
2736 if err:
2736 print >> Term.cerr,err
2737 print >> Term.cerr,err
2737 if opts.has_key('l'):
2738 if opts.has_key('l'):
2738 out = SList(out.split('\n'))
2739 out = SList(out.split('\n'))
2739 else:
2740 else:
2740 out = LSString(out)
2741 out = LSString(out)
2741 if opts.has_key('v'):
2742 if opts.has_key('v'):
2742 print '%s ==\n%s' % (var,pformat(out))
2743 print '%s ==\n%s' % (var,pformat(out))
2743 if var:
2744 if var:
2744 self.shell.user_ns.update({var:out})
2745 self.shell.user_ns.update({var:out})
2745 else:
2746 else:
2746 return out
2747 return out
2747
2748
2748 def magic_sx(self, parameter_s=''):
2749 def magic_sx(self, parameter_s=''):
2749 """Shell execute - run a shell command and capture its output.
2750 """Shell execute - run a shell command and capture its output.
2750
2751
2751 %sx command
2752 %sx command
2752
2753
2753 IPython will run the given command using commands.getoutput(), and
2754 IPython will run the given command using commands.getoutput(), and
2754 return the result formatted as a list (split on '\\n'). Since the
2755 return the result formatted as a list (split on '\\n'). Since the
2755 output is _returned_, it will be stored in ipython's regular output
2756 output is _returned_, it will be stored in ipython's regular output
2756 cache Out[N] and in the '_N' automatic variables.
2757 cache Out[N] and in the '_N' automatic variables.
2757
2758
2758 Notes:
2759 Notes:
2759
2760
2760 1) If an input line begins with '!!', then %sx is automatically
2761 1) If an input line begins with '!!', then %sx is automatically
2761 invoked. That is, while:
2762 invoked. That is, while:
2762 !ls
2763 !ls
2763 causes ipython to simply issue system('ls'), typing
2764 causes ipython to simply issue system('ls'), typing
2764 !!ls
2765 !!ls
2765 is a shorthand equivalent to:
2766 is a shorthand equivalent to:
2766 %sx ls
2767 %sx ls
2767
2768
2768 2) %sx differs from %sc in that %sx automatically splits into a list,
2769 2) %sx differs from %sc in that %sx automatically splits into a list,
2769 like '%sc -l'. The reason for this is to make it as easy as possible
2770 like '%sc -l'. The reason for this is to make it as easy as possible
2770 to process line-oriented shell output via further python commands.
2771 to process line-oriented shell output via further python commands.
2771 %sc is meant to provide much finer control, but requires more
2772 %sc is meant to provide much finer control, but requires more
2772 typing.
2773 typing.
2773
2774
2774 3) Just like %sc -l, this is a list with special attributes:
2775 3) Just like %sc -l, this is a list with special attributes:
2775
2776
2776 .l (or .list) : value as list.
2777 .l (or .list) : value as list.
2777 .n (or .nlstr): value as newline-separated string.
2778 .n (or .nlstr): value as newline-separated string.
2778 .s (or .spstr): value as whitespace-separated string.
2779 .s (or .spstr): value as whitespace-separated string.
2779
2780
2780 This is very useful when trying to use such lists as arguments to
2781 This is very useful when trying to use such lists as arguments to
2781 system commands."""
2782 system commands."""
2782
2783
2783 if parameter_s:
2784 if parameter_s:
2784 out,err = self.shell.getoutputerror(parameter_s)
2785 out,err = self.shell.getoutputerror(parameter_s)
2785 if err:
2786 if err:
2786 print >> Term.cerr,err
2787 print >> Term.cerr,err
2787 return SList(out.split('\n'))
2788 return SList(out.split('\n'))
2788
2789
2789 def magic_bg(self, parameter_s=''):
2790 def magic_bg(self, parameter_s=''):
2790 """Run a job in the background, in a separate thread.
2791 """Run a job in the background, in a separate thread.
2791
2792
2792 For example,
2793 For example,
2793
2794
2794 %bg myfunc(x,y,z=1)
2795 %bg myfunc(x,y,z=1)
2795
2796
2796 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2797 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2797 execution starts, a message will be printed indicating the job
2798 execution starts, a message will be printed indicating the job
2798 number. If your job number is 5, you can use
2799 number. If your job number is 5, you can use
2799
2800
2800 myvar = jobs.result(5) or myvar = jobs[5].result
2801 myvar = jobs.result(5) or myvar = jobs[5].result
2801
2802
2802 to assign this result to variable 'myvar'.
2803 to assign this result to variable 'myvar'.
2803
2804
2804 IPython has a job manager, accessible via the 'jobs' object. You can
2805 IPython has a job manager, accessible via the 'jobs' object. You can
2805 type jobs? to get more information about it, and use jobs.<TAB> to see
2806 type jobs? to get more information about it, and use jobs.<TAB> to see
2806 its attributes. All attributes not starting with an underscore are
2807 its attributes. All attributes not starting with an underscore are
2807 meant for public use.
2808 meant for public use.
2808
2809
2809 In particular, look at the jobs.new() method, which is used to create
2810 In particular, look at the jobs.new() method, which is used to create
2810 new jobs. This magic %bg function is just a convenience wrapper
2811 new jobs. This magic %bg function is just a convenience wrapper
2811 around jobs.new(), for expression-based jobs. If you want to create a
2812 around jobs.new(), for expression-based jobs. If you want to create a
2812 new job with an explicit function object and arguments, you must call
2813 new job with an explicit function object and arguments, you must call
2813 jobs.new() directly.
2814 jobs.new() directly.
2814
2815
2815 The jobs.new docstring also describes in detail several important
2816 The jobs.new docstring also describes in detail several important
2816 caveats associated with a thread-based model for background job
2817 caveats associated with a thread-based model for background job
2817 execution. Type jobs.new? for details.
2818 execution. Type jobs.new? for details.
2818
2819
2819 You can check the status of all jobs with jobs.status().
2820 You can check the status of all jobs with jobs.status().
2820
2821
2821 The jobs variable is set by IPython into the Python builtin namespace.
2822 The jobs variable is set by IPython into the Python builtin namespace.
2822 If you ever declare a variable named 'jobs', you will shadow this
2823 If you ever declare a variable named 'jobs', you will shadow this
2823 name. You can either delete your global jobs variable to regain
2824 name. You can either delete your global jobs variable to regain
2824 access to the job manager, or make a new name and assign it manually
2825 access to the job manager, or make a new name and assign it manually
2825 to the manager (stored in IPython's namespace). For example, to
2826 to the manager (stored in IPython's namespace). For example, to
2826 assign the job manager to the Jobs name, use:
2827 assign the job manager to the Jobs name, use:
2827
2828
2828 Jobs = __builtins__.jobs"""
2829 Jobs = __builtins__.jobs"""
2829
2830
2830 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2831 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2831
2832
2832
2833
2833 def magic_bookmark(self, parameter_s=''):
2834 def magic_bookmark(self, parameter_s=''):
2834 """Manage IPython's bookmark system.
2835 """Manage IPython's bookmark system.
2835
2836
2836 %bookmark <name> - set bookmark to current dir
2837 %bookmark <name> - set bookmark to current dir
2837 %bookmark <name> <dir> - set bookmark to <dir>
2838 %bookmark <name> <dir> - set bookmark to <dir>
2838 %bookmark -l - list all bookmarks
2839 %bookmark -l - list all bookmarks
2839 %bookmark -d <name> - remove bookmark
2840 %bookmark -d <name> - remove bookmark
2840 %bookmark -r - remove all bookmarks
2841 %bookmark -r - remove all bookmarks
2841
2842
2842 You can later on access a bookmarked folder with:
2843 You can later on access a bookmarked folder with:
2843 %cd -b <name>
2844 %cd -b <name>
2844 or simply '%cd <name>' if there is no directory called <name> AND
2845 or simply '%cd <name>' if there is no directory called <name> AND
2845 there is such a bookmark defined.
2846 there is such a bookmark defined.
2846
2847
2847 Your bookmarks persist through IPython sessions, but they are
2848 Your bookmarks persist through IPython sessions, but they are
2848 associated with each profile."""
2849 associated with each profile."""
2849
2850
2850 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2851 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2851 if len(args) > 2:
2852 if len(args) > 2:
2852 error('You can only give at most two arguments')
2853 error('You can only give at most two arguments')
2853 return
2854 return
2854
2855
2855 bkms = self.db.get('bookmarks',{})
2856 bkms = self.db.get('bookmarks',{})
2856
2857
2857 if opts.has_key('d'):
2858 if opts.has_key('d'):
2858 try:
2859 try:
2859 todel = args[0]
2860 todel = args[0]
2860 except IndexError:
2861 except IndexError:
2861 error('You must provide a bookmark to delete')
2862 error('You must provide a bookmark to delete')
2862 else:
2863 else:
2863 try:
2864 try:
2864 del bkms[todel]
2865 del bkms[todel]
2865 except:
2866 except:
2866 error("Can't delete bookmark '%s'" % todel)
2867 error("Can't delete bookmark '%s'" % todel)
2867 elif opts.has_key('r'):
2868 elif opts.has_key('r'):
2868 bkms = {}
2869 bkms = {}
2869 elif opts.has_key('l'):
2870 elif opts.has_key('l'):
2870 bks = bkms.keys()
2871 bks = bkms.keys()
2871 bks.sort()
2872 bks.sort()
2872 if bks:
2873 if bks:
2873 size = max(map(len,bks))
2874 size = max(map(len,bks))
2874 else:
2875 else:
2875 size = 0
2876 size = 0
2876 fmt = '%-'+str(size)+'s -> %s'
2877 fmt = '%-'+str(size)+'s -> %s'
2877 print 'Current bookmarks:'
2878 print 'Current bookmarks:'
2878 for bk in bks:
2879 for bk in bks:
2879 print fmt % (bk,bkms[bk])
2880 print fmt % (bk,bkms[bk])
2880 else:
2881 else:
2881 if not args:
2882 if not args:
2882 error("You must specify the bookmark name")
2883 error("You must specify the bookmark name")
2883 elif len(args)==1:
2884 elif len(args)==1:
2884 bkms[args[0]] = os.getcwd()
2885 bkms[args[0]] = os.getcwd()
2885 elif len(args)==2:
2886 elif len(args)==2:
2886 bkms[args[0]] = args[1]
2887 bkms[args[0]] = args[1]
2887 self.db['bookmarks'] = bkms
2888 self.db['bookmarks'] = bkms
2888
2889
2889 def magic_pycat(self, parameter_s=''):
2890 def magic_pycat(self, parameter_s=''):
2890 """Show a syntax-highlighted file through a pager.
2891 """Show a syntax-highlighted file through a pager.
2891
2892
2892 This magic is similar to the cat utility, but it will assume the file
2893 This magic is similar to the cat utility, but it will assume the file
2893 to be Python source and will show it with syntax highlighting. """
2894 to be Python source and will show it with syntax highlighting. """
2894
2895
2895 try:
2896 try:
2896 filename = get_py_filename(parameter_s)
2897 filename = get_py_filename(parameter_s)
2897 cont = file_read(filename)
2898 cont = file_read(filename)
2898 except IOError:
2899 except IOError:
2899 try:
2900 try:
2900 cont = eval(parameter_s,self.user_ns)
2901 cont = eval(parameter_s,self.user_ns)
2901 except NameError:
2902 except NameError:
2902 cont = None
2903 cont = None
2903 if cont is None:
2904 if cont is None:
2904 print "Error: no such file or variable"
2905 print "Error: no such file or variable"
2905 return
2906 return
2906
2907
2907 page(self.shell.pycolorize(cont),
2908 page(self.shell.pycolorize(cont),
2908 screen_lines=self.shell.rc.screen_length)
2909 screen_lines=self.shell.rc.screen_length)
2909
2910
2910 def magic_cpaste(self, parameter_s=''):
2911 def magic_cpaste(self, parameter_s=''):
2911 """Allows you to paste & execute a pre-formatted code block from clipboard
2912 """Allows you to paste & execute a pre-formatted code block from clipboard
2912
2913
2913 You must terminate the block with '--' (two minus-signs) alone on the
2914 You must terminate the block with '--' (two minus-signs) alone on the
2914 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2915 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2915 is the new sentinel for this operation)
2916 is the new sentinel for this operation)
2916
2917
2917 The block is dedented prior to execution to enable execution of
2918 The block is dedented prior to execution to enable execution of
2918 method definitions. '>' characters at the beginning of a line is
2919 method definitions. '>' characters at the beginning of a line is
2919 ignored, to allow pasting directly from e-mails. The executed block
2920 ignored, to allow pasting directly from e-mails. The executed block
2920 is also assigned to variable named 'pasted_block' for later editing
2921 is also assigned to variable named 'pasted_block' for later editing
2921 with '%edit pasted_block'.
2922 with '%edit pasted_block'.
2922
2923
2923 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2924 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2924 This assigns the pasted block to variable 'foo' as string, without
2925 This assigns the pasted block to variable 'foo' as string, without
2925 dedenting or executing it.
2926 dedenting or executing it.
2926
2927
2927 Do not be alarmed by garbled output on Windows (it's a readline bug).
2928 Do not be alarmed by garbled output on Windows (it's a readline bug).
2928 Just press enter and type -- (and press enter again) and the block
2929 Just press enter and type -- (and press enter again) and the block
2929 will be what was just pasted.
2930 will be what was just pasted.
2930
2931
2931 IPython statements (magics, shell escapes) are not supported (yet).
2932 IPython statements (magics, shell escapes) are not supported (yet).
2932 """
2933 """
2933 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2934 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2934 par = args.strip()
2935 par = args.strip()
2935 sentinel = opts.get('s','--')
2936 sentinel = opts.get('s','--')
2936
2937
2937 from IPython import iplib
2938 from IPython import iplib
2938 lines = []
2939 lines = []
2939 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2940 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2940 while 1:
2941 while 1:
2941 l = iplib.raw_input_original(':')
2942 l = iplib.raw_input_original(':')
2942 if l ==sentinel:
2943 if l ==sentinel:
2943 break
2944 break
2944 lines.append(l.lstrip('>'))
2945 lines.append(l.lstrip('>'))
2945 block = "\n".join(lines) + '\n'
2946 block = "\n".join(lines) + '\n'
2946 #print "block:\n",block
2947 #print "block:\n",block
2947 if not par:
2948 if not par:
2948 b = textwrap.dedent(block)
2949 b = textwrap.dedent(block)
2949 exec b in self.user_ns
2950 exec b in self.user_ns
2950 self.user_ns['pasted_block'] = b
2951 self.user_ns['pasted_block'] = b
2951 else:
2952 else:
2952 self.user_ns[par] = block
2953 self.user_ns[par] = block
2953 print "Block assigned to '%s'" % par
2954 print "Block assigned to '%s'" % par
2954
2955
2955 def magic_quickref(self,arg):
2956 def magic_quickref(self,arg):
2956 """ Show a quick reference sheet """
2957 """ Show a quick reference sheet """
2957 import IPython.usage
2958 import IPython.usage
2958 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
2959 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
2959
2960
2960 page(qr)
2961 page(qr)
2961
2962
2962 def magic_upgrade(self,arg):
2963 def magic_upgrade(self,arg):
2963 """ Upgrade your IPython installation
2964 """ Upgrade your IPython installation
2964
2965
2965 This will copy the config files that don't yet exist in your
2966 This will copy the config files that don't yet exist in your
2966 ipython dir from the system config dir. Use this after upgrading
2967 ipython dir from the system config dir. Use this after upgrading
2967 IPython if you don't wish to delete your .ipython dir.
2968 IPython if you don't wish to delete your .ipython dir.
2968
2969
2969 Call with -nolegacy to get rid of ipythonrc* files (recommended for
2970 Call with -nolegacy to get rid of ipythonrc* files (recommended for
2970 new users)
2971 new users)
2971
2972
2972 """
2973 """
2973 ip = self.getapi()
2974 ip = self.getapi()
2974 ipinstallation = path(IPython.__file__).dirname()
2975 ipinstallation = path(IPython.__file__).dirname()
2975 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
2976 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
2976 src_config = ipinstallation / 'UserConfig'
2977 src_config = ipinstallation / 'UserConfig'
2977 userdir = path(ip.options.ipythondir)
2978 userdir = path(ip.options.ipythondir)
2978 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
2979 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
2979 print ">",cmd
2980 print ">",cmd
2980 shell(cmd)
2981 shell(cmd)
2981 if arg == '-nolegacy':
2982 if arg == '-nolegacy':
2982 legacy = userdir.files('ipythonrc*')
2983 legacy = userdir.files('ipythonrc*')
2983 print "Nuking legacy files:",legacy
2984 print "Nuking legacy files:",legacy
2984
2985
2985 [p.remove() for p in legacy]
2986 [p.remove() for p in legacy]
2986 suffix = (sys.platform == 'win32' and '.ini' or '')
2987 suffix = (sys.platform == 'win32' and '.ini' or '')
2987 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
2988 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
2988
2989
2989
2990
2990 # end Magic
2991 # end Magic
@@ -1,2356 +1,2354 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.3 or newer.
5 Requires Python 2.3 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 $Id: iplib.py 1786 2006-09-27 05:47:28Z fperez $
9 $Id: iplib.py 1787 2006-09-27 06:56:29Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from IPython import Release
31 from IPython import Release
32 __author__ = '%s <%s>\n%s <%s>' % \
32 __author__ = '%s <%s>\n%s <%s>' % \
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 __license__ = Release.license
34 __license__ = Release.license
35 __version__ = Release.version
35 __version__ = Release.version
36
36
37 # Python standard modules
37 # Python standard modules
38 import __main__
38 import __main__
39 import __builtin__
39 import __builtin__
40 import StringIO
40 import StringIO
41 import bdb
41 import bdb
42 import cPickle as pickle
42 import cPickle as pickle
43 import codeop
43 import codeop
44 import exceptions
44 import exceptions
45 import glob
45 import glob
46 import inspect
46 import inspect
47 import keyword
47 import keyword
48 import new
48 import new
49 import os
49 import os
50 import pdb
50 import pdb
51 import pydoc
51 import pydoc
52 import re
52 import re
53 import shutil
53 import shutil
54 import string
54 import string
55 import sys
55 import sys
56 import tempfile
56 import tempfile
57 import traceback
57 import traceback
58 import types
58 import types
59 import pickleshare
59 import pickleshare
60
60
61 from pprint import pprint, pformat
61 from pprint import pprint, pformat
62
62
63 # IPython's own modules
63 # IPython's own modules
64 import IPython
64 import IPython
65 from IPython import OInspect,PyColorize,ultraTB
65 from IPython import OInspect,PyColorize,ultraTB
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.FakeModule import FakeModule
67 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
69 from IPython.Logger import Logger
70 from IPython.Magic import Magic
70 from IPython.Magic import Magic
71 from IPython.Prompts import CachedOutput
71 from IPython.Prompts import CachedOutput
72 from IPython.ipstruct import Struct
72 from IPython.ipstruct import Struct
73 from IPython.background_jobs import BackgroundJobManager
73 from IPython.background_jobs import BackgroundJobManager
74 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.genutils import *
75 from IPython.genutils import *
76 import IPython.ipapi
76 import IPython.ipapi
77
77
78 # Globals
78 # Globals
79
79
80 # store the builtin raw_input globally, and use this always, in case user code
80 # store the builtin raw_input globally, and use this always, in case user code
81 # overwrites it (like wx.py.PyShell does)
81 # overwrites it (like wx.py.PyShell does)
82 raw_input_original = raw_input
82 raw_input_original = raw_input
83
83
84 # compiled regexps for autoindent management
84 # compiled regexps for autoindent management
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86
86
87
87
88 #****************************************************************************
88 #****************************************************************************
89 # Some utility function definitions
89 # Some utility function definitions
90
90
91 ini_spaces_re = re.compile(r'^(\s+)')
91 ini_spaces_re = re.compile(r'^(\s+)')
92
92
93 def num_ini_spaces(strng):
93 def num_ini_spaces(strng):
94 """Return the number of initial spaces in a string"""
94 """Return the number of initial spaces in a string"""
95
95
96 ini_spaces = ini_spaces_re.match(strng)
96 ini_spaces = ini_spaces_re.match(strng)
97 if ini_spaces:
97 if ini_spaces:
98 return ini_spaces.end()
98 return ini_spaces.end()
99 else:
99 else:
100 return 0
100 return 0
101
101
102 def softspace(file, newvalue):
102 def softspace(file, newvalue):
103 """Copied from code.py, to remove the dependency"""
103 """Copied from code.py, to remove the dependency"""
104
104
105 oldvalue = 0
105 oldvalue = 0
106 try:
106 try:
107 oldvalue = file.softspace
107 oldvalue = file.softspace
108 except AttributeError:
108 except AttributeError:
109 pass
109 pass
110 try:
110 try:
111 file.softspace = newvalue
111 file.softspace = newvalue
112 except (AttributeError, TypeError):
112 except (AttributeError, TypeError):
113 # "attribute-less object" or "read-only attributes"
113 # "attribute-less object" or "read-only attributes"
114 pass
114 pass
115 return oldvalue
115 return oldvalue
116
116
117
117
118 #****************************************************************************
118 #****************************************************************************
119 # Local use exceptions
119 # Local use exceptions
120 class SpaceInInput(exceptions.Exception): pass
120 class SpaceInInput(exceptions.Exception): pass
121
121
122
122
123 #****************************************************************************
123 #****************************************************************************
124 # Local use classes
124 # Local use classes
125 class Bunch: pass
125 class Bunch: pass
126
126
127 class Undefined: pass
127 class Undefined: pass
128
128
129 class InputList(list):
129 class InputList(list):
130 """Class to store user input.
130 """Class to store user input.
131
131
132 It's basically a list, but slices return a string instead of a list, thus
132 It's basically a list, but slices return a string instead of a list, thus
133 allowing things like (assuming 'In' is an instance):
133 allowing things like (assuming 'In' is an instance):
134
134
135 exec In[4:7]
135 exec In[4:7]
136
136
137 or
137 or
138
138
139 exec In[5:9] + In[14] + In[21:25]"""
139 exec In[5:9] + In[14] + In[21:25]"""
140
140
141 def __getslice__(self,i,j):
141 def __getslice__(self,i,j):
142 return ''.join(list.__getslice__(self,i,j))
142 return ''.join(list.__getslice__(self,i,j))
143
143
144 class SyntaxTB(ultraTB.ListTB):
144 class SyntaxTB(ultraTB.ListTB):
145 """Extension which holds some state: the last exception value"""
145 """Extension which holds some state: the last exception value"""
146
146
147 def __init__(self,color_scheme = 'NoColor'):
147 def __init__(self,color_scheme = 'NoColor'):
148 ultraTB.ListTB.__init__(self,color_scheme)
148 ultraTB.ListTB.__init__(self,color_scheme)
149 self.last_syntax_error = None
149 self.last_syntax_error = None
150
150
151 def __call__(self, etype, value, elist):
151 def __call__(self, etype, value, elist):
152 self.last_syntax_error = value
152 self.last_syntax_error = value
153 ultraTB.ListTB.__call__(self,etype,value,elist)
153 ultraTB.ListTB.__call__(self,etype,value,elist)
154
154
155 def clear_err_state(self):
155 def clear_err_state(self):
156 """Return the current error state and clear it"""
156 """Return the current error state and clear it"""
157 e = self.last_syntax_error
157 e = self.last_syntax_error
158 self.last_syntax_error = None
158 self.last_syntax_error = None
159 return e
159 return e
160
160
161 #****************************************************************************
161 #****************************************************************************
162 # Main IPython class
162 # Main IPython class
163
163
164 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
164 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
165 # until a full rewrite is made. I've cleaned all cross-class uses of
165 # until a full rewrite is made. I've cleaned all cross-class uses of
166 # attributes and methods, but too much user code out there relies on the
166 # attributes and methods, but too much user code out there relies on the
167 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
167 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
168 #
168 #
169 # But at least now, all the pieces have been separated and we could, in
169 # But at least now, all the pieces have been separated and we could, in
170 # principle, stop using the mixin. This will ease the transition to the
170 # principle, stop using the mixin. This will ease the transition to the
171 # chainsaw branch.
171 # chainsaw branch.
172
172
173 # For reference, the following is the list of 'self.foo' uses in the Magic
173 # For reference, the following is the list of 'self.foo' uses in the Magic
174 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
174 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
175 # class, to prevent clashes.
175 # class, to prevent clashes.
176
176
177 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
177 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
178 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
178 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
179 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
179 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
180 # 'self.value']
180 # 'self.value']
181
181
182 class InteractiveShell(object,Magic):
182 class InteractiveShell(object,Magic):
183 """An enhanced console for Python."""
183 """An enhanced console for Python."""
184
184
185 # class attribute to indicate whether the class supports threads or not.
185 # class attribute to indicate whether the class supports threads or not.
186 # Subclasses with thread support should override this as needed.
186 # Subclasses with thread support should override this as needed.
187 isthreaded = False
187 isthreaded = False
188
188
189 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
189 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
190 user_ns = None,user_global_ns=None,banner2='',
190 user_ns = None,user_global_ns=None,banner2='',
191 custom_exceptions=((),None),embedded=False):
191 custom_exceptions=((),None),embedded=False):
192
192
193 # log system
193 # log system
194 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
194 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
195
195
196 # some minimal strict typechecks. For some core data structures, I
196 # some minimal strict typechecks. For some core data structures, I
197 # want actual basic python types, not just anything that looks like
197 # want actual basic python types, not just anything that looks like
198 # one. This is especially true for namespaces.
198 # one. This is especially true for namespaces.
199 for ns in (user_ns,user_global_ns):
199 for ns in (user_ns,user_global_ns):
200 if ns is not None and type(ns) != types.DictType:
200 if ns is not None and type(ns) != types.DictType:
201 raise TypeError,'namespace must be a dictionary'
201 raise TypeError,'namespace must be a dictionary'
202
202
203 # Job manager (for jobs run as background threads)
203 # Job manager (for jobs run as background threads)
204 self.jobs = BackgroundJobManager()
204 self.jobs = BackgroundJobManager()
205
205
206 # Store the actual shell's name
206 # Store the actual shell's name
207 self.name = name
207 self.name = name
208
208
209 # We need to know whether the instance is meant for embedding, since
209 # We need to know whether the instance is meant for embedding, since
210 # global/local namespaces need to be handled differently in that case
210 # global/local namespaces need to be handled differently in that case
211 self.embedded = embedded
211 self.embedded = embedded
212
212
213 # command compiler
213 # command compiler
214 self.compile = codeop.CommandCompiler()
214 self.compile = codeop.CommandCompiler()
215
215
216 # User input buffer
216 # User input buffer
217 self.buffer = []
217 self.buffer = []
218
218
219 # Default name given in compilation of code
219 # Default name given in compilation of code
220 self.filename = '<ipython console>'
220 self.filename = '<ipython console>'
221
221
222 # Install our own quitter instead of the builtins. For python2.3-2.4,
223 # this brings in behavior more like 2.5, and for 2.5 it's almost
224 # identical to Python's official behavior (except we lack the message,
225 # but with autocall the need for that is much less).
226 __builtin__.exit = __builtin__.quit = self.exit
227
222 # Make an empty namespace, which extension writers can rely on both
228 # Make an empty namespace, which extension writers can rely on both
223 # existing and NEVER being used by ipython itself. This gives them a
229 # existing and NEVER being used by ipython itself. This gives them a
224 # convenient location for storing additional information and state
230 # convenient location for storing additional information and state
225 # their extensions may require, without fear of collisions with other
231 # their extensions may require, without fear of collisions with other
226 # ipython names that may develop later.
232 # ipython names that may develop later.
227 self.meta = Struct()
233 self.meta = Struct()
228
234
229 # Create the namespace where the user will operate. user_ns is
235 # Create the namespace where the user will operate. user_ns is
230 # normally the only one used, and it is passed to the exec calls as
236 # normally the only one used, and it is passed to the exec calls as
231 # the locals argument. But we do carry a user_global_ns namespace
237 # the locals argument. But we do carry a user_global_ns namespace
232 # given as the exec 'globals' argument, This is useful in embedding
238 # given as the exec 'globals' argument, This is useful in embedding
233 # situations where the ipython shell opens in a context where the
239 # situations where the ipython shell opens in a context where the
234 # distinction between locals and globals is meaningful.
240 # distinction between locals and globals is meaningful.
235
241
236 # FIXME. For some strange reason, __builtins__ is showing up at user
242 # FIXME. For some strange reason, __builtins__ is showing up at user
237 # level as a dict instead of a module. This is a manual fix, but I
243 # level as a dict instead of a module. This is a manual fix, but I
238 # should really track down where the problem is coming from. Alex
244 # should really track down where the problem is coming from. Alex
239 # Schmolck reported this problem first.
245 # Schmolck reported this problem first.
240
246
241 # A useful post by Alex Martelli on this topic:
247 # A useful post by Alex Martelli on this topic:
242 # Re: inconsistent value from __builtins__
248 # Re: inconsistent value from __builtins__
243 # Von: Alex Martelli <aleaxit@yahoo.com>
249 # Von: Alex Martelli <aleaxit@yahoo.com>
244 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
250 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
245 # Gruppen: comp.lang.python
251 # Gruppen: comp.lang.python
246
252
247 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
253 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
248 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
254 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
249 # > <type 'dict'>
255 # > <type 'dict'>
250 # > >>> print type(__builtins__)
256 # > >>> print type(__builtins__)
251 # > <type 'module'>
257 # > <type 'module'>
252 # > Is this difference in return value intentional?
258 # > Is this difference in return value intentional?
253
259
254 # Well, it's documented that '__builtins__' can be either a dictionary
260 # Well, it's documented that '__builtins__' can be either a dictionary
255 # or a module, and it's been that way for a long time. Whether it's
261 # or a module, and it's been that way for a long time. Whether it's
256 # intentional (or sensible), I don't know. In any case, the idea is
262 # intentional (or sensible), I don't know. In any case, the idea is
257 # that if you need to access the built-in namespace directly, you
263 # that if you need to access the built-in namespace directly, you
258 # should start with "import __builtin__" (note, no 's') which will
264 # should start with "import __builtin__" (note, no 's') which will
259 # definitely give you a module. Yeah, it's somewhat confusing:-(.
265 # definitely give you a module. Yeah, it's somewhat confusing:-(.
260
266
261 # These routines return properly built dicts as needed by the rest of
267 # These routines return properly built dicts as needed by the rest of
262 # the code, and can also be used by extension writers to generate
268 # the code, and can also be used by extension writers to generate
263 # properly initialized namespaces.
269 # properly initialized namespaces.
264 user_ns = IPython.ipapi.make_user_ns(user_ns)
270 user_ns = IPython.ipapi.make_user_ns(user_ns)
265 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
271 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
266
272
267 # Assign namespaces
273 # Assign namespaces
268 # This is the namespace where all normal user variables live
274 # This is the namespace where all normal user variables live
269 self.user_ns = user_ns
275 self.user_ns = user_ns
270 # Embedded instances require a separate namespace for globals.
276 # Embedded instances require a separate namespace for globals.
271 # Normally this one is unused by non-embedded instances.
277 # Normally this one is unused by non-embedded instances.
272 self.user_global_ns = user_global_ns
278 self.user_global_ns = user_global_ns
273 # A namespace to keep track of internal data structures to prevent
279 # A namespace to keep track of internal data structures to prevent
274 # them from cluttering user-visible stuff. Will be updated later
280 # them from cluttering user-visible stuff. Will be updated later
275 self.internal_ns = {}
281 self.internal_ns = {}
276
282
277 # Namespace of system aliases. Each entry in the alias
283 # Namespace of system aliases. Each entry in the alias
278 # table must be a 2-tuple of the form (N,name), where N is the number
284 # table must be a 2-tuple of the form (N,name), where N is the number
279 # of positional arguments of the alias.
285 # of positional arguments of the alias.
280 self.alias_table = {}
286 self.alias_table = {}
281
287
282 # A table holding all the namespaces IPython deals with, so that
288 # A table holding all the namespaces IPython deals with, so that
283 # introspection facilities can search easily.
289 # introspection facilities can search easily.
284 self.ns_table = {'user':user_ns,
290 self.ns_table = {'user':user_ns,
285 'user_global':user_global_ns,
291 'user_global':user_global_ns,
286 'alias':self.alias_table,
292 'alias':self.alias_table,
287 'internal':self.internal_ns,
293 'internal':self.internal_ns,
288 'builtin':__builtin__.__dict__
294 'builtin':__builtin__.__dict__
289 }
295 }
290
296
291 # The user namespace MUST have a pointer to the shell itself.
297 # The user namespace MUST have a pointer to the shell itself.
292 self.user_ns[name] = self
298 self.user_ns[name] = self
293
299
294 # We need to insert into sys.modules something that looks like a
300 # We need to insert into sys.modules something that looks like a
295 # module but which accesses the IPython namespace, for shelve and
301 # module but which accesses the IPython namespace, for shelve and
296 # pickle to work interactively. Normally they rely on getting
302 # pickle to work interactively. Normally they rely on getting
297 # everything out of __main__, but for embedding purposes each IPython
303 # everything out of __main__, but for embedding purposes each IPython
298 # instance has its own private namespace, so we can't go shoving
304 # instance has its own private namespace, so we can't go shoving
299 # everything into __main__.
305 # everything into __main__.
300
306
301 # note, however, that we should only do this for non-embedded
307 # note, however, that we should only do this for non-embedded
302 # ipythons, which really mimic the __main__.__dict__ with their own
308 # ipythons, which really mimic the __main__.__dict__ with their own
303 # namespace. Embedded instances, on the other hand, should not do
309 # namespace. Embedded instances, on the other hand, should not do
304 # this because they need to manage the user local/global namespaces
310 # this because they need to manage the user local/global namespaces
305 # only, but they live within a 'normal' __main__ (meaning, they
311 # only, but they live within a 'normal' __main__ (meaning, they
306 # shouldn't overtake the execution environment of the script they're
312 # shouldn't overtake the execution environment of the script they're
307 # embedded in).
313 # embedded in).
308
314
309 if not embedded:
315 if not embedded:
310 try:
316 try:
311 main_name = self.user_ns['__name__']
317 main_name = self.user_ns['__name__']
312 except KeyError:
318 except KeyError:
313 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
319 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
314 else:
320 else:
315 #print "pickle hack in place" # dbg
321 #print "pickle hack in place" # dbg
316 #print 'main_name:',main_name # dbg
322 #print 'main_name:',main_name # dbg
317 sys.modules[main_name] = FakeModule(self.user_ns)
323 sys.modules[main_name] = FakeModule(self.user_ns)
318
324
319 # List of input with multi-line handling.
325 # List of input with multi-line handling.
320 # Fill its zero entry, user counter starts at 1
326 # Fill its zero entry, user counter starts at 1
321 self.input_hist = InputList(['\n'])
327 self.input_hist = InputList(['\n'])
322 # This one will hold the 'raw' input history, without any
328 # This one will hold the 'raw' input history, without any
323 # pre-processing. This will allow users to retrieve the input just as
329 # pre-processing. This will allow users to retrieve the input just as
324 # it was exactly typed in by the user, with %hist -r.
330 # it was exactly typed in by the user, with %hist -r.
325 self.input_hist_raw = InputList(['\n'])
331 self.input_hist_raw = InputList(['\n'])
326
332
327 # list of visited directories
333 # list of visited directories
328 try:
334 try:
329 self.dir_hist = [os.getcwd()]
335 self.dir_hist = [os.getcwd()]
330 except IOError, e:
336 except IOError, e:
331 self.dir_hist = []
337 self.dir_hist = []
332
338
333 # dict of output history
339 # dict of output history
334 self.output_hist = {}
340 self.output_hist = {}
335
341
336 # dict of things NOT to alias (keywords, builtins and some magics)
342 # dict of things NOT to alias (keywords, builtins and some magics)
337 no_alias = {}
343 no_alias = {}
338 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
344 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
339 for key in keyword.kwlist + no_alias_magics:
345 for key in keyword.kwlist + no_alias_magics:
340 no_alias[key] = 1
346 no_alias[key] = 1
341 no_alias.update(__builtin__.__dict__)
347 no_alias.update(__builtin__.__dict__)
342 self.no_alias = no_alias
348 self.no_alias = no_alias
343
349
344 # make global variables for user access to these
350 # make global variables for user access to these
345 self.user_ns['_ih'] = self.input_hist
351 self.user_ns['_ih'] = self.input_hist
346 self.user_ns['_oh'] = self.output_hist
352 self.user_ns['_oh'] = self.output_hist
347 self.user_ns['_dh'] = self.dir_hist
353 self.user_ns['_dh'] = self.dir_hist
348
354
349 # user aliases to input and output histories
355 # user aliases to input and output histories
350 self.user_ns['In'] = self.input_hist
356 self.user_ns['In'] = self.input_hist
351 self.user_ns['Out'] = self.output_hist
357 self.user_ns['Out'] = self.output_hist
352
358
353 # Object variable to store code object waiting execution. This is
359 # Object variable to store code object waiting execution. This is
354 # used mainly by the multithreaded shells, but it can come in handy in
360 # used mainly by the multithreaded shells, but it can come in handy in
355 # other situations. No need to use a Queue here, since it's a single
361 # other situations. No need to use a Queue here, since it's a single
356 # item which gets cleared once run.
362 # item which gets cleared once run.
357 self.code_to_run = None
363 self.code_to_run = None
358
364
359 # escapes for automatic behavior on the command line
365 # escapes for automatic behavior on the command line
360 self.ESC_SHELL = '!'
366 self.ESC_SHELL = '!'
361 self.ESC_HELP = '?'
367 self.ESC_HELP = '?'
362 self.ESC_MAGIC = '%'
368 self.ESC_MAGIC = '%'
363 self.ESC_QUOTE = ','
369 self.ESC_QUOTE = ','
364 self.ESC_QUOTE2 = ';'
370 self.ESC_QUOTE2 = ';'
365 self.ESC_PAREN = '/'
371 self.ESC_PAREN = '/'
366
372
367 # And their associated handlers
373 # And their associated handlers
368 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
374 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
369 self.ESC_QUOTE : self.handle_auto,
375 self.ESC_QUOTE : self.handle_auto,
370 self.ESC_QUOTE2 : self.handle_auto,
376 self.ESC_QUOTE2 : self.handle_auto,
371 self.ESC_MAGIC : self.handle_magic,
377 self.ESC_MAGIC : self.handle_magic,
372 self.ESC_HELP : self.handle_help,
378 self.ESC_HELP : self.handle_help,
373 self.ESC_SHELL : self.handle_shell_escape,
379 self.ESC_SHELL : self.handle_shell_escape,
374 }
380 }
375
381
376 # class initializations
382 # class initializations
377 Magic.__init__(self,self)
383 Magic.__init__(self,self)
378
384
379 # Python source parser/formatter for syntax highlighting
385 # Python source parser/formatter for syntax highlighting
380 pyformat = PyColorize.Parser().format
386 pyformat = PyColorize.Parser().format
381 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
387 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
382
388
383 # hooks holds pointers used for user-side customizations
389 # hooks holds pointers used for user-side customizations
384 self.hooks = Struct()
390 self.hooks = Struct()
385
391
386 # Set all default hooks, defined in the IPython.hooks module.
392 # Set all default hooks, defined in the IPython.hooks module.
387 hooks = IPython.hooks
393 hooks = IPython.hooks
388 for hook_name in hooks.__all__:
394 for hook_name in hooks.__all__:
389 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
395 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
390 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
396 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
391 #print "bound hook",hook_name
397 #print "bound hook",hook_name
392
398
393 # Flag to mark unconditional exit
399 # Flag to mark unconditional exit
394 self.exit_now = False
400 self.exit_now = False
395
401
396 self.usage_min = """\
402 self.usage_min = """\
397 An enhanced console for Python.
403 An enhanced console for Python.
398 Some of its features are:
404 Some of its features are:
399 - Readline support if the readline library is present.
405 - Readline support if the readline library is present.
400 - Tab completion in the local namespace.
406 - Tab completion in the local namespace.
401 - Logging of input, see command-line options.
407 - Logging of input, see command-line options.
402 - System shell escape via ! , eg !ls.
408 - System shell escape via ! , eg !ls.
403 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
409 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
404 - Keeps track of locally defined variables via %who, %whos.
410 - Keeps track of locally defined variables via %who, %whos.
405 - Show object information with a ? eg ?x or x? (use ?? for more info).
411 - Show object information with a ? eg ?x or x? (use ?? for more info).
406 """
412 """
407 if usage: self.usage = usage
413 if usage: self.usage = usage
408 else: self.usage = self.usage_min
414 else: self.usage = self.usage_min
409
415
410 # Storage
416 # Storage
411 self.rc = rc # This will hold all configuration information
417 self.rc = rc # This will hold all configuration information
412 self.pager = 'less'
418 self.pager = 'less'
413 # temporary files used for various purposes. Deleted at exit.
419 # temporary files used for various purposes. Deleted at exit.
414 self.tempfiles = []
420 self.tempfiles = []
415
421
416 # Keep track of readline usage (later set by init_readline)
422 # Keep track of readline usage (later set by init_readline)
417 self.has_readline = False
423 self.has_readline = False
418
424
419 # template for logfile headers. It gets resolved at runtime by the
425 # template for logfile headers. It gets resolved at runtime by the
420 # logstart method.
426 # logstart method.
421 self.loghead_tpl = \
427 self.loghead_tpl = \
422 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
428 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
423 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
429 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
424 #log# opts = %s
430 #log# opts = %s
425 #log# args = %s
431 #log# args = %s
426 #log# It is safe to make manual edits below here.
432 #log# It is safe to make manual edits below here.
427 #log#-----------------------------------------------------------------------
433 #log#-----------------------------------------------------------------------
428 """
434 """
429 # for pushd/popd management
435 # for pushd/popd management
430 try:
436 try:
431 self.home_dir = get_home_dir()
437 self.home_dir = get_home_dir()
432 except HomeDirError,msg:
438 except HomeDirError,msg:
433 fatal(msg)
439 fatal(msg)
434
440
435 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
441 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
436
442
437 # Functions to call the underlying shell.
443 # Functions to call the underlying shell.
438
444
439 # utility to expand user variables via Itpl
445 # utility to expand user variables via Itpl
440 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
446 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
441 self.user_ns))
447 self.user_ns))
442 # The first is similar to os.system, but it doesn't return a value,
448 # The first is similar to os.system, but it doesn't return a value,
443 # and it allows interpolation of variables in the user's namespace.
449 # and it allows interpolation of variables in the user's namespace.
444 self.system = lambda cmd: shell(self.var_expand(cmd),
450 self.system = lambda cmd: shell(self.var_expand(cmd),
445 header='IPython system call: ',
451 header='IPython system call: ',
446 verbose=self.rc.system_verbose)
452 verbose=self.rc.system_verbose)
447 # These are for getoutput and getoutputerror:
453 # These are for getoutput and getoutputerror:
448 self.getoutput = lambda cmd: \
454 self.getoutput = lambda cmd: \
449 getoutput(self.var_expand(cmd),
455 getoutput(self.var_expand(cmd),
450 header='IPython system call: ',
456 header='IPython system call: ',
451 verbose=self.rc.system_verbose)
457 verbose=self.rc.system_verbose)
452 self.getoutputerror = lambda cmd: \
458 self.getoutputerror = lambda cmd: \
453 getoutputerror(self.var_expand(cmd),
459 getoutputerror(self.var_expand(cmd),
454 header='IPython system call: ',
460 header='IPython system call: ',
455 verbose=self.rc.system_verbose)
461 verbose=self.rc.system_verbose)
456
462
457 # RegExp for splitting line contents into pre-char//first
463 # RegExp for splitting line contents into pre-char//first
458 # word-method//rest. For clarity, each group in on one line.
464 # word-method//rest. For clarity, each group in on one line.
459
465
460 # WARNING: update the regexp if the above escapes are changed, as they
466 # WARNING: update the regexp if the above escapes are changed, as they
461 # are hardwired in.
467 # are hardwired in.
462
468
463 # Don't get carried away with trying to make the autocalling catch too
469 # Don't get carried away with trying to make the autocalling catch too
464 # much: it's better to be conservative rather than to trigger hidden
470 # much: it's better to be conservative rather than to trigger hidden
465 # evals() somewhere and end up causing side effects.
471 # evals() somewhere and end up causing side effects.
466
472
467 self.line_split = re.compile(r'^([\s*,;/])'
473 self.line_split = re.compile(r'^([\s*,;/])'
468 r'([\?\w\.]+\w*\s*)'
474 r'([\?\w\.]+\w*\s*)'
469 r'(\(?.*$)')
475 r'(\(?.*$)')
470
476
471 # Original re, keep around for a while in case changes break something
477 # Original re, keep around for a while in case changes break something
472 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
478 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
473 # r'(\s*[\?\w\.]+\w*\s*)'
479 # r'(\s*[\?\w\.]+\w*\s*)'
474 # r'(\(?.*$)')
480 # r'(\(?.*$)')
475
481
476 # RegExp to identify potential function names
482 # RegExp to identify potential function names
477 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
483 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
478
484
479 # RegExp to exclude strings with this start from autocalling. In
485 # RegExp to exclude strings with this start from autocalling. In
480 # particular, all binary operators should be excluded, so that if foo
486 # particular, all binary operators should be excluded, so that if foo
481 # is callable, foo OP bar doesn't become foo(OP bar), which is
487 # is callable, foo OP bar doesn't become foo(OP bar), which is
482 # invalid. The characters '!=()' don't need to be checked for, as the
488 # invalid. The characters '!=()' don't need to be checked for, as the
483 # _prefilter routine explicitely does so, to catch direct calls and
489 # _prefilter routine explicitely does so, to catch direct calls and
484 # rebindings of existing names.
490 # rebindings of existing names.
485
491
486 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
492 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
487 # it affects the rest of the group in square brackets.
493 # it affects the rest of the group in square brackets.
488 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
494 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
489 '|^is |^not |^in |^and |^or ')
495 '|^is |^not |^in |^and |^or ')
490
496
491 # try to catch also methods for stuff in lists/tuples/dicts: off
497 # try to catch also methods for stuff in lists/tuples/dicts: off
492 # (experimental). For this to work, the line_split regexp would need
498 # (experimental). For this to work, the line_split regexp would need
493 # to be modified so it wouldn't break things at '['. That line is
499 # to be modified so it wouldn't break things at '['. That line is
494 # nasty enough that I shouldn't change it until I can test it _well_.
500 # nasty enough that I shouldn't change it until I can test it _well_.
495 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
501 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
496
502
497 # keep track of where we started running (mainly for crash post-mortem)
503 # keep track of where we started running (mainly for crash post-mortem)
498 self.starting_dir = os.getcwd()
504 self.starting_dir = os.getcwd()
499
505
500 # Various switches which can be set
506 # Various switches which can be set
501 self.CACHELENGTH = 5000 # this is cheap, it's just text
507 self.CACHELENGTH = 5000 # this is cheap, it's just text
502 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
508 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
503 self.banner2 = banner2
509 self.banner2 = banner2
504
510
505 # TraceBack handlers:
511 # TraceBack handlers:
506
512
507 # Syntax error handler.
513 # Syntax error handler.
508 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
514 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
509
515
510 # The interactive one is initialized with an offset, meaning we always
516 # The interactive one is initialized with an offset, meaning we always
511 # want to remove the topmost item in the traceback, which is our own
517 # want to remove the topmost item in the traceback, which is our own
512 # internal code. Valid modes: ['Plain','Context','Verbose']
518 # internal code. Valid modes: ['Plain','Context','Verbose']
513 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
519 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
514 color_scheme='NoColor',
520 color_scheme='NoColor',
515 tb_offset = 1)
521 tb_offset = 1)
516
522
517 # IPython itself shouldn't crash. This will produce a detailed
523 # IPython itself shouldn't crash. This will produce a detailed
518 # post-mortem if it does. But we only install the crash handler for
524 # post-mortem if it does. But we only install the crash handler for
519 # non-threaded shells, the threaded ones use a normal verbose reporter
525 # non-threaded shells, the threaded ones use a normal verbose reporter
520 # and lose the crash handler. This is because exceptions in the main
526 # and lose the crash handler. This is because exceptions in the main
521 # thread (such as in GUI code) propagate directly to sys.excepthook,
527 # thread (such as in GUI code) propagate directly to sys.excepthook,
522 # and there's no point in printing crash dumps for every user exception.
528 # and there's no point in printing crash dumps for every user exception.
523 if self.isthreaded:
529 if self.isthreaded:
524 sys.excepthook = ultraTB.FormattedTB()
530 sys.excepthook = ultraTB.FormattedTB()
525 else:
531 else:
526 from IPython import CrashHandler
532 from IPython import CrashHandler
527 sys.excepthook = CrashHandler.CrashHandler(self)
533 sys.excepthook = CrashHandler.CrashHandler(self)
528
534
529 # The instance will store a pointer to this, so that runtime code
535 # The instance will store a pointer to this, so that runtime code
530 # (such as magics) can access it. This is because during the
536 # (such as magics) can access it. This is because during the
531 # read-eval loop, it gets temporarily overwritten (to deal with GUI
537 # read-eval loop, it gets temporarily overwritten (to deal with GUI
532 # frameworks).
538 # frameworks).
533 self.sys_excepthook = sys.excepthook
539 self.sys_excepthook = sys.excepthook
534
540
535 # and add any custom exception handlers the user may have specified
541 # and add any custom exception handlers the user may have specified
536 self.set_custom_exc(*custom_exceptions)
542 self.set_custom_exc(*custom_exceptions)
537
543
538 # indentation management
544 # indentation management
539 self.autoindent = False
545 self.autoindent = False
540 self.indent_current_nsp = 0
546 self.indent_current_nsp = 0
541
547
542 # Make some aliases automatically
548 # Make some aliases automatically
543 # Prepare list of shell aliases to auto-define
549 # Prepare list of shell aliases to auto-define
544 if os.name == 'posix':
550 if os.name == 'posix':
545 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
551 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
546 'mv mv -i','rm rm -i','cp cp -i',
552 'mv mv -i','rm rm -i','cp cp -i',
547 'cat cat','less less','clear clear',
553 'cat cat','less less','clear clear',
548 # a better ls
554 # a better ls
549 'ls ls -F',
555 'ls ls -F',
550 # long ls
556 # long ls
551 'll ls -lF')
557 'll ls -lF')
552 # Extra ls aliases with color, which need special treatment on BSD
558 # Extra ls aliases with color, which need special treatment on BSD
553 # variants
559 # variants
554 ls_extra = ( # color ls
560 ls_extra = ( # color ls
555 'lc ls -F -o --color',
561 'lc ls -F -o --color',
556 # ls normal files only
562 # ls normal files only
557 'lf ls -F -o --color %l | grep ^-',
563 'lf ls -F -o --color %l | grep ^-',
558 # ls symbolic links
564 # ls symbolic links
559 'lk ls -F -o --color %l | grep ^l',
565 'lk ls -F -o --color %l | grep ^l',
560 # directories or links to directories,
566 # directories or links to directories,
561 'ldir ls -F -o --color %l | grep /$',
567 'ldir ls -F -o --color %l | grep /$',
562 # things which are executable
568 # things which are executable
563 'lx ls -F -o --color %l | grep ^-..x',
569 'lx ls -F -o --color %l | grep ^-..x',
564 )
570 )
565 # The BSDs don't ship GNU ls, so they don't understand the
571 # The BSDs don't ship GNU ls, so they don't understand the
566 # --color switch out of the box
572 # --color switch out of the box
567 if 'bsd' in sys.platform:
573 if 'bsd' in sys.platform:
568 ls_extra = ( # ls normal files only
574 ls_extra = ( # ls normal files only
569 'lf ls -lF | grep ^-',
575 'lf ls -lF | grep ^-',
570 # ls symbolic links
576 # ls symbolic links
571 'lk ls -lF | grep ^l',
577 'lk ls -lF | grep ^l',
572 # directories or links to directories,
578 # directories or links to directories,
573 'ldir ls -lF | grep /$',
579 'ldir ls -lF | grep /$',
574 # things which are executable
580 # things which are executable
575 'lx ls -lF | grep ^-..x',
581 'lx ls -lF | grep ^-..x',
576 )
582 )
577 auto_alias = auto_alias + ls_extra
583 auto_alias = auto_alias + ls_extra
578 elif os.name in ['nt','dos']:
584 elif os.name in ['nt','dos']:
579 auto_alias = ('dir dir /on', 'ls dir /on',
585 auto_alias = ('dir dir /on', 'ls dir /on',
580 'ddir dir /ad /on', 'ldir dir /ad /on',
586 'ddir dir /ad /on', 'ldir dir /ad /on',
581 'mkdir mkdir','rmdir rmdir','echo echo',
587 'mkdir mkdir','rmdir rmdir','echo echo',
582 'ren ren','cls cls','copy copy')
588 'ren ren','cls cls','copy copy')
583 else:
589 else:
584 auto_alias = ()
590 auto_alias = ()
585 self.auto_alias = [s.split(None,1) for s in auto_alias]
591 self.auto_alias = [s.split(None,1) for s in auto_alias]
586 # Call the actual (public) initializer
592 # Call the actual (public) initializer
587 self.init_auto_alias()
593 self.init_auto_alias()
588
594
589 # Produce a public API instance
595 # Produce a public API instance
590 self.api = IPython.ipapi.IPApi(self)
596 self.api = IPython.ipapi.IPApi(self)
591
597
592 # track which builtins we add, so we can clean up later
598 # track which builtins we add, so we can clean up later
593 self.builtins_added = {}
599 self.builtins_added = {}
594 # This method will add the necessary builtins for operation, but
600 # This method will add the necessary builtins for operation, but
595 # tracking what it did via the builtins_added dict.
601 # tracking what it did via the builtins_added dict.
596 self.add_builtins()
602 self.add_builtins()
597
603
598 # end __init__
604 # end __init__
599
605
600 def pre_config_initialization(self):
606 def pre_config_initialization(self):
601 """Pre-configuration init method
607 """Pre-configuration init method
602
608
603 This is called before the configuration files are processed to
609 This is called before the configuration files are processed to
604 prepare the services the config files might need.
610 prepare the services the config files might need.
605
611
606 self.rc already has reasonable default values at this point.
612 self.rc already has reasonable default values at this point.
607 """
613 """
608 rc = self.rc
614 rc = self.rc
609
615
610 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
616 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
611
617
612 def post_config_initialization(self):
618 def post_config_initialization(self):
613 """Post configuration init method
619 """Post configuration init method
614
620
615 This is called after the configuration files have been processed to
621 This is called after the configuration files have been processed to
616 'finalize' the initialization."""
622 'finalize' the initialization."""
617
623
618 rc = self.rc
624 rc = self.rc
619
625
620 # Object inspector
626 # Object inspector
621 self.inspector = OInspect.Inspector(OInspect.InspectColors,
627 self.inspector = OInspect.Inspector(OInspect.InspectColors,
622 PyColorize.ANSICodeColors,
628 PyColorize.ANSICodeColors,
623 'NoColor',
629 'NoColor',
624 rc.object_info_string_level)
630 rc.object_info_string_level)
625
631
626 # Load readline proper
632 # Load readline proper
627 if rc.readline:
633 if rc.readline:
628 self.init_readline()
634 self.init_readline()
629
635
630 # local shortcut, this is used a LOT
636 # local shortcut, this is used a LOT
631 self.log = self.logger.log
637 self.log = self.logger.log
632
638
633 # Initialize cache, set in/out prompts and printing system
639 # Initialize cache, set in/out prompts and printing system
634 self.outputcache = CachedOutput(self,
640 self.outputcache = CachedOutput(self,
635 rc.cache_size,
641 rc.cache_size,
636 rc.pprint,
642 rc.pprint,
637 input_sep = rc.separate_in,
643 input_sep = rc.separate_in,
638 output_sep = rc.separate_out,
644 output_sep = rc.separate_out,
639 output_sep2 = rc.separate_out2,
645 output_sep2 = rc.separate_out2,
640 ps1 = rc.prompt_in1,
646 ps1 = rc.prompt_in1,
641 ps2 = rc.prompt_in2,
647 ps2 = rc.prompt_in2,
642 ps_out = rc.prompt_out,
648 ps_out = rc.prompt_out,
643 pad_left = rc.prompts_pad_left)
649 pad_left = rc.prompts_pad_left)
644
650
645 # user may have over-ridden the default print hook:
651 # user may have over-ridden the default print hook:
646 try:
652 try:
647 self.outputcache.__class__.display = self.hooks.display
653 self.outputcache.__class__.display = self.hooks.display
648 except AttributeError:
654 except AttributeError:
649 pass
655 pass
650
656
651 # I don't like assigning globally to sys, because it means when embedding
657 # I don't like assigning globally to sys, because it means when embedding
652 # instances, each embedded instance overrides the previous choice. But
658 # instances, each embedded instance overrides the previous choice. But
653 # sys.displayhook seems to be called internally by exec, so I don't see a
659 # sys.displayhook seems to be called internally by exec, so I don't see a
654 # way around it.
660 # way around it.
655 sys.displayhook = self.outputcache
661 sys.displayhook = self.outputcache
656
662
657 # Set user colors (don't do it in the constructor above so that it
663 # Set user colors (don't do it in the constructor above so that it
658 # doesn't crash if colors option is invalid)
664 # doesn't crash if colors option is invalid)
659 self.magic_colors(rc.colors)
665 self.magic_colors(rc.colors)
660
666
661 # Set calling of pdb on exceptions
667 # Set calling of pdb on exceptions
662 self.call_pdb = rc.pdb
668 self.call_pdb = rc.pdb
663
669
664 # Load user aliases
670 # Load user aliases
665 for alias in rc.alias:
671 for alias in rc.alias:
666 self.magic_alias(alias)
672 self.magic_alias(alias)
667 self.hooks.late_startup_hook()
673 self.hooks.late_startup_hook()
668
674
669 batchrun = False
675 batchrun = False
670 for batchfile in [path(arg) for arg in self.rc.args
676 for batchfile in [path(arg) for arg in self.rc.args
671 if arg.lower().endswith('.ipy')]:
677 if arg.lower().endswith('.ipy')]:
672 if not batchfile.isfile():
678 if not batchfile.isfile():
673 print "No such batch file:", batchfile
679 print "No such batch file:", batchfile
674 continue
680 continue
675 self.api.runlines(batchfile.text())
681 self.api.runlines(batchfile.text())
676 batchrun = True
682 batchrun = True
677 if batchrun:
683 if batchrun:
678 self.exit_now = True
684 self.exit_now = True
679
685
680 def add_builtins(self):
686 def add_builtins(self):
681 """Store ipython references into the builtin namespace.
687 """Store ipython references into the builtin namespace.
682
688
683 Some parts of ipython operate via builtins injected here, which hold a
689 Some parts of ipython operate via builtins injected here, which hold a
684 reference to IPython itself."""
690 reference to IPython itself."""
685
691
686 # TODO: deprecate all except _ip; 'jobs' should be installed
692 # TODO: deprecate all except _ip; 'jobs' should be installed
687 # by an extension and the rest are under _ip, ipalias is redundant
693 # by an extension and the rest are under _ip, ipalias is redundant
688 builtins_new = dict(__IPYTHON__ = self,
694 builtins_new = dict(__IPYTHON__ = self,
689 ip_set_hook = self.set_hook,
695 ip_set_hook = self.set_hook,
690 jobs = self.jobs,
696 jobs = self.jobs,
691 ipmagic = self.ipmagic,
697 ipmagic = self.ipmagic,
692 ipalias = self.ipalias,
698 ipalias = self.ipalias,
693 ipsystem = self.ipsystem,
699 ipsystem = self.ipsystem,
694 _ip = self.api
700 _ip = self.api
695 )
701 )
696 for biname,bival in builtins_new.items():
702 for biname,bival in builtins_new.items():
697 try:
703 try:
698 # store the orignal value so we can restore it
704 # store the orignal value so we can restore it
699 self.builtins_added[biname] = __builtin__.__dict__[biname]
705 self.builtins_added[biname] = __builtin__.__dict__[biname]
700 except KeyError:
706 except KeyError:
701 # or mark that it wasn't defined, and we'll just delete it at
707 # or mark that it wasn't defined, and we'll just delete it at
702 # cleanup
708 # cleanup
703 self.builtins_added[biname] = Undefined
709 self.builtins_added[biname] = Undefined
704 __builtin__.__dict__[biname] = bival
710 __builtin__.__dict__[biname] = bival
705
711
706 # Keep in the builtins a flag for when IPython is active. We set it
712 # Keep in the builtins a flag for when IPython is active. We set it
707 # with setdefault so that multiple nested IPythons don't clobber one
713 # with setdefault so that multiple nested IPythons don't clobber one
708 # another. Each will increase its value by one upon being activated,
714 # another. Each will increase its value by one upon being activated,
709 # which also gives us a way to determine the nesting level.
715 # which also gives us a way to determine the nesting level.
710 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
716 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
711
717
712 def clean_builtins(self):
718 def clean_builtins(self):
713 """Remove any builtins which might have been added by add_builtins, or
719 """Remove any builtins which might have been added by add_builtins, or
714 restore overwritten ones to their previous values."""
720 restore overwritten ones to their previous values."""
715 for biname,bival in self.builtins_added.items():
721 for biname,bival in self.builtins_added.items():
716 if bival is Undefined:
722 if bival is Undefined:
717 del __builtin__.__dict__[biname]
723 del __builtin__.__dict__[biname]
718 else:
724 else:
719 __builtin__.__dict__[biname] = bival
725 __builtin__.__dict__[biname] = bival
720 self.builtins_added.clear()
726 self.builtins_added.clear()
721
727
722 def set_hook(self,name,hook, priority = 50):
728 def set_hook(self,name,hook, priority = 50):
723 """set_hook(name,hook) -> sets an internal IPython hook.
729 """set_hook(name,hook) -> sets an internal IPython hook.
724
730
725 IPython exposes some of its internal API as user-modifiable hooks. By
731 IPython exposes some of its internal API as user-modifiable hooks. By
726 adding your function to one of these hooks, you can modify IPython's
732 adding your function to one of these hooks, you can modify IPython's
727 behavior to call at runtime your own routines."""
733 behavior to call at runtime your own routines."""
728
734
729 # At some point in the future, this should validate the hook before it
735 # At some point in the future, this should validate the hook before it
730 # accepts it. Probably at least check that the hook takes the number
736 # accepts it. Probably at least check that the hook takes the number
731 # of args it's supposed to.
737 # of args it's supposed to.
732 dp = getattr(self.hooks, name, None)
738 dp = getattr(self.hooks, name, None)
733 if name not in IPython.hooks.__all__:
739 if name not in IPython.hooks.__all__:
734 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
740 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
735 if not dp:
741 if not dp:
736 dp = IPython.hooks.CommandChainDispatcher()
742 dp = IPython.hooks.CommandChainDispatcher()
737
743
738 f = new.instancemethod(hook,self,self.__class__)
744 f = new.instancemethod(hook,self,self.__class__)
739 try:
745 try:
740 dp.add(f,priority)
746 dp.add(f,priority)
741 except AttributeError:
747 except AttributeError:
742 # it was not commandchain, plain old func - replace
748 # it was not commandchain, plain old func - replace
743 dp = f
749 dp = f
744
750
745 setattr(self.hooks,name, dp)
751 setattr(self.hooks,name, dp)
746
752
747
753
748 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
754 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
749
755
750 def set_custom_exc(self,exc_tuple,handler):
756 def set_custom_exc(self,exc_tuple,handler):
751 """set_custom_exc(exc_tuple,handler)
757 """set_custom_exc(exc_tuple,handler)
752
758
753 Set a custom exception handler, which will be called if any of the
759 Set a custom exception handler, which will be called if any of the
754 exceptions in exc_tuple occur in the mainloop (specifically, in the
760 exceptions in exc_tuple occur in the mainloop (specifically, in the
755 runcode() method.
761 runcode() method.
756
762
757 Inputs:
763 Inputs:
758
764
759 - exc_tuple: a *tuple* of valid exceptions to call the defined
765 - exc_tuple: a *tuple* of valid exceptions to call the defined
760 handler for. It is very important that you use a tuple, and NOT A
766 handler for. It is very important that you use a tuple, and NOT A
761 LIST here, because of the way Python's except statement works. If
767 LIST here, because of the way Python's except statement works. If
762 you only want to trap a single exception, use a singleton tuple:
768 you only want to trap a single exception, use a singleton tuple:
763
769
764 exc_tuple == (MyCustomException,)
770 exc_tuple == (MyCustomException,)
765
771
766 - handler: this must be defined as a function with the following
772 - handler: this must be defined as a function with the following
767 basic interface: def my_handler(self,etype,value,tb).
773 basic interface: def my_handler(self,etype,value,tb).
768
774
769 This will be made into an instance method (via new.instancemethod)
775 This will be made into an instance method (via new.instancemethod)
770 of IPython itself, and it will be called if any of the exceptions
776 of IPython itself, and it will be called if any of the exceptions
771 listed in the exc_tuple are caught. If the handler is None, an
777 listed in the exc_tuple are caught. If the handler is None, an
772 internal basic one is used, which just prints basic info.
778 internal basic one is used, which just prints basic info.
773
779
774 WARNING: by putting in your own exception handler into IPython's main
780 WARNING: by putting in your own exception handler into IPython's main
775 execution loop, you run a very good chance of nasty crashes. This
781 execution loop, you run a very good chance of nasty crashes. This
776 facility should only be used if you really know what you are doing."""
782 facility should only be used if you really know what you are doing."""
777
783
778 assert type(exc_tuple)==type(()) , \
784 assert type(exc_tuple)==type(()) , \
779 "The custom exceptions must be given AS A TUPLE."
785 "The custom exceptions must be given AS A TUPLE."
780
786
781 def dummy_handler(self,etype,value,tb):
787 def dummy_handler(self,etype,value,tb):
782 print '*** Simple custom exception handler ***'
788 print '*** Simple custom exception handler ***'
783 print 'Exception type :',etype
789 print 'Exception type :',etype
784 print 'Exception value:',value
790 print 'Exception value:',value
785 print 'Traceback :',tb
791 print 'Traceback :',tb
786 print 'Source code :','\n'.join(self.buffer)
792 print 'Source code :','\n'.join(self.buffer)
787
793
788 if handler is None: handler = dummy_handler
794 if handler is None: handler = dummy_handler
789
795
790 self.CustomTB = new.instancemethod(handler,self,self.__class__)
796 self.CustomTB = new.instancemethod(handler,self,self.__class__)
791 self.custom_exceptions = exc_tuple
797 self.custom_exceptions = exc_tuple
792
798
793 def set_custom_completer(self,completer,pos=0):
799 def set_custom_completer(self,completer,pos=0):
794 """set_custom_completer(completer,pos=0)
800 """set_custom_completer(completer,pos=0)
795
801
796 Adds a new custom completer function.
802 Adds a new custom completer function.
797
803
798 The position argument (defaults to 0) is the index in the completers
804 The position argument (defaults to 0) is the index in the completers
799 list where you want the completer to be inserted."""
805 list where you want the completer to be inserted."""
800
806
801 newcomp = new.instancemethod(completer,self.Completer,
807 newcomp = new.instancemethod(completer,self.Completer,
802 self.Completer.__class__)
808 self.Completer.__class__)
803 self.Completer.matchers.insert(pos,newcomp)
809 self.Completer.matchers.insert(pos,newcomp)
804
810
805 def _get_call_pdb(self):
811 def _get_call_pdb(self):
806 return self._call_pdb
812 return self._call_pdb
807
813
808 def _set_call_pdb(self,val):
814 def _set_call_pdb(self,val):
809
815
810 if val not in (0,1,False,True):
816 if val not in (0,1,False,True):
811 raise ValueError,'new call_pdb value must be boolean'
817 raise ValueError,'new call_pdb value must be boolean'
812
818
813 # store value in instance
819 # store value in instance
814 self._call_pdb = val
820 self._call_pdb = val
815
821
816 # notify the actual exception handlers
822 # notify the actual exception handlers
817 self.InteractiveTB.call_pdb = val
823 self.InteractiveTB.call_pdb = val
818 if self.isthreaded:
824 if self.isthreaded:
819 try:
825 try:
820 self.sys_excepthook.call_pdb = val
826 self.sys_excepthook.call_pdb = val
821 except:
827 except:
822 warn('Failed to activate pdb for threaded exception handler')
828 warn('Failed to activate pdb for threaded exception handler')
823
829
824 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
830 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
825 'Control auto-activation of pdb at exceptions')
831 'Control auto-activation of pdb at exceptions')
826
832
827
833
828 # These special functions get installed in the builtin namespace, to
834 # These special functions get installed in the builtin namespace, to
829 # provide programmatic (pure python) access to magics, aliases and system
835 # provide programmatic (pure python) access to magics, aliases and system
830 # calls. This is important for logging, user scripting, and more.
836 # calls. This is important for logging, user scripting, and more.
831
837
832 # We are basically exposing, via normal python functions, the three
838 # We are basically exposing, via normal python functions, the three
833 # mechanisms in which ipython offers special call modes (magics for
839 # mechanisms in which ipython offers special call modes (magics for
834 # internal control, aliases for direct system access via pre-selected
840 # internal control, aliases for direct system access via pre-selected
835 # names, and !cmd for calling arbitrary system commands).
841 # names, and !cmd for calling arbitrary system commands).
836
842
837 def ipmagic(self,arg_s):
843 def ipmagic(self,arg_s):
838 """Call a magic function by name.
844 """Call a magic function by name.
839
845
840 Input: a string containing the name of the magic function to call and any
846 Input: a string containing the name of the magic function to call and any
841 additional arguments to be passed to the magic.
847 additional arguments to be passed to the magic.
842
848
843 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
849 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
844 prompt:
850 prompt:
845
851
846 In[1]: %name -opt foo bar
852 In[1]: %name -opt foo bar
847
853
848 To call a magic without arguments, simply use ipmagic('name').
854 To call a magic without arguments, simply use ipmagic('name').
849
855
850 This provides a proper Python function to call IPython's magics in any
856 This provides a proper Python function to call IPython's magics in any
851 valid Python code you can type at the interpreter, including loops and
857 valid Python code you can type at the interpreter, including loops and
852 compound statements. It is added by IPython to the Python builtin
858 compound statements. It is added by IPython to the Python builtin
853 namespace upon initialization."""
859 namespace upon initialization."""
854
860
855 args = arg_s.split(' ',1)
861 args = arg_s.split(' ',1)
856 magic_name = args[0]
862 magic_name = args[0]
857 magic_name = magic_name.lstrip(self.ESC_MAGIC)
863 magic_name = magic_name.lstrip(self.ESC_MAGIC)
858
864
859 try:
865 try:
860 magic_args = args[1]
866 magic_args = args[1]
861 except IndexError:
867 except IndexError:
862 magic_args = ''
868 magic_args = ''
863 fn = getattr(self,'magic_'+magic_name,None)
869 fn = getattr(self,'magic_'+magic_name,None)
864 if fn is None:
870 if fn is None:
865 error("Magic function `%s` not found." % magic_name)
871 error("Magic function `%s` not found." % magic_name)
866 else:
872 else:
867 magic_args = self.var_expand(magic_args)
873 magic_args = self.var_expand(magic_args)
868 return fn(magic_args)
874 return fn(magic_args)
869
875
870 def ipalias(self,arg_s):
876 def ipalias(self,arg_s):
871 """Call an alias by name.
877 """Call an alias by name.
872
878
873 Input: a string containing the name of the alias to call and any
879 Input: a string containing the name of the alias to call and any
874 additional arguments to be passed to the magic.
880 additional arguments to be passed to the magic.
875
881
876 ipalias('name -opt foo bar') is equivalent to typing at the ipython
882 ipalias('name -opt foo bar') is equivalent to typing at the ipython
877 prompt:
883 prompt:
878
884
879 In[1]: name -opt foo bar
885 In[1]: name -opt foo bar
880
886
881 To call an alias without arguments, simply use ipalias('name').
887 To call an alias without arguments, simply use ipalias('name').
882
888
883 This provides a proper Python function to call IPython's aliases in any
889 This provides a proper Python function to call IPython's aliases in any
884 valid Python code you can type at the interpreter, including loops and
890 valid Python code you can type at the interpreter, including loops and
885 compound statements. It is added by IPython to the Python builtin
891 compound statements. It is added by IPython to the Python builtin
886 namespace upon initialization."""
892 namespace upon initialization."""
887
893
888 args = arg_s.split(' ',1)
894 args = arg_s.split(' ',1)
889 alias_name = args[0]
895 alias_name = args[0]
890 try:
896 try:
891 alias_args = args[1]
897 alias_args = args[1]
892 except IndexError:
898 except IndexError:
893 alias_args = ''
899 alias_args = ''
894 if alias_name in self.alias_table:
900 if alias_name in self.alias_table:
895 self.call_alias(alias_name,alias_args)
901 self.call_alias(alias_name,alias_args)
896 else:
902 else:
897 error("Alias `%s` not found." % alias_name)
903 error("Alias `%s` not found." % alias_name)
898
904
899 def ipsystem(self,arg_s):
905 def ipsystem(self,arg_s):
900 """Make a system call, using IPython."""
906 """Make a system call, using IPython."""
901
907
902 self.system(arg_s)
908 self.system(arg_s)
903
909
904 def complete(self,text):
910 def complete(self,text):
905 """Return a sorted list of all possible completions on text.
911 """Return a sorted list of all possible completions on text.
906
912
907 Inputs:
913 Inputs:
908
914
909 - text: a string of text to be completed on.
915 - text: a string of text to be completed on.
910
916
911 This is a wrapper around the completion mechanism, similar to what
917 This is a wrapper around the completion mechanism, similar to what
912 readline does at the command line when the TAB key is hit. By
918 readline does at the command line when the TAB key is hit. By
913 exposing it as a method, it can be used by other non-readline
919 exposing it as a method, it can be used by other non-readline
914 environments (such as GUIs) for text completion.
920 environments (such as GUIs) for text completion.
915
921
916 Simple usage example:
922 Simple usage example:
917
923
918 In [1]: x = 'hello'
924 In [1]: x = 'hello'
919
925
920 In [2]: __IP.complete('x.l')
926 In [2]: __IP.complete('x.l')
921 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
927 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
922
928
923 complete = self.Completer.complete
929 complete = self.Completer.complete
924 state = 0
930 state = 0
925 # use a dict so we get unique keys, since ipyhton's multiple
931 # use a dict so we get unique keys, since ipyhton's multiple
926 # completers can return duplicates.
932 # completers can return duplicates.
927 comps = {}
933 comps = {}
928 while True:
934 while True:
929 newcomp = complete(text,state)
935 newcomp = complete(text,state)
930 if newcomp is None:
936 if newcomp is None:
931 break
937 break
932 comps[newcomp] = 1
938 comps[newcomp] = 1
933 state += 1
939 state += 1
934 outcomps = comps.keys()
940 outcomps = comps.keys()
935 outcomps.sort()
941 outcomps.sort()
936 return outcomps
942 return outcomps
937
943
938 def set_completer_frame(self, frame=None):
944 def set_completer_frame(self, frame=None):
939 if frame:
945 if frame:
940 self.Completer.namespace = frame.f_locals
946 self.Completer.namespace = frame.f_locals
941 self.Completer.global_namespace = frame.f_globals
947 self.Completer.global_namespace = frame.f_globals
942 else:
948 else:
943 self.Completer.namespace = self.user_ns
949 self.Completer.namespace = self.user_ns
944 self.Completer.global_namespace = self.user_global_ns
950 self.Completer.global_namespace = self.user_global_ns
945
951
946 def init_auto_alias(self):
952 def init_auto_alias(self):
947 """Define some aliases automatically.
953 """Define some aliases automatically.
948
954
949 These are ALL parameter-less aliases"""
955 These are ALL parameter-less aliases"""
950
956
951 for alias,cmd in self.auto_alias:
957 for alias,cmd in self.auto_alias:
952 self.alias_table[alias] = (0,cmd)
958 self.alias_table[alias] = (0,cmd)
953
959
954 def alias_table_validate(self,verbose=0):
960 def alias_table_validate(self,verbose=0):
955 """Update information about the alias table.
961 """Update information about the alias table.
956
962
957 In particular, make sure no Python keywords/builtins are in it."""
963 In particular, make sure no Python keywords/builtins are in it."""
958
964
959 no_alias = self.no_alias
965 no_alias = self.no_alias
960 for k in self.alias_table.keys():
966 for k in self.alias_table.keys():
961 if k in no_alias:
967 if k in no_alias:
962 del self.alias_table[k]
968 del self.alias_table[k]
963 if verbose:
969 if verbose:
964 print ("Deleting alias <%s>, it's a Python "
970 print ("Deleting alias <%s>, it's a Python "
965 "keyword or builtin." % k)
971 "keyword or builtin." % k)
966
972
967 def set_autoindent(self,value=None):
973 def set_autoindent(self,value=None):
968 """Set the autoindent flag, checking for readline support.
974 """Set the autoindent flag, checking for readline support.
969
975
970 If called with no arguments, it acts as a toggle."""
976 If called with no arguments, it acts as a toggle."""
971
977
972 if not self.has_readline:
978 if not self.has_readline:
973 if os.name == 'posix':
979 if os.name == 'posix':
974 warn("The auto-indent feature requires the readline library")
980 warn("The auto-indent feature requires the readline library")
975 self.autoindent = 0
981 self.autoindent = 0
976 return
982 return
977 if value is None:
983 if value is None:
978 self.autoindent = not self.autoindent
984 self.autoindent = not self.autoindent
979 else:
985 else:
980 self.autoindent = value
986 self.autoindent = value
981
987
982 def rc_set_toggle(self,rc_field,value=None):
988 def rc_set_toggle(self,rc_field,value=None):
983 """Set or toggle a field in IPython's rc config. structure.
989 """Set or toggle a field in IPython's rc config. structure.
984
990
985 If called with no arguments, it acts as a toggle.
991 If called with no arguments, it acts as a toggle.
986
992
987 If called with a non-existent field, the resulting AttributeError
993 If called with a non-existent field, the resulting AttributeError
988 exception will propagate out."""
994 exception will propagate out."""
989
995
990 rc_val = getattr(self.rc,rc_field)
996 rc_val = getattr(self.rc,rc_field)
991 if value is None:
997 if value is None:
992 value = not rc_val
998 value = not rc_val
993 setattr(self.rc,rc_field,value)
999 setattr(self.rc,rc_field,value)
994
1000
995 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1001 def user_setup(self,ipythondir,rc_suffix,mode='install'):
996 """Install the user configuration directory.
1002 """Install the user configuration directory.
997
1003
998 Can be called when running for the first time or to upgrade the user's
1004 Can be called when running for the first time or to upgrade the user's
999 .ipython/ directory with the mode parameter. Valid modes are 'install'
1005 .ipython/ directory with the mode parameter. Valid modes are 'install'
1000 and 'upgrade'."""
1006 and 'upgrade'."""
1001
1007
1002 def wait():
1008 def wait():
1003 try:
1009 try:
1004 raw_input("Please press <RETURN> to start IPython.")
1010 raw_input("Please press <RETURN> to start IPython.")
1005 except EOFError:
1011 except EOFError:
1006 print >> Term.cout
1012 print >> Term.cout
1007 print '*'*70
1013 print '*'*70
1008
1014
1009 cwd = os.getcwd() # remember where we started
1015 cwd = os.getcwd() # remember where we started
1010 glb = glob.glob
1016 glb = glob.glob
1011 print '*'*70
1017 print '*'*70
1012 if mode == 'install':
1018 if mode == 'install':
1013 print \
1019 print \
1014 """Welcome to IPython. I will try to create a personal configuration directory
1020 """Welcome to IPython. I will try to create a personal configuration directory
1015 where you can customize many aspects of IPython's functionality in:\n"""
1021 where you can customize many aspects of IPython's functionality in:\n"""
1016 else:
1022 else:
1017 print 'I am going to upgrade your configuration in:'
1023 print 'I am going to upgrade your configuration in:'
1018
1024
1019 print ipythondir
1025 print ipythondir
1020
1026
1021 rcdirend = os.path.join('IPython','UserConfig')
1027 rcdirend = os.path.join('IPython','UserConfig')
1022 cfg = lambda d: os.path.join(d,rcdirend)
1028 cfg = lambda d: os.path.join(d,rcdirend)
1023 try:
1029 try:
1024 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1030 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1025 except IOError:
1031 except IOError:
1026 warning = """
1032 warning = """
1027 Installation error. IPython's directory was not found.
1033 Installation error. IPython's directory was not found.
1028
1034
1029 Check the following:
1035 Check the following:
1030
1036
1031 The ipython/IPython directory should be in a directory belonging to your
1037 The ipython/IPython directory should be in a directory belonging to your
1032 PYTHONPATH environment variable (that is, it should be in a directory
1038 PYTHONPATH environment variable (that is, it should be in a directory
1033 belonging to sys.path). You can copy it explicitly there or just link to it.
1039 belonging to sys.path). You can copy it explicitly there or just link to it.
1034
1040
1035 IPython will proceed with builtin defaults.
1041 IPython will proceed with builtin defaults.
1036 """
1042 """
1037 warn(warning)
1043 warn(warning)
1038 wait()
1044 wait()
1039 return
1045 return
1040
1046
1041 if mode == 'install':
1047 if mode == 'install':
1042 try:
1048 try:
1043 shutil.copytree(rcdir,ipythondir)
1049 shutil.copytree(rcdir,ipythondir)
1044 os.chdir(ipythondir)
1050 os.chdir(ipythondir)
1045 rc_files = glb("ipythonrc*")
1051 rc_files = glb("ipythonrc*")
1046 for rc_file in rc_files:
1052 for rc_file in rc_files:
1047 os.rename(rc_file,rc_file+rc_suffix)
1053 os.rename(rc_file,rc_file+rc_suffix)
1048 except:
1054 except:
1049 warning = """
1055 warning = """
1050
1056
1051 There was a problem with the installation:
1057 There was a problem with the installation:
1052 %s
1058 %s
1053 Try to correct it or contact the developers if you think it's a bug.
1059 Try to correct it or contact the developers if you think it's a bug.
1054 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1060 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1055 warn(warning)
1061 warn(warning)
1056 wait()
1062 wait()
1057 return
1063 return
1058
1064
1059 elif mode == 'upgrade':
1065 elif mode == 'upgrade':
1060 try:
1066 try:
1061 os.chdir(ipythondir)
1067 os.chdir(ipythondir)
1062 except:
1068 except:
1063 print """
1069 print """
1064 Can not upgrade: changing to directory %s failed. Details:
1070 Can not upgrade: changing to directory %s failed. Details:
1065 %s
1071 %s
1066 """ % (ipythondir,sys.exc_info()[1])
1072 """ % (ipythondir,sys.exc_info()[1])
1067 wait()
1073 wait()
1068 return
1074 return
1069 else:
1075 else:
1070 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1076 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1071 for new_full_path in sources:
1077 for new_full_path in sources:
1072 new_filename = os.path.basename(new_full_path)
1078 new_filename = os.path.basename(new_full_path)
1073 if new_filename.startswith('ipythonrc'):
1079 if new_filename.startswith('ipythonrc'):
1074 new_filename = new_filename + rc_suffix
1080 new_filename = new_filename + rc_suffix
1075 # The config directory should only contain files, skip any
1081 # The config directory should only contain files, skip any
1076 # directories which may be there (like CVS)
1082 # directories which may be there (like CVS)
1077 if os.path.isdir(new_full_path):
1083 if os.path.isdir(new_full_path):
1078 continue
1084 continue
1079 if os.path.exists(new_filename):
1085 if os.path.exists(new_filename):
1080 old_file = new_filename+'.old'
1086 old_file = new_filename+'.old'
1081 if os.path.exists(old_file):
1087 if os.path.exists(old_file):
1082 os.remove(old_file)
1088 os.remove(old_file)
1083 os.rename(new_filename,old_file)
1089 os.rename(new_filename,old_file)
1084 shutil.copy(new_full_path,new_filename)
1090 shutil.copy(new_full_path,new_filename)
1085 else:
1091 else:
1086 raise ValueError,'unrecognized mode for install:',`mode`
1092 raise ValueError,'unrecognized mode for install:',`mode`
1087
1093
1088 # Fix line-endings to those native to each platform in the config
1094 # Fix line-endings to those native to each platform in the config
1089 # directory.
1095 # directory.
1090 try:
1096 try:
1091 os.chdir(ipythondir)
1097 os.chdir(ipythondir)
1092 except:
1098 except:
1093 print """
1099 print """
1094 Problem: changing to directory %s failed.
1100 Problem: changing to directory %s failed.
1095 Details:
1101 Details:
1096 %s
1102 %s
1097
1103
1098 Some configuration files may have incorrect line endings. This should not
1104 Some configuration files may have incorrect line endings. This should not
1099 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1105 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1100 wait()
1106 wait()
1101 else:
1107 else:
1102 for fname in glb('ipythonrc*'):
1108 for fname in glb('ipythonrc*'):
1103 try:
1109 try:
1104 native_line_ends(fname,backup=0)
1110 native_line_ends(fname,backup=0)
1105 except IOError:
1111 except IOError:
1106 pass
1112 pass
1107
1113
1108 if mode == 'install':
1114 if mode == 'install':
1109 print """
1115 print """
1110 Successful installation!
1116 Successful installation!
1111
1117
1112 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1118 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1113 IPython manual (there are both HTML and PDF versions supplied with the
1119 IPython manual (there are both HTML and PDF versions supplied with the
1114 distribution) to make sure that your system environment is properly configured
1120 distribution) to make sure that your system environment is properly configured
1115 to take advantage of IPython's features.
1121 to take advantage of IPython's features.
1116
1122
1117 Important note: the configuration system has changed! The old system is
1123 Important note: the configuration system has changed! The old system is
1118 still in place, but its setting may be partly overridden by the settings in
1124 still in place, but its setting may be partly overridden by the settings in
1119 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1125 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1120 if some of the new settings bother you.
1126 if some of the new settings bother you.
1121
1127
1122 """
1128 """
1123 else:
1129 else:
1124 print """
1130 print """
1125 Successful upgrade!
1131 Successful upgrade!
1126
1132
1127 All files in your directory:
1133 All files in your directory:
1128 %(ipythondir)s
1134 %(ipythondir)s
1129 which would have been overwritten by the upgrade were backed up with a .old
1135 which would have been overwritten by the upgrade were backed up with a .old
1130 extension. If you had made particular customizations in those files you may
1136 extension. If you had made particular customizations in those files you may
1131 want to merge them back into the new files.""" % locals()
1137 want to merge them back into the new files.""" % locals()
1132 wait()
1138 wait()
1133 os.chdir(cwd)
1139 os.chdir(cwd)
1134 # end user_setup()
1140 # end user_setup()
1135
1141
1136 def atexit_operations(self):
1142 def atexit_operations(self):
1137 """This will be executed at the time of exit.
1143 """This will be executed at the time of exit.
1138
1144
1139 Saving of persistent data should be performed here. """
1145 Saving of persistent data should be performed here. """
1140
1146
1141 #print '*** IPython exit cleanup ***' # dbg
1147 #print '*** IPython exit cleanup ***' # dbg
1142 # input history
1148 # input history
1143 self.savehist()
1149 self.savehist()
1144
1150
1145 # Cleanup all tempfiles left around
1151 # Cleanup all tempfiles left around
1146 for tfile in self.tempfiles:
1152 for tfile in self.tempfiles:
1147 try:
1153 try:
1148 os.unlink(tfile)
1154 os.unlink(tfile)
1149 except OSError:
1155 except OSError:
1150 pass
1156 pass
1151
1157
1152 # save the "persistent data" catch-all dictionary
1158 # save the "persistent data" catch-all dictionary
1153 self.hooks.shutdown_hook()
1159 self.hooks.shutdown_hook()
1154
1160
1155 def savehist(self):
1161 def savehist(self):
1156 """Save input history to a file (via readline library)."""
1162 """Save input history to a file (via readline library)."""
1157 try:
1163 try:
1158 self.readline.write_history_file(self.histfile)
1164 self.readline.write_history_file(self.histfile)
1159 except:
1165 except:
1160 print 'Unable to save IPython command history to file: ' + \
1166 print 'Unable to save IPython command history to file: ' + \
1161 `self.histfile`
1167 `self.histfile`
1162
1168
1163 def pre_readline(self):
1169 def pre_readline(self):
1164 """readline hook to be used at the start of each line.
1170 """readline hook to be used at the start of each line.
1165
1171
1166 Currently it handles auto-indent only."""
1172 Currently it handles auto-indent only."""
1167
1173
1168 #debugx('self.indent_current_nsp','pre_readline:')
1174 #debugx('self.indent_current_nsp','pre_readline:')
1169 self.readline.insert_text(self.indent_current_str())
1175 self.readline.insert_text(self.indent_current_str())
1170
1176
1171 def init_readline(self):
1177 def init_readline(self):
1172 """Command history completion/saving/reloading."""
1178 """Command history completion/saving/reloading."""
1173
1179
1174 import IPython.rlineimpl as readline
1180 import IPython.rlineimpl as readline
1175 if not readline.have_readline:
1181 if not readline.have_readline:
1176 self.has_readline = 0
1182 self.has_readline = 0
1177 self.readline = None
1183 self.readline = None
1178 # no point in bugging windows users with this every time:
1184 # no point in bugging windows users with this every time:
1179 warn('Readline services not available on this platform.')
1185 warn('Readline services not available on this platform.')
1180 else:
1186 else:
1181 sys.modules['readline'] = readline
1187 sys.modules['readline'] = readline
1182 import atexit
1188 import atexit
1183 from IPython.completer import IPCompleter
1189 from IPython.completer import IPCompleter
1184 self.Completer = IPCompleter(self,
1190 self.Completer = IPCompleter(self,
1185 self.user_ns,
1191 self.user_ns,
1186 self.user_global_ns,
1192 self.user_global_ns,
1187 self.rc.readline_omit__names,
1193 self.rc.readline_omit__names,
1188 self.alias_table)
1194 self.alias_table)
1189
1195
1190 # Platform-specific configuration
1196 # Platform-specific configuration
1191 if os.name == 'nt':
1197 if os.name == 'nt':
1192 self.readline_startup_hook = readline.set_pre_input_hook
1198 self.readline_startup_hook = readline.set_pre_input_hook
1193 else:
1199 else:
1194 self.readline_startup_hook = readline.set_startup_hook
1200 self.readline_startup_hook = readline.set_startup_hook
1195
1201
1196 # Load user's initrc file (readline config)
1202 # Load user's initrc file (readline config)
1197 inputrc_name = os.environ.get('INPUTRC')
1203 inputrc_name = os.environ.get('INPUTRC')
1198 if inputrc_name is None:
1204 if inputrc_name is None:
1199 home_dir = get_home_dir()
1205 home_dir = get_home_dir()
1200 if home_dir is not None:
1206 if home_dir is not None:
1201 inputrc_name = os.path.join(home_dir,'.inputrc')
1207 inputrc_name = os.path.join(home_dir,'.inputrc')
1202 if os.path.isfile(inputrc_name):
1208 if os.path.isfile(inputrc_name):
1203 try:
1209 try:
1204 readline.read_init_file(inputrc_name)
1210 readline.read_init_file(inputrc_name)
1205 except:
1211 except:
1206 warn('Problems reading readline initialization file <%s>'
1212 warn('Problems reading readline initialization file <%s>'
1207 % inputrc_name)
1213 % inputrc_name)
1208
1214
1209 self.has_readline = 1
1215 self.has_readline = 1
1210 self.readline = readline
1216 self.readline = readline
1211 # save this in sys so embedded copies can restore it properly
1217 # save this in sys so embedded copies can restore it properly
1212 sys.ipcompleter = self.Completer.complete
1218 sys.ipcompleter = self.Completer.complete
1213 readline.set_completer(self.Completer.complete)
1219 readline.set_completer(self.Completer.complete)
1214
1220
1215 # Configure readline according to user's prefs
1221 # Configure readline according to user's prefs
1216 for rlcommand in self.rc.readline_parse_and_bind:
1222 for rlcommand in self.rc.readline_parse_and_bind:
1217 readline.parse_and_bind(rlcommand)
1223 readline.parse_and_bind(rlcommand)
1218
1224
1219 # remove some chars from the delimiters list
1225 # remove some chars from the delimiters list
1220 delims = readline.get_completer_delims()
1226 delims = readline.get_completer_delims()
1221 delims = delims.translate(string._idmap,
1227 delims = delims.translate(string._idmap,
1222 self.rc.readline_remove_delims)
1228 self.rc.readline_remove_delims)
1223 readline.set_completer_delims(delims)
1229 readline.set_completer_delims(delims)
1224 # otherwise we end up with a monster history after a while:
1230 # otherwise we end up with a monster history after a while:
1225 readline.set_history_length(1000)
1231 readline.set_history_length(1000)
1226 try:
1232 try:
1227 #print '*** Reading readline history' # dbg
1233 #print '*** Reading readline history' # dbg
1228 readline.read_history_file(self.histfile)
1234 readline.read_history_file(self.histfile)
1229 except IOError:
1235 except IOError:
1230 pass # It doesn't exist yet.
1236 pass # It doesn't exist yet.
1231
1237
1232 atexit.register(self.atexit_operations)
1238 atexit.register(self.atexit_operations)
1233 del atexit
1239 del atexit
1234
1240
1235 # Configure auto-indent for all platforms
1241 # Configure auto-indent for all platforms
1236 self.set_autoindent(self.rc.autoindent)
1242 self.set_autoindent(self.rc.autoindent)
1237
1243
1238 def ask_yes_no(self,prompt,default=True):
1244 def ask_yes_no(self,prompt,default=True):
1239 if self.rc.quiet:
1245 if self.rc.quiet:
1240 return True
1246 return True
1241 return ask_yes_no(prompt,default)
1247 return ask_yes_no(prompt,default)
1242
1248
1243 def _should_recompile(self,e):
1249 def _should_recompile(self,e):
1244 """Utility routine for edit_syntax_error"""
1250 """Utility routine for edit_syntax_error"""
1245
1251
1246 if e.filename in ('<ipython console>','<input>','<string>',
1252 if e.filename in ('<ipython console>','<input>','<string>',
1247 '<console>','<BackgroundJob compilation>',
1253 '<console>','<BackgroundJob compilation>',
1248 None):
1254 None):
1249
1255
1250 return False
1256 return False
1251 try:
1257 try:
1252 if (self.rc.autoedit_syntax and
1258 if (self.rc.autoedit_syntax and
1253 not self.ask_yes_no('Return to editor to correct syntax error? '
1259 not self.ask_yes_no('Return to editor to correct syntax error? '
1254 '[Y/n] ','y')):
1260 '[Y/n] ','y')):
1255 return False
1261 return False
1256 except EOFError:
1262 except EOFError:
1257 return False
1263 return False
1258
1264
1259 def int0(x):
1265 def int0(x):
1260 try:
1266 try:
1261 return int(x)
1267 return int(x)
1262 except TypeError:
1268 except TypeError:
1263 return 0
1269 return 0
1264 # always pass integer line and offset values to editor hook
1270 # always pass integer line and offset values to editor hook
1265 self.hooks.fix_error_editor(e.filename,
1271 self.hooks.fix_error_editor(e.filename,
1266 int0(e.lineno),int0(e.offset),e.msg)
1272 int0(e.lineno),int0(e.offset),e.msg)
1267 return True
1273 return True
1268
1274
1269 def edit_syntax_error(self):
1275 def edit_syntax_error(self):
1270 """The bottom half of the syntax error handler called in the main loop.
1276 """The bottom half of the syntax error handler called in the main loop.
1271
1277
1272 Loop until syntax error is fixed or user cancels.
1278 Loop until syntax error is fixed or user cancels.
1273 """
1279 """
1274
1280
1275 while self.SyntaxTB.last_syntax_error:
1281 while self.SyntaxTB.last_syntax_error:
1276 # copy and clear last_syntax_error
1282 # copy and clear last_syntax_error
1277 err = self.SyntaxTB.clear_err_state()
1283 err = self.SyntaxTB.clear_err_state()
1278 if not self._should_recompile(err):
1284 if not self._should_recompile(err):
1279 return
1285 return
1280 try:
1286 try:
1281 # may set last_syntax_error again if a SyntaxError is raised
1287 # may set last_syntax_error again if a SyntaxError is raised
1282 self.safe_execfile(err.filename,self.user_ns)
1288 self.safe_execfile(err.filename,self.user_ns)
1283 except:
1289 except:
1284 self.showtraceback()
1290 self.showtraceback()
1285 else:
1291 else:
1286 try:
1292 try:
1287 f = file(err.filename)
1293 f = file(err.filename)
1288 try:
1294 try:
1289 sys.displayhook(f.read())
1295 sys.displayhook(f.read())
1290 finally:
1296 finally:
1291 f.close()
1297 f.close()
1292 except:
1298 except:
1293 self.showtraceback()
1299 self.showtraceback()
1294
1300
1295 def showsyntaxerror(self, filename=None):
1301 def showsyntaxerror(self, filename=None):
1296 """Display the syntax error that just occurred.
1302 """Display the syntax error that just occurred.
1297
1303
1298 This doesn't display a stack trace because there isn't one.
1304 This doesn't display a stack trace because there isn't one.
1299
1305
1300 If a filename is given, it is stuffed in the exception instead
1306 If a filename is given, it is stuffed in the exception instead
1301 of what was there before (because Python's parser always uses
1307 of what was there before (because Python's parser always uses
1302 "<string>" when reading from a string).
1308 "<string>" when reading from a string).
1303 """
1309 """
1304 etype, value, last_traceback = sys.exc_info()
1310 etype, value, last_traceback = sys.exc_info()
1305
1311
1306 # See note about these variables in showtraceback() below
1312 # See note about these variables in showtraceback() below
1307 sys.last_type = etype
1313 sys.last_type = etype
1308 sys.last_value = value
1314 sys.last_value = value
1309 sys.last_traceback = last_traceback
1315 sys.last_traceback = last_traceback
1310
1316
1311 if filename and etype is SyntaxError:
1317 if filename and etype is SyntaxError:
1312 # Work hard to stuff the correct filename in the exception
1318 # Work hard to stuff the correct filename in the exception
1313 try:
1319 try:
1314 msg, (dummy_filename, lineno, offset, line) = value
1320 msg, (dummy_filename, lineno, offset, line) = value
1315 except:
1321 except:
1316 # Not the format we expect; leave it alone
1322 # Not the format we expect; leave it alone
1317 pass
1323 pass
1318 else:
1324 else:
1319 # Stuff in the right filename
1325 # Stuff in the right filename
1320 try:
1326 try:
1321 # Assume SyntaxError is a class exception
1327 # Assume SyntaxError is a class exception
1322 value = SyntaxError(msg, (filename, lineno, offset, line))
1328 value = SyntaxError(msg, (filename, lineno, offset, line))
1323 except:
1329 except:
1324 # If that failed, assume SyntaxError is a string
1330 # If that failed, assume SyntaxError is a string
1325 value = msg, (filename, lineno, offset, line)
1331 value = msg, (filename, lineno, offset, line)
1326 self.SyntaxTB(etype,value,[])
1332 self.SyntaxTB(etype,value,[])
1327
1333
1328 def debugger(self):
1334 def debugger(self):
1329 """Call the pdb debugger."""
1335 """Call the pdb debugger."""
1330
1336
1331 if not self.rc.pdb:
1337 if not self.rc.pdb:
1332 return
1338 return
1333 pdb.pm()
1339 pdb.pm()
1334
1340
1335 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1341 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1336 """Display the exception that just occurred.
1342 """Display the exception that just occurred.
1337
1343
1338 If nothing is known about the exception, this is the method which
1344 If nothing is known about the exception, this is the method which
1339 should be used throughout the code for presenting user tracebacks,
1345 should be used throughout the code for presenting user tracebacks,
1340 rather than directly invoking the InteractiveTB object.
1346 rather than directly invoking the InteractiveTB object.
1341
1347
1342 A specific showsyntaxerror() also exists, but this method can take
1348 A specific showsyntaxerror() also exists, but this method can take
1343 care of calling it if needed, so unless you are explicitly catching a
1349 care of calling it if needed, so unless you are explicitly catching a
1344 SyntaxError exception, don't try to analyze the stack manually and
1350 SyntaxError exception, don't try to analyze the stack manually and
1345 simply call this method."""
1351 simply call this method."""
1346
1352
1347 # Though this won't be called by syntax errors in the input line,
1353 # Though this won't be called by syntax errors in the input line,
1348 # there may be SyntaxError cases whith imported code.
1354 # there may be SyntaxError cases whith imported code.
1349 if exc_tuple is None:
1355 if exc_tuple is None:
1350 etype, value, tb = sys.exc_info()
1356 etype, value, tb = sys.exc_info()
1351 else:
1357 else:
1352 etype, value, tb = exc_tuple
1358 etype, value, tb = exc_tuple
1353 if etype is SyntaxError:
1359 if etype is SyntaxError:
1354 self.showsyntaxerror(filename)
1360 self.showsyntaxerror(filename)
1355 else:
1361 else:
1356 # WARNING: these variables are somewhat deprecated and not
1362 # WARNING: these variables are somewhat deprecated and not
1357 # necessarily safe to use in a threaded environment, but tools
1363 # necessarily safe to use in a threaded environment, but tools
1358 # like pdb depend on their existence, so let's set them. If we
1364 # like pdb depend on their existence, so let's set them. If we
1359 # find problems in the field, we'll need to revisit their use.
1365 # find problems in the field, we'll need to revisit their use.
1360 sys.last_type = etype
1366 sys.last_type = etype
1361 sys.last_value = value
1367 sys.last_value = value
1362 sys.last_traceback = tb
1368 sys.last_traceback = tb
1363
1369
1364 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1370 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1365 if self.InteractiveTB.call_pdb and self.has_readline:
1371 if self.InteractiveTB.call_pdb and self.has_readline:
1366 # pdb mucks up readline, fix it back
1372 # pdb mucks up readline, fix it back
1367 self.readline.set_completer(self.Completer.complete)
1373 self.readline.set_completer(self.Completer.complete)
1368
1374
1369 def mainloop(self,banner=None):
1375 def mainloop(self,banner=None):
1370 """Creates the local namespace and starts the mainloop.
1376 """Creates the local namespace and starts the mainloop.
1371
1377
1372 If an optional banner argument is given, it will override the
1378 If an optional banner argument is given, it will override the
1373 internally created default banner."""
1379 internally created default banner."""
1374
1380
1375 if self.rc.c: # Emulate Python's -c option
1381 if self.rc.c: # Emulate Python's -c option
1376 self.exec_init_cmd()
1382 self.exec_init_cmd()
1377 if banner is None:
1383 if banner is None:
1378 if not self.rc.banner:
1384 if not self.rc.banner:
1379 banner = ''
1385 banner = ''
1380 # banner is string? Use it directly!
1386 # banner is string? Use it directly!
1381 elif isinstance(self.rc.banner,basestring):
1387 elif isinstance(self.rc.banner,basestring):
1382 banner = self.rc.banner
1388 banner = self.rc.banner
1383 else:
1389 else:
1384 banner = self.BANNER+self.banner2
1390 banner = self.BANNER+self.banner2
1385
1391
1386 self.interact(banner)
1392 self.interact(banner)
1387
1393
1388 def exec_init_cmd(self):
1394 def exec_init_cmd(self):
1389 """Execute a command given at the command line.
1395 """Execute a command given at the command line.
1390
1396
1391 This emulates Python's -c option."""
1397 This emulates Python's -c option."""
1392
1398
1393 #sys.argv = ['-c']
1399 #sys.argv = ['-c']
1394 self.push(self.rc.c)
1400 self.push(self.rc.c)
1395
1401
1396 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1402 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1397 """Embeds IPython into a running python program.
1403 """Embeds IPython into a running python program.
1398
1404
1399 Input:
1405 Input:
1400
1406
1401 - header: An optional header message can be specified.
1407 - header: An optional header message can be specified.
1402
1408
1403 - local_ns, global_ns: working namespaces. If given as None, the
1409 - local_ns, global_ns: working namespaces. If given as None, the
1404 IPython-initialized one is updated with __main__.__dict__, so that
1410 IPython-initialized one is updated with __main__.__dict__, so that
1405 program variables become visible but user-specific configuration
1411 program variables become visible but user-specific configuration
1406 remains possible.
1412 remains possible.
1407
1413
1408 - stack_depth: specifies how many levels in the stack to go to
1414 - stack_depth: specifies how many levels in the stack to go to
1409 looking for namespaces (when local_ns and global_ns are None). This
1415 looking for namespaces (when local_ns and global_ns are None). This
1410 allows an intermediate caller to make sure that this function gets
1416 allows an intermediate caller to make sure that this function gets
1411 the namespace from the intended level in the stack. By default (0)
1417 the namespace from the intended level in the stack. By default (0)
1412 it will get its locals and globals from the immediate caller.
1418 it will get its locals and globals from the immediate caller.
1413
1419
1414 Warning: it's possible to use this in a program which is being run by
1420 Warning: it's possible to use this in a program which is being run by
1415 IPython itself (via %run), but some funny things will happen (a few
1421 IPython itself (via %run), but some funny things will happen (a few
1416 globals get overwritten). In the future this will be cleaned up, as
1422 globals get overwritten). In the future this will be cleaned up, as
1417 there is no fundamental reason why it can't work perfectly."""
1423 there is no fundamental reason why it can't work perfectly."""
1418
1424
1419 # Get locals and globals from caller
1425 # Get locals and globals from caller
1420 if local_ns is None or global_ns is None:
1426 if local_ns is None or global_ns is None:
1421 call_frame = sys._getframe(stack_depth).f_back
1427 call_frame = sys._getframe(stack_depth).f_back
1422
1428
1423 if local_ns is None:
1429 if local_ns is None:
1424 local_ns = call_frame.f_locals
1430 local_ns = call_frame.f_locals
1425 if global_ns is None:
1431 if global_ns is None:
1426 global_ns = call_frame.f_globals
1432 global_ns = call_frame.f_globals
1427
1433
1428 # Update namespaces and fire up interpreter
1434 # Update namespaces and fire up interpreter
1429
1435
1430 # The global one is easy, we can just throw it in
1436 # The global one is easy, we can just throw it in
1431 self.user_global_ns = global_ns
1437 self.user_global_ns = global_ns
1432
1438
1433 # but the user/local one is tricky: ipython needs it to store internal
1439 # but the user/local one is tricky: ipython needs it to store internal
1434 # data, but we also need the locals. We'll copy locals in the user
1440 # data, but we also need the locals. We'll copy locals in the user
1435 # one, but will track what got copied so we can delete them at exit.
1441 # one, but will track what got copied so we can delete them at exit.
1436 # This is so that a later embedded call doesn't see locals from a
1442 # This is so that a later embedded call doesn't see locals from a
1437 # previous call (which most likely existed in a separate scope).
1443 # previous call (which most likely existed in a separate scope).
1438 local_varnames = local_ns.keys()
1444 local_varnames = local_ns.keys()
1439 self.user_ns.update(local_ns)
1445 self.user_ns.update(local_ns)
1440
1446
1441 # Patch for global embedding to make sure that things don't overwrite
1447 # Patch for global embedding to make sure that things don't overwrite
1442 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1448 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1443 # FIXME. Test this a bit more carefully (the if.. is new)
1449 # FIXME. Test this a bit more carefully (the if.. is new)
1444 if local_ns is None and global_ns is None:
1450 if local_ns is None and global_ns is None:
1445 self.user_global_ns.update(__main__.__dict__)
1451 self.user_global_ns.update(__main__.__dict__)
1446
1452
1447 # make sure the tab-completer has the correct frame information, so it
1453 # make sure the tab-completer has the correct frame information, so it
1448 # actually completes using the frame's locals/globals
1454 # actually completes using the frame's locals/globals
1449 self.set_completer_frame()
1455 self.set_completer_frame()
1450
1456
1451 # before activating the interactive mode, we need to make sure that
1457 # before activating the interactive mode, we need to make sure that
1452 # all names in the builtin namespace needed by ipython point to
1458 # all names in the builtin namespace needed by ipython point to
1453 # ourselves, and not to other instances.
1459 # ourselves, and not to other instances.
1454 self.add_builtins()
1460 self.add_builtins()
1455
1461
1456 self.interact(header)
1462 self.interact(header)
1457
1463
1458 # now, purge out the user namespace from anything we might have added
1464 # now, purge out the user namespace from anything we might have added
1459 # from the caller's local namespace
1465 # from the caller's local namespace
1460 delvar = self.user_ns.pop
1466 delvar = self.user_ns.pop
1461 for var in local_varnames:
1467 for var in local_varnames:
1462 delvar(var,None)
1468 delvar(var,None)
1463 # and clean builtins we may have overridden
1469 # and clean builtins we may have overridden
1464 self.clean_builtins()
1470 self.clean_builtins()
1465
1471
1466 def interact(self, banner=None):
1472 def interact(self, banner=None):
1467 """Closely emulate the interactive Python console.
1473 """Closely emulate the interactive Python console.
1468
1474
1469 The optional banner argument specify the banner to print
1475 The optional banner argument specify the banner to print
1470 before the first interaction; by default it prints a banner
1476 before the first interaction; by default it prints a banner
1471 similar to the one printed by the real Python interpreter,
1477 similar to the one printed by the real Python interpreter,
1472 followed by the current class name in parentheses (so as not
1478 followed by the current class name in parentheses (so as not
1473 to confuse this with the real interpreter -- since it's so
1479 to confuse this with the real interpreter -- since it's so
1474 close!).
1480 close!).
1475
1481
1476 """
1482 """
1477
1483
1478 if self.exit_now:
1484 if self.exit_now:
1479 # batch run -> do not interact
1485 # batch run -> do not interact
1480 return
1486 return
1481 cprt = 'Type "copyright", "credits" or "license" for more information.'
1487 cprt = 'Type "copyright", "credits" or "license" for more information.'
1482 if banner is None:
1488 if banner is None:
1483 self.write("Python %s on %s\n%s\n(%s)\n" %
1489 self.write("Python %s on %s\n%s\n(%s)\n" %
1484 (sys.version, sys.platform, cprt,
1490 (sys.version, sys.platform, cprt,
1485 self.__class__.__name__))
1491 self.__class__.__name__))
1486 else:
1492 else:
1487 self.write(banner)
1493 self.write(banner)
1488
1494
1489 more = 0
1495 more = 0
1490
1496
1491 # Mark activity in the builtins
1497 # Mark activity in the builtins
1492 __builtin__.__dict__['__IPYTHON__active'] += 1
1498 __builtin__.__dict__['__IPYTHON__active'] += 1
1493
1499
1494 # exit_now is set by a call to %Exit or %Quit
1500 # exit_now is set by a call to %Exit or %Quit
1495 while not self.exit_now:
1501 while not self.exit_now:
1496 if more:
1502 if more:
1497 prompt = self.hooks.generate_prompt(True)
1503 prompt = self.hooks.generate_prompt(True)
1498 if self.autoindent:
1504 if self.autoindent:
1499 self.readline_startup_hook(self.pre_readline)
1505 self.readline_startup_hook(self.pre_readline)
1500 else:
1506 else:
1501 prompt = self.hooks.generate_prompt(False)
1507 prompt = self.hooks.generate_prompt(False)
1502 try:
1508 try:
1503 line = self.raw_input(prompt,more)
1509 line = self.raw_input(prompt,more)
1504 if self.autoindent:
1510 if self.autoindent:
1505 self.readline_startup_hook(None)
1511 self.readline_startup_hook(None)
1506 except KeyboardInterrupt:
1512 except KeyboardInterrupt:
1507 self.write('\nKeyboardInterrupt\n')
1513 self.write('\nKeyboardInterrupt\n')
1508 self.resetbuffer()
1514 self.resetbuffer()
1509 # keep cache in sync with the prompt counter:
1515 # keep cache in sync with the prompt counter:
1510 self.outputcache.prompt_count -= 1
1516 self.outputcache.prompt_count -= 1
1511
1517
1512 if self.autoindent:
1518 if self.autoindent:
1513 self.indent_current_nsp = 0
1519 self.indent_current_nsp = 0
1514 more = 0
1520 more = 0
1515 except EOFError:
1521 except EOFError:
1516 if self.autoindent:
1522 if self.autoindent:
1517 self.readline_startup_hook(None)
1523 self.readline_startup_hook(None)
1518 self.write('\n')
1524 self.write('\n')
1519 self.exit()
1525 self.exit()
1520 except bdb.BdbQuit:
1526 except bdb.BdbQuit:
1521 warn('The Python debugger has exited with a BdbQuit exception.\n'
1527 warn('The Python debugger has exited with a BdbQuit exception.\n'
1522 'Because of how pdb handles the stack, it is impossible\n'
1528 'Because of how pdb handles the stack, it is impossible\n'
1523 'for IPython to properly format this particular exception.\n'
1529 'for IPython to properly format this particular exception.\n'
1524 'IPython will resume normal operation.')
1530 'IPython will resume normal operation.')
1525 except:
1531 except:
1526 # exceptions here are VERY RARE, but they can be triggered
1532 # exceptions here are VERY RARE, but they can be triggered
1527 # asynchronously by signal handlers, for example.
1533 # asynchronously by signal handlers, for example.
1528 self.showtraceback()
1534 self.showtraceback()
1529 else:
1535 else:
1530 more = self.push(line)
1536 more = self.push(line)
1531 if (self.SyntaxTB.last_syntax_error and
1537 if (self.SyntaxTB.last_syntax_error and
1532 self.rc.autoedit_syntax):
1538 self.rc.autoedit_syntax):
1533 self.edit_syntax_error()
1539 self.edit_syntax_error()
1534
1540
1535 # We are off again...
1541 # We are off again...
1536 __builtin__.__dict__['__IPYTHON__active'] -= 1
1542 __builtin__.__dict__['__IPYTHON__active'] -= 1
1537
1543
1538 def excepthook(self, etype, value, tb):
1544 def excepthook(self, etype, value, tb):
1539 """One more defense for GUI apps that call sys.excepthook.
1545 """One more defense for GUI apps that call sys.excepthook.
1540
1546
1541 GUI frameworks like wxPython trap exceptions and call
1547 GUI frameworks like wxPython trap exceptions and call
1542 sys.excepthook themselves. I guess this is a feature that
1548 sys.excepthook themselves. I guess this is a feature that
1543 enables them to keep running after exceptions that would
1549 enables them to keep running after exceptions that would
1544 otherwise kill their mainloop. This is a bother for IPython
1550 otherwise kill their mainloop. This is a bother for IPython
1545 which excepts to catch all of the program exceptions with a try:
1551 which excepts to catch all of the program exceptions with a try:
1546 except: statement.
1552 except: statement.
1547
1553
1548 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1554 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1549 any app directly invokes sys.excepthook, it will look to the user like
1555 any app directly invokes sys.excepthook, it will look to the user like
1550 IPython crashed. In order to work around this, we can disable the
1556 IPython crashed. In order to work around this, we can disable the
1551 CrashHandler and replace it with this excepthook instead, which prints a
1557 CrashHandler and replace it with this excepthook instead, which prints a
1552 regular traceback using our InteractiveTB. In this fashion, apps which
1558 regular traceback using our InteractiveTB. In this fashion, apps which
1553 call sys.excepthook will generate a regular-looking exception from
1559 call sys.excepthook will generate a regular-looking exception from
1554 IPython, and the CrashHandler will only be triggered by real IPython
1560 IPython, and the CrashHandler will only be triggered by real IPython
1555 crashes.
1561 crashes.
1556
1562
1557 This hook should be used sparingly, only in places which are not likely
1563 This hook should be used sparingly, only in places which are not likely
1558 to be true IPython errors.
1564 to be true IPython errors.
1559 """
1565 """
1560 self.showtraceback((etype,value,tb),tb_offset=0)
1566 self.showtraceback((etype,value,tb),tb_offset=0)
1561
1567
1562 def transform_alias(self, alias,rest=''):
1568 def transform_alias(self, alias,rest=''):
1563 """ Transform alias to system command string.
1569 """ Transform alias to system command string.
1564 """
1570 """
1565 nargs,cmd = self.alias_table[alias]
1571 nargs,cmd = self.alias_table[alias]
1566 if ' ' in cmd and os.path.isfile(cmd):
1572 if ' ' in cmd and os.path.isfile(cmd):
1567 cmd = '"%s"' % cmd
1573 cmd = '"%s"' % cmd
1568
1574
1569 # Expand the %l special to be the user's input line
1575 # Expand the %l special to be the user's input line
1570 if cmd.find('%l') >= 0:
1576 if cmd.find('%l') >= 0:
1571 cmd = cmd.replace('%l',rest)
1577 cmd = cmd.replace('%l',rest)
1572 rest = ''
1578 rest = ''
1573 if nargs==0:
1579 if nargs==0:
1574 # Simple, argument-less aliases
1580 # Simple, argument-less aliases
1575 cmd = '%s %s' % (cmd,rest)
1581 cmd = '%s %s' % (cmd,rest)
1576 else:
1582 else:
1577 # Handle aliases with positional arguments
1583 # Handle aliases with positional arguments
1578 args = rest.split(None,nargs)
1584 args = rest.split(None,nargs)
1579 if len(args)< nargs:
1585 if len(args)< nargs:
1580 error('Alias <%s> requires %s arguments, %s given.' %
1586 error('Alias <%s> requires %s arguments, %s given.' %
1581 (alias,nargs,len(args)))
1587 (alias,nargs,len(args)))
1582 return None
1588 return None
1583 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1589 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1584 # Now call the macro, evaluating in the user's namespace
1590 # Now call the macro, evaluating in the user's namespace
1585 #print 'new command: <%r>' % cmd # dbg
1591 #print 'new command: <%r>' % cmd # dbg
1586 return cmd
1592 return cmd
1587
1593
1588 def call_alias(self,alias,rest=''):
1594 def call_alias(self,alias,rest=''):
1589 """Call an alias given its name and the rest of the line.
1595 """Call an alias given its name and the rest of the line.
1590
1596
1591 This is only used to provide backwards compatibility for users of
1597 This is only used to provide backwards compatibility for users of
1592 ipalias(), use of which is not recommended for anymore."""
1598 ipalias(), use of which is not recommended for anymore."""
1593
1599
1594 # Now call the macro, evaluating in the user's namespace
1600 # Now call the macro, evaluating in the user's namespace
1595 cmd = self.transform_alias(alias, rest)
1601 cmd = self.transform_alias(alias, rest)
1596 try:
1602 try:
1597 self.system(cmd)
1603 self.system(cmd)
1598 except:
1604 except:
1599 self.showtraceback()
1605 self.showtraceback()
1600
1606
1601 def indent_current_str(self):
1607 def indent_current_str(self):
1602 """return the current level of indentation as a string"""
1608 """return the current level of indentation as a string"""
1603 return self.indent_current_nsp * ' '
1609 return self.indent_current_nsp * ' '
1604
1610
1605 def autoindent_update(self,line):
1611 def autoindent_update(self,line):
1606 """Keep track of the indent level."""
1612 """Keep track of the indent level."""
1607
1613
1608 #debugx('line')
1614 #debugx('line')
1609 #debugx('self.indent_current_nsp')
1615 #debugx('self.indent_current_nsp')
1610 if self.autoindent:
1616 if self.autoindent:
1611 if line:
1617 if line:
1612 inisp = num_ini_spaces(line)
1618 inisp = num_ini_spaces(line)
1613 if inisp < self.indent_current_nsp:
1619 if inisp < self.indent_current_nsp:
1614 self.indent_current_nsp = inisp
1620 self.indent_current_nsp = inisp
1615
1621
1616 if line[-1] == ':':
1622 if line[-1] == ':':
1617 self.indent_current_nsp += 4
1623 self.indent_current_nsp += 4
1618 elif dedent_re.match(line):
1624 elif dedent_re.match(line):
1619 self.indent_current_nsp -= 4
1625 self.indent_current_nsp -= 4
1620 else:
1626 else:
1621 self.indent_current_nsp = 0
1627 self.indent_current_nsp = 0
1622
1628
1623 def runlines(self,lines):
1629 def runlines(self,lines):
1624 """Run a string of one or more lines of source.
1630 """Run a string of one or more lines of source.
1625
1631
1626 This method is capable of running a string containing multiple source
1632 This method is capable of running a string containing multiple source
1627 lines, as if they had been entered at the IPython prompt. Since it
1633 lines, as if they had been entered at the IPython prompt. Since it
1628 exposes IPython's processing machinery, the given strings can contain
1634 exposes IPython's processing machinery, the given strings can contain
1629 magic calls (%magic), special shell access (!cmd), etc."""
1635 magic calls (%magic), special shell access (!cmd), etc."""
1630
1636
1631 # We must start with a clean buffer, in case this is run from an
1637 # We must start with a clean buffer, in case this is run from an
1632 # interactive IPython session (via a magic, for example).
1638 # interactive IPython session (via a magic, for example).
1633 self.resetbuffer()
1639 self.resetbuffer()
1634 lines = lines.split('\n')
1640 lines = lines.split('\n')
1635 more = 0
1641 more = 0
1636 for line in lines:
1642 for line in lines:
1637 # skip blank lines so we don't mess up the prompt counter, but do
1643 # skip blank lines so we don't mess up the prompt counter, but do
1638 # NOT skip even a blank line if we are in a code block (more is
1644 # NOT skip even a blank line if we are in a code block (more is
1639 # true)
1645 # true)
1640 if line or more:
1646 if line or more:
1641 more = self.push(self.prefilter(line,more))
1647 more = self.push(self.prefilter(line,more))
1642 # IPython's runsource returns None if there was an error
1648 # IPython's runsource returns None if there was an error
1643 # compiling the code. This allows us to stop processing right
1649 # compiling the code. This allows us to stop processing right
1644 # away, so the user gets the error message at the right place.
1650 # away, so the user gets the error message at the right place.
1645 if more is None:
1651 if more is None:
1646 break
1652 break
1647 # final newline in case the input didn't have it, so that the code
1653 # final newline in case the input didn't have it, so that the code
1648 # actually does get executed
1654 # actually does get executed
1649 if more:
1655 if more:
1650 self.push('\n')
1656 self.push('\n')
1651
1657
1652 def runsource(self, source, filename='<input>', symbol='single'):
1658 def runsource(self, source, filename='<input>', symbol='single'):
1653 """Compile and run some source in the interpreter.
1659 """Compile and run some source in the interpreter.
1654
1660
1655 Arguments are as for compile_command().
1661 Arguments are as for compile_command().
1656
1662
1657 One several things can happen:
1663 One several things can happen:
1658
1664
1659 1) The input is incorrect; compile_command() raised an
1665 1) The input is incorrect; compile_command() raised an
1660 exception (SyntaxError or OverflowError). A syntax traceback
1666 exception (SyntaxError or OverflowError). A syntax traceback
1661 will be printed by calling the showsyntaxerror() method.
1667 will be printed by calling the showsyntaxerror() method.
1662
1668
1663 2) The input is incomplete, and more input is required;
1669 2) The input is incomplete, and more input is required;
1664 compile_command() returned None. Nothing happens.
1670 compile_command() returned None. Nothing happens.
1665
1671
1666 3) The input is complete; compile_command() returned a code
1672 3) The input is complete; compile_command() returned a code
1667 object. The code is executed by calling self.runcode() (which
1673 object. The code is executed by calling self.runcode() (which
1668 also handles run-time exceptions, except for SystemExit).
1674 also handles run-time exceptions, except for SystemExit).
1669
1675
1670 The return value is:
1676 The return value is:
1671
1677
1672 - True in case 2
1678 - True in case 2
1673
1679
1674 - False in the other cases, unless an exception is raised, where
1680 - False in the other cases, unless an exception is raised, where
1675 None is returned instead. This can be used by external callers to
1681 None is returned instead. This can be used by external callers to
1676 know whether to continue feeding input or not.
1682 know whether to continue feeding input or not.
1677
1683
1678 The return value can be used to decide whether to use sys.ps1 or
1684 The return value can be used to decide whether to use sys.ps1 or
1679 sys.ps2 to prompt the next line."""
1685 sys.ps2 to prompt the next line."""
1680
1686
1681 try:
1687 try:
1682 code = self.compile(source,filename,symbol)
1688 code = self.compile(source,filename,symbol)
1683 except (OverflowError, SyntaxError, ValueError):
1689 except (OverflowError, SyntaxError, ValueError):
1684 # Case 1
1690 # Case 1
1685 self.showsyntaxerror(filename)
1691 self.showsyntaxerror(filename)
1686 return None
1692 return None
1687
1693
1688 if code is None:
1694 if code is None:
1689 # Case 2
1695 # Case 2
1690 return True
1696 return True
1691
1697
1692 # Case 3
1698 # Case 3
1693 # We store the code object so that threaded shells and
1699 # We store the code object so that threaded shells and
1694 # custom exception handlers can access all this info if needed.
1700 # custom exception handlers can access all this info if needed.
1695 # The source corresponding to this can be obtained from the
1701 # The source corresponding to this can be obtained from the
1696 # buffer attribute as '\n'.join(self.buffer).
1702 # buffer attribute as '\n'.join(self.buffer).
1697 self.code_to_run = code
1703 self.code_to_run = code
1698 # now actually execute the code object
1704 # now actually execute the code object
1699 if self.runcode(code) == 0:
1705 if self.runcode(code) == 0:
1700 return False
1706 return False
1701 else:
1707 else:
1702 return None
1708 return None
1703
1709
1704 def runcode(self,code_obj):
1710 def runcode(self,code_obj):
1705 """Execute a code object.
1711 """Execute a code object.
1706
1712
1707 When an exception occurs, self.showtraceback() is called to display a
1713 When an exception occurs, self.showtraceback() is called to display a
1708 traceback.
1714 traceback.
1709
1715
1710 Return value: a flag indicating whether the code to be run completed
1716 Return value: a flag indicating whether the code to be run completed
1711 successfully:
1717 successfully:
1712
1718
1713 - 0: successful execution.
1719 - 0: successful execution.
1714 - 1: an error occurred.
1720 - 1: an error occurred.
1715 """
1721 """
1716
1722
1717 # Set our own excepthook in case the user code tries to call it
1723 # Set our own excepthook in case the user code tries to call it
1718 # directly, so that the IPython crash handler doesn't get triggered
1724 # directly, so that the IPython crash handler doesn't get triggered
1719 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1725 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1720
1726
1721 # we save the original sys.excepthook in the instance, in case config
1727 # we save the original sys.excepthook in the instance, in case config
1722 # code (such as magics) needs access to it.
1728 # code (such as magics) needs access to it.
1723 self.sys_excepthook = old_excepthook
1729 self.sys_excepthook = old_excepthook
1724 outflag = 1 # happens in more places, so it's easier as default
1730 outflag = 1 # happens in more places, so it's easier as default
1725 try:
1731 try:
1726 try:
1732 try:
1727 # Embedded instances require separate global/local namespaces
1733 # Embedded instances require separate global/local namespaces
1728 # so they can see both the surrounding (local) namespace and
1734 # so they can see both the surrounding (local) namespace and
1729 # the module-level globals when called inside another function.
1735 # the module-level globals when called inside another function.
1730 if self.embedded:
1736 if self.embedded:
1731 exec code_obj in self.user_global_ns, self.user_ns
1737 exec code_obj in self.user_global_ns, self.user_ns
1732 # Normal (non-embedded) instances should only have a single
1738 # Normal (non-embedded) instances should only have a single
1733 # namespace for user code execution, otherwise functions won't
1739 # namespace for user code execution, otherwise functions won't
1734 # see interactive top-level globals.
1740 # see interactive top-level globals.
1735 else:
1741 else:
1736 exec code_obj in self.user_ns
1742 exec code_obj in self.user_ns
1737 finally:
1743 finally:
1738 # Reset our crash handler in place
1744 # Reset our crash handler in place
1739 sys.excepthook = old_excepthook
1745 sys.excepthook = old_excepthook
1740 except SystemExit:
1746 except SystemExit:
1741 self.resetbuffer()
1747 self.resetbuffer()
1742 self.showtraceback()
1748 self.showtraceback()
1743 warn("Type %exit or %quit to exit IPython "
1749 warn("Type %exit or %quit to exit IPython "
1744 "(%Exit or %Quit do so unconditionally).",level=1)
1750 "(%Exit or %Quit do so unconditionally).",level=1)
1745 except self.custom_exceptions:
1751 except self.custom_exceptions:
1746 etype,value,tb = sys.exc_info()
1752 etype,value,tb = sys.exc_info()
1747 self.CustomTB(etype,value,tb)
1753 self.CustomTB(etype,value,tb)
1748 except:
1754 except:
1749 self.showtraceback()
1755 self.showtraceback()
1750 else:
1756 else:
1751 outflag = 0
1757 outflag = 0
1752 if softspace(sys.stdout, 0):
1758 if softspace(sys.stdout, 0):
1753 print
1759 print
1754 # Flush out code object which has been run (and source)
1760 # Flush out code object which has been run (and source)
1755 self.code_to_run = None
1761 self.code_to_run = None
1756 return outflag
1762 return outflag
1757
1763
1758 def push(self, line):
1764 def push(self, line):
1759 """Push a line to the interpreter.
1765 """Push a line to the interpreter.
1760
1766
1761 The line should not have a trailing newline; it may have
1767 The line should not have a trailing newline; it may have
1762 internal newlines. The line is appended to a buffer and the
1768 internal newlines. The line is appended to a buffer and the
1763 interpreter's runsource() method is called with the
1769 interpreter's runsource() method is called with the
1764 concatenated contents of the buffer as source. If this
1770 concatenated contents of the buffer as source. If this
1765 indicates that the command was executed or invalid, the buffer
1771 indicates that the command was executed or invalid, the buffer
1766 is reset; otherwise, the command is incomplete, and the buffer
1772 is reset; otherwise, the command is incomplete, and the buffer
1767 is left as it was after the line was appended. The return
1773 is left as it was after the line was appended. The return
1768 value is 1 if more input is required, 0 if the line was dealt
1774 value is 1 if more input is required, 0 if the line was dealt
1769 with in some way (this is the same as runsource()).
1775 with in some way (this is the same as runsource()).
1770 """
1776 """
1771
1777
1772 # autoindent management should be done here, and not in the
1778 # autoindent management should be done here, and not in the
1773 # interactive loop, since that one is only seen by keyboard input. We
1779 # interactive loop, since that one is only seen by keyboard input. We
1774 # need this done correctly even for code run via runlines (which uses
1780 # need this done correctly even for code run via runlines (which uses
1775 # push).
1781 # push).
1776
1782
1777 #print 'push line: <%s>' % line # dbg
1783 #print 'push line: <%s>' % line # dbg
1778 for subline in line.splitlines():
1784 for subline in line.splitlines():
1779 self.autoindent_update(subline)
1785 self.autoindent_update(subline)
1780 self.buffer.append(line)
1786 self.buffer.append(line)
1781 more = self.runsource('\n'.join(self.buffer), self.filename)
1787 more = self.runsource('\n'.join(self.buffer), self.filename)
1782 if not more:
1788 if not more:
1783 self.resetbuffer()
1789 self.resetbuffer()
1784 return more
1790 return more
1785
1791
1786 def resetbuffer(self):
1792 def resetbuffer(self):
1787 """Reset the input buffer."""
1793 """Reset the input buffer."""
1788 self.buffer[:] = []
1794 self.buffer[:] = []
1789
1795
1790 def raw_input(self,prompt='',continue_prompt=False):
1796 def raw_input(self,prompt='',continue_prompt=False):
1791 """Write a prompt and read a line.
1797 """Write a prompt and read a line.
1792
1798
1793 The returned line does not include the trailing newline.
1799 The returned line does not include the trailing newline.
1794 When the user enters the EOF key sequence, EOFError is raised.
1800 When the user enters the EOF key sequence, EOFError is raised.
1795
1801
1796 Optional inputs:
1802 Optional inputs:
1797
1803
1798 - prompt(''): a string to be printed to prompt the user.
1804 - prompt(''): a string to be printed to prompt the user.
1799
1805
1800 - continue_prompt(False): whether this line is the first one or a
1806 - continue_prompt(False): whether this line is the first one or a
1801 continuation in a sequence of inputs.
1807 continuation in a sequence of inputs.
1802 """
1808 """
1803
1809
1804 try:
1810 line = raw_input_original(prompt)
1805 line = raw_input_original(prompt)
1806 except ValueError:
1807 # python 2.5 closes stdin on exit -> ValueError
1808 # xxx should we delete 'exit' and 'quit' from builtin?
1809 self.exit_now = True
1810 return ''
1811
1812
1811
1813 # Try to be reasonably smart about not re-indenting pasted input more
1812 # Try to be reasonably smart about not re-indenting pasted input more
1814 # than necessary. We do this by trimming out the auto-indent initial
1813 # than necessary. We do this by trimming out the auto-indent initial
1815 # spaces, if the user's actual input started itself with whitespace.
1814 # spaces, if the user's actual input started itself with whitespace.
1816 #debugx('self.buffer[-1]')
1815 #debugx('self.buffer[-1]')
1817
1816
1818 if self.autoindent:
1817 if self.autoindent:
1819 if num_ini_spaces(line) > self.indent_current_nsp:
1818 if num_ini_spaces(line) > self.indent_current_nsp:
1820 line = line[self.indent_current_nsp:]
1819 line = line[self.indent_current_nsp:]
1821 self.indent_current_nsp = 0
1820 self.indent_current_nsp = 0
1822
1821
1823 # store the unfiltered input before the user has any chance to modify
1822 # store the unfiltered input before the user has any chance to modify
1824 # it.
1823 # it.
1825 if line.strip():
1824 if line.strip():
1826 if continue_prompt:
1825 if continue_prompt:
1827 self.input_hist_raw[-1] += '%s\n' % line
1826 self.input_hist_raw[-1] += '%s\n' % line
1828 if self.has_readline: # and some config option is set?
1827 if self.has_readline: # and some config option is set?
1829 try:
1828 try:
1830 histlen = self.readline.get_current_history_length()
1829 histlen = self.readline.get_current_history_length()
1831 newhist = self.input_hist_raw[-1].rstrip()
1830 newhist = self.input_hist_raw[-1].rstrip()
1832 self.readline.remove_history_item(histlen-1)
1831 self.readline.remove_history_item(histlen-1)
1833 self.readline.replace_history_item(histlen-2,newhist)
1832 self.readline.replace_history_item(histlen-2,newhist)
1834 except AttributeError:
1833 except AttributeError:
1835 pass # re{move,place}_history_item are new in 2.4.
1834 pass # re{move,place}_history_item are new in 2.4.
1836 else:
1835 else:
1837 self.input_hist_raw.append('%s\n' % line)
1836 self.input_hist_raw.append('%s\n' % line)
1838
1837
1839 try:
1838 try:
1840 lineout = self.prefilter(line,continue_prompt)
1839 lineout = self.prefilter(line,continue_prompt)
1841 except:
1840 except:
1842 # blanket except, in case a user-defined prefilter crashes, so it
1841 # blanket except, in case a user-defined prefilter crashes, so it
1843 # can't take all of ipython with it.
1842 # can't take all of ipython with it.
1844 self.showtraceback()
1843 self.showtraceback()
1845 return ''
1844 return ''
1846 else:
1845 else:
1847 return lineout
1846 return lineout
1848
1847
1849 def split_user_input(self,line):
1848 def split_user_input(self,line):
1850 """Split user input into pre-char, function part and rest."""
1849 """Split user input into pre-char, function part and rest."""
1851
1850
1852 lsplit = self.line_split.match(line)
1851 lsplit = self.line_split.match(line)
1853 if lsplit is None: # no regexp match returns None
1852 if lsplit is None: # no regexp match returns None
1854 try:
1853 try:
1855 iFun,theRest = line.split(None,1)
1854 iFun,theRest = line.split(None,1)
1856 except ValueError:
1855 except ValueError:
1857 iFun,theRest = line,''
1856 iFun,theRest = line,''
1858 pre = re.match('^(\s*)(.*)',line).groups()[0]
1857 pre = re.match('^(\s*)(.*)',line).groups()[0]
1859 else:
1858 else:
1860 pre,iFun,theRest = lsplit.groups()
1859 pre,iFun,theRest = lsplit.groups()
1861
1860
1862 #print 'line:<%s>' % line # dbg
1861 #print 'line:<%s>' % line # dbg
1863 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1862 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1864 return pre,iFun.strip(),theRest
1863 return pre,iFun.strip(),theRest
1865
1864
1866 def _prefilter(self, line, continue_prompt):
1865 def _prefilter(self, line, continue_prompt):
1867 """Calls different preprocessors, depending on the form of line."""
1866 """Calls different preprocessors, depending on the form of line."""
1868
1867
1869 # All handlers *must* return a value, even if it's blank ('').
1868 # All handlers *must* return a value, even if it's blank ('').
1870
1869
1871 # Lines are NOT logged here. Handlers should process the line as
1870 # Lines are NOT logged here. Handlers should process the line as
1872 # needed, update the cache AND log it (so that the input cache array
1871 # needed, update the cache AND log it (so that the input cache array
1873 # stays synced).
1872 # stays synced).
1874
1873
1875 # This function is _very_ delicate, and since it's also the one which
1874 # This function is _very_ delicate, and since it's also the one which
1876 # determines IPython's response to user input, it must be as efficient
1875 # determines IPython's response to user input, it must be as efficient
1877 # as possible. For this reason it has _many_ returns in it, trying
1876 # as possible. For this reason it has _many_ returns in it, trying
1878 # always to exit as quickly as it can figure out what it needs to do.
1877 # always to exit as quickly as it can figure out what it needs to do.
1879
1878
1880 # This function is the main responsible for maintaining IPython's
1879 # This function is the main responsible for maintaining IPython's
1881 # behavior respectful of Python's semantics. So be _very_ careful if
1880 # behavior respectful of Python's semantics. So be _very_ careful if
1882 # making changes to anything here.
1881 # making changes to anything here.
1883
1882
1884 #.....................................................................
1883 #.....................................................................
1885 # Code begins
1884 # Code begins
1886
1885
1887 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1886 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1888
1887
1889 # save the line away in case we crash, so the post-mortem handler can
1888 # save the line away in case we crash, so the post-mortem handler can
1890 # record it
1889 # record it
1891 self._last_input_line = line
1890 self._last_input_line = line
1892
1891
1893 #print '***line: <%s>' % line # dbg
1892 #print '***line: <%s>' % line # dbg
1894
1893
1895 # the input history needs to track even empty lines
1894 # the input history needs to track even empty lines
1896 stripped = line.strip()
1895 stripped = line.strip()
1897
1896
1898 if not stripped:
1897 if not stripped:
1899 if not continue_prompt:
1898 if not continue_prompt:
1900 self.outputcache.prompt_count -= 1
1899 self.outputcache.prompt_count -= 1
1901 return self.handle_normal(line,continue_prompt)
1900 return self.handle_normal(line,continue_prompt)
1902 #return self.handle_normal('',continue_prompt)
1901 #return self.handle_normal('',continue_prompt)
1903
1902
1904 # print '***cont',continue_prompt # dbg
1903 # print '***cont',continue_prompt # dbg
1905 # special handlers are only allowed for single line statements
1904 # special handlers are only allowed for single line statements
1906 if continue_prompt and not self.rc.multi_line_specials:
1905 if continue_prompt and not self.rc.multi_line_specials:
1907 return self.handle_normal(line,continue_prompt)
1906 return self.handle_normal(line,continue_prompt)
1908
1907
1909
1908
1910 # For the rest, we need the structure of the input
1909 # For the rest, we need the structure of the input
1911 pre,iFun,theRest = self.split_user_input(line)
1910 pre,iFun,theRest = self.split_user_input(line)
1912
1911
1913 # See whether any pre-existing handler can take care of it
1912 # See whether any pre-existing handler can take care of it
1914
1913
1915 rewritten = self.hooks.input_prefilter(stripped)
1914 rewritten = self.hooks.input_prefilter(stripped)
1916 if rewritten != stripped: # ok, some prefilter did something
1915 if rewritten != stripped: # ok, some prefilter did something
1917 rewritten = pre + rewritten # add indentation
1916 rewritten = pre + rewritten # add indentation
1918 return self.handle_normal(rewritten)
1917 return self.handle_normal(rewritten)
1919
1918
1920 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1919 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1921
1920
1922 # First check for explicit escapes in the last/first character
1921 # First check for explicit escapes in the last/first character
1923 handler = None
1922 handler = None
1924 if line[-1] == self.ESC_HELP:
1923 if line[-1] == self.ESC_HELP:
1925 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1924 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1926 if handler is None:
1925 if handler is None:
1927 # look at the first character of iFun, NOT of line, so we skip
1926 # look at the first character of iFun, NOT of line, so we skip
1928 # leading whitespace in multiline input
1927 # leading whitespace in multiline input
1929 handler = self.esc_handlers.get(iFun[0:1])
1928 handler = self.esc_handlers.get(iFun[0:1])
1930 if handler is not None:
1929 if handler is not None:
1931 return handler(line,continue_prompt,pre,iFun,theRest)
1930 return handler(line,continue_prompt,pre,iFun,theRest)
1932 # Emacs ipython-mode tags certain input lines
1931 # Emacs ipython-mode tags certain input lines
1933 if line.endswith('# PYTHON-MODE'):
1932 if line.endswith('# PYTHON-MODE'):
1934 return self.handle_emacs(line,continue_prompt)
1933 return self.handle_emacs(line,continue_prompt)
1935
1934
1936 # Next, check if we can automatically execute this thing
1935 # Next, check if we can automatically execute this thing
1937
1936
1938 # Allow ! in multi-line statements if multi_line_specials is on:
1937 # Allow ! in multi-line statements if multi_line_specials is on:
1939 if continue_prompt and self.rc.multi_line_specials and \
1938 if continue_prompt and self.rc.multi_line_specials and \
1940 iFun.startswith(self.ESC_SHELL):
1939 iFun.startswith(self.ESC_SHELL):
1941 return self.handle_shell_escape(line,continue_prompt,
1940 return self.handle_shell_escape(line,continue_prompt,
1942 pre=pre,iFun=iFun,
1941 pre=pre,iFun=iFun,
1943 theRest=theRest)
1942 theRest=theRest)
1944
1943
1945 # Let's try to find if the input line is a magic fn
1944 # Let's try to find if the input line is a magic fn
1946 oinfo = None
1945 oinfo = None
1947 if hasattr(self,'magic_'+iFun):
1946 if hasattr(self,'magic_'+iFun):
1948 # WARNING: _ofind uses getattr(), so it can consume generators and
1947 # WARNING: _ofind uses getattr(), so it can consume generators and
1949 # cause other side effects.
1948 # cause other side effects.
1950 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1949 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1951 if oinfo['ismagic']:
1950 if oinfo['ismagic']:
1952 # Be careful not to call magics when a variable assignment is
1951 # Be careful not to call magics when a variable assignment is
1953 # being made (ls='hi', for example)
1952 # being made (ls='hi', for example)
1954 if self.rc.automagic and \
1953 if self.rc.automagic and \
1955 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1954 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1956 (self.rc.multi_line_specials or not continue_prompt):
1955 (self.rc.multi_line_specials or not continue_prompt):
1957 return self.handle_magic(line,continue_prompt,
1956 return self.handle_magic(line,continue_prompt,
1958 pre,iFun,theRest)
1957 pre,iFun,theRest)
1959 else:
1958 else:
1960 return self.handle_normal(line,continue_prompt)
1959 return self.handle_normal(line,continue_prompt)
1961
1960
1962 # If the rest of the line begins with an (in)equality, assginment or
1961 # If the rest of the line begins with an (in)equality, assginment or
1963 # function call, we should not call _ofind but simply execute it.
1962 # function call, we should not call _ofind but simply execute it.
1964 # This avoids spurious geattr() accesses on objects upon assignment.
1963 # This avoids spurious geattr() accesses on objects upon assignment.
1965 #
1964 #
1966 # It also allows users to assign to either alias or magic names true
1965 # It also allows users to assign to either alias or magic names true
1967 # python variables (the magic/alias systems always take second seat to
1966 # python variables (the magic/alias systems always take second seat to
1968 # true python code).
1967 # true python code).
1969 if theRest and theRest[0] in '!=()':
1968 if theRest and theRest[0] in '!=()':
1970 return self.handle_normal(line,continue_prompt)
1969 return self.handle_normal(line,continue_prompt)
1971
1970
1972 if oinfo is None:
1971 if oinfo is None:
1973 # let's try to ensure that _oinfo is ONLY called when autocall is
1972 # let's try to ensure that _oinfo is ONLY called when autocall is
1974 # on. Since it has inevitable potential side effects, at least
1973 # on. Since it has inevitable potential side effects, at least
1975 # having autocall off should be a guarantee to the user that no
1974 # having autocall off should be a guarantee to the user that no
1976 # weird things will happen.
1975 # weird things will happen.
1977
1976
1978 if self.rc.autocall:
1977 if self.rc.autocall:
1979 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1978 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1980 else:
1979 else:
1981 # in this case, all that's left is either an alias or
1980 # in this case, all that's left is either an alias or
1982 # processing the line normally.
1981 # processing the line normally.
1983 if iFun in self.alias_table:
1982 if iFun in self.alias_table:
1984 # if autocall is off, by not running _ofind we won't know
1983 # if autocall is off, by not running _ofind we won't know
1985 # whether the given name may also exist in one of the
1984 # whether the given name may also exist in one of the
1986 # user's namespace. At this point, it's best to do a
1985 # user's namespace. At this point, it's best to do a
1987 # quick check just to be sure that we don't let aliases
1986 # quick check just to be sure that we don't let aliases
1988 # shadow variables.
1987 # shadow variables.
1989 head = iFun.split('.',1)[0]
1988 head = iFun.split('.',1)[0]
1990 if head in self.user_ns or head in self.internal_ns \
1989 if head in self.user_ns or head in self.internal_ns \
1991 or head in __builtin__.__dict__:
1990 or head in __builtin__.__dict__:
1992 return self.handle_normal(line,continue_prompt)
1991 return self.handle_normal(line,continue_prompt)
1993 else:
1992 else:
1994 return self.handle_alias(line,continue_prompt,
1993 return self.handle_alias(line,continue_prompt,
1995 pre,iFun,theRest)
1994 pre,iFun,theRest)
1996
1995
1997 else:
1996 else:
1998 return self.handle_normal(line,continue_prompt)
1997 return self.handle_normal(line,continue_prompt)
1999
1998
2000 if not oinfo['found']:
1999 if not oinfo['found']:
2001 return self.handle_normal(line,continue_prompt)
2000 return self.handle_normal(line,continue_prompt)
2002 else:
2001 else:
2003 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2002 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2004 if oinfo['isalias']:
2003 if oinfo['isalias']:
2005 return self.handle_alias(line,continue_prompt,
2004 return self.handle_alias(line,continue_prompt,
2006 pre,iFun,theRest)
2005 pre,iFun,theRest)
2007
2006
2008 if (self.rc.autocall
2007 if (self.rc.autocall
2009 and
2008 and
2010 (
2009 (
2011 #only consider exclusion re if not "," or ";" autoquoting
2010 #only consider exclusion re if not "," or ";" autoquoting
2012 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
2011 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
2013 or pre == self.ESC_PAREN) or
2012 or pre == self.ESC_PAREN) or
2014 (not self.re_exclude_auto.match(theRest)))
2013 (not self.re_exclude_auto.match(theRest)))
2015 and
2014 and
2016 self.re_fun_name.match(iFun) and
2015 self.re_fun_name.match(iFun) and
2017 callable(oinfo['obj'])) :
2016 callable(oinfo['obj'])) :
2018 #print 'going auto' # dbg
2017 #print 'going auto' # dbg
2019 return self.handle_auto(line,continue_prompt,
2018 return self.handle_auto(line,continue_prompt,
2020 pre,iFun,theRest,oinfo['obj'])
2019 pre,iFun,theRest,oinfo['obj'])
2021 else:
2020 else:
2022 #print 'was callable?', callable(oinfo['obj']) # dbg
2021 #print 'was callable?', callable(oinfo['obj']) # dbg
2023 return self.handle_normal(line,continue_prompt)
2022 return self.handle_normal(line,continue_prompt)
2024
2023
2025 # If we get here, we have a normal Python line. Log and return.
2024 # If we get here, we have a normal Python line. Log and return.
2026 return self.handle_normal(line,continue_prompt)
2025 return self.handle_normal(line,continue_prompt)
2027
2026
2028 def _prefilter_dumb(self, line, continue_prompt):
2027 def _prefilter_dumb(self, line, continue_prompt):
2029 """simple prefilter function, for debugging"""
2028 """simple prefilter function, for debugging"""
2030 return self.handle_normal(line,continue_prompt)
2029 return self.handle_normal(line,continue_prompt)
2031
2030
2032
2031
2033 def multiline_prefilter(self, line, continue_prompt):
2032 def multiline_prefilter(self, line, continue_prompt):
2034 """ Run _prefilter for each line of input
2033 """ Run _prefilter for each line of input
2035
2034
2036 Covers cases where there are multiple lines in the user entry,
2035 Covers cases where there are multiple lines in the user entry,
2037 which is the case when the user goes back to a multiline history
2036 which is the case when the user goes back to a multiline history
2038 entry and presses enter.
2037 entry and presses enter.
2039
2038
2040 """
2039 """
2041 out = []
2040 out = []
2042 for l in line.rstrip('\n').split('\n'):
2041 for l in line.rstrip('\n').split('\n'):
2043 out.append(self._prefilter(l, continue_prompt))
2042 out.append(self._prefilter(l, continue_prompt))
2044 return '\n'.join(out)
2043 return '\n'.join(out)
2045
2044
2046 # Set the default prefilter() function (this can be user-overridden)
2045 # Set the default prefilter() function (this can be user-overridden)
2047 prefilter = multiline_prefilter
2046 prefilter = multiline_prefilter
2048
2047
2049 def handle_normal(self,line,continue_prompt=None,
2048 def handle_normal(self,line,continue_prompt=None,
2050 pre=None,iFun=None,theRest=None):
2049 pre=None,iFun=None,theRest=None):
2051 """Handle normal input lines. Use as a template for handlers."""
2050 """Handle normal input lines. Use as a template for handlers."""
2052
2051
2053 # With autoindent on, we need some way to exit the input loop, and I
2052 # With autoindent on, we need some way to exit the input loop, and I
2054 # don't want to force the user to have to backspace all the way to
2053 # don't want to force the user to have to backspace all the way to
2055 # clear the line. The rule will be in this case, that either two
2054 # clear the line. The rule will be in this case, that either two
2056 # lines of pure whitespace in a row, or a line of pure whitespace but
2055 # lines of pure whitespace in a row, or a line of pure whitespace but
2057 # of a size different to the indent level, will exit the input loop.
2056 # of a size different to the indent level, will exit the input loop.
2058
2057
2059 if (continue_prompt and self.autoindent and line.isspace() and
2058 if (continue_prompt and self.autoindent and line.isspace() and
2060 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2059 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2061 (self.buffer[-1]).isspace() )):
2060 (self.buffer[-1]).isspace() )):
2062 line = ''
2061 line = ''
2063
2062
2064 self.log(line,line,continue_prompt)
2063 self.log(line,line,continue_prompt)
2065 return line
2064 return line
2066
2065
2067 def handle_alias(self,line,continue_prompt=None,
2066 def handle_alias(self,line,continue_prompt=None,
2068 pre=None,iFun=None,theRest=None):
2067 pre=None,iFun=None,theRest=None):
2069 """Handle alias input lines. """
2068 """Handle alias input lines. """
2070
2069
2071 # pre is needed, because it carries the leading whitespace. Otherwise
2070 # pre is needed, because it carries the leading whitespace. Otherwise
2072 # aliases won't work in indented sections.
2071 # aliases won't work in indented sections.
2073 transformed = self.transform_alias(iFun, theRest)
2072 transformed = self.transform_alias(iFun, theRest)
2074 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2073 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2075 self.log(line,line_out,continue_prompt)
2074 self.log(line,line_out,continue_prompt)
2076 #print 'line out:',line_out # dbg
2075 #print 'line out:',line_out # dbg
2077 return line_out
2076 return line_out
2078
2077
2079 def handle_shell_escape(self, line, continue_prompt=None,
2078 def handle_shell_escape(self, line, continue_prompt=None,
2080 pre=None,iFun=None,theRest=None):
2079 pre=None,iFun=None,theRest=None):
2081 """Execute the line in a shell, empty return value"""
2080 """Execute the line in a shell, empty return value"""
2082
2081
2083 #print 'line in :', `line` # dbg
2082 #print 'line in :', `line` # dbg
2084 # Example of a special handler. Others follow a similar pattern.
2083 # Example of a special handler. Others follow a similar pattern.
2085 if line.lstrip().startswith('!!'):
2084 if line.lstrip().startswith('!!'):
2086 # rewrite iFun/theRest to properly hold the call to %sx and
2085 # rewrite iFun/theRest to properly hold the call to %sx and
2087 # the actual command to be executed, so handle_magic can work
2086 # the actual command to be executed, so handle_magic can work
2088 # correctly
2087 # correctly
2089 theRest = '%s %s' % (iFun[2:],theRest)
2088 theRest = '%s %s' % (iFun[2:],theRest)
2090 iFun = 'sx'
2089 iFun = 'sx'
2091 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2090 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2092 line.lstrip()[2:]),
2091 line.lstrip()[2:]),
2093 continue_prompt,pre,iFun,theRest)
2092 continue_prompt,pre,iFun,theRest)
2094 else:
2093 else:
2095 cmd=line.lstrip().lstrip('!')
2094 cmd=line.lstrip().lstrip('!')
2096 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2095 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2097 # update cache/log and return
2096 # update cache/log and return
2098 self.log(line,line_out,continue_prompt)
2097 self.log(line,line_out,continue_prompt)
2099 return line_out
2098 return line_out
2100
2099
2101 def handle_magic(self, line, continue_prompt=None,
2100 def handle_magic(self, line, continue_prompt=None,
2102 pre=None,iFun=None,theRest=None):
2101 pre=None,iFun=None,theRest=None):
2103 """Execute magic functions."""
2102 """Execute magic functions."""
2104
2103
2105
2104
2106 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2105 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2107 self.log(line,cmd,continue_prompt)
2106 self.log(line,cmd,continue_prompt)
2108 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2107 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2109 return cmd
2108 return cmd
2110
2109
2111 def handle_auto(self, line, continue_prompt=None,
2110 def handle_auto(self, line, continue_prompt=None,
2112 pre=None,iFun=None,theRest=None,obj=None):
2111 pre=None,iFun=None,theRest=None,obj=None):
2113 """Hande lines which can be auto-executed, quoting if requested."""
2112 """Hande lines which can be auto-executed, quoting if requested."""
2114
2113
2115 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2114 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2116
2115
2117 # This should only be active for single-line input!
2116 # This should only be active for single-line input!
2118 if continue_prompt:
2117 if continue_prompt:
2119 self.log(line,line,continue_prompt)
2118 self.log(line,line,continue_prompt)
2120 return line
2119 return line
2121
2120
2122 auto_rewrite = True
2121 auto_rewrite = True
2123
2122
2124 if pre == self.ESC_QUOTE:
2123 if pre == self.ESC_QUOTE:
2125 # Auto-quote splitting on whitespace
2124 # Auto-quote splitting on whitespace
2126 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2125 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2127 elif pre == self.ESC_QUOTE2:
2126 elif pre == self.ESC_QUOTE2:
2128 # Auto-quote whole string
2127 # Auto-quote whole string
2129 newcmd = '%s("%s")' % (iFun,theRest)
2128 newcmd = '%s("%s")' % (iFun,theRest)
2130 elif pre == self.ESC_PAREN:
2129 elif pre == self.ESC_PAREN:
2131 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2130 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2132 else:
2131 else:
2133 # Auto-paren.
2132 # Auto-paren.
2134 # We only apply it to argument-less calls if the autocall
2133 # We only apply it to argument-less calls if the autocall
2135 # parameter is set to 2. We only need to check that autocall is <
2134 # parameter is set to 2. We only need to check that autocall is <
2136 # 2, since this function isn't called unless it's at least 1.
2135 # 2, since this function isn't called unless it's at least 1.
2137 if not theRest and (self.rc.autocall < 2):
2136 if not theRest and (self.rc.autocall < 2):
2138 newcmd = '%s %s' % (iFun,theRest)
2137 newcmd = '%s %s' % (iFun,theRest)
2139 auto_rewrite = False
2138 auto_rewrite = False
2140 else:
2139 else:
2141 if theRest.startswith('['):
2140 if theRest.startswith('['):
2142 if hasattr(obj,'__getitem__'):
2141 if hasattr(obj,'__getitem__'):
2143 # Don't autocall in this case: item access for an object
2142 # Don't autocall in this case: item access for an object
2144 # which is BOTH callable and implements __getitem__.
2143 # which is BOTH callable and implements __getitem__.
2145 newcmd = '%s %s' % (iFun,theRest)
2144 newcmd = '%s %s' % (iFun,theRest)
2146 auto_rewrite = False
2145 auto_rewrite = False
2147 else:
2146 else:
2148 # if the object doesn't support [] access, go ahead and
2147 # if the object doesn't support [] access, go ahead and
2149 # autocall
2148 # autocall
2150 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2149 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2151 elif theRest.endswith(';'):
2150 elif theRest.endswith(';'):
2152 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2151 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2153 else:
2152 else:
2154 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2153 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2155
2154
2156 if auto_rewrite:
2155 if auto_rewrite:
2157 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2156 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2158 # log what is now valid Python, not the actual user input (without the
2157 # log what is now valid Python, not the actual user input (without the
2159 # final newline)
2158 # final newline)
2160 self.log(line,newcmd,continue_prompt)
2159 self.log(line,newcmd,continue_prompt)
2161 return newcmd
2160 return newcmd
2162
2161
2163 def handle_help(self, line, continue_prompt=None,
2162 def handle_help(self, line, continue_prompt=None,
2164 pre=None,iFun=None,theRest=None):
2163 pre=None,iFun=None,theRest=None):
2165 """Try to get some help for the object.
2164 """Try to get some help for the object.
2166
2165
2167 obj? or ?obj -> basic information.
2166 obj? or ?obj -> basic information.
2168 obj?? or ??obj -> more details.
2167 obj?? or ??obj -> more details.
2169 """
2168 """
2170
2169
2171 # We need to make sure that we don't process lines which would be
2170 # We need to make sure that we don't process lines which would be
2172 # otherwise valid python, such as "x=1 # what?"
2171 # otherwise valid python, such as "x=1 # what?"
2173 try:
2172 try:
2174 codeop.compile_command(line)
2173 codeop.compile_command(line)
2175 except SyntaxError:
2174 except SyntaxError:
2176 # We should only handle as help stuff which is NOT valid syntax
2175 # We should only handle as help stuff which is NOT valid syntax
2177 if line[0]==self.ESC_HELP:
2176 if line[0]==self.ESC_HELP:
2178 line = line[1:]
2177 line = line[1:]
2179 elif line[-1]==self.ESC_HELP:
2178 elif line[-1]==self.ESC_HELP:
2180 line = line[:-1]
2179 line = line[:-1]
2181 self.log(line,'#?'+line,continue_prompt)
2180 self.log(line,'#?'+line,continue_prompt)
2182 if line:
2181 if line:
2183 self.magic_pinfo(line)
2182 self.magic_pinfo(line)
2184 else:
2183 else:
2185 page(self.usage,screen_lines=self.rc.screen_length)
2184 page(self.usage,screen_lines=self.rc.screen_length)
2186 return '' # Empty string is needed here!
2185 return '' # Empty string is needed here!
2187 except:
2186 except:
2188 # Pass any other exceptions through to the normal handler
2187 # Pass any other exceptions through to the normal handler
2189 return self.handle_normal(line,continue_prompt)
2188 return self.handle_normal(line,continue_prompt)
2190 else:
2189 else:
2191 # If the code compiles ok, we should handle it normally
2190 # If the code compiles ok, we should handle it normally
2192 return self.handle_normal(line,continue_prompt)
2191 return self.handle_normal(line,continue_prompt)
2193
2192
2194 def getapi(self):
2193 def getapi(self):
2195 """ Get an IPApi object for this shell instance
2194 """ Get an IPApi object for this shell instance
2196
2195
2197 Getting an IPApi object is always preferable to accessing the shell
2196 Getting an IPApi object is always preferable to accessing the shell
2198 directly, but this holds true especially for extensions.
2197 directly, but this holds true especially for extensions.
2199
2198
2200 It should always be possible to implement an extension with IPApi
2199 It should always be possible to implement an extension with IPApi
2201 alone. If not, contact maintainer to request an addition.
2200 alone. If not, contact maintainer to request an addition.
2202
2201
2203 """
2202 """
2204 return self.api
2203 return self.api
2205
2204
2206 def handle_emacs(self,line,continue_prompt=None,
2205 def handle_emacs(self,line,continue_prompt=None,
2207 pre=None,iFun=None,theRest=None):
2206 pre=None,iFun=None,theRest=None):
2208 """Handle input lines marked by python-mode."""
2207 """Handle input lines marked by python-mode."""
2209
2208
2210 # Currently, nothing is done. Later more functionality can be added
2209 # Currently, nothing is done. Later more functionality can be added
2211 # here if needed.
2210 # here if needed.
2212
2211
2213 # The input cache shouldn't be updated
2212 # The input cache shouldn't be updated
2214
2213
2215 return line
2214 return line
2216
2215
2217 def mktempfile(self,data=None):
2216 def mktempfile(self,data=None):
2218 """Make a new tempfile and return its filename.
2217 """Make a new tempfile and return its filename.
2219
2218
2220 This makes a call to tempfile.mktemp, but it registers the created
2219 This makes a call to tempfile.mktemp, but it registers the created
2221 filename internally so ipython cleans it up at exit time.
2220 filename internally so ipython cleans it up at exit time.
2222
2221
2223 Optional inputs:
2222 Optional inputs:
2224
2223
2225 - data(None): if data is given, it gets written out to the temp file
2224 - data(None): if data is given, it gets written out to the temp file
2226 immediately, and the file is closed again."""
2225 immediately, and the file is closed again."""
2227
2226
2228 filename = tempfile.mktemp('.py','ipython_edit_')
2227 filename = tempfile.mktemp('.py','ipython_edit_')
2229 self.tempfiles.append(filename)
2228 self.tempfiles.append(filename)
2230
2229
2231 if data:
2230 if data:
2232 tmp_file = open(filename,'w')
2231 tmp_file = open(filename,'w')
2233 tmp_file.write(data)
2232 tmp_file.write(data)
2234 tmp_file.close()
2233 tmp_file.close()
2235 return filename
2234 return filename
2236
2235
2237 def write(self,data):
2236 def write(self,data):
2238 """Write a string to the default output"""
2237 """Write a string to the default output"""
2239 Term.cout.write(data)
2238 Term.cout.write(data)
2240
2239
2241 def write_err(self,data):
2240 def write_err(self,data):
2242 """Write a string to the default error output"""
2241 """Write a string to the default error output"""
2243 Term.cerr.write(data)
2242 Term.cerr.write(data)
2244
2243
2245 def exit(self):
2244 def exit(self):
2246 """Handle interactive exit.
2245 """Handle interactive exit.
2247
2246
2248 This method sets the exit_now attribute."""
2247 This method sets the exit_now attribute."""
2249
2248
2250 if self.rc.confirm_exit:
2249 if self.rc.confirm_exit:
2251 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2250 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2252 self.exit_now = True
2251 self.exit_now = True
2253 else:
2252 else:
2254 self.exit_now = True
2253 self.exit_now = True
2255 return self.exit_now
2256
2254
2257 def safe_execfile(self,fname,*where,**kw):
2255 def safe_execfile(self,fname,*where,**kw):
2258 fname = os.path.expanduser(fname)
2256 fname = os.path.expanduser(fname)
2259
2257
2260 # find things also in current directory
2258 # find things also in current directory
2261 dname = os.path.dirname(fname)
2259 dname = os.path.dirname(fname)
2262 if not sys.path.count(dname):
2260 if not sys.path.count(dname):
2263 sys.path.append(dname)
2261 sys.path.append(dname)
2264
2262
2265 try:
2263 try:
2266 xfile = open(fname)
2264 xfile = open(fname)
2267 except:
2265 except:
2268 print >> Term.cerr, \
2266 print >> Term.cerr, \
2269 'Could not open file <%s> for safe execution.' % fname
2267 'Could not open file <%s> for safe execution.' % fname
2270 return None
2268 return None
2271
2269
2272 kw.setdefault('islog',0)
2270 kw.setdefault('islog',0)
2273 kw.setdefault('quiet',1)
2271 kw.setdefault('quiet',1)
2274 kw.setdefault('exit_ignore',0)
2272 kw.setdefault('exit_ignore',0)
2275 first = xfile.readline()
2273 first = xfile.readline()
2276 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2274 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2277 xfile.close()
2275 xfile.close()
2278 # line by line execution
2276 # line by line execution
2279 if first.startswith(loghead) or kw['islog']:
2277 if first.startswith(loghead) or kw['islog']:
2280 print 'Loading log file <%s> one line at a time...' % fname
2278 print 'Loading log file <%s> one line at a time...' % fname
2281 if kw['quiet']:
2279 if kw['quiet']:
2282 stdout_save = sys.stdout
2280 stdout_save = sys.stdout
2283 sys.stdout = StringIO.StringIO()
2281 sys.stdout = StringIO.StringIO()
2284 try:
2282 try:
2285 globs,locs = where[0:2]
2283 globs,locs = where[0:2]
2286 except:
2284 except:
2287 try:
2285 try:
2288 globs = locs = where[0]
2286 globs = locs = where[0]
2289 except:
2287 except:
2290 globs = locs = globals()
2288 globs = locs = globals()
2291 badblocks = []
2289 badblocks = []
2292
2290
2293 # we also need to identify indented blocks of code when replaying
2291 # we also need to identify indented blocks of code when replaying
2294 # logs and put them together before passing them to an exec
2292 # logs and put them together before passing them to an exec
2295 # statement. This takes a bit of regexp and look-ahead work in the
2293 # statement. This takes a bit of regexp and look-ahead work in the
2296 # file. It's easiest if we swallow the whole thing in memory
2294 # file. It's easiest if we swallow the whole thing in memory
2297 # first, and manually walk through the lines list moving the
2295 # first, and manually walk through the lines list moving the
2298 # counter ourselves.
2296 # counter ourselves.
2299 indent_re = re.compile('\s+\S')
2297 indent_re = re.compile('\s+\S')
2300 xfile = open(fname)
2298 xfile = open(fname)
2301 filelines = xfile.readlines()
2299 filelines = xfile.readlines()
2302 xfile.close()
2300 xfile.close()
2303 nlines = len(filelines)
2301 nlines = len(filelines)
2304 lnum = 0
2302 lnum = 0
2305 while lnum < nlines:
2303 while lnum < nlines:
2306 line = filelines[lnum]
2304 line = filelines[lnum]
2307 lnum += 1
2305 lnum += 1
2308 # don't re-insert logger status info into cache
2306 # don't re-insert logger status info into cache
2309 if line.startswith('#log#'):
2307 if line.startswith('#log#'):
2310 continue
2308 continue
2311 else:
2309 else:
2312 # build a block of code (maybe a single line) for execution
2310 # build a block of code (maybe a single line) for execution
2313 block = line
2311 block = line
2314 try:
2312 try:
2315 next = filelines[lnum] # lnum has already incremented
2313 next = filelines[lnum] # lnum has already incremented
2316 except:
2314 except:
2317 next = None
2315 next = None
2318 while next and indent_re.match(next):
2316 while next and indent_re.match(next):
2319 block += next
2317 block += next
2320 lnum += 1
2318 lnum += 1
2321 try:
2319 try:
2322 next = filelines[lnum]
2320 next = filelines[lnum]
2323 except:
2321 except:
2324 next = None
2322 next = None
2325 # now execute the block of one or more lines
2323 # now execute the block of one or more lines
2326 try:
2324 try:
2327 exec block in globs,locs
2325 exec block in globs,locs
2328 except SystemExit:
2326 except SystemExit:
2329 pass
2327 pass
2330 except:
2328 except:
2331 badblocks.append(block.rstrip())
2329 badblocks.append(block.rstrip())
2332 if kw['quiet']: # restore stdout
2330 if kw['quiet']: # restore stdout
2333 sys.stdout.close()
2331 sys.stdout.close()
2334 sys.stdout = stdout_save
2332 sys.stdout = stdout_save
2335 print 'Finished replaying log file <%s>' % fname
2333 print 'Finished replaying log file <%s>' % fname
2336 if badblocks:
2334 if badblocks:
2337 print >> sys.stderr, ('\nThe following lines/blocks in file '
2335 print >> sys.stderr, ('\nThe following lines/blocks in file '
2338 '<%s> reported errors:' % fname)
2336 '<%s> reported errors:' % fname)
2339
2337
2340 for badline in badblocks:
2338 for badline in badblocks:
2341 print >> sys.stderr, badline
2339 print >> sys.stderr, badline
2342 else: # regular file execution
2340 else: # regular file execution
2343 try:
2341 try:
2344 execfile(fname,*where)
2342 execfile(fname,*where)
2345 except SyntaxError:
2343 except SyntaxError:
2346 self.showsyntaxerror()
2344 self.showsyntaxerror()
2347 warn('Failure executing file: <%s>' % fname)
2345 warn('Failure executing file: <%s>' % fname)
2348 except SystemExit,status:
2346 except SystemExit,status:
2349 if not kw['exit_ignore']:
2347 if not kw['exit_ignore']:
2350 self.showtraceback()
2348 self.showtraceback()
2351 warn('Failure executing file: <%s>' % fname)
2349 warn('Failure executing file: <%s>' % fname)
2352 except:
2350 except:
2353 self.showtraceback()
2351 self.showtraceback()
2354 warn('Failure executing file: <%s>' % fname)
2352 warn('Failure executing file: <%s>' % fname)
2355
2353
2356 #************************* end of file <iplib.py> *****************************
2354 #************************* end of file <iplib.py> *****************************
@@ -1,319 +1,297 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Module for interactively running scripts.
2 """Module for interactively running scripts.
3
3
4 This module implements classes for interactively running scripts written for
4 This module implements classes for interactively running scripts written for
5 any system with a prompt which can be matched by a regexp suitable for
5 any system with a prompt which can be matched by a regexp suitable for
6 pexpect. It can be used to run as if they had been typed up interactively, an
6 pexpect. It can be used to run as if they had been typed up interactively, an
7 arbitrary series of commands for the target system.
7 arbitrary series of commands for the target system.
8
8
9 The module includes classes ready for IPython (with the default prompts),
9 The module includes classes ready for IPython (with the default prompts),
10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
11 simply run the module as a script:
11 simply run the module as a script:
12
12
13 ./irunner.py --help
13 ./irunner.py --help
14
14
15
15
16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
17 contributed on the ipython-user list:
17 contributed on the ipython-user list:
18
18
19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
20
20
21
21
22 NOTES:
22 NOTES:
23
23
24 - This module requires pexpect, available in most linux distros, or which can
24 - This module requires pexpect, available in most linux distros, or which can
25 be downloaded from
25 be downloaded from
26
26
27 http://pexpect.sourceforge.net
27 http://pexpect.sourceforge.net
28
28
29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
30 limitations. This means that it will NOT work under native windows Python.
30 limitations. This means that it will NOT work under native windows Python.
31 """
31 """
32
32
33 # Stdlib imports
33 # Stdlib imports
34 import optparse
34 import optparse
35 import os
35 import os
36 import sys
36 import sys
37
37
38 # Third-party modules.
38 # Third-party modules.
39 import pexpect
39 import pexpect
40
40
41 # Global usage strings, to avoid indentation issues when typing it below.
41 # Global usage strings, to avoid indentation issues when typing it below.
42 USAGE = """
42 USAGE = """
43 Interactive script runner, type: %s
43 Interactive script runner, type: %s
44
44
45 runner [opts] script_name
45 runner [opts] script_name
46 """
46 """
47
47
48 # The generic runner class
48 # The generic runner class
49 class InteractiveRunner(object):
49 class InteractiveRunner(object):
50 """Class to run a sequence of commands through an interactive program."""
50 """Class to run a sequence of commands through an interactive program."""
51
51
52 def __init__(self,program,prompts,args=None):
52 def __init__(self,program,prompts,args=None):
53 """Construct a runner.
53 """Construct a runner.
54
54
55 Inputs:
55 Inputs:
56
56
57 - program: command to execute the given program.
57 - program: command to execute the given program.
58
58
59 - prompts: a list of patterns to match as valid prompts, in the
59 - prompts: a list of patterns to match as valid prompts, in the
60 format used by pexpect. This basically means that it can be either
60 format used by pexpect. This basically means that it can be either
61 a string (to be compiled as a regular expression) or a list of such
61 a string (to be compiled as a regular expression) or a list of such
62 (it must be a true list, as pexpect does type checks).
62 (it must be a true list, as pexpect does type checks).
63
63
64 If more than one prompt is given, the first is treated as the main
64 If more than one prompt is given, the first is treated as the main
65 program prompt and the others as 'continuation' prompts, like
65 program prompt and the others as 'continuation' prompts, like
66 python's. This means that blank lines in the input source are
66 python's. This means that blank lines in the input source are
67 ommitted when the first prompt is matched, but are NOT ommitted when
67 ommitted when the first prompt is matched, but are NOT ommitted when
68 the continuation one matches, since this is how python signals the
68 the continuation one matches, since this is how python signals the
69 end of multiline input interactively.
69 end of multiline input interactively.
70
70
71 Optional inputs:
71 Optional inputs:
72
72
73 - args(None): optional list of strings to pass as arguments to the
73 - args(None): optional list of strings to pass as arguments to the
74 child program.
74 child program.
75
75
76 Public members not parameterized in the constructor:
76 Public members not parameterized in the constructor:
77
77
78 - delaybeforesend(0): Newer versions of pexpect have a delay before
78 - delaybeforesend(0): Newer versions of pexpect have a delay before
79 sending each new input. For our purposes here, it's typically best
79 sending each new input. For our purposes here, it's typically best
80 to just set this to zero, but if you encounter reliability problems
80 to just set this to zero, but if you encounter reliability problems
81 or want an interactive run to pause briefly at each prompt, just
81 or want an interactive run to pause briefly at each prompt, just
82 increase this value (it is measured in seconds). Note that this
82 increase this value (it is measured in seconds). Note that this
83 variable is not honored at all by older versions of pexpect.
83 variable is not honored at all by older versions of pexpect.
84 """
84 """
85
85
86 self.program = program
86 self.program = program
87 self.prompts = prompts
87 self.prompts = prompts
88 if args is None: args = []
88 if args is None: args = []
89 self.args = args
89 self.args = args
90 # Other public members which we don't make as parameters, but which
90 # Other public members which we don't make as parameters, but which
91 # users may occasionally want to tweak
91 # users may occasionally want to tweak
92 self.delaybeforesend = 0
92 self.delaybeforesend = 0
93
93
94 def run_file(self,fname,interact=False):
94 def run_file(self,fname,interact=False):
95 """Run the given file interactively.
95 """Run the given file interactively.
96
96
97 Inputs:
97 Inputs:
98
98
99 -fname: name of the file to execute.
99 -fname: name of the file to execute.
100
100
101 See the run_source docstring for the meaning of the optional
101 See the run_source docstring for the meaning of the optional
102 arguments."""
102 arguments."""
103
103
104 fobj = open(fname,'r')
104 fobj = open(fname,'r')
105 try:
105 try:
106 self.run_source(fobj,interact)
106 self.run_source(fobj,interact)
107 finally:
107 finally:
108 fobj.close()
108 fobj.close()
109
109
110 def run_source(self,source,interact=False):
110 def run_source(self,source,interact=False):
111 """Run the given source code interactively.
111 """Run the given source code interactively.
112
112
113 Inputs:
113 Inputs:
114
114
115 - source: a string of code to be executed, or an open file object we
115 - source: a string of code to be executed, or an open file object we
116 can iterate over.
116 can iterate over.
117
117
118 Optional inputs:
118 Optional inputs:
119
119
120 - interact(False): if true, start to interact with the running
120 - interact(False): if true, start to interact with the running
121 program at the end of the script. Otherwise, just exit.
121 program at the end of the script. Otherwise, just exit.
122 """
122 """
123
123
124 # if the source is a string, chop it up in lines so we can iterate
124 # if the source is a string, chop it up in lines so we can iterate
125 # over it just as if it were an open file.
125 # over it just as if it were an open file.
126 if not isinstance(source,file):
126 if not isinstance(source,file):
127 source = source.splitlines(True)
127 source = source.splitlines(True)
128
128
129 # grab the true write method of stdout, in case anything later
129 # grab the true write method of stdout, in case anything later
130 # reassigns sys.stdout, so that we really are writing to the true
130 # reassigns sys.stdout, so that we really are writing to the true
131 # stdout and not to something else. We also normalize all strings we
131 # stdout and not to something else. We also normalize all strings we
132 # write to use the native OS line separators.
132 # write to use the native OS line separators.
133 linesep = os.linesep
133 linesep = os.linesep
134 stdwrite = sys.stdout.write
134 stdwrite = sys.stdout.write
135 write = lambda s: stdwrite(s.replace('\r\n',linesep))
135 write = lambda s: stdwrite(s.replace('\r\n',linesep))
136
136
137 c = pexpect.spawn(self.program,self.args,timeout=None)
137 c = pexpect.spawn(self.program,self.args,timeout=None)
138 c.delaybeforesend = self.delaybeforesend
138 c.delaybeforesend = self.delaybeforesend
139
139
140 prompts = c.compile_pattern_list(self.prompts)
140 prompts = c.compile_pattern_list(self.prompts)
141
141
142 prompt_idx = c.expect_list(prompts)
142 prompt_idx = c.expect_list(prompts)
143 # Flag whether the script ends normally or not, to know whether we can
143 # Flag whether the script ends normally or not, to know whether we can
144 # do anything further with the underlying process.
144 # do anything further with the underlying process.
145 end_normal = True
145 end_normal = True
146 for cmd in source:
146 for cmd in source:
147 # skip blank lines for all matches to the 'main' prompt, while the
147 # skip blank lines for all matches to the 'main' prompt, while the
148 # secondary prompts do not
148 # secondary prompts do not
149 if prompt_idx==0 and \
149 if prompt_idx==0 and \
150 (cmd.isspace() or cmd.lstrip().startswith('#')):
150 (cmd.isspace() or cmd.lstrip().startswith('#')):
151 print cmd,
151 print cmd,
152 continue
152 continue
153
153
154 write(c.after)
154 write(c.after)
155 c.send(cmd)
155 c.send(cmd)
156 try:
156 try:
157 prompt_idx = c.expect_list(prompts)
157 prompt_idx = c.expect_list(prompts)
158 except pexpect.EOF:
158 except pexpect.EOF:
159 # this will happen if the child dies unexpectedly
159 # this will happen if the child dies unexpectedly
160 write(c.before)
160 write(c.before)
161 end_normal = False
161 end_normal = False
162 break
162 break
163 write(c.before)
163 write(c.before)
164
164
165 if end_normal:
165 if end_normal:
166 if interact:
166 if interact:
167 c.send('\n')
167 c.send('\n')
168 print '<< Starting interactive mode >>',
168 print '<< Starting interactive mode >>',
169 try:
169 try:
170 c.interact()
170 c.interact()
171 except OSError:
171 except OSError:
172 # This is what fires when the child stops. Simply print a
172 # This is what fires when the child stops. Simply print a
173 # newline so the system prompt is aligned. The extra
173 # newline so the system prompt is aligned. The extra
174 # space is there to make sure it gets printed, otherwise
174 # space is there to make sure it gets printed, otherwise
175 # OS buffering sometimes just suppresses it.
175 # OS buffering sometimes just suppresses it.
176 write(' \n')
176 write(' \n')
177 sys.stdout.flush()
177 sys.stdout.flush()
178 else:
178 else:
179 c.close()
179 c.close()
180 else:
180 else:
181 if interact:
181 if interact:
182 e="Further interaction is not possible: child process is dead."
182 e="Further interaction is not possible: child process is dead."
183 print >> sys.stderr, e
183 print >> sys.stderr, e
184
184
185 def main(self,argv=None):
185 def main(self,argv=None):
186 """Run as a command-line script."""
186 """Run as a command-line script."""
187
187
188 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
188 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
189 newopt = parser.add_option
189 newopt = parser.add_option
190 newopt('-i','--interact',action='store_true',default=False,
190 newopt('-i','--interact',action='store_true',default=False,
191 help='Interact with the program after the script is run.')
191 help='Interact with the program after the script is run.')
192
192
193 opts,args = parser.parse_args(argv)
193 opts,args = parser.parse_args(argv)
194
194
195 if len(args) != 1:
195 if len(args) != 1:
196 print >> sys.stderr,"You must supply exactly one file to run."
196 print >> sys.stderr,"You must supply exactly one file to run."
197 sys.exit(1)
197 sys.exit(1)
198
198
199 self.run_file(args[0],opts.interact)
199 self.run_file(args[0],opts.interact)
200
200
201
201
202 # Specific runners for particular programs
202 # Specific runners for particular programs
203 class IPythonRunner(InteractiveRunner):
203 class IPythonRunner(InteractiveRunner):
204 """Interactive IPython runner.
204 """Interactive IPython runner.
205
205
206 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
206 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
207 avoid having to write a regexp that matches ANSI sequences, though pexpect
207 avoid having to write a regexp that matches ANSI sequences, though pexpect
208 does support them. If anyone contributes patches for ANSI color support,
208 does support them. If anyone contributes patches for ANSI color support,
209 they will be welcome.
209 they will be welcome.
210
210
211 It also sets the prompts manually, since the prompt regexps for
211 It also sets the prompts manually, since the prompt regexps for
212 pexpect need to be matched to the actual prompts, so user-customized
212 pexpect need to be matched to the actual prompts, so user-customized
213 prompts would break this.
213 prompts would break this.
214 """
214 """
215
215
216 def __init__(self,program = 'ipython',args=None):
216 def __init__(self,program = 'ipython',args=None):
217 """New runner, optionally passing the ipython command to use."""
217 """New runner, optionally passing the ipython command to use."""
218
218
219 args0 = ['-colors','NoColor',
219 args0 = ['-colors','NoColor',
220 '-pi1','In [\\#]: ',
220 '-pi1','In [\\#]: ',
221 '-pi2',' .\\D.: ']
221 '-pi2',' .\\D.: ']
222 if args is None: args = args0
222 if args is None: args = args0
223 else: args = args0 + args
223 else: args = args0 + args
224 prompts = [r'In \[\d+\]: ',r' \.*: ']
224 prompts = [r'In \[\d+\]: ',r' \.*: ']
225 InteractiveRunner.__init__(self,program,prompts,args)
225 InteractiveRunner.__init__(self,program,prompts,args)
226
226
227
227
228 class PythonRunner(InteractiveRunner):
228 class PythonRunner(InteractiveRunner):
229 """Interactive Python runner."""
229 """Interactive Python runner."""
230
230
231 def __init__(self,program='python',args=None):
231 def __init__(self,program='python',args=None):
232 """New runner, optionally passing the python command to use."""
232 """New runner, optionally passing the python command to use."""
233
233
234 prompts = [r'>>> ',r'\.\.\. ']
234 prompts = [r'>>> ',r'\.\.\. ']
235 InteractiveRunner.__init__(self,program,prompts,args)
235 InteractiveRunner.__init__(self,program,prompts,args)
236
236
237
237
238 class DocTestRunner(PythonRunner):
239 """A python runner customized for doctest usage."""
240
241 def run_source(self,source,interact=False):
242 """Run the given source code interactively.
243
244 See the parent docstring for details.
245 """
246
247 # if the source is a string, chop it up in lines so we can iterate
248 # over it just as if it were an open file.
249 if not isinstance(source,file):
250 source = source.splitlines(True)
251
252
253 for line in source:
254 pass
255 # finish by calling the parent run_source method
256 super(DocTestRunner,self).run_source(dsource,interact)
257
258
259
260 class SAGERunner(InteractiveRunner):
238 class SAGERunner(InteractiveRunner):
261 """Interactive SAGE runner.
239 """Interactive SAGE runner.
262
240
263 WARNING: this runner only works if you manually configure your SAGE copy
241 WARNING: this runner only works if you manually configure your SAGE copy
264 to use 'colors NoColor' in the ipythonrc config file, since currently the
242 to use 'colors NoColor' in the ipythonrc config file, since currently the
265 prompt matching regexp does not identify color sequences."""
243 prompt matching regexp does not identify color sequences."""
266
244
267 def __init__(self,program='sage',args=None):
245 def __init__(self,program='sage',args=None):
268 """New runner, optionally passing the sage command to use."""
246 """New runner, optionally passing the sage command to use."""
269
247
270 prompts = ['sage: ',r'\s*\.\.\. ']
248 prompts = ['sage: ',r'\s*\.\.\. ']
271 InteractiveRunner.__init__(self,program,prompts,args)
249 InteractiveRunner.__init__(self,program,prompts,args)
272
250
273 # Global usage string, to avoid indentation issues if typed in a function def.
251 # Global usage string, to avoid indentation issues if typed in a function def.
274 MAIN_USAGE = """
252 MAIN_USAGE = """
275 %prog [options] file_to_run
253 %prog [options] file_to_run
276
254
277 This is an interface to the various interactive runners available in this
255 This is an interface to the various interactive runners available in this
278 module. If you want to pass specific options to one of the runners, you need
256 module. If you want to pass specific options to one of the runners, you need
279 to first terminate the main options with a '--', and then provide the runner's
257 to first terminate the main options with a '--', and then provide the runner's
280 options. For example:
258 options. For example:
281
259
282 irunner.py --python -- --help
260 irunner.py --python -- --help
283
261
284 will pass --help to the python runner. Similarly,
262 will pass --help to the python runner. Similarly,
285
263
286 irunner.py --ipython -- --interact script.ipy
264 irunner.py --ipython -- --interact script.ipy
287
265
288 will run the script.ipy file under the IPython runner, and then will start to
266 will run the script.ipy file under the IPython runner, and then will start to
289 interact with IPython at the end of the script (instead of exiting).
267 interact with IPython at the end of the script (instead of exiting).
290
268
291 The already implemented runners are listed below; adding one for a new program
269 The already implemented runners are listed below; adding one for a new program
292 is a trivial task, see the source for examples.
270 is a trivial task, see the source for examples.
293
271
294 WARNING: the SAGE runner only works if you manually configure your SAGE copy
272 WARNING: the SAGE runner only works if you manually configure your SAGE copy
295 to use 'colors NoColor' in the ipythonrc config file, since currently the
273 to use 'colors NoColor' in the ipythonrc config file, since currently the
296 prompt matching regexp does not identify color sequences.
274 prompt matching regexp does not identify color sequences.
297 """
275 """
298
276
299 def main():
277 def main():
300 """Run as a command-line script."""
278 """Run as a command-line script."""
301
279
302 parser = optparse.OptionParser(usage=MAIN_USAGE)
280 parser = optparse.OptionParser(usage=MAIN_USAGE)
303 newopt = parser.add_option
281 newopt = parser.add_option
304 parser.set_defaults(mode='ipython')
282 parser.set_defaults(mode='ipython')
305 newopt('--ipython',action='store_const',dest='mode',const='ipython',
283 newopt('--ipython',action='store_const',dest='mode',const='ipython',
306 help='IPython interactive runner (default).')
284 help='IPython interactive runner (default).')
307 newopt('--python',action='store_const',dest='mode',const='python',
285 newopt('--python',action='store_const',dest='mode',const='python',
308 help='Python interactive runner.')
286 help='Python interactive runner.')
309 newopt('--sage',action='store_const',dest='mode',const='sage',
287 newopt('--sage',action='store_const',dest='mode',const='sage',
310 help='SAGE interactive runner.')
288 help='SAGE interactive runner.')
311
289
312 opts,args = parser.parse_args()
290 opts,args = parser.parse_args()
313 runners = dict(ipython=IPythonRunner,
291 runners = dict(ipython=IPythonRunner,
314 python=PythonRunner,
292 python=PythonRunner,
315 sage=SAGERunner)
293 sage=SAGERunner)
316 runners[opts.mode]().main(args)
294 runners[opts.mode]().main(args)
317
295
318 if __name__ == '__main__':
296 if __name__ == '__main__':
319 main()
297 main()
@@ -1,883 +1,887 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 ultraTB.py -- Spice up your tracebacks!
3 ultraTB.py -- Spice up your tracebacks!
4
4
5 * ColorTB
5 * ColorTB
6 I've always found it a bit hard to visually parse tracebacks in Python. The
6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 ColorTB class is a solution to that problem. It colors the different parts of a
7 ColorTB class is a solution to that problem. It colors the different parts of a
8 traceback in a manner similar to what you would expect from a syntax-highlighting
8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 text editor.
9 text editor.
10
10
11 Installation instructions for ColorTB:
11 Installation instructions for ColorTB:
12 import sys,ultraTB
12 import sys,ultraTB
13 sys.excepthook = ultraTB.ColorTB()
13 sys.excepthook = ultraTB.ColorTB()
14
14
15 * VerboseTB
15 * VerboseTB
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 and intended it for CGI programmers, but why should they have all the fun? I
18 and intended it for CGI programmers, but why should they have all the fun? I
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 but kind of neat, and maybe useful for long-running programs that you believe
20 but kind of neat, and maybe useful for long-running programs that you believe
21 are bug-free. If a crash *does* occur in that type of program you want details.
21 are bug-free. If a crash *does* occur in that type of program you want details.
22 Give it a shot--you'll love it or you'll hate it.
22 Give it a shot--you'll love it or you'll hate it.
23
23
24 Note:
24 Note:
25
25
26 The Verbose mode prints the variables currently visible where the exception
26 The Verbose mode prints the variables currently visible where the exception
27 happened (shortening their strings if too long). This can potentially be
27 happened (shortening their strings if too long). This can potentially be
28 very slow, if you happen to have a huge data structure whose string
28 very slow, if you happen to have a huge data structure whose string
29 representation is complex to compute. Your computer may appear to freeze for
29 representation is complex to compute. Your computer may appear to freeze for
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 with Ctrl-C (maybe hitting it more than once).
31 with Ctrl-C (maybe hitting it more than once).
32
32
33 If you encounter this kind of situation often, you may want to use the
33 If you encounter this kind of situation often, you may want to use the
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 variables (but otherwise includes the information and context given by
35 variables (but otherwise includes the information and context given by
36 Verbose).
36 Verbose).
37
37
38
38
39 Installation instructions for ColorTB:
39 Installation instructions for ColorTB:
40 import sys,ultraTB
40 import sys,ultraTB
41 sys.excepthook = ultraTB.VerboseTB()
41 sys.excepthook = ultraTB.VerboseTB()
42
42
43 Note: Much of the code in this module was lifted verbatim from the standard
43 Note: Much of the code in this module was lifted verbatim from the standard
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45
45
46 * Color schemes
46 * Color schemes
47 The colors are defined in the class TBTools through the use of the
47 The colors are defined in the class TBTools through the use of the
48 ColorSchemeTable class. Currently the following exist:
48 ColorSchemeTable class. Currently the following exist:
49
49
50 - NoColor: allows all of this module to be used in any terminal (the color
50 - NoColor: allows all of this module to be used in any terminal (the color
51 escapes are just dummy blank strings).
51 escapes are just dummy blank strings).
52
52
53 - Linux: is meant to look good in a terminal like the Linux console (black
53 - Linux: is meant to look good in a terminal like the Linux console (black
54 or very dark background).
54 or very dark background).
55
55
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 in light background terminals.
57 in light background terminals.
58
58
59 You can implement other color schemes easily, the syntax is fairly
59 You can implement other color schemes easily, the syntax is fairly
60 self-explanatory. Please send back new schemes you develop to the author for
60 self-explanatory. Please send back new schemes you develop to the author for
61 possible inclusion in future releases.
61 possible inclusion in future releases.
62
62
63 $Id: ultraTB.py 1786 2006-09-27 05:47:28Z fperez $"""
63 $Id: ultraTB.py 1787 2006-09-27 06:56:29Z fperez $"""
64
64
65 #*****************************************************************************
65 #*****************************************************************************
66 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
66 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
67 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
67 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
68 #
68 #
69 # Distributed under the terms of the BSD License. The full license is in
69 # Distributed under the terms of the BSD License. The full license is in
70 # the file COPYING, distributed as part of this software.
70 # the file COPYING, distributed as part of this software.
71 #*****************************************************************************
71 #*****************************************************************************
72
72
73 from IPython import Release
73 from IPython import Release
74 __author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
74 __author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
75 Release.authors['Fernando'])
75 Release.authors['Fernando'])
76 __license__ = Release.license
76 __license__ = Release.license
77
77
78 # Required modules
78 # Required modules
79 import inspect
79 import inspect
80 import keyword
80 import keyword
81 import linecache
81 import linecache
82 import os
82 import os
83 import pydoc
83 import pydoc
84 import string
84 import string
85 import sys
85 import sys
86 import time
86 import time
87 import tokenize
87 import tokenize
88 import traceback
88 import traceback
89 import types
89 import types
90
90
91 # IPython's own modules
91 # IPython's own modules
92 # Modified pdb which doesn't damage IPython's readline handling
92 # Modified pdb which doesn't damage IPython's readline handling
93 from IPython import Debugger
93 from IPython import Debugger
94 from IPython.ipstruct import Struct
94 from IPython.ipstruct import Struct
95 from IPython.excolors import ExceptionColors
95 from IPython.excolors import ExceptionColors
96 from IPython.genutils import Term,uniq_stable,error,info
96 from IPython.genutils import Term,uniq_stable,error,info
97
97
98 # Globals
98 # Globals
99 # amount of space to put line numbers before verbose tracebacks
99 # amount of space to put line numbers before verbose tracebacks
100 INDENT_SIZE = 8
100 INDENT_SIZE = 8
101
101
102 #---------------------------------------------------------------------------
102 #---------------------------------------------------------------------------
103 # Code begins
103 # Code begins
104
104
105 # Utility functions
105 # Utility functions
106 def inspect_error():
106 def inspect_error():
107 """Print a message about internal inspect errors.
107 """Print a message about internal inspect errors.
108
108
109 These are unfortunately quite common."""
109 These are unfortunately quite common."""
110
110
111 error('Internal Python error in the inspect module.\n'
111 error('Internal Python error in the inspect module.\n'
112 'Below is the traceback from this internal error.\n')
112 'Below is the traceback from this internal error.\n')
113
113
114 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
114 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
115 import linecache
115 import linecache
116 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
116 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
117
117
118 records = inspect.getinnerframes(etb, context)
118 records = inspect.getinnerframes(etb, context)
119
119
120 # If the error is at the console, don't build any context, since it would
120 # If the error is at the console, don't build any context, since it would
121 # otherwise produce 5 blank lines printed out (there is no file at the
121 # otherwise produce 5 blank lines printed out (there is no file at the
122 # console)
122 # console)
123 rec_check = records[tb_offset:]
123 rec_check = records[tb_offset:]
124 try:
124 try:
125 rname = rec_check[0][1]
125 rname = rec_check[0][1]
126 if rname == '<ipython console>' or rname.endswith('<string>'):
126 if rname == '<ipython console>' or rname.endswith('<string>'):
127 return rec_check
127 return rec_check
128 except IndexError:
128 except IndexError:
129 pass
129 pass
130
130
131 aux = traceback.extract_tb(etb)
131 aux = traceback.extract_tb(etb)
132 assert len(records) == len(aux)
132 assert len(records) == len(aux)
133 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
133 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
134 maybeStart = lnum-1 - context//2
134 maybeStart = lnum-1 - context//2
135 start = max(maybeStart, 0)
135 start = max(maybeStart, 0)
136 end = start + context
136 end = start + context
137 lines = linecache.getlines(file)[start:end]
137 lines = linecache.getlines(file)[start:end]
138 # pad with empty lines if necessary
138 # pad with empty lines if necessary
139 if maybeStart < 0:
139 if maybeStart < 0:
140 lines = (['\n'] * -maybeStart) + lines
140 lines = (['\n'] * -maybeStart) + lines
141 if len(lines) < context:
141 if len(lines) < context:
142 lines += ['\n'] * (context - len(lines))
142 lines += ['\n'] * (context - len(lines))
143 buf = list(records[i])
143 buf = list(records[i])
144 buf[LNUM_POS] = lnum
144 buf[LNUM_POS] = lnum
145 buf[INDEX_POS] = lnum - 1 - start
145 buf[INDEX_POS] = lnum - 1 - start
146 buf[LINES_POS] = lines
146 buf[LINES_POS] = lines
147 records[i] = tuple(buf)
147 records[i] = tuple(buf)
148 return records[tb_offset:]
148 return records[tb_offset:]
149
149
150 # Helper function -- largely belongs to VerboseTB, but we need the same
150 # Helper function -- largely belongs to VerboseTB, but we need the same
151 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
151 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
152 # can be recognized properly by ipython.el's py-traceback-line-re
152 # can be recognized properly by ipython.el's py-traceback-line-re
153 # (SyntaxErrors have to be treated specially because they have no traceback)
153 # (SyntaxErrors have to be treated specially because they have no traceback)
154 def _formatTracebackLines(lnum, index, lines, Colors, lvals=None):
154 def _formatTracebackLines(lnum, index, lines, Colors, lvals=None):
155 numbers_width = INDENT_SIZE - 1
155 numbers_width = INDENT_SIZE - 1
156 res = []
156 res = []
157 i = lnum - index
157 i = lnum - index
158 for line in lines:
158 for line in lines:
159 if i == lnum:
159 if i == lnum:
160 # This is the line with the error
160 # This is the line with the error
161 pad = numbers_width - len(str(i))
161 pad = numbers_width - len(str(i))
162 if pad >= 3:
162 if pad >= 3:
163 marker = '-'*(pad-3) + '-> '
163 marker = '-'*(pad-3) + '-> '
164 elif pad == 2:
164 elif pad == 2:
165 marker = '> '
165 marker = '> '
166 elif pad == 1:
166 elif pad == 1:
167 marker = '>'
167 marker = '>'
168 else:
168 else:
169 marker = ''
169 marker = ''
170 num = marker + str(i)
170 num = marker + str(i)
171 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
171 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
172 Colors.line, line, Colors.Normal)
172 Colors.line, line, Colors.Normal)
173 else:
173 else:
174 num = '%*s' % (numbers_width,i)
174 num = '%*s' % (numbers_width,i)
175 line = '%s%s%s %s' %(Colors.lineno, num,
175 line = '%s%s%s %s' %(Colors.lineno, num,
176 Colors.Normal, line)
176 Colors.Normal, line)
177
177
178 res.append(line)
178 res.append(line)
179 if lvals and i == lnum:
179 if lvals and i == lnum:
180 res.append(lvals + '\n')
180 res.append(lvals + '\n')
181 i = i + 1
181 i = i + 1
182 return res
182 return res
183
183
184 #---------------------------------------------------------------------------
184 #---------------------------------------------------------------------------
185 # Module classes
185 # Module classes
186 class TBTools:
186 class TBTools:
187 """Basic tools used by all traceback printer classes."""
187 """Basic tools used by all traceback printer classes."""
188
188
189 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
189 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
190 # Whether to call the interactive pdb debugger after printing
190 # Whether to call the interactive pdb debugger after printing
191 # tracebacks or not
191 # tracebacks or not
192 self.call_pdb = call_pdb
192 self.call_pdb = call_pdb
193
193
194 # Create color table
194 # Create color table
195 self.color_scheme_table = ExceptionColors
195 self.color_scheme_table = ExceptionColors
196
196
197 self.set_colors(color_scheme)
197 self.set_colors(color_scheme)
198 self.old_scheme = color_scheme # save initial value for toggles
198 self.old_scheme = color_scheme # save initial value for toggles
199
199
200 if call_pdb:
200 if call_pdb:
201 self.pdb = Debugger.Pdb(self.color_scheme_table.active_scheme_name)
201 self.pdb = Debugger.Pdb(self.color_scheme_table.active_scheme_name)
202 else:
202 else:
203 self.pdb = None
203 self.pdb = None
204
204
205 def set_colors(self,*args,**kw):
205 def set_colors(self,*args,**kw):
206 """Shorthand access to the color table scheme selector method."""
206 """Shorthand access to the color table scheme selector method."""
207
207
208 # Set own color table
208 self.color_scheme_table.set_active_scheme(*args,**kw)
209 self.color_scheme_table.set_active_scheme(*args,**kw)
209 # for convenience, set Colors to the active scheme
210 # for convenience, set Colors to the active scheme
210 self.Colors = self.color_scheme_table.active_colors
211 self.Colors = self.color_scheme_table.active_colors
212 # Also set colors of debugger
213 if hasattr(self,'pdb') and self.pdb is not None:
214 self.pdb.set_colors(*args,**kw)
211
215
212 def color_toggle(self):
216 def color_toggle(self):
213 """Toggle between the currently active color scheme and NoColor."""
217 """Toggle between the currently active color scheme and NoColor."""
214
218
215 if self.color_scheme_table.active_scheme_name == 'NoColor':
219 if self.color_scheme_table.active_scheme_name == 'NoColor':
216 self.color_scheme_table.set_active_scheme(self.old_scheme)
220 self.color_scheme_table.set_active_scheme(self.old_scheme)
217 self.Colors = self.color_scheme_table.active_colors
221 self.Colors = self.color_scheme_table.active_colors
218 else:
222 else:
219 self.old_scheme = self.color_scheme_table.active_scheme_name
223 self.old_scheme = self.color_scheme_table.active_scheme_name
220 self.color_scheme_table.set_active_scheme('NoColor')
224 self.color_scheme_table.set_active_scheme('NoColor')
221 self.Colors = self.color_scheme_table.active_colors
225 self.Colors = self.color_scheme_table.active_colors
222
226
223 #---------------------------------------------------------------------------
227 #---------------------------------------------------------------------------
224 class ListTB(TBTools):
228 class ListTB(TBTools):
225 """Print traceback information from a traceback list, with optional color.
229 """Print traceback information from a traceback list, with optional color.
226
230
227 Calling: requires 3 arguments:
231 Calling: requires 3 arguments:
228 (etype, evalue, elist)
232 (etype, evalue, elist)
229 as would be obtained by:
233 as would be obtained by:
230 etype, evalue, tb = sys.exc_info()
234 etype, evalue, tb = sys.exc_info()
231 if tb:
235 if tb:
232 elist = traceback.extract_tb(tb)
236 elist = traceback.extract_tb(tb)
233 else:
237 else:
234 elist = None
238 elist = None
235
239
236 It can thus be used by programs which need to process the traceback before
240 It can thus be used by programs which need to process the traceback before
237 printing (such as console replacements based on the code module from the
241 printing (such as console replacements based on the code module from the
238 standard library).
242 standard library).
239
243
240 Because they are meant to be called without a full traceback (only a
244 Because they are meant to be called without a full traceback (only a
241 list), instances of this class can't call the interactive pdb debugger."""
245 list), instances of this class can't call the interactive pdb debugger."""
242
246
243 def __init__(self,color_scheme = 'NoColor'):
247 def __init__(self,color_scheme = 'NoColor'):
244 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
248 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
245
249
246 def __call__(self, etype, value, elist):
250 def __call__(self, etype, value, elist):
247 print >> Term.cerr, self.text(etype,value,elist)
251 print >> Term.cerr, self.text(etype,value,elist)
248
252
249 def text(self,etype, value, elist,context=5):
253 def text(self,etype, value, elist,context=5):
250 """Return a color formatted string with the traceback info."""
254 """Return a color formatted string with the traceback info."""
251
255
252 Colors = self.Colors
256 Colors = self.Colors
253 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
257 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
254 if elist:
258 if elist:
255 out_string.append('Traceback %s(most recent call last)%s:' % \
259 out_string.append('Traceback %s(most recent call last)%s:' % \
256 (Colors.normalEm, Colors.Normal) + '\n')
260 (Colors.normalEm, Colors.Normal) + '\n')
257 out_string.extend(self._format_list(elist))
261 out_string.extend(self._format_list(elist))
258 lines = self._format_exception_only(etype, value)
262 lines = self._format_exception_only(etype, value)
259 for line in lines[:-1]:
263 for line in lines[:-1]:
260 out_string.append(" "+line)
264 out_string.append(" "+line)
261 out_string.append(lines[-1])
265 out_string.append(lines[-1])
262 return ''.join(out_string)
266 return ''.join(out_string)
263
267
264 def _format_list(self, extracted_list):
268 def _format_list(self, extracted_list):
265 """Format a list of traceback entry tuples for printing.
269 """Format a list of traceback entry tuples for printing.
266
270
267 Given a list of tuples as returned by extract_tb() or
271 Given a list of tuples as returned by extract_tb() or
268 extract_stack(), return a list of strings ready for printing.
272 extract_stack(), return a list of strings ready for printing.
269 Each string in the resulting list corresponds to the item with the
273 Each string in the resulting list corresponds to the item with the
270 same index in the argument list. Each string ends in a newline;
274 same index in the argument list. Each string ends in a newline;
271 the strings may contain internal newlines as well, for those items
275 the strings may contain internal newlines as well, for those items
272 whose source text line is not None.
276 whose source text line is not None.
273
277
274 Lifted almost verbatim from traceback.py
278 Lifted almost verbatim from traceback.py
275 """
279 """
276
280
277 Colors = self.Colors
281 Colors = self.Colors
278 list = []
282 list = []
279 for filename, lineno, name, line in extracted_list[:-1]:
283 for filename, lineno, name, line in extracted_list[:-1]:
280 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
284 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
281 (Colors.filename, filename, Colors.Normal,
285 (Colors.filename, filename, Colors.Normal,
282 Colors.lineno, lineno, Colors.Normal,
286 Colors.lineno, lineno, Colors.Normal,
283 Colors.name, name, Colors.Normal)
287 Colors.name, name, Colors.Normal)
284 if line:
288 if line:
285 item = item + ' %s\n' % line.strip()
289 item = item + ' %s\n' % line.strip()
286 list.append(item)
290 list.append(item)
287 # Emphasize the last entry
291 # Emphasize the last entry
288 filename, lineno, name, line = extracted_list[-1]
292 filename, lineno, name, line = extracted_list[-1]
289 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
293 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
290 (Colors.normalEm,
294 (Colors.normalEm,
291 Colors.filenameEm, filename, Colors.normalEm,
295 Colors.filenameEm, filename, Colors.normalEm,
292 Colors.linenoEm, lineno, Colors.normalEm,
296 Colors.linenoEm, lineno, Colors.normalEm,
293 Colors.nameEm, name, Colors.normalEm,
297 Colors.nameEm, name, Colors.normalEm,
294 Colors.Normal)
298 Colors.Normal)
295 if line:
299 if line:
296 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
300 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
297 Colors.Normal)
301 Colors.Normal)
298 list.append(item)
302 list.append(item)
299 return list
303 return list
300
304
301 def _format_exception_only(self, etype, value):
305 def _format_exception_only(self, etype, value):
302 """Format the exception part of a traceback.
306 """Format the exception part of a traceback.
303
307
304 The arguments are the exception type and value such as given by
308 The arguments are the exception type and value such as given by
305 sys.exc_info()[:2]. The return value is a list of strings, each ending
309 sys.exc_info()[:2]. The return value is a list of strings, each ending
306 in a newline. Normally, the list contains a single string; however,
310 in a newline. Normally, the list contains a single string; however,
307 for SyntaxError exceptions, it contains several lines that (when
311 for SyntaxError exceptions, it contains several lines that (when
308 printed) display detailed information about where the syntax error
312 printed) display detailed information about where the syntax error
309 occurred. The message indicating which exception occurred is the
313 occurred. The message indicating which exception occurred is the
310 always last string in the list.
314 always last string in the list.
311
315
312 Also lifted nearly verbatim from traceback.py
316 Also lifted nearly verbatim from traceback.py
313 """
317 """
314
318
315 Colors = self.Colors
319 Colors = self.Colors
316 list = []
320 list = []
317 if type(etype) == types.ClassType:
321 if type(etype) == types.ClassType:
318 stype = Colors.excName + etype.__name__ + Colors.Normal
322 stype = Colors.excName + etype.__name__ + Colors.Normal
319 else:
323 else:
320 stype = etype # String exceptions don't get special coloring
324 stype = etype # String exceptions don't get special coloring
321 if value is None:
325 if value is None:
322 list.append( str(stype) + '\n')
326 list.append( str(stype) + '\n')
323 else:
327 else:
324 if etype is SyntaxError:
328 if etype is SyntaxError:
325 try:
329 try:
326 msg, (filename, lineno, offset, line) = value
330 msg, (filename, lineno, offset, line) = value
327 except:
331 except:
328 pass
332 pass
329 else:
333 else:
330 #print 'filename is',filename # dbg
334 #print 'filename is',filename # dbg
331 if not filename: filename = "<string>"
335 if not filename: filename = "<string>"
332 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
336 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
333 (Colors.normalEm,
337 (Colors.normalEm,
334 Colors.filenameEm, filename, Colors.normalEm,
338 Colors.filenameEm, filename, Colors.normalEm,
335 Colors.linenoEm, lineno, Colors.Normal ))
339 Colors.linenoEm, lineno, Colors.Normal ))
336 if line is not None:
340 if line is not None:
337 i = 0
341 i = 0
338 while i < len(line) and line[i].isspace():
342 while i < len(line) and line[i].isspace():
339 i = i+1
343 i = i+1
340 list.append('%s %s%s\n' % (Colors.line,
344 list.append('%s %s%s\n' % (Colors.line,
341 line.strip(),
345 line.strip(),
342 Colors.Normal))
346 Colors.Normal))
343 if offset is not None:
347 if offset is not None:
344 s = ' '
348 s = ' '
345 for c in line[i:offset-1]:
349 for c in line[i:offset-1]:
346 if c.isspace():
350 if c.isspace():
347 s = s + c
351 s = s + c
348 else:
352 else:
349 s = s + ' '
353 s = s + ' '
350 list.append('%s%s^%s\n' % (Colors.caret, s,
354 list.append('%s%s^%s\n' % (Colors.caret, s,
351 Colors.Normal) )
355 Colors.Normal) )
352 value = msg
356 value = msg
353 s = self._some_str(value)
357 s = self._some_str(value)
354 if s:
358 if s:
355 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
359 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
356 Colors.Normal, s))
360 Colors.Normal, s))
357 else:
361 else:
358 list.append('%s\n' % str(stype))
362 list.append('%s\n' % str(stype))
359 return list
363 return list
360
364
361 def _some_str(self, value):
365 def _some_str(self, value):
362 # Lifted from traceback.py
366 # Lifted from traceback.py
363 try:
367 try:
364 return str(value)
368 return str(value)
365 except:
369 except:
366 return '<unprintable %s object>' % type(value).__name__
370 return '<unprintable %s object>' % type(value).__name__
367
371
368 #----------------------------------------------------------------------------
372 #----------------------------------------------------------------------------
369 class VerboseTB(TBTools):
373 class VerboseTB(TBTools):
370 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
374 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
371 of HTML. Requires inspect and pydoc. Crazy, man.
375 of HTML. Requires inspect and pydoc. Crazy, man.
372
376
373 Modified version which optionally strips the topmost entries from the
377 Modified version which optionally strips the topmost entries from the
374 traceback, to be used with alternate interpreters (because their own code
378 traceback, to be used with alternate interpreters (because their own code
375 would appear in the traceback)."""
379 would appear in the traceback)."""
376
380
377 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
381 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
378 call_pdb = 0, include_vars=1):
382 call_pdb = 0, include_vars=1):
379 """Specify traceback offset, headers and color scheme.
383 """Specify traceback offset, headers and color scheme.
380
384
381 Define how many frames to drop from the tracebacks. Calling it with
385 Define how many frames to drop from the tracebacks. Calling it with
382 tb_offset=1 allows use of this handler in interpreters which will have
386 tb_offset=1 allows use of this handler in interpreters which will have
383 their own code at the top of the traceback (VerboseTB will first
387 their own code at the top of the traceback (VerboseTB will first
384 remove that frame before printing the traceback info)."""
388 remove that frame before printing the traceback info)."""
385 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
389 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
386 self.tb_offset = tb_offset
390 self.tb_offset = tb_offset
387 self.long_header = long_header
391 self.long_header = long_header
388 self.include_vars = include_vars
392 self.include_vars = include_vars
389
393
390 def text(self, etype, evalue, etb, context=5):
394 def text(self, etype, evalue, etb, context=5):
391 """Return a nice text document describing the traceback."""
395 """Return a nice text document describing the traceback."""
392
396
393 # some locals
397 # some locals
394 Colors = self.Colors # just a shorthand + quicker name lookup
398 Colors = self.Colors # just a shorthand + quicker name lookup
395 ColorsNormal = Colors.Normal # used a lot
399 ColorsNormal = Colors.Normal # used a lot
396 indent = ' '*INDENT_SIZE
400 indent = ' '*INDENT_SIZE
397 exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
401 exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
398 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
402 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
399 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
403 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
400
404
401 # some internal-use functions
405 # some internal-use functions
402 def text_repr(value):
406 def text_repr(value):
403 """Hopefully pretty robust repr equivalent."""
407 """Hopefully pretty robust repr equivalent."""
404 # this is pretty horrible but should always return *something*
408 # this is pretty horrible but should always return *something*
405 try:
409 try:
406 return pydoc.text.repr(value)
410 return pydoc.text.repr(value)
407 except KeyboardInterrupt:
411 except KeyboardInterrupt:
408 raise
412 raise
409 except:
413 except:
410 try:
414 try:
411 return repr(value)
415 return repr(value)
412 except KeyboardInterrupt:
416 except KeyboardInterrupt:
413 raise
417 raise
414 except:
418 except:
415 try:
419 try:
416 # all still in an except block so we catch
420 # all still in an except block so we catch
417 # getattr raising
421 # getattr raising
418 name = getattr(value, '__name__', None)
422 name = getattr(value, '__name__', None)
419 if name:
423 if name:
420 # ick, recursion
424 # ick, recursion
421 return text_repr(name)
425 return text_repr(name)
422 klass = getattr(value, '__class__', None)
426 klass = getattr(value, '__class__', None)
423 if klass:
427 if klass:
424 return '%s instance' % text_repr(klass)
428 return '%s instance' % text_repr(klass)
425 except KeyboardInterrupt:
429 except KeyboardInterrupt:
426 raise
430 raise
427 except:
431 except:
428 return 'UNRECOVERABLE REPR FAILURE'
432 return 'UNRECOVERABLE REPR FAILURE'
429 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
433 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
430 def nullrepr(value, repr=text_repr): return ''
434 def nullrepr(value, repr=text_repr): return ''
431
435
432 # meat of the code begins
436 # meat of the code begins
433 if type(etype) is types.ClassType:
437 if type(etype) is types.ClassType:
434 etype = etype.__name__
438 etype = etype.__name__
435
439
436 if self.long_header:
440 if self.long_header:
437 # Header with the exception type, python version, and date
441 # Header with the exception type, python version, and date
438 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
442 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
439 date = time.ctime(time.time())
443 date = time.ctime(time.time())
440
444
441 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
445 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
442 exc, ' '*(75-len(str(etype))-len(pyver)),
446 exc, ' '*(75-len(str(etype))-len(pyver)),
443 pyver, string.rjust(date, 75) )
447 pyver, string.rjust(date, 75) )
444 head += "\nA problem occured executing Python code. Here is the sequence of function"\
448 head += "\nA problem occured executing Python code. Here is the sequence of function"\
445 "\ncalls leading up to the error, with the most recent (innermost) call last."
449 "\ncalls leading up to the error, with the most recent (innermost) call last."
446 else:
450 else:
447 # Simplified header
451 # Simplified header
448 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
452 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
449 string.rjust('Traceback (most recent call last)',
453 string.rjust('Traceback (most recent call last)',
450 75 - len(str(etype)) ) )
454 75 - len(str(etype)) ) )
451 frames = []
455 frames = []
452 # Flush cache before calling inspect. This helps alleviate some of the
456 # Flush cache before calling inspect. This helps alleviate some of the
453 # problems with python 2.3's inspect.py.
457 # problems with python 2.3's inspect.py.
454 linecache.checkcache()
458 linecache.checkcache()
455 # Drop topmost frames if requested
459 # Drop topmost frames if requested
456 try:
460 try:
457 # Try the default getinnerframes and Alex's: Alex's fixes some
461 # Try the default getinnerframes and Alex's: Alex's fixes some
458 # problems, but it generates empty tracebacks for console errors
462 # problems, but it generates empty tracebacks for console errors
459 # (5 blanks lines) where none should be returned.
463 # (5 blanks lines) where none should be returned.
460 #records = inspect.getinnerframes(etb, context)[self.tb_offset:]
464 #records = inspect.getinnerframes(etb, context)[self.tb_offset:]
461 #print 'python records:', records # dbg
465 #print 'python records:', records # dbg
462 records = _fixed_getinnerframes(etb, context,self.tb_offset)
466 records = _fixed_getinnerframes(etb, context,self.tb_offset)
463 #print 'alex records:', records # dbg
467 #print 'alex records:', records # dbg
464 except:
468 except:
465
469
466 # FIXME: I've been getting many crash reports from python 2.3
470 # FIXME: I've been getting many crash reports from python 2.3
467 # users, traceable to inspect.py. If I can find a small test-case
471 # users, traceable to inspect.py. If I can find a small test-case
468 # to reproduce this, I should either write a better workaround or
472 # to reproduce this, I should either write a better workaround or
469 # file a bug report against inspect (if that's the real problem).
473 # file a bug report against inspect (if that's the real problem).
470 # So far, I haven't been able to find an isolated example to
474 # So far, I haven't been able to find an isolated example to
471 # reproduce the problem.
475 # reproduce the problem.
472 inspect_error()
476 inspect_error()
473 traceback.print_exc(file=Term.cerr)
477 traceback.print_exc(file=Term.cerr)
474 info('\nUnfortunately, your original traceback can not be constructed.\n')
478 info('\nUnfortunately, your original traceback can not be constructed.\n')
475 return ''
479 return ''
476
480
477 # build some color string templates outside these nested loops
481 # build some color string templates outside these nested loops
478 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
482 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
479 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
483 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
480 ColorsNormal)
484 ColorsNormal)
481 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
485 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
482 (Colors.vName, Colors.valEm, ColorsNormal)
486 (Colors.vName, Colors.valEm, ColorsNormal)
483 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
487 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
484 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
488 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
485 Colors.vName, ColorsNormal)
489 Colors.vName, ColorsNormal)
486 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
490 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
487 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
491 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
488 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
492 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
489 ColorsNormal)
493 ColorsNormal)
490
494
491 # now, loop over all records printing context and info
495 # now, loop over all records printing context and info
492 abspath = os.path.abspath
496 abspath = os.path.abspath
493 for frame, file, lnum, func, lines, index in records:
497 for frame, file, lnum, func, lines, index in records:
494 #print '*** record:',file,lnum,func,lines,index # dbg
498 #print '*** record:',file,lnum,func,lines,index # dbg
495 try:
499 try:
496 file = file and abspath(file) or '?'
500 file = file and abspath(file) or '?'
497 except OSError:
501 except OSError:
498 # if file is '<console>' or something not in the filesystem,
502 # if file is '<console>' or something not in the filesystem,
499 # the abspath call will throw an OSError. Just ignore it and
503 # the abspath call will throw an OSError. Just ignore it and
500 # keep the original file string.
504 # keep the original file string.
501 pass
505 pass
502 link = tpl_link % file
506 link = tpl_link % file
503 try:
507 try:
504 args, varargs, varkw, locals = inspect.getargvalues(frame)
508 args, varargs, varkw, locals = inspect.getargvalues(frame)
505 except:
509 except:
506 # This can happen due to a bug in python2.3. We should be
510 # This can happen due to a bug in python2.3. We should be
507 # able to remove this try/except when 2.4 becomes a
511 # able to remove this try/except when 2.4 becomes a
508 # requirement. Bug details at http://python.org/sf/1005466
512 # requirement. Bug details at http://python.org/sf/1005466
509 inspect_error()
513 inspect_error()
510 traceback.print_exc(file=Term.cerr)
514 traceback.print_exc(file=Term.cerr)
511 info("\nIPython's exception reporting continues...\n")
515 info("\nIPython's exception reporting continues...\n")
512
516
513 if func == '?':
517 if func == '?':
514 call = ''
518 call = ''
515 else:
519 else:
516 # Decide whether to include variable details or not
520 # Decide whether to include variable details or not
517 var_repr = self.include_vars and eqrepr or nullrepr
521 var_repr = self.include_vars and eqrepr or nullrepr
518 try:
522 try:
519 call = tpl_call % (func,inspect.formatargvalues(args,
523 call = tpl_call % (func,inspect.formatargvalues(args,
520 varargs, varkw,
524 varargs, varkw,
521 locals,formatvalue=var_repr))
525 locals,formatvalue=var_repr))
522 except KeyError:
526 except KeyError:
523 # Very odd crash from inspect.formatargvalues(). The
527 # Very odd crash from inspect.formatargvalues(). The
524 # scenario under which it appeared was a call to
528 # scenario under which it appeared was a call to
525 # view(array,scale) in NumTut.view.view(), where scale had
529 # view(array,scale) in NumTut.view.view(), where scale had
526 # been defined as a scalar (it should be a tuple). Somehow
530 # been defined as a scalar (it should be a tuple). Somehow
527 # inspect messes up resolving the argument list of view()
531 # inspect messes up resolving the argument list of view()
528 # and barfs out. At some point I should dig into this one
532 # and barfs out. At some point I should dig into this one
529 # and file a bug report about it.
533 # and file a bug report about it.
530 inspect_error()
534 inspect_error()
531 traceback.print_exc(file=Term.cerr)
535 traceback.print_exc(file=Term.cerr)
532 info("\nIPython's exception reporting continues...\n")
536 info("\nIPython's exception reporting continues...\n")
533 call = tpl_call_fail % func
537 call = tpl_call_fail % func
534
538
535 # Initialize a list of names on the current line, which the
539 # Initialize a list of names on the current line, which the
536 # tokenizer below will populate.
540 # tokenizer below will populate.
537 names = []
541 names = []
538
542
539 def tokeneater(token_type, token, start, end, line):
543 def tokeneater(token_type, token, start, end, line):
540 """Stateful tokeneater which builds dotted names.
544 """Stateful tokeneater which builds dotted names.
541
545
542 The list of names it appends to (from the enclosing scope) can
546 The list of names it appends to (from the enclosing scope) can
543 contain repeated composite names. This is unavoidable, since
547 contain repeated composite names. This is unavoidable, since
544 there is no way to disambguate partial dotted structures until
548 there is no way to disambguate partial dotted structures until
545 the full list is known. The caller is responsible for pruning
549 the full list is known. The caller is responsible for pruning
546 the final list of duplicates before using it."""
550 the final list of duplicates before using it."""
547
551
548 # build composite names
552 # build composite names
549 if token == '.':
553 if token == '.':
550 try:
554 try:
551 names[-1] += '.'
555 names[-1] += '.'
552 # store state so the next token is added for x.y.z names
556 # store state so the next token is added for x.y.z names
553 tokeneater.name_cont = True
557 tokeneater.name_cont = True
554 return
558 return
555 except IndexError:
559 except IndexError:
556 pass
560 pass
557 if token_type == tokenize.NAME and token not in keyword.kwlist:
561 if token_type == tokenize.NAME and token not in keyword.kwlist:
558 if tokeneater.name_cont:
562 if tokeneater.name_cont:
559 # Dotted names
563 # Dotted names
560 names[-1] += token
564 names[-1] += token
561 tokeneater.name_cont = False
565 tokeneater.name_cont = False
562 else:
566 else:
563 # Regular new names. We append everything, the caller
567 # Regular new names. We append everything, the caller
564 # will be responsible for pruning the list later. It's
568 # will be responsible for pruning the list later. It's
565 # very tricky to try to prune as we go, b/c composite
569 # very tricky to try to prune as we go, b/c composite
566 # names can fool us. The pruning at the end is easy
570 # names can fool us. The pruning at the end is easy
567 # to do (or the caller can print a list with repeated
571 # to do (or the caller can print a list with repeated
568 # names if so desired.
572 # names if so desired.
569 names.append(token)
573 names.append(token)
570 elif token_type == tokenize.NEWLINE:
574 elif token_type == tokenize.NEWLINE:
571 raise IndexError
575 raise IndexError
572 # we need to store a bit of state in the tokenizer to build
576 # we need to store a bit of state in the tokenizer to build
573 # dotted names
577 # dotted names
574 tokeneater.name_cont = False
578 tokeneater.name_cont = False
575
579
576 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
580 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
577 line = getline(file, lnum[0])
581 line = getline(file, lnum[0])
578 lnum[0] += 1
582 lnum[0] += 1
579 return line
583 return line
580
584
581 # Build the list of names on this line of code where the exception
585 # Build the list of names on this line of code where the exception
582 # occurred.
586 # occurred.
583 try:
587 try:
584 # This builds the names list in-place by capturing it from the
588 # This builds the names list in-place by capturing it from the
585 # enclosing scope.
589 # enclosing scope.
586 tokenize.tokenize(linereader, tokeneater)
590 tokenize.tokenize(linereader, tokeneater)
587 except IndexError:
591 except IndexError:
588 # signals exit of tokenizer
592 # signals exit of tokenizer
589 pass
593 pass
590 except tokenize.TokenError,msg:
594 except tokenize.TokenError,msg:
591 _m = ("An unexpected error occurred while tokenizing input\n"
595 _m = ("An unexpected error occurred while tokenizing input\n"
592 "The following traceback may be corrupted or invalid\n"
596 "The following traceback may be corrupted or invalid\n"
593 "The error message is: %s\n" % msg)
597 "The error message is: %s\n" % msg)
594 error(_m)
598 error(_m)
595
599
596 # prune names list of duplicates, but keep the right order
600 # prune names list of duplicates, but keep the right order
597 unique_names = uniq_stable(names)
601 unique_names = uniq_stable(names)
598
602
599 # Start loop over vars
603 # Start loop over vars
600 lvals = []
604 lvals = []
601 if self.include_vars:
605 if self.include_vars:
602 for name_full in unique_names:
606 for name_full in unique_names:
603 name_base = name_full.split('.',1)[0]
607 name_base = name_full.split('.',1)[0]
604 if name_base in frame.f_code.co_varnames:
608 if name_base in frame.f_code.co_varnames:
605 if locals.has_key(name_base):
609 if locals.has_key(name_base):
606 try:
610 try:
607 value = repr(eval(name_full,locals))
611 value = repr(eval(name_full,locals))
608 except:
612 except:
609 value = undefined
613 value = undefined
610 else:
614 else:
611 value = undefined
615 value = undefined
612 name = tpl_local_var % name_full
616 name = tpl_local_var % name_full
613 else:
617 else:
614 if frame.f_globals.has_key(name_base):
618 if frame.f_globals.has_key(name_base):
615 try:
619 try:
616 value = repr(eval(name_full,frame.f_globals))
620 value = repr(eval(name_full,frame.f_globals))
617 except:
621 except:
618 value = undefined
622 value = undefined
619 else:
623 else:
620 value = undefined
624 value = undefined
621 name = tpl_global_var % name_full
625 name = tpl_global_var % name_full
622 lvals.append(tpl_name_val % (name,value))
626 lvals.append(tpl_name_val % (name,value))
623 if lvals:
627 if lvals:
624 lvals = '%s%s' % (indent,em_normal.join(lvals))
628 lvals = '%s%s' % (indent,em_normal.join(lvals))
625 else:
629 else:
626 lvals = ''
630 lvals = ''
627
631
628 level = '%s %s\n' % (link,call)
632 level = '%s %s\n' % (link,call)
629
633
630 if index is None:
634 if index is None:
631 frames.append(level)
635 frames.append(level)
632 else:
636 else:
633 frames.append('%s%s' % (level,''.join(
637 frames.append('%s%s' % (level,''.join(
634 _formatTracebackLines(lnum,index,lines,self.Colors,lvals))))
638 _formatTracebackLines(lnum,index,lines,self.Colors,lvals))))
635
639
636 # Get (safely) a string form of the exception info
640 # Get (safely) a string form of the exception info
637 try:
641 try:
638 etype_str,evalue_str = map(str,(etype,evalue))
642 etype_str,evalue_str = map(str,(etype,evalue))
639 except:
643 except:
640 # User exception is improperly defined.
644 # User exception is improperly defined.
641 etype,evalue = str,sys.exc_info()[:2]
645 etype,evalue = str,sys.exc_info()[:2]
642 etype_str,evalue_str = map(str,(etype,evalue))
646 etype_str,evalue_str = map(str,(etype,evalue))
643 # ... and format it
647 # ... and format it
644 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
648 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
645 ColorsNormal, evalue_str)]
649 ColorsNormal, evalue_str)]
646 if type(evalue) is types.InstanceType:
650 if type(evalue) is types.InstanceType:
647 try:
651 try:
648 names = [w for w in dir(evalue) if isinstance(w, basestring)]
652 names = [w for w in dir(evalue) if isinstance(w, basestring)]
649 except:
653 except:
650 # Every now and then, an object with funny inernals blows up
654 # Every now and then, an object with funny inernals blows up
651 # when dir() is called on it. We do the best we can to report
655 # when dir() is called on it. We do the best we can to report
652 # the problem and continue
656 # the problem and continue
653 _m = '%sException reporting error (object with broken dir())%s:'
657 _m = '%sException reporting error (object with broken dir())%s:'
654 exception.append(_m % (Colors.excName,ColorsNormal))
658 exception.append(_m % (Colors.excName,ColorsNormal))
655 etype_str,evalue_str = map(str,sys.exc_info()[:2])
659 etype_str,evalue_str = map(str,sys.exc_info()[:2])
656 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
660 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
657 ColorsNormal, evalue_str))
661 ColorsNormal, evalue_str))
658 names = []
662 names = []
659 for name in names:
663 for name in names:
660 value = text_repr(getattr(evalue, name))
664 value = text_repr(getattr(evalue, name))
661 exception.append('\n%s%s = %s' % (indent, name, value))
665 exception.append('\n%s%s = %s' % (indent, name, value))
662 # return all our info assembled as a single string
666 # return all our info assembled as a single string
663 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
667 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
664
668
665 def debugger(self):
669 def debugger(self):
666 """Call up the pdb debugger if desired, always clean up the tb reference.
670 """Call up the pdb debugger if desired, always clean up the tb reference.
667
671
668 If the call_pdb flag is set, the pdb interactive debugger is
672 If the call_pdb flag is set, the pdb interactive debugger is
669 invoked. In all cases, the self.tb reference to the current traceback
673 invoked. In all cases, the self.tb reference to the current traceback
670 is deleted to prevent lingering references which hamper memory
674 is deleted to prevent lingering references which hamper memory
671 management.
675 management.
672
676
673 Note that each call to pdb() does an 'import readline', so if your app
677 Note that each call to pdb() does an 'import readline', so if your app
674 requires a special setup for the readline completers, you'll have to
678 requires a special setup for the readline completers, you'll have to
675 fix that by hand after invoking the exception handler."""
679 fix that by hand after invoking the exception handler."""
676
680
677 if self.call_pdb:
681 if self.call_pdb:
678 if self.pdb is None:
682 if self.pdb is None:
679 self.pdb = Debugger.Pdb(
683 self.pdb = Debugger.Pdb(
680 self.color_scheme_table.active_scheme_name)
684 self.color_scheme_table.active_scheme_name)
681 # the system displayhook may have changed, restore the original
685 # the system displayhook may have changed, restore the original
682 # for pdb
686 # for pdb
683 dhook = sys.displayhook
687 dhook = sys.displayhook
684 sys.displayhook = sys.__displayhook__
688 sys.displayhook = sys.__displayhook__
685 self.pdb.reset()
689 self.pdb.reset()
686 # Find the right frame so we don't pop up inside ipython itself
690 # Find the right frame so we don't pop up inside ipython itself
687 etb = self.tb
691 etb = self.tb
688 while self.tb.tb_next is not None:
692 while self.tb.tb_next is not None:
689 self.tb = self.tb.tb_next
693 self.tb = self.tb.tb_next
690 try:
694 try:
691 if etb and etb.tb_next:
695 if etb and etb.tb_next:
692 etb = etb.tb_next
696 etb = etb.tb_next
693 self.pdb.botframe = etb.tb_frame
697 self.pdb.botframe = etb.tb_frame
694 self.pdb.interaction(self.tb.tb_frame, self.tb)
698 self.pdb.interaction(self.tb.tb_frame, self.tb)
695 except 'ha': # dbg
699 except:
696 print '*** ERROR ***'
700 print '*** ERROR ***'
697 print 'This version of pdb has a bug and crashed.'
701 print 'This version of pdb has a bug and crashed.'
698 print 'Returning to IPython...'
702 print 'Returning to IPython...'
699 sys.displayhook = dhook
703 sys.displayhook = dhook
700 del self.tb
704 del self.tb
701
705
702 def handler(self, info=None):
706 def handler(self, info=None):
703 (etype, evalue, etb) = info or sys.exc_info()
707 (etype, evalue, etb) = info or sys.exc_info()
704 self.tb = etb
708 self.tb = etb
705 print >> Term.cerr, self.text(etype, evalue, etb)
709 print >> Term.cerr, self.text(etype, evalue, etb)
706
710
707 # Changed so an instance can just be called as VerboseTB_inst() and print
711 # Changed so an instance can just be called as VerboseTB_inst() and print
708 # out the right info on its own.
712 # out the right info on its own.
709 def __call__(self, etype=None, evalue=None, etb=None):
713 def __call__(self, etype=None, evalue=None, etb=None):
710 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
714 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
711 if etb is None:
715 if etb is None:
712 self.handler()
716 self.handler()
713 else:
717 else:
714 self.handler((etype, evalue, etb))
718 self.handler((etype, evalue, etb))
715 self.debugger()
719 self.debugger()
716
720
717 #----------------------------------------------------------------------------
721 #----------------------------------------------------------------------------
718 class FormattedTB(VerboseTB,ListTB):
722 class FormattedTB(VerboseTB,ListTB):
719 """Subclass ListTB but allow calling with a traceback.
723 """Subclass ListTB but allow calling with a traceback.
720
724
721 It can thus be used as a sys.excepthook for Python > 2.1.
725 It can thus be used as a sys.excepthook for Python > 2.1.
722
726
723 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
727 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
724
728
725 Allows a tb_offset to be specified. This is useful for situations where
729 Allows a tb_offset to be specified. This is useful for situations where
726 one needs to remove a number of topmost frames from the traceback (such as
730 one needs to remove a number of topmost frames from the traceback (such as
727 occurs with python programs that themselves execute other python code,
731 occurs with python programs that themselves execute other python code,
728 like Python shells). """
732 like Python shells). """
729
733
730 def __init__(self, mode = 'Plain', color_scheme='Linux',
734 def __init__(self, mode = 'Plain', color_scheme='Linux',
731 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
735 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
732
736
733 # NEVER change the order of this list. Put new modes at the end:
737 # NEVER change the order of this list. Put new modes at the end:
734 self.valid_modes = ['Plain','Context','Verbose']
738 self.valid_modes = ['Plain','Context','Verbose']
735 self.verbose_modes = self.valid_modes[1:3]
739 self.verbose_modes = self.valid_modes[1:3]
736
740
737 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
741 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
738 call_pdb=call_pdb,include_vars=include_vars)
742 call_pdb=call_pdb,include_vars=include_vars)
739 self.set_mode(mode)
743 self.set_mode(mode)
740
744
741 def _extract_tb(self,tb):
745 def _extract_tb(self,tb):
742 if tb:
746 if tb:
743 return traceback.extract_tb(tb)
747 return traceback.extract_tb(tb)
744 else:
748 else:
745 return None
749 return None
746
750
747 def text(self, etype, value, tb,context=5,mode=None):
751 def text(self, etype, value, tb,context=5,mode=None):
748 """Return formatted traceback.
752 """Return formatted traceback.
749
753
750 If the optional mode parameter is given, it overrides the current
754 If the optional mode parameter is given, it overrides the current
751 mode."""
755 mode."""
752
756
753 if mode is None:
757 if mode is None:
754 mode = self.mode
758 mode = self.mode
755 if mode in self.verbose_modes:
759 if mode in self.verbose_modes:
756 # verbose modes need a full traceback
760 # verbose modes need a full traceback
757 return VerboseTB.text(self,etype, value, tb,context=5)
761 return VerboseTB.text(self,etype, value, tb,context=5)
758 else:
762 else:
759 # We must check the source cache because otherwise we can print
763 # We must check the source cache because otherwise we can print
760 # out-of-date source code.
764 # out-of-date source code.
761 linecache.checkcache()
765 linecache.checkcache()
762 # Now we can extract and format the exception
766 # Now we can extract and format the exception
763 elist = self._extract_tb(tb)
767 elist = self._extract_tb(tb)
764 if len(elist) > self.tb_offset:
768 if len(elist) > self.tb_offset:
765 del elist[:self.tb_offset]
769 del elist[:self.tb_offset]
766 return ListTB.text(self,etype,value,elist)
770 return ListTB.text(self,etype,value,elist)
767
771
768 def set_mode(self,mode=None):
772 def set_mode(self,mode=None):
769 """Switch to the desired mode.
773 """Switch to the desired mode.
770
774
771 If mode is not specified, cycles through the available modes."""
775 If mode is not specified, cycles through the available modes."""
772
776
773 if not mode:
777 if not mode:
774 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
778 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
775 len(self.valid_modes)
779 len(self.valid_modes)
776 self.mode = self.valid_modes[new_idx]
780 self.mode = self.valid_modes[new_idx]
777 elif mode not in self.valid_modes:
781 elif mode not in self.valid_modes:
778 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
782 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
779 'Valid modes: '+str(self.valid_modes)
783 'Valid modes: '+str(self.valid_modes)
780 else:
784 else:
781 self.mode = mode
785 self.mode = mode
782 # include variable details only in 'Verbose' mode
786 # include variable details only in 'Verbose' mode
783 self.include_vars = (self.mode == self.valid_modes[2])
787 self.include_vars = (self.mode == self.valid_modes[2])
784
788
785 # some convenient shorcuts
789 # some convenient shorcuts
786 def plain(self):
790 def plain(self):
787 self.set_mode(self.valid_modes[0])
791 self.set_mode(self.valid_modes[0])
788
792
789 def context(self):
793 def context(self):
790 self.set_mode(self.valid_modes[1])
794 self.set_mode(self.valid_modes[1])
791
795
792 def verbose(self):
796 def verbose(self):
793 self.set_mode(self.valid_modes[2])
797 self.set_mode(self.valid_modes[2])
794
798
795 #----------------------------------------------------------------------------
799 #----------------------------------------------------------------------------
796 class AutoFormattedTB(FormattedTB):
800 class AutoFormattedTB(FormattedTB):
797 """A traceback printer which can be called on the fly.
801 """A traceback printer which can be called on the fly.
798
802
799 It will find out about exceptions by itself.
803 It will find out about exceptions by itself.
800
804
801 A brief example:
805 A brief example:
802
806
803 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
807 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
804 try:
808 try:
805 ...
809 ...
806 except:
810 except:
807 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
811 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
808 """
812 """
809 def __call__(self,etype=None,evalue=None,etb=None,
813 def __call__(self,etype=None,evalue=None,etb=None,
810 out=None,tb_offset=None):
814 out=None,tb_offset=None):
811 """Print out a formatted exception traceback.
815 """Print out a formatted exception traceback.
812
816
813 Optional arguments:
817 Optional arguments:
814 - out: an open file-like object to direct output to.
818 - out: an open file-like object to direct output to.
815
819
816 - tb_offset: the number of frames to skip over in the stack, on a
820 - tb_offset: the number of frames to skip over in the stack, on a
817 per-call basis (this overrides temporarily the instance's tb_offset
821 per-call basis (this overrides temporarily the instance's tb_offset
818 given at initialization time. """
822 given at initialization time. """
819
823
820 if out is None:
824 if out is None:
821 out = Term.cerr
825 out = Term.cerr
822 if tb_offset is not None:
826 if tb_offset is not None:
823 tb_offset, self.tb_offset = self.tb_offset, tb_offset
827 tb_offset, self.tb_offset = self.tb_offset, tb_offset
824 print >> out, self.text(etype, evalue, etb)
828 print >> out, self.text(etype, evalue, etb)
825 self.tb_offset = tb_offset
829 self.tb_offset = tb_offset
826 else:
830 else:
827 print >> out, self.text(etype, evalue, etb)
831 print >> out, self.text(etype, evalue, etb)
828 self.debugger()
832 self.debugger()
829
833
830 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
834 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
831 if etype is None:
835 if etype is None:
832 etype,value,tb = sys.exc_info()
836 etype,value,tb = sys.exc_info()
833 self.tb = tb
837 self.tb = tb
834 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
838 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
835
839
836 #---------------------------------------------------------------------------
840 #---------------------------------------------------------------------------
837 # A simple class to preserve Nathan's original functionality.
841 # A simple class to preserve Nathan's original functionality.
838 class ColorTB(FormattedTB):
842 class ColorTB(FormattedTB):
839 """Shorthand to initialize a FormattedTB in Linux colors mode."""
843 """Shorthand to initialize a FormattedTB in Linux colors mode."""
840 def __init__(self,color_scheme='Linux',call_pdb=0):
844 def __init__(self,color_scheme='Linux',call_pdb=0):
841 FormattedTB.__init__(self,color_scheme=color_scheme,
845 FormattedTB.__init__(self,color_scheme=color_scheme,
842 call_pdb=call_pdb)
846 call_pdb=call_pdb)
843
847
844 #----------------------------------------------------------------------------
848 #----------------------------------------------------------------------------
845 # module testing (minimal)
849 # module testing (minimal)
846 if __name__ == "__main__":
850 if __name__ == "__main__":
847 def spam(c, (d, e)):
851 def spam(c, (d, e)):
848 x = c + d
852 x = c + d
849 y = c * d
853 y = c * d
850 foo(x, y)
854 foo(x, y)
851
855
852 def foo(a, b, bar=1):
856 def foo(a, b, bar=1):
853 eggs(a, b + bar)
857 eggs(a, b + bar)
854
858
855 def eggs(f, g, z=globals()):
859 def eggs(f, g, z=globals()):
856 h = f + g
860 h = f + g
857 i = f - g
861 i = f - g
858 return h / i
862 return h / i
859
863
860 print ''
864 print ''
861 print '*** Before ***'
865 print '*** Before ***'
862 try:
866 try:
863 print spam(1, (2, 3))
867 print spam(1, (2, 3))
864 except:
868 except:
865 traceback.print_exc()
869 traceback.print_exc()
866 print ''
870 print ''
867
871
868 handler = ColorTB()
872 handler = ColorTB()
869 print '*** ColorTB ***'
873 print '*** ColorTB ***'
870 try:
874 try:
871 print spam(1, (2, 3))
875 print spam(1, (2, 3))
872 except:
876 except:
873 apply(handler, sys.exc_info() )
877 apply(handler, sys.exc_info() )
874 print ''
878 print ''
875
879
876 handler = VerboseTB()
880 handler = VerboseTB()
877 print '*** VerboseTB ***'
881 print '*** VerboseTB ***'
878 try:
882 try:
879 print spam(1, (2, 3))
883 print spam(1, (2, 3))
880 except:
884 except:
881 apply(handler, sys.exc_info() )
885 apply(handler, sys.exc_info() )
882 print ''
886 print ''
883
887
@@ -1,5735 +1,5753 b''
1 2006-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
2
3 * IPython/irunner.py (InteractiveRunner.run_source): small fixes
4 to help in handling doctests. irunner is now pretty useful for
5 running standalone scripts and simulate a full interactive session
6 in a format that can be then pasted as a doctest.
7
8 * IPython/iplib.py (InteractiveShell.__init__): Install exit/quit
9 on top of the default (useless) ones. This also fixes the nasty
10 way in which 2.5's Quitter() exits (reverted [1785]).
11
12 * IPython/Debugger.py (Pdb.__init__): Fix ipdb to work with python
13 2.5.
14
15 * IPython/ultraTB.py (TBTools.set_colors): Make sure that ipdb
16 color scheme is updated as well when color scheme is changed
17 interactively.
18
1 2006-09-27 Ville Vainio <vivainio@gmail.com>
19 2006-09-27 Ville Vainio <vivainio@gmail.com>
2
20
3 * iplib.py (raw_input): python 2.5 closes stdin on quit -> avoid
21 * iplib.py (raw_input): python 2.5 closes stdin on quit -> avoid
4 infinite loop and just exit. It's a hack, but will do for a while.
22 infinite loop and just exit. It's a hack, but will do for a while.
5
23
6 2006-08-25 Walter Doerwald <walter@livinglogic.de>
24 2006-08-25 Walter Doerwald <walter@livinglogic.de>
7
25
8 * IPython/Extensions/ipipe.py (ils): Add arguments dirs and files to
26 * IPython/Extensions/ipipe.py (ils): Add arguments dirs and files to
9 the constructor, this makes it possible to get a list of only directories
27 the constructor, this makes it possible to get a list of only directories
10 or only files.
28 or only files.
11
29
12 2006-08-12 Ville Vainio <vivainio@gmail.com>
30 2006-08-12 Ville Vainio <vivainio@gmail.com>
13
31
14 * Fakemodule.py, OInspect.py: Reverted 2006-08-11 mods,
32 * Fakemodule.py, OInspect.py: Reverted 2006-08-11 mods,
15 they broke unittest
33 they broke unittest
16
34
17 2006-08-11 Ville Vainio <vivainio@gmail.com>
35 2006-08-11 Ville Vainio <vivainio@gmail.com>
18
36
19 * Fakemodule.py, OInspect.py: remove 2006-08-09 monkepatch
37 * Fakemodule.py, OInspect.py: remove 2006-08-09 monkepatch
20 by resolving issue properly, i.e. by inheriting FakeModule
38 by resolving issue properly, i.e. by inheriting FakeModule
21 from types.ModuleType. Pickling ipython interactive data
39 from types.ModuleType. Pickling ipython interactive data
22 should still work as usual (testing appreciated).
40 should still work as usual (testing appreciated).
23
41
24 2006-08-09 Fernando Perez <Fernando.Perez@colorado.edu>
42 2006-08-09 Fernando Perez <Fernando.Perez@colorado.edu>
25
43
26 * IPython/OInspect.py: monkeypatch inspect from the stdlib if
44 * IPython/OInspect.py: monkeypatch inspect from the stdlib if
27 running under python 2.3 with code from 2.4 to fix a bug with
45 running under python 2.3 with code from 2.4 to fix a bug with
28 help(). Reported by the Debian maintainers, Norbert Tretkowski
46 help(). Reported by the Debian maintainers, Norbert Tretkowski
29 <norbert-AT-tretkowski.de> and Alexandre Fayolle
47 <norbert-AT-tretkowski.de> and Alexandre Fayolle
30 <afayolle-AT-debian.org>.
48 <afayolle-AT-debian.org>.
31
49
32 2006-08-04 Walter Doerwald <walter@livinglogic.de>
50 2006-08-04 Walter Doerwald <walter@livinglogic.de>
33
51
34 * IPython/Extensions/ibrowse.py: Fixed the help message in the footer
52 * IPython/Extensions/ibrowse.py: Fixed the help message in the footer
35 (which was displaying "quit" twice).
53 (which was displaying "quit" twice).
36
54
37 2006-07-28 Walter Doerwald <walter@livinglogic.de>
55 2006-07-28 Walter Doerwald <walter@livinglogic.de>
38
56
39 * IPython/Extensions/ipipe.py: Fix isort.__iter__() (was still using
57 * IPython/Extensions/ipipe.py: Fix isort.__iter__() (was still using
40 the mode argument).
58 the mode argument).
41
59
42 2006-07-27 Walter Doerwald <walter@livinglogic.de>
60 2006-07-27 Walter Doerwald <walter@livinglogic.de>
43
61
44 * IPython/Extensions/ipipe.py: Fix getglobals() if we're
62 * IPython/Extensions/ipipe.py: Fix getglobals() if we're
45 not running under IPython.
63 not running under IPython.
46
64
47 * IPython/Extensions/ipipe.py: Rename XAttr to AttributeDetail
65 * IPython/Extensions/ipipe.py: Rename XAttr to AttributeDetail
48 and make it iterable (iterating over the attribute itself). Add two new
66 and make it iterable (iterating over the attribute itself). Add two new
49 magic strings for __xattrs__(): If the string starts with "-", the attribute
67 magic strings for __xattrs__(): If the string starts with "-", the attribute
50 will not be displayed in ibrowse's detail view (but it can still be
68 will not be displayed in ibrowse's detail view (but it can still be
51 iterated over). This makes it possible to add attributes that are large
69 iterated over). This makes it possible to add attributes that are large
52 lists or generator methods to the detail view. Replace magic attribute names
70 lists or generator methods to the detail view. Replace magic attribute names
53 and _attrname() and _getattr() with "descriptors": For each type of magic
71 and _attrname() and _getattr() with "descriptors": For each type of magic
54 attribute name there's a subclass of Descriptor: None -> SelfDescriptor();
72 attribute name there's a subclass of Descriptor: None -> SelfDescriptor();
55 "foo" -> AttributeDescriptor("foo"); "foo()" -> MethodDescriptor("foo");
73 "foo" -> AttributeDescriptor("foo"); "foo()" -> MethodDescriptor("foo");
56 "-foo" -> IterAttributeDescriptor("foo"); "-foo()" -> IterMethodDescriptor("foo");
74 "-foo" -> IterAttributeDescriptor("foo"); "-foo()" -> IterMethodDescriptor("foo");
57 foo() -> FunctionDescriptor(foo). Magic strings returned from __xattrs__()
75 foo() -> FunctionDescriptor(foo). Magic strings returned from __xattrs__()
58 are still supported.
76 are still supported.
59
77
60 * IPython/Extensions/ibrowse.py: If fetching the next row from the input
78 * IPython/Extensions/ibrowse.py: If fetching the next row from the input
61 fails in ibrowse.fetch(), the exception object is added as the last item
79 fails in ibrowse.fetch(), the exception object is added as the last item
62 and item fetching is canceled. This prevents ibrowse from aborting if e.g.
80 and item fetching is canceled. This prevents ibrowse from aborting if e.g.
63 a generator throws an exception midway through execution.
81 a generator throws an exception midway through execution.
64
82
65 * IPython/Extensions/ipipe.py: Turn ifile's properties mimetype and
83 * IPython/Extensions/ipipe.py: Turn ifile's properties mimetype and
66 encoding into methods.
84 encoding into methods.
67
85
68 2006-07-26 Ville Vainio <vivainio@gmail.com>
86 2006-07-26 Ville Vainio <vivainio@gmail.com>
69
87
70 * iplib.py: history now stores multiline input as single
88 * iplib.py: history now stores multiline input as single
71 history entries. Patch by Jorgen Cederlof.
89 history entries. Patch by Jorgen Cederlof.
72
90
73 2006-07-18 Walter Doerwald <walter@livinglogic.de>
91 2006-07-18 Walter Doerwald <walter@livinglogic.de>
74
92
75 * IPython/Extensions/ibrowse.py: Make cursor visible over
93 * IPython/Extensions/ibrowse.py: Make cursor visible over
76 non existing attributes.
94 non existing attributes.
77
95
78 2006-07-14 Walter Doerwald <walter@livinglogic.de>
96 2006-07-14 Walter Doerwald <walter@livinglogic.de>
79
97
80 * IPython/Extensions/ipipe.py (ix): Use os.popen4() so that the
98 * IPython/Extensions/ipipe.py (ix): Use os.popen4() so that the
81 error output of the running command doesn't mess up the screen.
99 error output of the running command doesn't mess up the screen.
82
100
83 2006-07-13 Walter Doerwald <walter@livinglogic.de>
101 2006-07-13 Walter Doerwald <walter@livinglogic.de>
84
102
85 * IPython/Extensions/ipipe.py (isort): Make isort usable without
103 * IPython/Extensions/ipipe.py (isort): Make isort usable without
86 argument. This sorts the items themselves.
104 argument. This sorts the items themselves.
87
105
88 2006-07-12 Walter Doerwald <walter@livinglogic.de>
106 2006-07-12 Walter Doerwald <walter@livinglogic.de>
89
107
90 * IPython/Extensions/ipipe.py (eval, ifilter, isort, ieval):
108 * IPython/Extensions/ipipe.py (eval, ifilter, isort, ieval):
91 Compile expression strings into code objects. This should speed
109 Compile expression strings into code objects. This should speed
92 up ifilter and friends somewhat.
110 up ifilter and friends somewhat.
93
111
94 2006-07-08 Ville Vainio <vivainio@gmail.com>
112 2006-07-08 Ville Vainio <vivainio@gmail.com>
95
113
96 * Magic.py: %cpaste now strips > from the beginning of lines
114 * Magic.py: %cpaste now strips > from the beginning of lines
97 to ease pasting quoted code from emails. Contributed by
115 to ease pasting quoted code from emails. Contributed by
98 Stefan van der Walt.
116 Stefan van der Walt.
99
117
100 2006-06-29 Ville Vainio <vivainio@gmail.com>
118 2006-06-29 Ville Vainio <vivainio@gmail.com>
101
119
102 * ipmaker.py, Shell.py: qt4agg matplotlib backend support for pylab
120 * ipmaker.py, Shell.py: qt4agg matplotlib backend support for pylab
103 mode, patch contributed by Darren Dale. NEEDS TESTING!
121 mode, patch contributed by Darren Dale. NEEDS TESTING!
104
122
105 2006-06-28 Walter Doerwald <walter@livinglogic.de>
123 2006-06-28 Walter Doerwald <walter@livinglogic.de>
106
124
107 * IPython/Extensions/ibrowse.py: Give the ibrowse cursor row
125 * IPython/Extensions/ibrowse.py: Give the ibrowse cursor row
108 a blue background. Fix fetching new display rows when the browser
126 a blue background. Fix fetching new display rows when the browser
109 scrolls more than a screenful (e.g. by using the goto command).
127 scrolls more than a screenful (e.g. by using the goto command).
110
128
111 2006-06-27 Ville Vainio <vivainio@gmail.com>
129 2006-06-27 Ville Vainio <vivainio@gmail.com>
112
130
113 * Magic.py (_inspect, _ofind) Apply David Huard's
131 * Magic.py (_inspect, _ofind) Apply David Huard's
114 patch for displaying the correct docstring for 'property'
132 patch for displaying the correct docstring for 'property'
115 attributes.
133 attributes.
116
134
117 2006-06-23 Walter Doerwald <walter@livinglogic.de>
135 2006-06-23 Walter Doerwald <walter@livinglogic.de>
118
136
119 * IPython/Extensions/ibrowse.py: Put the documentation of the keyboard
137 * IPython/Extensions/ibrowse.py: Put the documentation of the keyboard
120 commands into the methods implementing them.
138 commands into the methods implementing them.
121
139
122 2006-06-22 Fernando Perez <Fernando.Perez@colorado.edu>
140 2006-06-22 Fernando Perez <Fernando.Perez@colorado.edu>
123
141
124 * ipython.el (ipython-indentation-hook): cleanup patch, submitted
142 * ipython.el (ipython-indentation-hook): cleanup patch, submitted
125 by Kov Chai <tchaikov-AT-gmail.com>. He notes that the original
143 by Kov Chai <tchaikov-AT-gmail.com>. He notes that the original
126 autoindent support was authored by Jin Liu.
144 autoindent support was authored by Jin Liu.
127
145
128 2006-06-22 Walter Doerwald <walter@livinglogic.de>
146 2006-06-22 Walter Doerwald <walter@livinglogic.de>
129
147
130 * IPython/Extensions/ibrowse.py: Replace the plain dictionaries used
148 * IPython/Extensions/ibrowse.py: Replace the plain dictionaries used
131 for keymaps with a custom class that simplifies handling.
149 for keymaps with a custom class that simplifies handling.
132
150
133 2006-06-19 Walter Doerwald <walter@livinglogic.de>
151 2006-06-19 Walter Doerwald <walter@livinglogic.de>
134
152
135 * IPython/Extensions/ibrowse.py: ibrowse now properly handles terminal
153 * IPython/Extensions/ibrowse.py: ibrowse now properly handles terminal
136 resizing. This requires Python 2.5 to work.
154 resizing. This requires Python 2.5 to work.
137
155
138 2006-06-16 Walter Doerwald <walter@livinglogic.de>
156 2006-06-16 Walter Doerwald <walter@livinglogic.de>
139
157
140 * IPython/Extensions/ibrowse.py: Add two new commands to
158 * IPython/Extensions/ibrowse.py: Add two new commands to
141 ibrowse: "hideattr" (mapped to "h") hides the attribute under
159 ibrowse: "hideattr" (mapped to "h") hides the attribute under
142 the cursor. "unhiderattrs" (mapped to "H") reveals all hidden
160 the cursor. "unhiderattrs" (mapped to "H") reveals all hidden
143 attributes again. Remapped the help command to "?". Display
161 attributes again. Remapped the help command to "?". Display
144 keycodes in the range 0x01-0x1F as CTRL-xx. Add CTRL-a and CTRL-e
162 keycodes in the range 0x01-0x1F as CTRL-xx. Add CTRL-a and CTRL-e
145 as keys for the "home" and "end" commands. Add three new commands
163 as keys for the "home" and "end" commands. Add three new commands
146 to the input mode for "find" and friends: "delend" (CTRL-K)
164 to the input mode for "find" and friends: "delend" (CTRL-K)
147 deletes to the end of line. "incsearchup" searches upwards in the
165 deletes to the end of line. "incsearchup" searches upwards in the
148 command history for an input that starts with the text before the cursor.
166 command history for an input that starts with the text before the cursor.
149 "incsearchdown" does the same downwards. Removed a bogus mapping of
167 "incsearchdown" does the same downwards. Removed a bogus mapping of
150 the x key to "delete".
168 the x key to "delete".
151
169
152 2006-06-15 Ville Vainio <vivainio@gmail.com>
170 2006-06-15 Ville Vainio <vivainio@gmail.com>
153
171
154 * iplib.py, hooks.py: Added new generate_prompt hook that can be
172 * iplib.py, hooks.py: Added new generate_prompt hook that can be
155 used to create prompts dynamically, instead of the "old" way of
173 used to create prompts dynamically, instead of the "old" way of
156 assigning "magic" strings to prompt_in1 and prompt_in2. The old
174 assigning "magic" strings to prompt_in1 and prompt_in2. The old
157 way still works (it's invoked by the default hook), of course.
175 way still works (it's invoked by the default hook), of course.
158
176
159 * Prompts.py: added generate_output_prompt hook for altering output
177 * Prompts.py: added generate_output_prompt hook for altering output
160 prompt
178 prompt
161
179
162 * Release.py: Changed version string to 0.7.3.svn.
180 * Release.py: Changed version string to 0.7.3.svn.
163
181
164 2006-06-15 Walter Doerwald <walter@livinglogic.de>
182 2006-06-15 Walter Doerwald <walter@livinglogic.de>
165
183
166 * IPython/Extensions/ibrowse.py: Change _BrowserLevel.moveto() so that
184 * IPython/Extensions/ibrowse.py: Change _BrowserLevel.moveto() so that
167 the call to fetch() always tries to fetch enough data for at least one
185 the call to fetch() always tries to fetch enough data for at least one
168 full screen. This makes it possible to simply call moveto(0,0,True) in
186 full screen. This makes it possible to simply call moveto(0,0,True) in
169 the constructor. Fix typos and removed the obsolete goto attribute.
187 the constructor. Fix typos and removed the obsolete goto attribute.
170
188
171 2006-06-12 Ville Vainio <vivainio@gmail.com>
189 2006-06-12 Ville Vainio <vivainio@gmail.com>
172
190
173 * ipy_profile_sh.py: applied Krisha Mohan Gundu's patch for
191 * ipy_profile_sh.py: applied Krisha Mohan Gundu's patch for
174 allowing $variable interpolation within multiline statements,
192 allowing $variable interpolation within multiline statements,
175 though so far only with "sh" profile for a testing period.
193 though so far only with "sh" profile for a testing period.
176 The patch also enables splitting long commands with \ but it
194 The patch also enables splitting long commands with \ but it
177 doesn't work properly yet.
195 doesn't work properly yet.
178
196
179 2006-06-12 Walter Doerwald <walter@livinglogic.de>
197 2006-06-12 Walter Doerwald <walter@livinglogic.de>
180
198
181 * IPython/Extensions/ibrowse.py (_dodisplay): Display the length of the
199 * IPython/Extensions/ibrowse.py (_dodisplay): Display the length of the
182 input history and the position of the cursor in the input history for
200 input history and the position of the cursor in the input history for
183 the find, findbackwards and goto command.
201 the find, findbackwards and goto command.
184
202
185 2006-06-10 Walter Doerwald <walter@livinglogic.de>
203 2006-06-10 Walter Doerwald <walter@livinglogic.de>
186
204
187 * IPython/Extensions/ibrowse.py: Add a class _CommandInput that
205 * IPython/Extensions/ibrowse.py: Add a class _CommandInput that
188 implements the basic functionality of browser commands that require
206 implements the basic functionality of browser commands that require
189 input. Reimplement the goto, find and findbackwards commands as
207 input. Reimplement the goto, find and findbackwards commands as
190 subclasses of _CommandInput. Add an input history and keymaps to those
208 subclasses of _CommandInput. Add an input history and keymaps to those
191 commands. Add "\r" as a keyboard shortcut for the enterdefault and
209 commands. Add "\r" as a keyboard shortcut for the enterdefault and
192 execute commands.
210 execute commands.
193
211
194 2006-06-07 Ville Vainio <vivainio@gmail.com>
212 2006-06-07 Ville Vainio <vivainio@gmail.com>
195
213
196 * iplib.py: ipython mybatch.ipy exits ipython immediately after
214 * iplib.py: ipython mybatch.ipy exits ipython immediately after
197 running the batch files instead of leaving the session open.
215 running the batch files instead of leaving the session open.
198
216
199 2006-06-07 Fernando Perez <Fernando.Perez@colorado.edu>
217 2006-06-07 Fernando Perez <Fernando.Perez@colorado.edu>
200
218
201 * IPython/iplib.py (InteractiveShell.__init__): update BSD fix, as
219 * IPython/iplib.py (InteractiveShell.__init__): update BSD fix, as
202 the original fix was incomplete. Patch submitted by W. Maier.
220 the original fix was incomplete. Patch submitted by W. Maier.
203
221
204 2006-06-07 Ville Vainio <vivainio@gmail.com>
222 2006-06-07 Ville Vainio <vivainio@gmail.com>
205
223
206 * iplib.py,Magic.py, ipmaker.py (magic_rehashx):
224 * iplib.py,Magic.py, ipmaker.py (magic_rehashx):
207 Confirmation prompts can be supressed by 'quiet' option.
225 Confirmation prompts can be supressed by 'quiet' option.
208 _ip.options.quiet = 1 means "assume yes for all yes/no queries".
226 _ip.options.quiet = 1 means "assume yes for all yes/no queries".
209
227
210 2006-06-06 *** Released version 0.7.2
228 2006-06-06 *** Released version 0.7.2
211
229
212 2006-06-06 Fernando Perez <Fernando.Perez@colorado.edu>
230 2006-06-06 Fernando Perez <Fernando.Perez@colorado.edu>
213
231
214 * IPython/Release.py (version): Made 0.7.2 final for release.
232 * IPython/Release.py (version): Made 0.7.2 final for release.
215 Repo tagged and release cut.
233 Repo tagged and release cut.
216
234
217 2006-06-05 Ville Vainio <vivainio@gmail.com>
235 2006-06-05 Ville Vainio <vivainio@gmail.com>
218
236
219 * Magic.py (magic_rehashx): Honor no_alias list earlier in
237 * Magic.py (magic_rehashx): Honor no_alias list earlier in
220 %rehashx, to avoid clobbering builtins in ipy_profile_sh.py
238 %rehashx, to avoid clobbering builtins in ipy_profile_sh.py
221
239
222 * upgrade_dir.py: try import 'path' module a bit harder
240 * upgrade_dir.py: try import 'path' module a bit harder
223 (for %upgrade)
241 (for %upgrade)
224
242
225 2006-06-03 Fernando Perez <Fernando.Perez@colorado.edu>
243 2006-06-03 Fernando Perez <Fernando.Perez@colorado.edu>
226
244
227 * IPython/genutils.py (ask_yes_no): treat EOF as a default answer
245 * IPython/genutils.py (ask_yes_no): treat EOF as a default answer
228 instead of looping 20 times.
246 instead of looping 20 times.
229
247
230 * IPython/ipmaker.py (make_IPython): honor -ipythondir flag
248 * IPython/ipmaker.py (make_IPython): honor -ipythondir flag
231 correctly at initialization time. Bug reported by Krishna Mohan
249 correctly at initialization time. Bug reported by Krishna Mohan
232 Gundu <gkmohan-AT-gmail.com> on the user list.
250 Gundu <gkmohan-AT-gmail.com> on the user list.
233
251
234 * IPython/Release.py (version): Mark 0.7.2 version to start
252 * IPython/Release.py (version): Mark 0.7.2 version to start
235 testing for release on 06/06.
253 testing for release on 06/06.
236
254
237 2006-05-31 Fernando Perez <Fernando.Perez@colorado.edu>
255 2006-05-31 Fernando Perez <Fernando.Perez@colorado.edu>
238
256
239 * scripts/irunner: thin script interface so users don't have to
257 * scripts/irunner: thin script interface so users don't have to
240 find the module and call it as an executable, since modules rarely
258 find the module and call it as an executable, since modules rarely
241 live in people's PATH.
259 live in people's PATH.
242
260
243 * IPython/irunner.py (InteractiveRunner.__init__): added
261 * IPython/irunner.py (InteractiveRunner.__init__): added
244 delaybeforesend attribute to control delays with newer versions of
262 delaybeforesend attribute to control delays with newer versions of
245 pexpect. Thanks to detailed help from pexpect's author, Noah
263 pexpect. Thanks to detailed help from pexpect's author, Noah
246 Spurrier <noah-AT-noah.org>. Noted how to use the SAGE runner
264 Spurrier <noah-AT-noah.org>. Noted how to use the SAGE runner
247 correctly (it works in NoColor mode).
265 correctly (it works in NoColor mode).
248
266
249 * IPython/iplib.py (handle_normal): fix nasty crash reported on
267 * IPython/iplib.py (handle_normal): fix nasty crash reported on
250 SAGE list, from improper log() calls.
268 SAGE list, from improper log() calls.
251
269
252 2006-05-31 Ville Vainio <vivainio@gmail.com>
270 2006-05-31 Ville Vainio <vivainio@gmail.com>
253
271
254 * upgrade_dir.py, Magic.py (magic_upgrade): call upgrade_dir
272 * upgrade_dir.py, Magic.py (magic_upgrade): call upgrade_dir
255 with args in parens to work correctly with dirs that have spaces.
273 with args in parens to work correctly with dirs that have spaces.
256
274
257 2006-05-30 Fernando Perez <Fernando.Perez@colorado.edu>
275 2006-05-30 Fernando Perez <Fernando.Perez@colorado.edu>
258
276
259 * IPython/Logger.py (Logger.logstart): add option to log raw input
277 * IPython/Logger.py (Logger.logstart): add option to log raw input
260 instead of the processed one. A -r flag was added to the
278 instead of the processed one. A -r flag was added to the
261 %logstart magic used for controlling logging.
279 %logstart magic used for controlling logging.
262
280
263 2006-05-29 Fernando Perez <Fernando.Perez@colorado.edu>
281 2006-05-29 Fernando Perez <Fernando.Perez@colorado.edu>
264
282
265 * IPython/iplib.py (InteractiveShell.__init__): add check for the
283 * IPython/iplib.py (InteractiveShell.__init__): add check for the
266 *BSDs to omit --color from all 'ls' aliases, since *BSD ls doesn't
284 *BSDs to omit --color from all 'ls' aliases, since *BSD ls doesn't
267 recognize the option. After a bug report by Will Maier. This
285 recognize the option. After a bug report by Will Maier. This
268 closes #64 (will do it after confirmation from W. Maier).
286 closes #64 (will do it after confirmation from W. Maier).
269
287
270 * IPython/irunner.py: New module to run scripts as if manually
288 * IPython/irunner.py: New module to run scripts as if manually
271 typed into an interactive environment, based on pexpect. After a
289 typed into an interactive environment, based on pexpect. After a
272 submission by Ken Schutte <kschutte-AT-csail.mit.edu> on the
290 submission by Ken Schutte <kschutte-AT-csail.mit.edu> on the
273 ipython-user list. Simple unittests in the tests/ directory.
291 ipython-user list. Simple unittests in the tests/ directory.
274
292
275 * tools/release: add Will Maier, OpenBSD port maintainer, to
293 * tools/release: add Will Maier, OpenBSD port maintainer, to
276 recepients list. We are now officially part of the OpenBSD ports:
294 recepients list. We are now officially part of the OpenBSD ports:
277 http://www.openbsd.org/ports.html ! Many thanks to Will for the
295 http://www.openbsd.org/ports.html ! Many thanks to Will for the
278 work.
296 work.
279
297
280 2006-05-26 Fernando Perez <Fernando.Perez@colorado.edu>
298 2006-05-26 Fernando Perez <Fernando.Perez@colorado.edu>
281
299
282 * IPython/ipmaker.py (make_IPython): modify sys.argv fix (below)
300 * IPython/ipmaker.py (make_IPython): modify sys.argv fix (below)
283 so that it doesn't break tkinter apps.
301 so that it doesn't break tkinter apps.
284
302
285 * IPython/iplib.py (_prefilter): fix bug where aliases would
303 * IPython/iplib.py (_prefilter): fix bug where aliases would
286 shadow variables when autocall was fully off. Reported by SAGE
304 shadow variables when autocall was fully off. Reported by SAGE
287 author William Stein.
305 author William Stein.
288
306
289 * IPython/OInspect.py (Inspector.__init__): add a flag to control
307 * IPython/OInspect.py (Inspector.__init__): add a flag to control
290 at what detail level strings are computed when foo? is requested.
308 at what detail level strings are computed when foo? is requested.
291 This allows users to ask for example that the string form of an
309 This allows users to ask for example that the string form of an
292 object is only computed when foo?? is called, or even never, by
310 object is only computed when foo?? is called, or even never, by
293 setting the object_info_string_level >= 2 in the configuration
311 setting the object_info_string_level >= 2 in the configuration
294 file. This new option has been added and documented. After a
312 file. This new option has been added and documented. After a
295 request by SAGE to be able to control the printing of very large
313 request by SAGE to be able to control the printing of very large
296 objects more easily.
314 objects more easily.
297
315
298 2006-05-25 Fernando Perez <Fernando.Perez@colorado.edu>
316 2006-05-25 Fernando Perez <Fernando.Perez@colorado.edu>
299
317
300 * IPython/ipmaker.py (make_IPython): remove the ipython call path
318 * IPython/ipmaker.py (make_IPython): remove the ipython call path
301 from sys.argv, to be 100% consistent with how Python itself works
319 from sys.argv, to be 100% consistent with how Python itself works
302 (as seen for example with python -i file.py). After a bug report
320 (as seen for example with python -i file.py). After a bug report
303 by Jeffrey Collins.
321 by Jeffrey Collins.
304
322
305 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix
323 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix
306 nasty bug which was preventing custom namespaces with -pylab,
324 nasty bug which was preventing custom namespaces with -pylab,
307 reported by M. Foord. Minor cleanup, remove old matplotlib.matlab
325 reported by M. Foord. Minor cleanup, remove old matplotlib.matlab
308 compatibility (long gone from mpl).
326 compatibility (long gone from mpl).
309
327
310 * IPython/ipapi.py (make_session): name change: create->make. We
328 * IPython/ipapi.py (make_session): name change: create->make. We
311 use make in other places (ipmaker,...), it's shorter and easier to
329 use make in other places (ipmaker,...), it's shorter and easier to
312 type and say, etc. I'm trying to clean things before 0.7.2 so
330 type and say, etc. I'm trying to clean things before 0.7.2 so
313 that I can keep things stable wrt to ipapi in the chainsaw branch.
331 that I can keep things stable wrt to ipapi in the chainsaw branch.
314
332
315 * ipython.el: fix the py-pdbtrack-input-prompt variable so that
333 * ipython.el: fix the py-pdbtrack-input-prompt variable so that
316 python-mode recognizes our debugger mode. Add support for
334 python-mode recognizes our debugger mode. Add support for
317 autoindent inside (X)emacs. After a patch sent in by Jin Liu
335 autoindent inside (X)emacs. After a patch sent in by Jin Liu
318 <m.liu.jin-AT-gmail.com> originally written by
336 <m.liu.jin-AT-gmail.com> originally written by
319 doxgen-AT-newsmth.net (with minor modifications for xemacs
337 doxgen-AT-newsmth.net (with minor modifications for xemacs
320 compatibility)
338 compatibility)
321
339
322 * IPython/Debugger.py (Pdb.format_stack_entry): fix formatting of
340 * IPython/Debugger.py (Pdb.format_stack_entry): fix formatting of
323 tracebacks when walking the stack so that the stack tracking system
341 tracebacks when walking the stack so that the stack tracking system
324 in emacs' python-mode can identify the frames correctly.
342 in emacs' python-mode can identify the frames correctly.
325
343
326 * IPython/ipmaker.py (make_IPython): make the internal (and
344 * IPython/ipmaker.py (make_IPython): make the internal (and
327 default config) autoedit_syntax value false by default. Too many
345 default config) autoedit_syntax value false by default. Too many
328 users have complained to me (both on and off-list) about problems
346 users have complained to me (both on and off-list) about problems
329 with this option being on by default, so I'm making it default to
347 with this option being on by default, so I'm making it default to
330 off. It can still be enabled by anyone via the usual mechanisms.
348 off. It can still be enabled by anyone via the usual mechanisms.
331
349
332 * IPython/completer.py (Completer.attr_matches): add support for
350 * IPython/completer.py (Completer.attr_matches): add support for
333 PyCrust-style _getAttributeNames magic method. Patch contributed
351 PyCrust-style _getAttributeNames magic method. Patch contributed
334 by <mscott-AT-goldenspud.com>. Closes #50.
352 by <mscott-AT-goldenspud.com>. Closes #50.
335
353
336 * IPython/iplib.py (InteractiveShell.__init__): remove the
354 * IPython/iplib.py (InteractiveShell.__init__): remove the
337 deletion of exit/quit from __builtin__, which can break
355 deletion of exit/quit from __builtin__, which can break
338 third-party tools like the Zope debugging console. The
356 third-party tools like the Zope debugging console. The
339 %exit/%quit magics remain. In general, it's probably a good idea
357 %exit/%quit magics remain. In general, it's probably a good idea
340 not to delete anything from __builtin__, since we never know what
358 not to delete anything from __builtin__, since we never know what
341 that will break. In any case, python now (for 2.5) will support
359 that will break. In any case, python now (for 2.5) will support
342 'real' exit/quit, so this issue is moot. Closes #55.
360 'real' exit/quit, so this issue is moot. Closes #55.
343
361
344 * IPython/genutils.py (with_obj): rename the 'with' function to
362 * IPython/genutils.py (with_obj): rename the 'with' function to
345 'withobj' to avoid incompatibilities with Python 2.5, where 'with'
363 'withobj' to avoid incompatibilities with Python 2.5, where 'with'
346 becomes a language keyword. Closes #53.
364 becomes a language keyword. Closes #53.
347
365
348 * IPython/FakeModule.py (FakeModule.__init__): add a proper
366 * IPython/FakeModule.py (FakeModule.__init__): add a proper
349 __file__ attribute to this so it fools more things into thinking
367 __file__ attribute to this so it fools more things into thinking
350 it is a real module. Closes #59.
368 it is a real module. Closes #59.
351
369
352 * IPython/Magic.py (magic_edit): add -n option to open the editor
370 * IPython/Magic.py (magic_edit): add -n option to open the editor
353 at a specific line number. After a patch by Stefan van der Walt.
371 at a specific line number. After a patch by Stefan van der Walt.
354
372
355 2006-05-23 Fernando Perez <Fernando.Perez@colorado.edu>
373 2006-05-23 Fernando Perez <Fernando.Perez@colorado.edu>
356
374
357 * IPython/iplib.py (edit_syntax_error): fix crash when for some
375 * IPython/iplib.py (edit_syntax_error): fix crash when for some
358 reason the file could not be opened. After automatic crash
376 reason the file could not be opened. After automatic crash
359 reports sent by James Graham <jgraham-AT-ast.cam.ac.uk> and
377 reports sent by James Graham <jgraham-AT-ast.cam.ac.uk> and
360 Charles Dolan <charlespatrickdolan-AT-yahoo.com>.
378 Charles Dolan <charlespatrickdolan-AT-yahoo.com>.
361 (_should_recompile): Don't fire editor if using %bg, since there
379 (_should_recompile): Don't fire editor if using %bg, since there
362 is no file in the first place. From the same report as above.
380 is no file in the first place. From the same report as above.
363 (raw_input): protect against faulty third-party prefilters. After
381 (raw_input): protect against faulty third-party prefilters. After
364 an automatic crash report sent by Dirk Laurie <dirk-AT-sun.ac.za>
382 an automatic crash report sent by Dirk Laurie <dirk-AT-sun.ac.za>
365 while running under SAGE.
383 while running under SAGE.
366
384
367 2006-05-23 Ville Vainio <vivainio@gmail.com>
385 2006-05-23 Ville Vainio <vivainio@gmail.com>
368
386
369 * ipapi.py: Stripped down ip.to_user_ns() to work only as
387 * ipapi.py: Stripped down ip.to_user_ns() to work only as
370 ip.to_user_ns("x1 y1"), which exposes vars x1 and y1. ipapi.get()
388 ip.to_user_ns("x1 y1"), which exposes vars x1 and y1. ipapi.get()
371 now returns None (again), unless dummy is specifically allowed by
389 now returns None (again), unless dummy is specifically allowed by
372 ipapi.get(allow_dummy=True).
390 ipapi.get(allow_dummy=True).
373
391
374 2006-05-18 Fernando Perez <Fernando.Perez@colorado.edu>
392 2006-05-18 Fernando Perez <Fernando.Perez@colorado.edu>
375
393
376 * IPython: remove all 2.2-compatibility objects and hacks from
394 * IPython: remove all 2.2-compatibility objects and hacks from
377 everywhere, since we only support 2.3 at this point. Docs
395 everywhere, since we only support 2.3 at this point. Docs
378 updated.
396 updated.
379
397
380 * IPython/ipapi.py (IPApi.__init__): Cleanup of all getters.
398 * IPython/ipapi.py (IPApi.__init__): Cleanup of all getters.
381 Anything requiring extra validation can be turned into a Python
399 Anything requiring extra validation can be turned into a Python
382 property in the future. I used a property for the db one b/c
400 property in the future. I used a property for the db one b/c
383 there was a nasty circularity problem with the initialization
401 there was a nasty circularity problem with the initialization
384 order, which right now I don't have time to clean up.
402 order, which right now I don't have time to clean up.
385
403
386 * IPython/Shell.py (MTInteractiveShell.runcode): Fix, I think,
404 * IPython/Shell.py (MTInteractiveShell.runcode): Fix, I think,
387 another locking bug reported by Jorgen. I'm not 100% sure though,
405 another locking bug reported by Jorgen. I'm not 100% sure though,
388 so more testing is needed...
406 so more testing is needed...
389
407
390 2006-05-17 Fernando Perez <Fernando.Perez@colorado.edu>
408 2006-05-17 Fernando Perez <Fernando.Perez@colorado.edu>
391
409
392 * IPython/ipapi.py (IPApi.to_user_ns): New function to inject
410 * IPython/ipapi.py (IPApi.to_user_ns): New function to inject
393 local variables from any routine in user code (typically executed
411 local variables from any routine in user code (typically executed
394 with %run) directly into the interactive namespace. Very useful
412 with %run) directly into the interactive namespace. Very useful
395 when doing complex debugging.
413 when doing complex debugging.
396 (IPythonNotRunning): Changed the default None object to a dummy
414 (IPythonNotRunning): Changed the default None object to a dummy
397 whose attributes can be queried as well as called without
415 whose attributes can be queried as well as called without
398 exploding, to ease writing code which works transparently both in
416 exploding, to ease writing code which works transparently both in
399 and out of ipython and uses some of this API.
417 and out of ipython and uses some of this API.
400
418
401 2006-05-16 Fernando Perez <Fernando.Perez@colorado.edu>
419 2006-05-16 Fernando Perez <Fernando.Perez@colorado.edu>
402
420
403 * IPython/hooks.py (result_display): Fix the fact that our display
421 * IPython/hooks.py (result_display): Fix the fact that our display
404 hook was using str() instead of repr(), as the default python
422 hook was using str() instead of repr(), as the default python
405 console does. This had gone unnoticed b/c it only happened if
423 console does. This had gone unnoticed b/c it only happened if
406 %Pprint was off, but the inconsistency was there.
424 %Pprint was off, but the inconsistency was there.
407
425
408 2006-05-15 Ville Vainio <vivainio@gmail.com>
426 2006-05-15 Ville Vainio <vivainio@gmail.com>
409
427
410 * Oinspect.py: Only show docstring for nonexisting/binary files
428 * Oinspect.py: Only show docstring for nonexisting/binary files
411 when doing object??, closing ticket #62
429 when doing object??, closing ticket #62
412
430
413 2006-05-13 Fernando Perez <Fernando.Perez@colorado.edu>
431 2006-05-13 Fernando Perez <Fernando.Perez@colorado.edu>
414
432
415 * IPython/Shell.py (MTInteractiveShell.runsource): Fix threading
433 * IPython/Shell.py (MTInteractiveShell.runsource): Fix threading
416 bug, closes http://www.scipy.net/roundup/ipython/issue55. A lock
434 bug, closes http://www.scipy.net/roundup/ipython/issue55. A lock
417 was being released in a routine which hadn't checked if it had
435 was being released in a routine which hadn't checked if it had
418 been the one to acquire it.
436 been the one to acquire it.
419
437
420 2006-05-07 Fernando Perez <Fernando.Perez@colorado.edu>
438 2006-05-07 Fernando Perez <Fernando.Perez@colorado.edu>
421
439
422 * IPython/Release.py (version): put out 0.7.2.rc1 for testing.
440 * IPython/Release.py (version): put out 0.7.2.rc1 for testing.
423
441
424 2006-04-11 Ville Vainio <vivainio@gmail.com>
442 2006-04-11 Ville Vainio <vivainio@gmail.com>
425
443
426 * iplib.py, ipmaker.py: .ipy extension now means "ipython batch file"
444 * iplib.py, ipmaker.py: .ipy extension now means "ipython batch file"
427 in command line. E.g. "ipython test.ipy" runs test.ipy with ipython
445 in command line. E.g. "ipython test.ipy" runs test.ipy with ipython
428 prefilters, allowing stuff like magics and aliases in the file.
446 prefilters, allowing stuff like magics and aliases in the file.
429
447
430 * Prompts.py, Extensions/clearcmd.py, ipy_system_conf.py: %clear magic
448 * Prompts.py, Extensions/clearcmd.py, ipy_system_conf.py: %clear magic
431 added. Supported now are "%clear in" and "%clear out" (clear input and
449 added. Supported now are "%clear in" and "%clear out" (clear input and
432 output history, respectively). Also fixed CachedOutput.flush to
450 output history, respectively). Also fixed CachedOutput.flush to
433 properly flush the output cache.
451 properly flush the output cache.
434
452
435 * Extensions/pspersistence.py: Fix %store to avoid "%store obj.attr"
453 * Extensions/pspersistence.py: Fix %store to avoid "%store obj.attr"
436 half-success (and fail explicitly).
454 half-success (and fail explicitly).
437
455
438 2006-03-28 Ville Vainio <vivainio@gmail.com>
456 2006-03-28 Ville Vainio <vivainio@gmail.com>
439
457
440 * iplib.py: Fix quoting of aliases so that only argless ones
458 * iplib.py: Fix quoting of aliases so that only argless ones
441 are quoted
459 are quoted
442
460
443 2006-03-28 Ville Vainio <vivainio@gmail.com>
461 2006-03-28 Ville Vainio <vivainio@gmail.com>
444
462
445 * iplib.py: Quote aliases with spaces in the name.
463 * iplib.py: Quote aliases with spaces in the name.
446 "c:\program files\blah\bin" is now legal alias target.
464 "c:\program files\blah\bin" is now legal alias target.
447
465
448 * ext_rehashdir.py: Space no longer allowed as arg
466 * ext_rehashdir.py: Space no longer allowed as arg
449 separator, since space is legal in path names.
467 separator, since space is legal in path names.
450
468
451 2006-03-16 Ville Vainio <vivainio@gmail.com>
469 2006-03-16 Ville Vainio <vivainio@gmail.com>
452
470
453 * upgrade_dir.py: Take path.py from Extensions, correcting
471 * upgrade_dir.py: Take path.py from Extensions, correcting
454 %upgrade magic
472 %upgrade magic
455
473
456 * ipmaker.py: Suggest using %upgrade if ipy_user_conf.py isn't found.
474 * ipmaker.py: Suggest using %upgrade if ipy_user_conf.py isn't found.
457
475
458 * hooks.py: Only enclose editor binary in quotes if legal and
476 * hooks.py: Only enclose editor binary in quotes if legal and
459 necessary (space in the name, and is an existing file). Fixes a bug
477 necessary (space in the name, and is an existing file). Fixes a bug
460 reported by Zachary Pincus.
478 reported by Zachary Pincus.
461
479
462 2006-03-13 Fernando Perez <Fernando.Perez@colorado.edu>
480 2006-03-13 Fernando Perez <Fernando.Perez@colorado.edu>
463
481
464 * Manual: thanks to a tip on proper color handling for Emacs, by
482 * Manual: thanks to a tip on proper color handling for Emacs, by
465 Eric J Haywiser <ejh1-AT-MIT.EDU>.
483 Eric J Haywiser <ejh1-AT-MIT.EDU>.
466
484
467 * ipython.el: close http://www.scipy.net/roundup/ipython/issue57
485 * ipython.el: close http://www.scipy.net/roundup/ipython/issue57
468 by applying the provided patch. Thanks to Liu Jin
486 by applying the provided patch. Thanks to Liu Jin
469 <m.liu.jin-AT-gmail.com> for the contribution. No problems under
487 <m.liu.jin-AT-gmail.com> for the contribution. No problems under
470 XEmacs/Linux, I'm trusting the submitter that it actually helps
488 XEmacs/Linux, I'm trusting the submitter that it actually helps
471 under win32/GNU Emacs. Will revisit if any problems are reported.
489 under win32/GNU Emacs. Will revisit if any problems are reported.
472
490
473 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
491 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
474
492
475 * IPython/Gnuplot2.py (_FileClass): update for current Gnuplot.py
493 * IPython/Gnuplot2.py (_FileClass): update for current Gnuplot.py
476 from SVN, thanks to a patch by Ryan Woodard <rywo@bas.ac.uk>.
494 from SVN, thanks to a patch by Ryan Woodard <rywo@bas.ac.uk>.
477
495
478 2006-03-12 Ville Vainio <vivainio@gmail.com>
496 2006-03-12 Ville Vainio <vivainio@gmail.com>
479
497
480 * Magic.py (magic_timeit): Added %timeit magic, contributed by
498 * Magic.py (magic_timeit): Added %timeit magic, contributed by
481 Torsten Marek.
499 Torsten Marek.
482
500
483 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
501 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
484
502
485 * IPython/Magic.py (magic_macro): fix so that the n1-n2 syntax for
503 * IPython/Magic.py (magic_macro): fix so that the n1-n2 syntax for
486 line ranges works again.
504 line ranges works again.
487
505
488 2006-03-11 Fernando Perez <Fernando.Perez@colorado.edu>
506 2006-03-11 Fernando Perez <Fernando.Perez@colorado.edu>
489
507
490 * IPython/iplib.py (showtraceback): add back sys.last_traceback
508 * IPython/iplib.py (showtraceback): add back sys.last_traceback
491 and friends, after a discussion with Zach Pincus on ipython-user.
509 and friends, after a discussion with Zach Pincus on ipython-user.
492 I'm not 100% sure, but after thinking about it quite a bit, it may
510 I'm not 100% sure, but after thinking about it quite a bit, it may
493 be OK. Testing with the multithreaded shells didn't reveal any
511 be OK. Testing with the multithreaded shells didn't reveal any
494 problems, but let's keep an eye out.
512 problems, but let's keep an eye out.
495
513
496 In the process, I fixed a few things which were calling
514 In the process, I fixed a few things which were calling
497 self.InteractiveTB() directly (like safe_execfile), which is a
515 self.InteractiveTB() directly (like safe_execfile), which is a
498 mistake: ALL exception reporting should be done by calling
516 mistake: ALL exception reporting should be done by calling
499 self.showtraceback(), which handles state and tab-completion and
517 self.showtraceback(), which handles state and tab-completion and
500 more.
518 more.
501
519
502 2006-03-01 Ville Vainio <vivainio@gmail.com>
520 2006-03-01 Ville Vainio <vivainio@gmail.com>
503
521
504 * Extensions/ipipe.py: Added Walter Doerwald's "ipipe" module.
522 * Extensions/ipipe.py: Added Walter Doerwald's "ipipe" module.
505 To use, do "from ipipe import *".
523 To use, do "from ipipe import *".
506
524
507 2006-02-24 Ville Vainio <vivainio@gmail.com>
525 2006-02-24 Ville Vainio <vivainio@gmail.com>
508
526
509 * Magic.py, upgrade_dir.py: %upgrade magic added. Does things more
527 * Magic.py, upgrade_dir.py: %upgrade magic added. Does things more
510 "cleanly" and safely than the older upgrade mechanism.
528 "cleanly" and safely than the older upgrade mechanism.
511
529
512 2006-02-21 Ville Vainio <vivainio@gmail.com>
530 2006-02-21 Ville Vainio <vivainio@gmail.com>
513
531
514 * Magic.py: %save works again.
532 * Magic.py: %save works again.
515
533
516 2006-02-15 Ville Vainio <vivainio@gmail.com>
534 2006-02-15 Ville Vainio <vivainio@gmail.com>
517
535
518 * Magic.py: %Pprint works again
536 * Magic.py: %Pprint works again
519
537
520 * Extensions/ipy_sane_defaults.py: Provide everything provided
538 * Extensions/ipy_sane_defaults.py: Provide everything provided
521 in default ipythonrc, to make it possible to have a completely empty
539 in default ipythonrc, to make it possible to have a completely empty
522 ipythonrc (and thus completely rc-file free configuration)
540 ipythonrc (and thus completely rc-file free configuration)
523
541
524 2006-02-11 Fernando Perez <Fernando.Perez@colorado.edu>
542 2006-02-11 Fernando Perez <Fernando.Perez@colorado.edu>
525
543
526 * IPython/hooks.py (editor): quote the call to the editor command,
544 * IPython/hooks.py (editor): quote the call to the editor command,
527 to allow commands with spaces in them. Problem noted by watching
545 to allow commands with spaces in them. Problem noted by watching
528 Ian Oswald's video about textpad under win32 at
546 Ian Oswald's video about textpad under win32 at
529 http://showmedo.com/videoListPage?listKey=PythonIPythonSeries
547 http://showmedo.com/videoListPage?listKey=PythonIPythonSeries
530
548
531 * IPython/UserConfig/ipythonrc: Replace @ signs with % when
549 * IPython/UserConfig/ipythonrc: Replace @ signs with % when
532 describing magics (we haven't used @ for a loong time).
550 describing magics (we haven't used @ for a loong time).
533
551
534 * IPython/ultraTB.py (VerboseTB.text.text_repr): Added patch
552 * IPython/ultraTB.py (VerboseTB.text.text_repr): Added patch
535 contributed by marienz to close
553 contributed by marienz to close
536 http://www.scipy.net/roundup/ipython/issue53.
554 http://www.scipy.net/roundup/ipython/issue53.
537
555
538 2006-02-10 Ville Vainio <vivainio@gmail.com>
556 2006-02-10 Ville Vainio <vivainio@gmail.com>
539
557
540 * genutils.py: getoutput now works in win32 too
558 * genutils.py: getoutput now works in win32 too
541
559
542 * completer.py: alias and magic completion only invoked
560 * completer.py: alias and magic completion only invoked
543 at the first "item" in the line, to avoid "cd %store"
561 at the first "item" in the line, to avoid "cd %store"
544 nonsense.
562 nonsense.
545
563
546 2006-02-09 Ville Vainio <vivainio@gmail.com>
564 2006-02-09 Ville Vainio <vivainio@gmail.com>
547
565
548 * test/*: Added a unit testing framework (finally).
566 * test/*: Added a unit testing framework (finally).
549 '%run runtests.py' to run test_*.
567 '%run runtests.py' to run test_*.
550
568
551 * ipapi.py: Exposed runlines and set_custom_exc
569 * ipapi.py: Exposed runlines and set_custom_exc
552
570
553 2006-02-07 Ville Vainio <vivainio@gmail.com>
571 2006-02-07 Ville Vainio <vivainio@gmail.com>
554
572
555 * iplib.py: don't split "f 1 2" to "f(1,2)" in autocall,
573 * iplib.py: don't split "f 1 2" to "f(1,2)" in autocall,
556 instead use "f(1 2)" as before.
574 instead use "f(1 2)" as before.
557
575
558 2006-02-05 Fernando Perez <Fernando.Perez@colorado.edu>
576 2006-02-05 Fernando Perez <Fernando.Perez@colorado.edu>
559
577
560 * IPython/demo.py (IPythonDemo): Add new classes to the demo
578 * IPython/demo.py (IPythonDemo): Add new classes to the demo
561 facilities, for demos processed by the IPython input filter
579 facilities, for demos processed by the IPython input filter
562 (IPythonDemo), and for running a script one-line-at-a-time as a
580 (IPythonDemo), and for running a script one-line-at-a-time as a
563 demo, both for pure Python (LineDemo) and for IPython-processed
581 demo, both for pure Python (LineDemo) and for IPython-processed
564 input (IPythonLineDemo). After a request by Dave Kohel, from the
582 input (IPythonLineDemo). After a request by Dave Kohel, from the
565 SAGE team.
583 SAGE team.
566 (Demo.edit): added an edit() method to the demo objects, to edit
584 (Demo.edit): added an edit() method to the demo objects, to edit
567 the in-memory copy of the last executed block.
585 the in-memory copy of the last executed block.
568
586
569 * IPython/Magic.py (magic_edit): add '-r' option for 'raw'
587 * IPython/Magic.py (magic_edit): add '-r' option for 'raw'
570 processing to %edit, %macro and %save. These commands can now be
588 processing to %edit, %macro and %save. These commands can now be
571 invoked on the unprocessed input as it was typed by the user
589 invoked on the unprocessed input as it was typed by the user
572 (without any prefilters applied). After requests by the SAGE team
590 (without any prefilters applied). After requests by the SAGE team
573 at SAGE days 2006: http://modular.ucsd.edu/sage/days1/schedule.html.
591 at SAGE days 2006: http://modular.ucsd.edu/sage/days1/schedule.html.
574
592
575 2006-02-01 Ville Vainio <vivainio@gmail.com>
593 2006-02-01 Ville Vainio <vivainio@gmail.com>
576
594
577 * setup.py, eggsetup.py: easy_install ipython==dev works
595 * setup.py, eggsetup.py: easy_install ipython==dev works
578 correctly now (on Linux)
596 correctly now (on Linux)
579
597
580 * ipy_user_conf,ipmaker: user config changes, removed spurious
598 * ipy_user_conf,ipmaker: user config changes, removed spurious
581 warnings
599 warnings
582
600
583 * iplib: if rc.banner is string, use it as is.
601 * iplib: if rc.banner is string, use it as is.
584
602
585 * Magic: %pycat accepts a string argument and pages it's contents.
603 * Magic: %pycat accepts a string argument and pages it's contents.
586
604
587
605
588 2006-01-30 Ville Vainio <vivainio@gmail.com>
606 2006-01-30 Ville Vainio <vivainio@gmail.com>
589
607
590 * pickleshare,pspersistence,ipapi,Magic: persistence overhaul.
608 * pickleshare,pspersistence,ipapi,Magic: persistence overhaul.
591 Now %store and bookmarks work through PickleShare, meaning that
609 Now %store and bookmarks work through PickleShare, meaning that
592 concurrent access is possible and all ipython sessions see the
610 concurrent access is possible and all ipython sessions see the
593 same database situation all the time, instead of snapshot of
611 same database situation all the time, instead of snapshot of
594 the situation when the session was started. Hence, %bookmark
612 the situation when the session was started. Hence, %bookmark
595 results are immediately accessible from othes sessions. The database
613 results are immediately accessible from othes sessions. The database
596 is also available for use by user extensions. See:
614 is also available for use by user extensions. See:
597 http://www.python.org/pypi/pickleshare
615 http://www.python.org/pypi/pickleshare
598
616
599 * hooks.py: Two new hooks, 'shutdown_hook' and 'late_startup_hook'.
617 * hooks.py: Two new hooks, 'shutdown_hook' and 'late_startup_hook'.
600
618
601 * aliases can now be %store'd
619 * aliases can now be %store'd
602
620
603 * path.py moved to Extensions so that pickleshare does not need
621 * path.py moved to Extensions so that pickleshare does not need
604 IPython-specific import. Extensions added to pythonpath right
622 IPython-specific import. Extensions added to pythonpath right
605 at __init__.
623 at __init__.
606
624
607 * iplib.py: ipalias deprecated/redundant; aliases are converted and
625 * iplib.py: ipalias deprecated/redundant; aliases are converted and
608 called with _ip.system and the pre-transformed command string.
626 called with _ip.system and the pre-transformed command string.
609
627
610 2006-01-29 Fernando Perez <Fernando.Perez@colorado.edu>
628 2006-01-29 Fernando Perez <Fernando.Perez@colorado.edu>
611
629
612 * IPython/iplib.py (interact): Fix that we were not catching
630 * IPython/iplib.py (interact): Fix that we were not catching
613 KeyboardInterrupt exceptions properly. I'm not quite sure why the
631 KeyboardInterrupt exceptions properly. I'm not quite sure why the
614 logic here had to change, but it's fixed now.
632 logic here had to change, but it's fixed now.
615
633
616 2006-01-29 Ville Vainio <vivainio@gmail.com>
634 2006-01-29 Ville Vainio <vivainio@gmail.com>
617
635
618 * iplib.py: Try to import pyreadline on Windows.
636 * iplib.py: Try to import pyreadline on Windows.
619
637
620 2006-01-27 Ville Vainio <vivainio@gmail.com>
638 2006-01-27 Ville Vainio <vivainio@gmail.com>
621
639
622 * iplib.py: Expose ipapi as _ip in builtin namespace.
640 * iplib.py: Expose ipapi as _ip in builtin namespace.
623 Makes ipmagic (-> _ip.magic), ipsystem (-> _ip.system)
641 Makes ipmagic (-> _ip.magic), ipsystem (-> _ip.system)
624 and ip_set_hook (-> _ip.set_hook) redundant. % and !
642 and ip_set_hook (-> _ip.set_hook) redundant. % and !
625 syntax now produce _ip.* variant of the commands.
643 syntax now produce _ip.* variant of the commands.
626
644
627 * "_ip.options().autoedit_syntax = 2" automatically throws
645 * "_ip.options().autoedit_syntax = 2" automatically throws
628 user to editor for syntax error correction without prompting.
646 user to editor for syntax error correction without prompting.
629
647
630 2006-01-27 Ville Vainio <vivainio@gmail.com>
648 2006-01-27 Ville Vainio <vivainio@gmail.com>
631
649
632 * ipmaker.py: Give "realistic" sys.argv for scripts (without
650 * ipmaker.py: Give "realistic" sys.argv for scripts (without
633 'ipython' at argv[0]) executed through command line.
651 'ipython' at argv[0]) executed through command line.
634 NOTE: this DEPRECATES calling ipython with multiple scripts
652 NOTE: this DEPRECATES calling ipython with multiple scripts
635 ("ipython a.py b.py c.py")
653 ("ipython a.py b.py c.py")
636
654
637 * iplib.py, hooks.py: Added configurable input prefilter,
655 * iplib.py, hooks.py: Added configurable input prefilter,
638 named 'input_prefilter'. See ext_rescapture.py for example
656 named 'input_prefilter'. See ext_rescapture.py for example
639 usage.
657 usage.
640
658
641 * ext_rescapture.py, Magic.py: Better system command output capture
659 * ext_rescapture.py, Magic.py: Better system command output capture
642 through 'var = !ls' (deprecates user-visible %sc). Same notation
660 through 'var = !ls' (deprecates user-visible %sc). Same notation
643 applies for magics, 'var = %alias' assigns alias list to var.
661 applies for magics, 'var = %alias' assigns alias list to var.
644
662
645 * ipapi.py: added meta() for accessing extension-usable data store.
663 * ipapi.py: added meta() for accessing extension-usable data store.
646
664
647 * iplib.py: added InteractiveShell.getapi(). New magics should be
665 * iplib.py: added InteractiveShell.getapi(). New magics should be
648 written doing self.getapi() instead of using the shell directly.
666 written doing self.getapi() instead of using the shell directly.
649
667
650 * Magic.py: %store now allows doing %store foo > ~/myfoo.txt and
668 * Magic.py: %store now allows doing %store foo > ~/myfoo.txt and
651 %store foo >> ~/myfoo.txt to store variables to files (in clean
669 %store foo >> ~/myfoo.txt to store variables to files (in clean
652 textual form, not a restorable pickle).
670 textual form, not a restorable pickle).
653
671
654 * ipmaker.py: now import ipy_profile_PROFILENAME automatically
672 * ipmaker.py: now import ipy_profile_PROFILENAME automatically
655
673
656 * usage.py, Magic.py: added %quickref
674 * usage.py, Magic.py: added %quickref
657
675
658 * iplib.py: ESC_PAREN fixes: /f 1 2 -> f(1,2), not f(1 2).
676 * iplib.py: ESC_PAREN fixes: /f 1 2 -> f(1,2), not f(1 2).
659
677
660 * GetoptErrors when invoking magics etc. with wrong args
678 * GetoptErrors when invoking magics etc. with wrong args
661 are now more helpful:
679 are now more helpful:
662 GetoptError: option -l not recognized (allowed: "qb" )
680 GetoptError: option -l not recognized (allowed: "qb" )
663
681
664 2006-01-25 Fernando Perez <Fernando.Perez@colorado.edu>
682 2006-01-25 Fernando Perez <Fernando.Perez@colorado.edu>
665
683
666 * IPython/demo.py (Demo.show): Flush stdout after each block, so
684 * IPython/demo.py (Demo.show): Flush stdout after each block, so
667 computationally intensive blocks don't appear to stall the demo.
685 computationally intensive blocks don't appear to stall the demo.
668
686
669 2006-01-24 Ville Vainio <vivainio@gmail.com>
687 2006-01-24 Ville Vainio <vivainio@gmail.com>
670
688
671 * iplib.py, hooks.py: 'result_display' hook can return a non-None
689 * iplib.py, hooks.py: 'result_display' hook can return a non-None
672 value to manipulate resulting history entry.
690 value to manipulate resulting history entry.
673
691
674 * ipapi.py: Moved TryNext here from hooks.py. Moved functions
692 * ipapi.py: Moved TryNext here from hooks.py. Moved functions
675 to instance methods of IPApi class, to make extending an embedded
693 to instance methods of IPApi class, to make extending an embedded
676 IPython feasible. See ext_rehashdir.py for example usage.
694 IPython feasible. See ext_rehashdir.py for example usage.
677
695
678 * Merged 1071-1076 from branches/0.7.1
696 * Merged 1071-1076 from branches/0.7.1
679
697
680
698
681 2006-01-23 Fernando Perez <Fernando.Perez@colorado.edu>
699 2006-01-23 Fernando Perez <Fernando.Perez@colorado.edu>
682
700
683 * tools/release (daystamp): Fix build tools to use the new
701 * tools/release (daystamp): Fix build tools to use the new
684 eggsetup.py script to build lightweight eggs.
702 eggsetup.py script to build lightweight eggs.
685
703
686 * Applied changesets 1062 and 1064 before 0.7.1 release.
704 * Applied changesets 1062 and 1064 before 0.7.1 release.
687
705
688 * IPython/Magic.py (magic_history): Add '-r' option to %hist, to
706 * IPython/Magic.py (magic_history): Add '-r' option to %hist, to
689 see the raw input history (without conversions like %ls ->
707 see the raw input history (without conversions like %ls ->
690 ipmagic("ls")). After a request from W. Stein, SAGE
708 ipmagic("ls")). After a request from W. Stein, SAGE
691 (http://modular.ucsd.edu/sage) developer. This information is
709 (http://modular.ucsd.edu/sage) developer. This information is
692 stored in the input_hist_raw attribute of the IPython instance, so
710 stored in the input_hist_raw attribute of the IPython instance, so
693 developers can access it if needed (it's an InputList instance).
711 developers can access it if needed (it's an InputList instance).
694
712
695 * Versionstring = 0.7.2.svn
713 * Versionstring = 0.7.2.svn
696
714
697 * eggsetup.py: A separate script for constructing eggs, creates
715 * eggsetup.py: A separate script for constructing eggs, creates
698 proper launch scripts even on Windows (an .exe file in
716 proper launch scripts even on Windows (an .exe file in
699 \python24\scripts).
717 \python24\scripts).
700
718
701 * ipapi.py: launch_new_instance, launch entry point needed for the
719 * ipapi.py: launch_new_instance, launch entry point needed for the
702 egg.
720 egg.
703
721
704 2006-01-23 Ville Vainio <vivainio@gmail.com>
722 2006-01-23 Ville Vainio <vivainio@gmail.com>
705
723
706 * Added %cpaste magic for pasting python code
724 * Added %cpaste magic for pasting python code
707
725
708 2006-01-22 Ville Vainio <vivainio@gmail.com>
726 2006-01-22 Ville Vainio <vivainio@gmail.com>
709
727
710 * Merge from branches/0.7.1 into trunk, revs 1052-1057
728 * Merge from branches/0.7.1 into trunk, revs 1052-1057
711
729
712 * Versionstring = 0.7.2.svn
730 * Versionstring = 0.7.2.svn
713
731
714 * eggsetup.py: A separate script for constructing eggs, creates
732 * eggsetup.py: A separate script for constructing eggs, creates
715 proper launch scripts even on Windows (an .exe file in
733 proper launch scripts even on Windows (an .exe file in
716 \python24\scripts).
734 \python24\scripts).
717
735
718 * ipapi.py: launch_new_instance, launch entry point needed for the
736 * ipapi.py: launch_new_instance, launch entry point needed for the
719 egg.
737 egg.
720
738
721 2006-01-22 Fernando Perez <Fernando.Perez@colorado.edu>
739 2006-01-22 Fernando Perez <Fernando.Perez@colorado.edu>
722
740
723 * IPython/OInspect.py (Inspector.pinfo): fix bug where foo?? or
741 * IPython/OInspect.py (Inspector.pinfo): fix bug where foo?? or
724 %pfile foo would print the file for foo even if it was a binary.
742 %pfile foo would print the file for foo even if it was a binary.
725 Now, extensions '.so' and '.dll' are skipped.
743 Now, extensions '.so' and '.dll' are skipped.
726
744
727 * IPython/Shell.py (MTInteractiveShell.__init__): Fix threading
745 * IPython/Shell.py (MTInteractiveShell.__init__): Fix threading
728 bug, where macros would fail in all threaded modes. I'm not 100%
746 bug, where macros would fail in all threaded modes. I'm not 100%
729 sure, so I'm going to put out an rc instead of making a release
747 sure, so I'm going to put out an rc instead of making a release
730 today, and wait for feedback for at least a few days.
748 today, and wait for feedback for at least a few days.
731
749
732 * IPython/iplib.py (handle_normal): fix (finally? somehow I doubt
750 * IPython/iplib.py (handle_normal): fix (finally? somehow I doubt
733 it...) the handling of pasting external code with autoindent on.
751 it...) the handling of pasting external code with autoindent on.
734 To get out of a multiline input, the rule will appear for most
752 To get out of a multiline input, the rule will appear for most
735 users unchanged: two blank lines or change the indent level
753 users unchanged: two blank lines or change the indent level
736 proposed by IPython. But there is a twist now: you can
754 proposed by IPython. But there is a twist now: you can
737 add/subtract only *one or two spaces*. If you add/subtract three
755 add/subtract only *one or two spaces*. If you add/subtract three
738 or more (unless you completely delete the line), IPython will
756 or more (unless you completely delete the line), IPython will
739 accept that line, and you'll need to enter a second one of pure
757 accept that line, and you'll need to enter a second one of pure
740 whitespace. I know it sounds complicated, but I can't find a
758 whitespace. I know it sounds complicated, but I can't find a
741 different solution that covers all the cases, with the right
759 different solution that covers all the cases, with the right
742 heuristics. Hopefully in actual use, nobody will really notice
760 heuristics. Hopefully in actual use, nobody will really notice
743 all these strange rules and things will 'just work'.
761 all these strange rules and things will 'just work'.
744
762
745 2006-01-21 Fernando Perez <Fernando.Perez@colorado.edu>
763 2006-01-21 Fernando Perez <Fernando.Perez@colorado.edu>
746
764
747 * IPython/iplib.py (interact): catch exceptions which can be
765 * IPython/iplib.py (interact): catch exceptions which can be
748 triggered asynchronously by signal handlers. Thanks to an
766 triggered asynchronously by signal handlers. Thanks to an
749 automatic crash report, submitted by Colin Kingsley
767 automatic crash report, submitted by Colin Kingsley
750 <tercel-AT-gentoo.org>.
768 <tercel-AT-gentoo.org>.
751
769
752 2006-01-20 Ville Vainio <vivainio@gmail.com>
770 2006-01-20 Ville Vainio <vivainio@gmail.com>
753
771
754 * Ipython/Extensions/ext_rehashdir.py: Created a usable example
772 * Ipython/Extensions/ext_rehashdir.py: Created a usable example
755 (%rehashdir, very useful, try it out) of how to extend ipython
773 (%rehashdir, very useful, try it out) of how to extend ipython
756 with new magics. Also added Extensions dir to pythonpath to make
774 with new magics. Also added Extensions dir to pythonpath to make
757 importing extensions easy.
775 importing extensions easy.
758
776
759 * %store now complains when trying to store interactively declared
777 * %store now complains when trying to store interactively declared
760 classes / instances of those classes.
778 classes / instances of those classes.
761
779
762 * Extensions/ipy_system_conf.py, UserConfig/ipy_user_conf.py,
780 * Extensions/ipy_system_conf.py, UserConfig/ipy_user_conf.py,
763 ipmaker.py: Config rehaul. Now ipy_..._conf.py are always imported
781 ipmaker.py: Config rehaul. Now ipy_..._conf.py are always imported
764 if they exist, and ipy_user_conf.py with some defaults is created for
782 if they exist, and ipy_user_conf.py with some defaults is created for
765 the user.
783 the user.
766
784
767 * Startup rehashing done by the config file, not InterpreterExec.
785 * Startup rehashing done by the config file, not InterpreterExec.
768 This means system commands are available even without selecting the
786 This means system commands are available even without selecting the
769 pysh profile. It's the sensible default after all.
787 pysh profile. It's the sensible default after all.
770
788
771 2006-01-20 Fernando Perez <Fernando.Perez@colorado.edu>
789 2006-01-20 Fernando Perez <Fernando.Perez@colorado.edu>
772
790
773 * IPython/iplib.py (raw_input): I _think_ I got the pasting of
791 * IPython/iplib.py (raw_input): I _think_ I got the pasting of
774 multiline code with autoindent on working. But I am really not
792 multiline code with autoindent on working. But I am really not
775 sure, so this needs more testing. Will commit a debug-enabled
793 sure, so this needs more testing. Will commit a debug-enabled
776 version for now, while I test it some more, so that Ville and
794 version for now, while I test it some more, so that Ville and
777 others may also catch any problems. Also made
795 others may also catch any problems. Also made
778 self.indent_current_str() a method, to ensure that there's no
796 self.indent_current_str() a method, to ensure that there's no
779 chance of the indent space count and the corresponding string
797 chance of the indent space count and the corresponding string
780 falling out of sync. All code needing the string should just call
798 falling out of sync. All code needing the string should just call
781 the method.
799 the method.
782
800
783 2006-01-18 Fernando Perez <Fernando.Perez@colorado.edu>
801 2006-01-18 Fernando Perez <Fernando.Perez@colorado.edu>
784
802
785 * IPython/Magic.py (magic_edit): fix check for when users don't
803 * IPython/Magic.py (magic_edit): fix check for when users don't
786 save their output files, the try/except was in the wrong section.
804 save their output files, the try/except was in the wrong section.
787
805
788 2006-01-17 Fernando Perez <Fernando.Perez@colorado.edu>
806 2006-01-17 Fernando Perez <Fernando.Perez@colorado.edu>
789
807
790 * IPython/Magic.py (magic_run): fix __file__ global missing from
808 * IPython/Magic.py (magic_run): fix __file__ global missing from
791 script's namespace when executed via %run. After a report by
809 script's namespace when executed via %run. After a report by
792 Vivian.
810 Vivian.
793
811
794 * IPython/Debugger.py (Pdb.__init__): Fix breakage with '%run -d'
812 * IPython/Debugger.py (Pdb.__init__): Fix breakage with '%run -d'
795 when using python 2.4. The parent constructor changed in 2.4, and
813 when using python 2.4. The parent constructor changed in 2.4, and
796 we need to track it directly (we can't call it, as it messes up
814 we need to track it directly (we can't call it, as it messes up
797 readline and tab-completion inside our pdb would stop working).
815 readline and tab-completion inside our pdb would stop working).
798 After a bug report by R. Bernstein <rocky-AT-panix.com>.
816 After a bug report by R. Bernstein <rocky-AT-panix.com>.
799
817
800 2006-01-16 Ville Vainio <vivainio@gmail.com>
818 2006-01-16 Ville Vainio <vivainio@gmail.com>
801
819
802 * Ipython/magic.py: Reverted back to old %edit functionality
820 * Ipython/magic.py: Reverted back to old %edit functionality
803 that returns file contents on exit.
821 that returns file contents on exit.
804
822
805 * IPython/path.py: Added Jason Orendorff's "path" module to
823 * IPython/path.py: Added Jason Orendorff's "path" module to
806 IPython tree, http://www.jorendorff.com/articles/python/path/.
824 IPython tree, http://www.jorendorff.com/articles/python/path/.
807 You can get path objects conveniently through %sc, and !!, e.g.:
825 You can get path objects conveniently through %sc, and !!, e.g.:
808 sc files=ls
826 sc files=ls
809 for p in files.paths: # or files.p
827 for p in files.paths: # or files.p
810 print p,p.mtime
828 print p,p.mtime
811
829
812 * Ipython/iplib.py:"," and ";" autoquoting-upon-autocall
830 * Ipython/iplib.py:"," and ";" autoquoting-upon-autocall
813 now work again without considering the exclusion regexp -
831 now work again without considering the exclusion regexp -
814 hence, things like ',foo my/path' turn to 'foo("my/path")'
832 hence, things like ',foo my/path' turn to 'foo("my/path")'
815 instead of syntax error.
833 instead of syntax error.
816
834
817
835
818 2006-01-14 Ville Vainio <vivainio@gmail.com>
836 2006-01-14 Ville Vainio <vivainio@gmail.com>
819
837
820 * IPython/ipapi.py (ashook, asmagic, options): Added convenience
838 * IPython/ipapi.py (ashook, asmagic, options): Added convenience
821 ipapi decorators for python 2.4 users, options() provides access to rc
839 ipapi decorators for python 2.4 users, options() provides access to rc
822 data.
840 data.
823
841
824 * IPython/Magic.py (magic_cd): %cd now accepts backslashes
842 * IPython/Magic.py (magic_cd): %cd now accepts backslashes
825 as path separators (even on Linux ;-). Space character after
843 as path separators (even on Linux ;-). Space character after
826 backslash (as yielded by tab completer) is still space;
844 backslash (as yielded by tab completer) is still space;
827 "%cd long\ name" works as expected.
845 "%cd long\ name" works as expected.
828
846
829 * IPython/ipapi.py,hooks.py,iplib.py: Hooks now implemented
847 * IPython/ipapi.py,hooks.py,iplib.py: Hooks now implemented
830 as "chain of command", with priority. API stays the same,
848 as "chain of command", with priority. API stays the same,
831 TryNext exception raised by a hook function signals that
849 TryNext exception raised by a hook function signals that
832 current hook failed and next hook should try handling it, as
850 current hook failed and next hook should try handling it, as
833 suggested by Walter DΓΆrwald <walter@livinglogic.de>. Walter also
851 suggested by Walter DΓΆrwald <walter@livinglogic.de>. Walter also
834 requested configurable display hook, which is now implemented.
852 requested configurable display hook, which is now implemented.
835
853
836 2006-01-13 Ville Vainio <vivainio@gmail.com>
854 2006-01-13 Ville Vainio <vivainio@gmail.com>
837
855
838 * IPython/platutils*.py: platform specific utility functions,
856 * IPython/platutils*.py: platform specific utility functions,
839 so far only set_term_title is implemented (change terminal
857 so far only set_term_title is implemented (change terminal
840 label in windowing systems). %cd now changes the title to
858 label in windowing systems). %cd now changes the title to
841 current dir.
859 current dir.
842
860
843 * IPython/Release.py: Added myself to "authors" list,
861 * IPython/Release.py: Added myself to "authors" list,
844 had to create new files.
862 had to create new files.
845
863
846 * IPython/iplib.py (handle_shell_escape): fixed logical flaw in
864 * IPython/iplib.py (handle_shell_escape): fixed logical flaw in
847 shell escape; not a known bug but had potential to be one in the
865 shell escape; not a known bug but had potential to be one in the
848 future.
866 future.
849
867
850 * IPython/ipapi.py (added),OInspect.py,iplib.py: "Public"
868 * IPython/ipapi.py (added),OInspect.py,iplib.py: "Public"
851 extension API for IPython! See the module for usage example. Fix
869 extension API for IPython! See the module for usage example. Fix
852 OInspect for docstring-less magic functions.
870 OInspect for docstring-less magic functions.
853
871
854
872
855 2006-01-13 Fernando Perez <Fernando.Perez@colorado.edu>
873 2006-01-13 Fernando Perez <Fernando.Perez@colorado.edu>
856
874
857 * IPython/iplib.py (raw_input): temporarily deactivate all
875 * IPython/iplib.py (raw_input): temporarily deactivate all
858 attempts at allowing pasting of code with autoindent on. It
876 attempts at allowing pasting of code with autoindent on. It
859 introduced bugs (reported by Prabhu) and I can't seem to find a
877 introduced bugs (reported by Prabhu) and I can't seem to find a
860 robust combination which works in all cases. Will have to revisit
878 robust combination which works in all cases. Will have to revisit
861 later.
879 later.
862
880
863 * IPython/genutils.py: remove isspace() function. We've dropped
881 * IPython/genutils.py: remove isspace() function. We've dropped
864 2.2 compatibility, so it's OK to use the string method.
882 2.2 compatibility, so it's OK to use the string method.
865
883
866 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
884 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
867
885
868 * IPython/iplib.py (InteractiveShell.__init__): fix regexp
886 * IPython/iplib.py (InteractiveShell.__init__): fix regexp
869 matching what NOT to autocall on, to include all python binary
887 matching what NOT to autocall on, to include all python binary
870 operators (including things like 'and', 'or', 'is' and 'in').
888 operators (including things like 'and', 'or', 'is' and 'in').
871 Prompted by a bug report on 'foo & bar', but I realized we had
889 Prompted by a bug report on 'foo & bar', but I realized we had
872 many more potential bug cases with other operators. The regexp is
890 many more potential bug cases with other operators. The regexp is
873 self.re_exclude_auto, it's fairly commented.
891 self.re_exclude_auto, it's fairly commented.
874
892
875 2006-01-12 Ville Vainio <vivainio@gmail.com>
893 2006-01-12 Ville Vainio <vivainio@gmail.com>
876
894
877 * IPython/iplib.py (make_quoted_expr,handle_shell_escape):
895 * IPython/iplib.py (make_quoted_expr,handle_shell_escape):
878 Prettified and hardened string/backslash quoting with ipsystem(),
896 Prettified and hardened string/backslash quoting with ipsystem(),
879 ipalias() and ipmagic(). Now even \ characters are passed to
897 ipalias() and ipmagic(). Now even \ characters are passed to
880 %magics, !shell escapes and aliases exactly as they are in the
898 %magics, !shell escapes and aliases exactly as they are in the
881 ipython command line. Should improve backslash experience,
899 ipython command line. Should improve backslash experience,
882 particularly in Windows (path delimiter for some commands that
900 particularly in Windows (path delimiter for some commands that
883 won't understand '/'), but Unix benefits as well (regexps). %cd
901 won't understand '/'), but Unix benefits as well (regexps). %cd
884 magic still doesn't support backslash path delimiters, though. Also
902 magic still doesn't support backslash path delimiters, though. Also
885 deleted all pretense of supporting multiline command strings in
903 deleted all pretense of supporting multiline command strings in
886 !system or %magic commands. Thanks to Jerry McRae for suggestions.
904 !system or %magic commands. Thanks to Jerry McRae for suggestions.
887
905
888 * doc/build_doc_instructions.txt added. Documentation on how to
906 * doc/build_doc_instructions.txt added. Documentation on how to
889 use doc/update_manual.py, added yesterday. Both files contributed
907 use doc/update_manual.py, added yesterday. Both files contributed
890 by JΓΆrgen Stenarson <jorgen.stenarson-AT-bostream.nu>. This slates
908 by JΓΆrgen Stenarson <jorgen.stenarson-AT-bostream.nu>. This slates
891 doc/*.sh for deprecation at a later date.
909 doc/*.sh for deprecation at a later date.
892
910
893 * /ipython.py Added ipython.py to root directory for
911 * /ipython.py Added ipython.py to root directory for
894 zero-installation (tar xzvf ipython.tgz; cd ipython; python
912 zero-installation (tar xzvf ipython.tgz; cd ipython; python
895 ipython.py) and development convenience (no need to keep doing
913 ipython.py) and development convenience (no need to keep doing
896 "setup.py install" between changes).
914 "setup.py install" between changes).
897
915
898 * Made ! and !! shell escapes work (again) in multiline expressions:
916 * Made ! and !! shell escapes work (again) in multiline expressions:
899 if 1:
917 if 1:
900 !ls
918 !ls
901 !!ls
919 !!ls
902
920
903 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
921 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
904
922
905 * IPython/ipstruct.py (Struct): Rename IPython.Struct to
923 * IPython/ipstruct.py (Struct): Rename IPython.Struct to
906 IPython.ipstruct, to avoid local shadowing of the stdlib 'struct'
924 IPython.ipstruct, to avoid local shadowing of the stdlib 'struct'
907 module in case-insensitive installation. Was causing crashes
925 module in case-insensitive installation. Was causing crashes
908 under win32. Closes http://www.scipy.net/roundup/ipython/issue49.
926 under win32. Closes http://www.scipy.net/roundup/ipython/issue49.
909
927
910 * IPython/Magic.py (magic_pycat): Fix pycat, patch by Marien Zwart
928 * IPython/Magic.py (magic_pycat): Fix pycat, patch by Marien Zwart
911 <marienz-AT-gentoo.org>, closes
929 <marienz-AT-gentoo.org>, closes
912 http://www.scipy.net/roundup/ipython/issue51.
930 http://www.scipy.net/roundup/ipython/issue51.
913
931
914 2006-01-11 Fernando Perez <Fernando.Perez@colorado.edu>
932 2006-01-11 Fernando Perez <Fernando.Perez@colorado.edu>
915
933
916 * IPython/Shell.py (IPShellGTK.on_timer): Finally fix the
934 * IPython/Shell.py (IPShellGTK.on_timer): Finally fix the
917 problem of excessive CPU usage under *nix and keyboard lag under
935 problem of excessive CPU usage under *nix and keyboard lag under
918 win32.
936 win32.
919
937
920 2006-01-10 *** Released version 0.7.0
938 2006-01-10 *** Released version 0.7.0
921
939
922 2006-01-10 Fernando Perez <Fernando.Perez@colorado.edu>
940 2006-01-10 Fernando Perez <Fernando.Perez@colorado.edu>
923
941
924 * IPython/Release.py (revision): tag version number to 0.7.0,
942 * IPython/Release.py (revision): tag version number to 0.7.0,
925 ready for release.
943 ready for release.
926
944
927 * IPython/Magic.py (magic_edit): Add print statement to %edit so
945 * IPython/Magic.py (magic_edit): Add print statement to %edit so
928 it informs the user of the name of the temp. file used. This can
946 it informs the user of the name of the temp. file used. This can
929 help if you decide later to reuse that same file, so you know
947 help if you decide later to reuse that same file, so you know
930 where to copy the info from.
948 where to copy the info from.
931
949
932 2006-01-09 Fernando Perez <Fernando.Perez@colorado.edu>
950 2006-01-09 Fernando Perez <Fernando.Perez@colorado.edu>
933
951
934 * setup_bdist_egg.py: little script to build an egg. Added
952 * setup_bdist_egg.py: little script to build an egg. Added
935 support in the release tools as well.
953 support in the release tools as well.
936
954
937 2006-01-08 Fernando Perez <Fernando.Perez@colorado.edu>
955 2006-01-08 Fernando Perez <Fernando.Perez@colorado.edu>
938
956
939 * IPython/Shell.py (IPShellWX.__init__): add support for WXPython
957 * IPython/Shell.py (IPShellWX.__init__): add support for WXPython
940 version selection (new -wxversion command line and ipythonrc
958 version selection (new -wxversion command line and ipythonrc
941 parameter). Patch contributed by Arnd Baecker
959 parameter). Patch contributed by Arnd Baecker
942 <arnd.baecker-AT-web.de>.
960 <arnd.baecker-AT-web.de>.
943
961
944 * IPython/iplib.py (embed_mainloop): fix tab-completion in
962 * IPython/iplib.py (embed_mainloop): fix tab-completion in
945 embedded instances, for variables defined at the interactive
963 embedded instances, for variables defined at the interactive
946 prompt of the embedded ipython. Reported by Arnd.
964 prompt of the embedded ipython. Reported by Arnd.
947
965
948 * IPython/Magic.py (magic_autocall): Fix %autocall magic. Now
966 * IPython/Magic.py (magic_autocall): Fix %autocall magic. Now
949 it can be used as a (stateful) toggle, or with a direct parameter.
967 it can be used as a (stateful) toggle, or with a direct parameter.
950
968
951 * IPython/ultraTB.py (_fixed_getinnerframes): remove debug assert which
969 * IPython/ultraTB.py (_fixed_getinnerframes): remove debug assert which
952 could be triggered in certain cases and cause the traceback
970 could be triggered in certain cases and cause the traceback
953 printer not to work.
971 printer not to work.
954
972
955 2006-01-07 Fernando Perez <Fernando.Perez@colorado.edu>
973 2006-01-07 Fernando Perez <Fernando.Perez@colorado.edu>
956
974
957 * IPython/iplib.py (_should_recompile): Small fix, closes
975 * IPython/iplib.py (_should_recompile): Small fix, closes
958 http://www.scipy.net/roundup/ipython/issue48. Patch by Scott.
976 http://www.scipy.net/roundup/ipython/issue48. Patch by Scott.
959
977
960 2006-01-04 Fernando Perez <Fernando.Perez@colorado.edu>
978 2006-01-04 Fernando Perez <Fernando.Perez@colorado.edu>
961
979
962 * IPython/Shell.py (IPShellGTK.mainloop): fix bug in the GTK
980 * IPython/Shell.py (IPShellGTK.mainloop): fix bug in the GTK
963 backend for matplotlib (100% cpu utiliziation). Thanks to Charlie
981 backend for matplotlib (100% cpu utiliziation). Thanks to Charlie
964 Moad for help with tracking it down.
982 Moad for help with tracking it down.
965
983
966 * IPython/iplib.py (handle_auto): fix autocall handling for
984 * IPython/iplib.py (handle_auto): fix autocall handling for
967 objects which support BOTH __getitem__ and __call__ (so that f [x]
985 objects which support BOTH __getitem__ and __call__ (so that f [x]
968 is left alone, instead of becoming f([x]) automatically).
986 is left alone, instead of becoming f([x]) automatically).
969
987
970 * IPython/Magic.py (magic_cd): fix crash when cd -b was used.
988 * IPython/Magic.py (magic_cd): fix crash when cd -b was used.
971 Ville's patch.
989 Ville's patch.
972
990
973 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
991 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
974
992
975 * IPython/iplib.py (handle_auto): changed autocall semantics to
993 * IPython/iplib.py (handle_auto): changed autocall semantics to
976 include 'smart' mode, where the autocall transformation is NOT
994 include 'smart' mode, where the autocall transformation is NOT
977 applied if there are no arguments on the line. This allows you to
995 applied if there are no arguments on the line. This allows you to
978 just type 'foo' if foo is a callable to see its internal form,
996 just type 'foo' if foo is a callable to see its internal form,
979 instead of having it called with no arguments (typically a
997 instead of having it called with no arguments (typically a
980 mistake). The old 'full' autocall still exists: for that, you
998 mistake). The old 'full' autocall still exists: for that, you
981 need to set the 'autocall' parameter to 2 in your ipythonrc file.
999 need to set the 'autocall' parameter to 2 in your ipythonrc file.
982
1000
983 * IPython/completer.py (Completer.attr_matches): add
1001 * IPython/completer.py (Completer.attr_matches): add
984 tab-completion support for Enthoughts' traits. After a report by
1002 tab-completion support for Enthoughts' traits. After a report by
985 Arnd and a patch by Prabhu.
1003 Arnd and a patch by Prabhu.
986
1004
987 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
1005 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
988
1006
989 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
1007 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
990 Schmolck's patch to fix inspect.getinnerframes().
1008 Schmolck's patch to fix inspect.getinnerframes().
991
1009
992 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
1010 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
993 for embedded instances, regarding handling of namespaces and items
1011 for embedded instances, regarding handling of namespaces and items
994 added to the __builtin__ one. Multiple embedded instances and
1012 added to the __builtin__ one. Multiple embedded instances and
995 recursive embeddings should work better now (though I'm not sure
1013 recursive embeddings should work better now (though I'm not sure
996 I've got all the corner cases fixed, that code is a bit of a brain
1014 I've got all the corner cases fixed, that code is a bit of a brain
997 twister).
1015 twister).
998
1016
999 * IPython/Magic.py (magic_edit): added support to edit in-memory
1017 * IPython/Magic.py (magic_edit): added support to edit in-memory
1000 macros (automatically creates the necessary temp files). %edit
1018 macros (automatically creates the necessary temp files). %edit
1001 also doesn't return the file contents anymore, it's just noise.
1019 also doesn't return the file contents anymore, it's just noise.
1002
1020
1003 * IPython/completer.py (Completer.attr_matches): revert change to
1021 * IPython/completer.py (Completer.attr_matches): revert change to
1004 complete only on attributes listed in __all__. I realized it
1022 complete only on attributes listed in __all__. I realized it
1005 cripples the tab-completion system as a tool for exploring the
1023 cripples the tab-completion system as a tool for exploring the
1006 internals of unknown libraries (it renders any non-__all__
1024 internals of unknown libraries (it renders any non-__all__
1007 attribute off-limits). I got bit by this when trying to see
1025 attribute off-limits). I got bit by this when trying to see
1008 something inside the dis module.
1026 something inside the dis module.
1009
1027
1010 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
1028 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
1011
1029
1012 * IPython/iplib.py (InteractiveShell.__init__): add .meta
1030 * IPython/iplib.py (InteractiveShell.__init__): add .meta
1013 namespace for users and extension writers to hold data in. This
1031 namespace for users and extension writers to hold data in. This
1014 follows the discussion in
1032 follows the discussion in
1015 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
1033 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
1016
1034
1017 * IPython/completer.py (IPCompleter.complete): small patch to help
1035 * IPython/completer.py (IPCompleter.complete): small patch to help
1018 tab-completion under Emacs, after a suggestion by John Barnard
1036 tab-completion under Emacs, after a suggestion by John Barnard
1019 <barnarj-AT-ccf.org>.
1037 <barnarj-AT-ccf.org>.
1020
1038
1021 * IPython/Magic.py (Magic.extract_input_slices): added support for
1039 * IPython/Magic.py (Magic.extract_input_slices): added support for
1022 the slice notation in magics to use N-M to represent numbers N...M
1040 the slice notation in magics to use N-M to represent numbers N...M
1023 (closed endpoints). This is used by %macro and %save.
1041 (closed endpoints). This is used by %macro and %save.
1024
1042
1025 * IPython/completer.py (Completer.attr_matches): for modules which
1043 * IPython/completer.py (Completer.attr_matches): for modules which
1026 define __all__, complete only on those. After a patch by Jeffrey
1044 define __all__, complete only on those. After a patch by Jeffrey
1027 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
1045 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
1028 speed up this routine.
1046 speed up this routine.
1029
1047
1030 * IPython/Logger.py (Logger.log): fix a history handling bug. I
1048 * IPython/Logger.py (Logger.log): fix a history handling bug. I
1031 don't know if this is the end of it, but the behavior now is
1049 don't know if this is the end of it, but the behavior now is
1032 certainly much more correct. Note that coupled with macros,
1050 certainly much more correct. Note that coupled with macros,
1033 slightly surprising (at first) behavior may occur: a macro will in
1051 slightly surprising (at first) behavior may occur: a macro will in
1034 general expand to multiple lines of input, so upon exiting, the
1052 general expand to multiple lines of input, so upon exiting, the
1035 in/out counters will both be bumped by the corresponding amount
1053 in/out counters will both be bumped by the corresponding amount
1036 (as if the macro's contents had been typed interactively). Typing
1054 (as if the macro's contents had been typed interactively). Typing
1037 %hist will reveal the intermediate (silently processed) lines.
1055 %hist will reveal the intermediate (silently processed) lines.
1038
1056
1039 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
1057 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
1040 pickle to fail (%run was overwriting __main__ and not restoring
1058 pickle to fail (%run was overwriting __main__ and not restoring
1041 it, but pickle relies on __main__ to operate).
1059 it, but pickle relies on __main__ to operate).
1042
1060
1043 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
1061 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
1044 using properties, but forgot to make the main InteractiveShell
1062 using properties, but forgot to make the main InteractiveShell
1045 class a new-style class. Properties fail silently, and
1063 class a new-style class. Properties fail silently, and
1046 mysteriously, with old-style class (getters work, but
1064 mysteriously, with old-style class (getters work, but
1047 setters don't do anything).
1065 setters don't do anything).
1048
1066
1049 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
1067 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
1050
1068
1051 * IPython/Magic.py (magic_history): fix history reporting bug (I
1069 * IPython/Magic.py (magic_history): fix history reporting bug (I
1052 know some nasties are still there, I just can't seem to find a
1070 know some nasties are still there, I just can't seem to find a
1053 reproducible test case to track them down; the input history is
1071 reproducible test case to track them down; the input history is
1054 falling out of sync...)
1072 falling out of sync...)
1055
1073
1056 * IPython/iplib.py (handle_shell_escape): fix bug where both
1074 * IPython/iplib.py (handle_shell_escape): fix bug where both
1057 aliases and system accesses where broken for indented code (such
1075 aliases and system accesses where broken for indented code (such
1058 as loops).
1076 as loops).
1059
1077
1060 * IPython/genutils.py (shell): fix small but critical bug for
1078 * IPython/genutils.py (shell): fix small but critical bug for
1061 win32 system access.
1079 win32 system access.
1062
1080
1063 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
1081 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
1064
1082
1065 * IPython/iplib.py (showtraceback): remove use of the
1083 * IPython/iplib.py (showtraceback): remove use of the
1066 sys.last_{type/value/traceback} structures, which are non
1084 sys.last_{type/value/traceback} structures, which are non
1067 thread-safe.
1085 thread-safe.
1068 (_prefilter): change control flow to ensure that we NEVER
1086 (_prefilter): change control flow to ensure that we NEVER
1069 introspect objects when autocall is off. This will guarantee that
1087 introspect objects when autocall is off. This will guarantee that
1070 having an input line of the form 'x.y', where access to attribute
1088 having an input line of the form 'x.y', where access to attribute
1071 'y' has side effects, doesn't trigger the side effect TWICE. It
1089 'y' has side effects, doesn't trigger the side effect TWICE. It
1072 is important to note that, with autocall on, these side effects
1090 is important to note that, with autocall on, these side effects
1073 can still happen.
1091 can still happen.
1074 (ipsystem): new builtin, to complete the ip{magic/alias/system}
1092 (ipsystem): new builtin, to complete the ip{magic/alias/system}
1075 trio. IPython offers these three kinds of special calls which are
1093 trio. IPython offers these three kinds of special calls which are
1076 not python code, and it's a good thing to have their call method
1094 not python code, and it's a good thing to have their call method
1077 be accessible as pure python functions (not just special syntax at
1095 be accessible as pure python functions (not just special syntax at
1078 the command line). It gives us a better internal implementation
1096 the command line). It gives us a better internal implementation
1079 structure, as well as exposing these for user scripting more
1097 structure, as well as exposing these for user scripting more
1080 cleanly.
1098 cleanly.
1081
1099
1082 * IPython/macro.py (Macro.__init__): moved macros to a standalone
1100 * IPython/macro.py (Macro.__init__): moved macros to a standalone
1083 file. Now that they'll be more likely to be used with the
1101 file. Now that they'll be more likely to be used with the
1084 persistance system (%store), I want to make sure their module path
1102 persistance system (%store), I want to make sure their module path
1085 doesn't change in the future, so that we don't break things for
1103 doesn't change in the future, so that we don't break things for
1086 users' persisted data.
1104 users' persisted data.
1087
1105
1088 * IPython/iplib.py (autoindent_update): move indentation
1106 * IPython/iplib.py (autoindent_update): move indentation
1089 management into the _text_ processing loop, not the keyboard
1107 management into the _text_ processing loop, not the keyboard
1090 interactive one. This is necessary to correctly process non-typed
1108 interactive one. This is necessary to correctly process non-typed
1091 multiline input (such as macros).
1109 multiline input (such as macros).
1092
1110
1093 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
1111 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
1094 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
1112 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
1095 which was producing problems in the resulting manual.
1113 which was producing problems in the resulting manual.
1096 (magic_whos): improve reporting of instances (show their class,
1114 (magic_whos): improve reporting of instances (show their class,
1097 instead of simply printing 'instance' which isn't terribly
1115 instead of simply printing 'instance' which isn't terribly
1098 informative).
1116 informative).
1099
1117
1100 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
1118 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
1101 (minor mods) to support network shares under win32.
1119 (minor mods) to support network shares under win32.
1102
1120
1103 * IPython/winconsole.py (get_console_size): add new winconsole
1121 * IPython/winconsole.py (get_console_size): add new winconsole
1104 module and fixes to page_dumb() to improve its behavior under
1122 module and fixes to page_dumb() to improve its behavior under
1105 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
1123 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
1106
1124
1107 * IPython/Magic.py (Macro): simplified Macro class to just
1125 * IPython/Magic.py (Macro): simplified Macro class to just
1108 subclass list. We've had only 2.2 compatibility for a very long
1126 subclass list. We've had only 2.2 compatibility for a very long
1109 time, yet I was still avoiding subclassing the builtin types. No
1127 time, yet I was still avoiding subclassing the builtin types. No
1110 more (I'm also starting to use properties, though I won't shift to
1128 more (I'm also starting to use properties, though I won't shift to
1111 2.3-specific features quite yet).
1129 2.3-specific features quite yet).
1112 (magic_store): added Ville's patch for lightweight variable
1130 (magic_store): added Ville's patch for lightweight variable
1113 persistence, after a request on the user list by Matt Wilkie
1131 persistence, after a request on the user list by Matt Wilkie
1114 <maphew-AT-gmail.com>. The new %store magic's docstring has full
1132 <maphew-AT-gmail.com>. The new %store magic's docstring has full
1115 details.
1133 details.
1116
1134
1117 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1135 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1118 changed the default logfile name from 'ipython.log' to
1136 changed the default logfile name from 'ipython.log' to
1119 'ipython_log.py'. These logs are real python files, and now that
1137 'ipython_log.py'. These logs are real python files, and now that
1120 we have much better multiline support, people are more likely to
1138 we have much better multiline support, people are more likely to
1121 want to use them as such. Might as well name them correctly.
1139 want to use them as such. Might as well name them correctly.
1122
1140
1123 * IPython/Magic.py: substantial cleanup. While we can't stop
1141 * IPython/Magic.py: substantial cleanup. While we can't stop
1124 using magics as mixins, due to the existing customizations 'out
1142 using magics as mixins, due to the existing customizations 'out
1125 there' which rely on the mixin naming conventions, at least I
1143 there' which rely on the mixin naming conventions, at least I
1126 cleaned out all cross-class name usage. So once we are OK with
1144 cleaned out all cross-class name usage. So once we are OK with
1127 breaking compatibility, the two systems can be separated.
1145 breaking compatibility, the two systems can be separated.
1128
1146
1129 * IPython/Logger.py: major cleanup. This one is NOT a mixin
1147 * IPython/Logger.py: major cleanup. This one is NOT a mixin
1130 anymore, and the class is a fair bit less hideous as well. New
1148 anymore, and the class is a fair bit less hideous as well. New
1131 features were also introduced: timestamping of input, and logging
1149 features were also introduced: timestamping of input, and logging
1132 of output results. These are user-visible with the -t and -o
1150 of output results. These are user-visible with the -t and -o
1133 options to %logstart. Closes
1151 options to %logstart. Closes
1134 http://www.scipy.net/roundup/ipython/issue11 and a request by
1152 http://www.scipy.net/roundup/ipython/issue11 and a request by
1135 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
1153 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
1136
1154
1137 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
1155 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
1138
1156
1139 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
1157 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
1140 better handle backslashes in paths. See the thread 'More Windows
1158 better handle backslashes in paths. See the thread 'More Windows
1141 questions part 2 - \/ characters revisited' on the iypthon user
1159 questions part 2 - \/ characters revisited' on the iypthon user
1142 list:
1160 list:
1143 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
1161 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
1144
1162
1145 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
1163 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
1146
1164
1147 (InteractiveShell.__init__): change threaded shells to not use the
1165 (InteractiveShell.__init__): change threaded shells to not use the
1148 ipython crash handler. This was causing more problems than not,
1166 ipython crash handler. This was causing more problems than not,
1149 as exceptions in the main thread (GUI code, typically) would
1167 as exceptions in the main thread (GUI code, typically) would
1150 always show up as a 'crash', when they really weren't.
1168 always show up as a 'crash', when they really weren't.
1151
1169
1152 The colors and exception mode commands (%colors/%xmode) have been
1170 The colors and exception mode commands (%colors/%xmode) have been
1153 synchronized to also take this into account, so users can get
1171 synchronized to also take this into account, so users can get
1154 verbose exceptions for their threaded code as well. I also added
1172 verbose exceptions for their threaded code as well. I also added
1155 support for activating pdb inside this exception handler as well,
1173 support for activating pdb inside this exception handler as well,
1156 so now GUI authors can use IPython's enhanced pdb at runtime.
1174 so now GUI authors can use IPython's enhanced pdb at runtime.
1157
1175
1158 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
1176 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
1159 true by default, and add it to the shipped ipythonrc file. Since
1177 true by default, and add it to the shipped ipythonrc file. Since
1160 this asks the user before proceeding, I think it's OK to make it
1178 this asks the user before proceeding, I think it's OK to make it
1161 true by default.
1179 true by default.
1162
1180
1163 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
1181 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
1164 of the previous special-casing of input in the eval loop. I think
1182 of the previous special-casing of input in the eval loop. I think
1165 this is cleaner, as they really are commands and shouldn't have
1183 this is cleaner, as they really are commands and shouldn't have
1166 a special role in the middle of the core code.
1184 a special role in the middle of the core code.
1167
1185
1168 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
1186 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
1169
1187
1170 * IPython/iplib.py (edit_syntax_error): added support for
1188 * IPython/iplib.py (edit_syntax_error): added support for
1171 automatically reopening the editor if the file had a syntax error
1189 automatically reopening the editor if the file had a syntax error
1172 in it. Thanks to scottt who provided the patch at:
1190 in it. Thanks to scottt who provided the patch at:
1173 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
1191 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
1174 version committed).
1192 version committed).
1175
1193
1176 * IPython/iplib.py (handle_normal): add suport for multi-line
1194 * IPython/iplib.py (handle_normal): add suport for multi-line
1177 input with emtpy lines. This fixes
1195 input with emtpy lines. This fixes
1178 http://www.scipy.net/roundup/ipython/issue43 and a similar
1196 http://www.scipy.net/roundup/ipython/issue43 and a similar
1179 discussion on the user list.
1197 discussion on the user list.
1180
1198
1181 WARNING: a behavior change is necessarily introduced to support
1199 WARNING: a behavior change is necessarily introduced to support
1182 blank lines: now a single blank line with whitespace does NOT
1200 blank lines: now a single blank line with whitespace does NOT
1183 break the input loop, which means that when autoindent is on, by
1201 break the input loop, which means that when autoindent is on, by
1184 default hitting return on the next (indented) line does NOT exit.
1202 default hitting return on the next (indented) line does NOT exit.
1185
1203
1186 Instead, to exit a multiline input you can either have:
1204 Instead, to exit a multiline input you can either have:
1187
1205
1188 - TWO whitespace lines (just hit return again), or
1206 - TWO whitespace lines (just hit return again), or
1189 - a single whitespace line of a different length than provided
1207 - a single whitespace line of a different length than provided
1190 by the autoindent (add or remove a space).
1208 by the autoindent (add or remove a space).
1191
1209
1192 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
1210 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
1193 module to better organize all readline-related functionality.
1211 module to better organize all readline-related functionality.
1194 I've deleted FlexCompleter and put all completion clases here.
1212 I've deleted FlexCompleter and put all completion clases here.
1195
1213
1196 * IPython/iplib.py (raw_input): improve indentation management.
1214 * IPython/iplib.py (raw_input): improve indentation management.
1197 It is now possible to paste indented code with autoindent on, and
1215 It is now possible to paste indented code with autoindent on, and
1198 the code is interpreted correctly (though it still looks bad on
1216 the code is interpreted correctly (though it still looks bad on
1199 screen, due to the line-oriented nature of ipython).
1217 screen, due to the line-oriented nature of ipython).
1200 (MagicCompleter.complete): change behavior so that a TAB key on an
1218 (MagicCompleter.complete): change behavior so that a TAB key on an
1201 otherwise empty line actually inserts a tab, instead of completing
1219 otherwise empty line actually inserts a tab, instead of completing
1202 on the entire global namespace. This makes it easier to use the
1220 on the entire global namespace. This makes it easier to use the
1203 TAB key for indentation. After a request by Hans Meine
1221 TAB key for indentation. After a request by Hans Meine
1204 <hans_meine-AT-gmx.net>
1222 <hans_meine-AT-gmx.net>
1205 (_prefilter): add support so that typing plain 'exit' or 'quit'
1223 (_prefilter): add support so that typing plain 'exit' or 'quit'
1206 does a sensible thing. Originally I tried to deviate as little as
1224 does a sensible thing. Originally I tried to deviate as little as
1207 possible from the default python behavior, but even that one may
1225 possible from the default python behavior, but even that one may
1208 change in this direction (thread on python-dev to that effect).
1226 change in this direction (thread on python-dev to that effect).
1209 Regardless, ipython should do the right thing even if CPython's
1227 Regardless, ipython should do the right thing even if CPython's
1210 '>>>' prompt doesn't.
1228 '>>>' prompt doesn't.
1211 (InteractiveShell): removed subclassing code.InteractiveConsole
1229 (InteractiveShell): removed subclassing code.InteractiveConsole
1212 class. By now we'd overridden just about all of its methods: I've
1230 class. By now we'd overridden just about all of its methods: I've
1213 copied the remaining two over, and now ipython is a standalone
1231 copied the remaining two over, and now ipython is a standalone
1214 class. This will provide a clearer picture for the chainsaw
1232 class. This will provide a clearer picture for the chainsaw
1215 branch refactoring.
1233 branch refactoring.
1216
1234
1217 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
1235 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
1218
1236
1219 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
1237 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
1220 failures for objects which break when dir() is called on them.
1238 failures for objects which break when dir() is called on them.
1221
1239
1222 * IPython/FlexCompleter.py (Completer.__init__): Added support for
1240 * IPython/FlexCompleter.py (Completer.__init__): Added support for
1223 distinct local and global namespaces in the completer API. This
1241 distinct local and global namespaces in the completer API. This
1224 change allows us to properly handle completion with distinct
1242 change allows us to properly handle completion with distinct
1225 scopes, including in embedded instances (this had never really
1243 scopes, including in embedded instances (this had never really
1226 worked correctly).
1244 worked correctly).
1227
1245
1228 Note: this introduces a change in the constructor for
1246 Note: this introduces a change in the constructor for
1229 MagicCompleter, as a new global_namespace parameter is now the
1247 MagicCompleter, as a new global_namespace parameter is now the
1230 second argument (the others were bumped one position).
1248 second argument (the others were bumped one position).
1231
1249
1232 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
1250 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
1233
1251
1234 * IPython/iplib.py (embed_mainloop): fix tab-completion in
1252 * IPython/iplib.py (embed_mainloop): fix tab-completion in
1235 embedded instances (which can be done now thanks to Vivian's
1253 embedded instances (which can be done now thanks to Vivian's
1236 frame-handling fixes for pdb).
1254 frame-handling fixes for pdb).
1237 (InteractiveShell.__init__): Fix namespace handling problem in
1255 (InteractiveShell.__init__): Fix namespace handling problem in
1238 embedded instances. We were overwriting __main__ unconditionally,
1256 embedded instances. We were overwriting __main__ unconditionally,
1239 and this should only be done for 'full' (non-embedded) IPython;
1257 and this should only be done for 'full' (non-embedded) IPython;
1240 embedded instances must respect the caller's __main__. Thanks to
1258 embedded instances must respect the caller's __main__. Thanks to
1241 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
1259 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
1242
1260
1243 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
1261 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
1244
1262
1245 * setup.py: added download_url to setup(). This registers the
1263 * setup.py: added download_url to setup(). This registers the
1246 download address at PyPI, which is not only useful to humans
1264 download address at PyPI, which is not only useful to humans
1247 browsing the site, but is also picked up by setuptools (the Eggs
1265 browsing the site, but is also picked up by setuptools (the Eggs
1248 machinery). Thanks to Ville and R. Kern for the info/discussion
1266 machinery). Thanks to Ville and R. Kern for the info/discussion
1249 on this.
1267 on this.
1250
1268
1251 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
1269 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
1252
1270
1253 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
1271 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
1254 This brings a lot of nice functionality to the pdb mode, which now
1272 This brings a lot of nice functionality to the pdb mode, which now
1255 has tab-completion, syntax highlighting, and better stack handling
1273 has tab-completion, syntax highlighting, and better stack handling
1256 than before. Many thanks to Vivian De Smedt
1274 than before. Many thanks to Vivian De Smedt
1257 <vivian-AT-vdesmedt.com> for the original patches.
1275 <vivian-AT-vdesmedt.com> for the original patches.
1258
1276
1259 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
1277 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
1260
1278
1261 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
1279 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
1262 sequence to consistently accept the banner argument. The
1280 sequence to consistently accept the banner argument. The
1263 inconsistency was tripping SAGE, thanks to Gary Zablackis
1281 inconsistency was tripping SAGE, thanks to Gary Zablackis
1264 <gzabl-AT-yahoo.com> for the report.
1282 <gzabl-AT-yahoo.com> for the report.
1265
1283
1266 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
1284 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
1267
1285
1268 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1286 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1269 Fix bug where a naked 'alias' call in the ipythonrc file would
1287 Fix bug where a naked 'alias' call in the ipythonrc file would
1270 cause a crash. Bug reported by Jorgen Stenarson.
1288 cause a crash. Bug reported by Jorgen Stenarson.
1271
1289
1272 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
1290 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
1273
1291
1274 * IPython/ipmaker.py (make_IPython): cleanups which should improve
1292 * IPython/ipmaker.py (make_IPython): cleanups which should improve
1275 startup time.
1293 startup time.
1276
1294
1277 * IPython/iplib.py (runcode): my globals 'fix' for embedded
1295 * IPython/iplib.py (runcode): my globals 'fix' for embedded
1278 instances had introduced a bug with globals in normal code. Now
1296 instances had introduced a bug with globals in normal code. Now
1279 it's working in all cases.
1297 it's working in all cases.
1280
1298
1281 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
1299 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
1282 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
1300 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
1283 has been introduced to set the default case sensitivity of the
1301 has been introduced to set the default case sensitivity of the
1284 searches. Users can still select either mode at runtime on a
1302 searches. Users can still select either mode at runtime on a
1285 per-search basis.
1303 per-search basis.
1286
1304
1287 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
1305 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
1288
1306
1289 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
1307 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
1290 attributes in wildcard searches for subclasses. Modified version
1308 attributes in wildcard searches for subclasses. Modified version
1291 of a patch by Jorgen.
1309 of a patch by Jorgen.
1292
1310
1293 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
1311 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
1294
1312
1295 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
1313 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
1296 embedded instances. I added a user_global_ns attribute to the
1314 embedded instances. I added a user_global_ns attribute to the
1297 InteractiveShell class to handle this.
1315 InteractiveShell class to handle this.
1298
1316
1299 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
1317 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
1300
1318
1301 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
1319 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
1302 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
1320 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
1303 (reported under win32, but may happen also in other platforms).
1321 (reported under win32, but may happen also in other platforms).
1304 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
1322 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
1305
1323
1306 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
1324 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
1307
1325
1308 * IPython/Magic.py (magic_psearch): new support for wildcard
1326 * IPython/Magic.py (magic_psearch): new support for wildcard
1309 patterns. Now, typing ?a*b will list all names which begin with a
1327 patterns. Now, typing ?a*b will list all names which begin with a
1310 and end in b, for example. The %psearch magic has full
1328 and end in b, for example. The %psearch magic has full
1311 docstrings. Many thanks to JΓΆrgen Stenarson
1329 docstrings. Many thanks to JΓΆrgen Stenarson
1312 <jorgen.stenarson-AT-bostream.nu>, author of the patches
1330 <jorgen.stenarson-AT-bostream.nu>, author of the patches
1313 implementing this functionality.
1331 implementing this functionality.
1314
1332
1315 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
1333 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
1316
1334
1317 * Manual: fixed long-standing annoyance of double-dashes (as in
1335 * Manual: fixed long-standing annoyance of double-dashes (as in
1318 --prefix=~, for example) being stripped in the HTML version. This
1336 --prefix=~, for example) being stripped in the HTML version. This
1319 is a latex2html bug, but a workaround was provided. Many thanks
1337 is a latex2html bug, but a workaround was provided. Many thanks
1320 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
1338 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
1321 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
1339 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
1322 rolling. This seemingly small issue had tripped a number of users
1340 rolling. This seemingly small issue had tripped a number of users
1323 when first installing, so I'm glad to see it gone.
1341 when first installing, so I'm glad to see it gone.
1324
1342
1325 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
1343 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
1326
1344
1327 * IPython/Extensions/numeric_formats.py: fix missing import,
1345 * IPython/Extensions/numeric_formats.py: fix missing import,
1328 reported by Stephen Walton.
1346 reported by Stephen Walton.
1329
1347
1330 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
1348 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
1331
1349
1332 * IPython/demo.py: finish demo module, fully documented now.
1350 * IPython/demo.py: finish demo module, fully documented now.
1333
1351
1334 * IPython/genutils.py (file_read): simple little utility to read a
1352 * IPython/genutils.py (file_read): simple little utility to read a
1335 file and ensure it's closed afterwards.
1353 file and ensure it's closed afterwards.
1336
1354
1337 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
1355 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
1338
1356
1339 * IPython/demo.py (Demo.__init__): added support for individually
1357 * IPython/demo.py (Demo.__init__): added support for individually
1340 tagging blocks for automatic execution.
1358 tagging blocks for automatic execution.
1341
1359
1342 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
1360 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
1343 syntax-highlighted python sources, requested by John.
1361 syntax-highlighted python sources, requested by John.
1344
1362
1345 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
1363 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
1346
1364
1347 * IPython/demo.py (Demo.again): fix bug where again() blocks after
1365 * IPython/demo.py (Demo.again): fix bug where again() blocks after
1348 finishing.
1366 finishing.
1349
1367
1350 * IPython/genutils.py (shlex_split): moved from Magic to here,
1368 * IPython/genutils.py (shlex_split): moved from Magic to here,
1351 where all 2.2 compatibility stuff lives. I needed it for demo.py.
1369 where all 2.2 compatibility stuff lives. I needed it for demo.py.
1352
1370
1353 * IPython/demo.py (Demo.__init__): added support for silent
1371 * IPython/demo.py (Demo.__init__): added support for silent
1354 blocks, improved marks as regexps, docstrings written.
1372 blocks, improved marks as regexps, docstrings written.
1355 (Demo.__init__): better docstring, added support for sys.argv.
1373 (Demo.__init__): better docstring, added support for sys.argv.
1356
1374
1357 * IPython/genutils.py (marquee): little utility used by the demo
1375 * IPython/genutils.py (marquee): little utility used by the demo
1358 code, handy in general.
1376 code, handy in general.
1359
1377
1360 * IPython/demo.py (Demo.__init__): new class for interactive
1378 * IPython/demo.py (Demo.__init__): new class for interactive
1361 demos. Not documented yet, I just wrote it in a hurry for
1379 demos. Not documented yet, I just wrote it in a hurry for
1362 scipy'05. Will docstring later.
1380 scipy'05. Will docstring later.
1363
1381
1364 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
1382 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
1365
1383
1366 * IPython/Shell.py (sigint_handler): Drastic simplification which
1384 * IPython/Shell.py (sigint_handler): Drastic simplification which
1367 also seems to make Ctrl-C work correctly across threads! This is
1385 also seems to make Ctrl-C work correctly across threads! This is
1368 so simple, that I can't beleive I'd missed it before. Needs more
1386 so simple, that I can't beleive I'd missed it before. Needs more
1369 testing, though.
1387 testing, though.
1370 (KBINT): Never mind, revert changes. I'm sure I'd tried something
1388 (KBINT): Never mind, revert changes. I'm sure I'd tried something
1371 like this before...
1389 like this before...
1372
1390
1373 * IPython/genutils.py (get_home_dir): add protection against
1391 * IPython/genutils.py (get_home_dir): add protection against
1374 non-dirs in win32 registry.
1392 non-dirs in win32 registry.
1375
1393
1376 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
1394 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
1377 bug where dict was mutated while iterating (pysh crash).
1395 bug where dict was mutated while iterating (pysh crash).
1378
1396
1379 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
1397 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
1380
1398
1381 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
1399 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
1382 spurious newlines added by this routine. After a report by
1400 spurious newlines added by this routine. After a report by
1383 F. Mantegazza.
1401 F. Mantegazza.
1384
1402
1385 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
1403 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
1386
1404
1387 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
1405 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
1388 calls. These were a leftover from the GTK 1.x days, and can cause
1406 calls. These were a leftover from the GTK 1.x days, and can cause
1389 problems in certain cases (after a report by John Hunter).
1407 problems in certain cases (after a report by John Hunter).
1390
1408
1391 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
1409 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
1392 os.getcwd() fails at init time. Thanks to patch from David Remahl
1410 os.getcwd() fails at init time. Thanks to patch from David Remahl
1393 <chmod007-AT-mac.com>.
1411 <chmod007-AT-mac.com>.
1394 (InteractiveShell.__init__): prevent certain special magics from
1412 (InteractiveShell.__init__): prevent certain special magics from
1395 being shadowed by aliases. Closes
1413 being shadowed by aliases. Closes
1396 http://www.scipy.net/roundup/ipython/issue41.
1414 http://www.scipy.net/roundup/ipython/issue41.
1397
1415
1398 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
1416 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
1399
1417
1400 * IPython/iplib.py (InteractiveShell.complete): Added new
1418 * IPython/iplib.py (InteractiveShell.complete): Added new
1401 top-level completion method to expose the completion mechanism
1419 top-level completion method to expose the completion mechanism
1402 beyond readline-based environments.
1420 beyond readline-based environments.
1403
1421
1404 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
1422 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
1405
1423
1406 * tools/ipsvnc (svnversion): fix svnversion capture.
1424 * tools/ipsvnc (svnversion): fix svnversion capture.
1407
1425
1408 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
1426 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
1409 attribute to self, which was missing. Before, it was set by a
1427 attribute to self, which was missing. Before, it was set by a
1410 routine which in certain cases wasn't being called, so the
1428 routine which in certain cases wasn't being called, so the
1411 instance could end up missing the attribute. This caused a crash.
1429 instance could end up missing the attribute. This caused a crash.
1412 Closes http://www.scipy.net/roundup/ipython/issue40.
1430 Closes http://www.scipy.net/roundup/ipython/issue40.
1413
1431
1414 2005-08-16 Fernando Perez <fperez@colorado.edu>
1432 2005-08-16 Fernando Perez <fperez@colorado.edu>
1415
1433
1416 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
1434 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
1417 contains non-string attribute. Closes
1435 contains non-string attribute. Closes
1418 http://www.scipy.net/roundup/ipython/issue38.
1436 http://www.scipy.net/roundup/ipython/issue38.
1419
1437
1420 2005-08-14 Fernando Perez <fperez@colorado.edu>
1438 2005-08-14 Fernando Perez <fperez@colorado.edu>
1421
1439
1422 * tools/ipsvnc: Minor improvements, to add changeset info.
1440 * tools/ipsvnc: Minor improvements, to add changeset info.
1423
1441
1424 2005-08-12 Fernando Perez <fperez@colorado.edu>
1442 2005-08-12 Fernando Perez <fperez@colorado.edu>
1425
1443
1426 * IPython/iplib.py (runsource): remove self.code_to_run_src
1444 * IPython/iplib.py (runsource): remove self.code_to_run_src
1427 attribute. I realized this is nothing more than
1445 attribute. I realized this is nothing more than
1428 '\n'.join(self.buffer), and having the same data in two different
1446 '\n'.join(self.buffer), and having the same data in two different
1429 places is just asking for synchronization bugs. This may impact
1447 places is just asking for synchronization bugs. This may impact
1430 people who have custom exception handlers, so I need to warn
1448 people who have custom exception handlers, so I need to warn
1431 ipython-dev about it (F. Mantegazza may use them).
1449 ipython-dev about it (F. Mantegazza may use them).
1432
1450
1433 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
1451 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
1434
1452
1435 * IPython/genutils.py: fix 2.2 compatibility (generators)
1453 * IPython/genutils.py: fix 2.2 compatibility (generators)
1436
1454
1437 2005-07-18 Fernando Perez <fperez@colorado.edu>
1455 2005-07-18 Fernando Perez <fperez@colorado.edu>
1438
1456
1439 * IPython/genutils.py (get_home_dir): fix to help users with
1457 * IPython/genutils.py (get_home_dir): fix to help users with
1440 invalid $HOME under win32.
1458 invalid $HOME under win32.
1441
1459
1442 2005-07-17 Fernando Perez <fperez@colorado.edu>
1460 2005-07-17 Fernando Perez <fperez@colorado.edu>
1443
1461
1444 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
1462 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
1445 some old hacks and clean up a bit other routines; code should be
1463 some old hacks and clean up a bit other routines; code should be
1446 simpler and a bit faster.
1464 simpler and a bit faster.
1447
1465
1448 * IPython/iplib.py (interact): removed some last-resort attempts
1466 * IPython/iplib.py (interact): removed some last-resort attempts
1449 to survive broken stdout/stderr. That code was only making it
1467 to survive broken stdout/stderr. That code was only making it
1450 harder to abstract out the i/o (necessary for gui integration),
1468 harder to abstract out the i/o (necessary for gui integration),
1451 and the crashes it could prevent were extremely rare in practice
1469 and the crashes it could prevent were extremely rare in practice
1452 (besides being fully user-induced in a pretty violent manner).
1470 (besides being fully user-induced in a pretty violent manner).
1453
1471
1454 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
1472 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
1455 Nothing major yet, but the code is simpler to read; this should
1473 Nothing major yet, but the code is simpler to read; this should
1456 make it easier to do more serious modifications in the future.
1474 make it easier to do more serious modifications in the future.
1457
1475
1458 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
1476 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
1459 which broke in .15 (thanks to a report by Ville).
1477 which broke in .15 (thanks to a report by Ville).
1460
1478
1461 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
1479 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
1462 be quite correct, I know next to nothing about unicode). This
1480 be quite correct, I know next to nothing about unicode). This
1463 will allow unicode strings to be used in prompts, amongst other
1481 will allow unicode strings to be used in prompts, amongst other
1464 cases. It also will prevent ipython from crashing when unicode
1482 cases. It also will prevent ipython from crashing when unicode
1465 shows up unexpectedly in many places. If ascii encoding fails, we
1483 shows up unexpectedly in many places. If ascii encoding fails, we
1466 assume utf_8. Currently the encoding is not a user-visible
1484 assume utf_8. Currently the encoding is not a user-visible
1467 setting, though it could be made so if there is demand for it.
1485 setting, though it could be made so if there is demand for it.
1468
1486
1469 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
1487 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
1470
1488
1471 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
1489 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
1472
1490
1473 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
1491 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
1474
1492
1475 * IPython/genutils.py: Add 2.2 compatibility here, so all other
1493 * IPython/genutils.py: Add 2.2 compatibility here, so all other
1476 code can work transparently for 2.2/2.3.
1494 code can work transparently for 2.2/2.3.
1477
1495
1478 2005-07-16 Fernando Perez <fperez@colorado.edu>
1496 2005-07-16 Fernando Perez <fperez@colorado.edu>
1479
1497
1480 * IPython/ultraTB.py (ExceptionColors): Make a global variable
1498 * IPython/ultraTB.py (ExceptionColors): Make a global variable
1481 out of the color scheme table used for coloring exception
1499 out of the color scheme table used for coloring exception
1482 tracebacks. This allows user code to add new schemes at runtime.
1500 tracebacks. This allows user code to add new schemes at runtime.
1483 This is a minimally modified version of the patch at
1501 This is a minimally modified version of the patch at
1484 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
1502 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
1485 for the contribution.
1503 for the contribution.
1486
1504
1487 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
1505 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
1488 slightly modified version of the patch in
1506 slightly modified version of the patch in
1489 http://www.scipy.net/roundup/ipython/issue34, which also allows me
1507 http://www.scipy.net/roundup/ipython/issue34, which also allows me
1490 to remove the previous try/except solution (which was costlier).
1508 to remove the previous try/except solution (which was costlier).
1491 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
1509 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
1492
1510
1493 2005-06-08 Fernando Perez <fperez@colorado.edu>
1511 2005-06-08 Fernando Perez <fperez@colorado.edu>
1494
1512
1495 * IPython/iplib.py (write/write_err): Add methods to abstract all
1513 * IPython/iplib.py (write/write_err): Add methods to abstract all
1496 I/O a bit more.
1514 I/O a bit more.
1497
1515
1498 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
1516 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
1499 warning, reported by Aric Hagberg, fix by JD Hunter.
1517 warning, reported by Aric Hagberg, fix by JD Hunter.
1500
1518
1501 2005-06-02 *** Released version 0.6.15
1519 2005-06-02 *** Released version 0.6.15
1502
1520
1503 2005-06-01 Fernando Perez <fperez@colorado.edu>
1521 2005-06-01 Fernando Perez <fperez@colorado.edu>
1504
1522
1505 * IPython/iplib.py (MagicCompleter.file_matches): Fix
1523 * IPython/iplib.py (MagicCompleter.file_matches): Fix
1506 tab-completion of filenames within open-quoted strings. Note that
1524 tab-completion of filenames within open-quoted strings. Note that
1507 this requires that in ~/.ipython/ipythonrc, users change the
1525 this requires that in ~/.ipython/ipythonrc, users change the
1508 readline delimiters configuration to read:
1526 readline delimiters configuration to read:
1509
1527
1510 readline_remove_delims -/~
1528 readline_remove_delims -/~
1511
1529
1512
1530
1513 2005-05-31 *** Released version 0.6.14
1531 2005-05-31 *** Released version 0.6.14
1514
1532
1515 2005-05-29 Fernando Perez <fperez@colorado.edu>
1533 2005-05-29 Fernando Perez <fperez@colorado.edu>
1516
1534
1517 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
1535 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
1518 with files not on the filesystem. Reported by Eliyahu Sandler
1536 with files not on the filesystem. Reported by Eliyahu Sandler
1519 <eli@gondolin.net>
1537 <eli@gondolin.net>
1520
1538
1521 2005-05-22 Fernando Perez <fperez@colorado.edu>
1539 2005-05-22 Fernando Perez <fperez@colorado.edu>
1522
1540
1523 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
1541 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
1524 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
1542 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
1525
1543
1526 2005-05-19 Fernando Perez <fperez@colorado.edu>
1544 2005-05-19 Fernando Perez <fperez@colorado.edu>
1527
1545
1528 * IPython/iplib.py (safe_execfile): close a file which could be
1546 * IPython/iplib.py (safe_execfile): close a file which could be
1529 left open (causing problems in win32, which locks open files).
1547 left open (causing problems in win32, which locks open files).
1530 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
1548 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
1531
1549
1532 2005-05-18 Fernando Perez <fperez@colorado.edu>
1550 2005-05-18 Fernando Perez <fperez@colorado.edu>
1533
1551
1534 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
1552 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
1535 keyword arguments correctly to safe_execfile().
1553 keyword arguments correctly to safe_execfile().
1536
1554
1537 2005-05-13 Fernando Perez <fperez@colorado.edu>
1555 2005-05-13 Fernando Perez <fperez@colorado.edu>
1538
1556
1539 * ipython.1: Added info about Qt to manpage, and threads warning
1557 * ipython.1: Added info about Qt to manpage, and threads warning
1540 to usage page (invoked with --help).
1558 to usage page (invoked with --help).
1541
1559
1542 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
1560 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
1543 new matcher (it goes at the end of the priority list) to do
1561 new matcher (it goes at the end of the priority list) to do
1544 tab-completion on named function arguments. Submitted by George
1562 tab-completion on named function arguments. Submitted by George
1545 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
1563 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
1546 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
1564 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
1547 for more details.
1565 for more details.
1548
1566
1549 * IPython/Magic.py (magic_run): Added new -e flag to ignore
1567 * IPython/Magic.py (magic_run): Added new -e flag to ignore
1550 SystemExit exceptions in the script being run. Thanks to a report
1568 SystemExit exceptions in the script being run. Thanks to a report
1551 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
1569 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
1552 producing very annoying behavior when running unit tests.
1570 producing very annoying behavior when running unit tests.
1553
1571
1554 2005-05-12 Fernando Perez <fperez@colorado.edu>
1572 2005-05-12 Fernando Perez <fperez@colorado.edu>
1555
1573
1556 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
1574 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
1557 which I'd broken (again) due to a changed regexp. In the process,
1575 which I'd broken (again) due to a changed regexp. In the process,
1558 added ';' as an escape to auto-quote the whole line without
1576 added ';' as an escape to auto-quote the whole line without
1559 splitting its arguments. Thanks to a report by Jerry McRae
1577 splitting its arguments. Thanks to a report by Jerry McRae
1560 <qrs0xyc02-AT-sneakemail.com>.
1578 <qrs0xyc02-AT-sneakemail.com>.
1561
1579
1562 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
1580 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
1563 possible crashes caused by a TokenError. Reported by Ed Schofield
1581 possible crashes caused by a TokenError. Reported by Ed Schofield
1564 <schofield-AT-ftw.at>.
1582 <schofield-AT-ftw.at>.
1565
1583
1566 2005-05-06 Fernando Perez <fperez@colorado.edu>
1584 2005-05-06 Fernando Perez <fperez@colorado.edu>
1567
1585
1568 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
1586 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
1569
1587
1570 2005-04-29 Fernando Perez <fperez@colorado.edu>
1588 2005-04-29 Fernando Perez <fperez@colorado.edu>
1571
1589
1572 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
1590 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
1573 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
1591 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
1574 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
1592 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
1575 which provides support for Qt interactive usage (similar to the
1593 which provides support for Qt interactive usage (similar to the
1576 existing one for WX and GTK). This had been often requested.
1594 existing one for WX and GTK). This had been often requested.
1577
1595
1578 2005-04-14 *** Released version 0.6.13
1596 2005-04-14 *** Released version 0.6.13
1579
1597
1580 2005-04-08 Fernando Perez <fperez@colorado.edu>
1598 2005-04-08 Fernando Perez <fperez@colorado.edu>
1581
1599
1582 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
1600 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
1583 from _ofind, which gets called on almost every input line. Now,
1601 from _ofind, which gets called on almost every input line. Now,
1584 we only try to get docstrings if they are actually going to be
1602 we only try to get docstrings if they are actually going to be
1585 used (the overhead of fetching unnecessary docstrings can be
1603 used (the overhead of fetching unnecessary docstrings can be
1586 noticeable for certain objects, such as Pyro proxies).
1604 noticeable for certain objects, such as Pyro proxies).
1587
1605
1588 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
1606 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
1589 for completers. For some reason I had been passing them the state
1607 for completers. For some reason I had been passing them the state
1590 variable, which completers never actually need, and was in
1608 variable, which completers never actually need, and was in
1591 conflict with the rlcompleter API. Custom completers ONLY need to
1609 conflict with the rlcompleter API. Custom completers ONLY need to
1592 take the text parameter.
1610 take the text parameter.
1593
1611
1594 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
1612 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
1595 work correctly in pysh. I've also moved all the logic which used
1613 work correctly in pysh. I've also moved all the logic which used
1596 to be in pysh.py here, which will prevent problems with future
1614 to be in pysh.py here, which will prevent problems with future
1597 upgrades. However, this time I must warn users to update their
1615 upgrades. However, this time I must warn users to update their
1598 pysh profile to include the line
1616 pysh profile to include the line
1599
1617
1600 import_all IPython.Extensions.InterpreterExec
1618 import_all IPython.Extensions.InterpreterExec
1601
1619
1602 because otherwise things won't work for them. They MUST also
1620 because otherwise things won't work for them. They MUST also
1603 delete pysh.py and the line
1621 delete pysh.py and the line
1604
1622
1605 execfile pysh.py
1623 execfile pysh.py
1606
1624
1607 from their ipythonrc-pysh.
1625 from their ipythonrc-pysh.
1608
1626
1609 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
1627 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
1610 robust in the face of objects whose dir() returns non-strings
1628 robust in the face of objects whose dir() returns non-strings
1611 (which it shouldn't, but some broken libs like ITK do). Thanks to
1629 (which it shouldn't, but some broken libs like ITK do). Thanks to
1612 a patch by John Hunter (implemented differently, though). Also
1630 a patch by John Hunter (implemented differently, though). Also
1613 minor improvements by using .extend instead of + on lists.
1631 minor improvements by using .extend instead of + on lists.
1614
1632
1615 * pysh.py:
1633 * pysh.py:
1616
1634
1617 2005-04-06 Fernando Perez <fperez@colorado.edu>
1635 2005-04-06 Fernando Perez <fperez@colorado.edu>
1618
1636
1619 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
1637 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
1620 by default, so that all users benefit from it. Those who don't
1638 by default, so that all users benefit from it. Those who don't
1621 want it can still turn it off.
1639 want it can still turn it off.
1622
1640
1623 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
1641 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
1624 config file, I'd forgotten about this, so users were getting it
1642 config file, I'd forgotten about this, so users were getting it
1625 off by default.
1643 off by default.
1626
1644
1627 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
1645 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
1628 consistency. Now magics can be called in multiline statements,
1646 consistency. Now magics can be called in multiline statements,
1629 and python variables can be expanded in magic calls via $var.
1647 and python variables can be expanded in magic calls via $var.
1630 This makes the magic system behave just like aliases or !system
1648 This makes the magic system behave just like aliases or !system
1631 calls.
1649 calls.
1632
1650
1633 2005-03-28 Fernando Perez <fperez@colorado.edu>
1651 2005-03-28 Fernando Perez <fperez@colorado.edu>
1634
1652
1635 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
1653 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
1636 expensive string additions for building command. Add support for
1654 expensive string additions for building command. Add support for
1637 trailing ';' when autocall is used.
1655 trailing ';' when autocall is used.
1638
1656
1639 2005-03-26 Fernando Perez <fperez@colorado.edu>
1657 2005-03-26 Fernando Perez <fperez@colorado.edu>
1640
1658
1641 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
1659 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
1642 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
1660 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
1643 ipython.el robust against prompts with any number of spaces
1661 ipython.el robust against prompts with any number of spaces
1644 (including 0) after the ':' character.
1662 (including 0) after the ':' character.
1645
1663
1646 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
1664 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
1647 continuation prompt, which misled users to think the line was
1665 continuation prompt, which misled users to think the line was
1648 already indented. Closes debian Bug#300847, reported to me by
1666 already indented. Closes debian Bug#300847, reported to me by
1649 Norbert Tretkowski <tretkowski-AT-inittab.de>.
1667 Norbert Tretkowski <tretkowski-AT-inittab.de>.
1650
1668
1651 2005-03-23 Fernando Perez <fperez@colorado.edu>
1669 2005-03-23 Fernando Perez <fperez@colorado.edu>
1652
1670
1653 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
1671 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
1654 properly aligned if they have embedded newlines.
1672 properly aligned if they have embedded newlines.
1655
1673
1656 * IPython/iplib.py (runlines): Add a public method to expose
1674 * IPython/iplib.py (runlines): Add a public method to expose
1657 IPython's code execution machinery, so that users can run strings
1675 IPython's code execution machinery, so that users can run strings
1658 as if they had been typed at the prompt interactively.
1676 as if they had been typed at the prompt interactively.
1659 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
1677 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
1660 methods which can call the system shell, but with python variable
1678 methods which can call the system shell, but with python variable
1661 expansion. The three such methods are: __IPYTHON__.system,
1679 expansion. The three such methods are: __IPYTHON__.system,
1662 .getoutput and .getoutputerror. These need to be documented in a
1680 .getoutput and .getoutputerror. These need to be documented in a
1663 'public API' section (to be written) of the manual.
1681 'public API' section (to be written) of the manual.
1664
1682
1665 2005-03-20 Fernando Perez <fperez@colorado.edu>
1683 2005-03-20 Fernando Perez <fperez@colorado.edu>
1666
1684
1667 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
1685 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
1668 for custom exception handling. This is quite powerful, and it
1686 for custom exception handling. This is quite powerful, and it
1669 allows for user-installable exception handlers which can trap
1687 allows for user-installable exception handlers which can trap
1670 custom exceptions at runtime and treat them separately from
1688 custom exceptions at runtime and treat them separately from
1671 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
1689 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
1672 Mantegazza <mantegazza-AT-ill.fr>.
1690 Mantegazza <mantegazza-AT-ill.fr>.
1673 (InteractiveShell.set_custom_completer): public API function to
1691 (InteractiveShell.set_custom_completer): public API function to
1674 add new completers at runtime.
1692 add new completers at runtime.
1675
1693
1676 2005-03-19 Fernando Perez <fperez@colorado.edu>
1694 2005-03-19 Fernando Perez <fperez@colorado.edu>
1677
1695
1678 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
1696 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
1679 allow objects which provide their docstrings via non-standard
1697 allow objects which provide their docstrings via non-standard
1680 mechanisms (like Pyro proxies) to still be inspected by ipython's
1698 mechanisms (like Pyro proxies) to still be inspected by ipython's
1681 ? system.
1699 ? system.
1682
1700
1683 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
1701 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
1684 automatic capture system. I tried quite hard to make it work
1702 automatic capture system. I tried quite hard to make it work
1685 reliably, and simply failed. I tried many combinations with the
1703 reliably, and simply failed. I tried many combinations with the
1686 subprocess module, but eventually nothing worked in all needed
1704 subprocess module, but eventually nothing worked in all needed
1687 cases (not blocking stdin for the child, duplicating stdout
1705 cases (not blocking stdin for the child, duplicating stdout
1688 without blocking, etc). The new %sc/%sx still do capture to these
1706 without blocking, etc). The new %sc/%sx still do capture to these
1689 magical list/string objects which make shell use much more
1707 magical list/string objects which make shell use much more
1690 conveninent, so not all is lost.
1708 conveninent, so not all is lost.
1691
1709
1692 XXX - FIX MANUAL for the change above!
1710 XXX - FIX MANUAL for the change above!
1693
1711
1694 (runsource): I copied code.py's runsource() into ipython to modify
1712 (runsource): I copied code.py's runsource() into ipython to modify
1695 it a bit. Now the code object and source to be executed are
1713 it a bit. Now the code object and source to be executed are
1696 stored in ipython. This makes this info accessible to third-party
1714 stored in ipython. This makes this info accessible to third-party
1697 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
1715 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
1698 Mantegazza <mantegazza-AT-ill.fr>.
1716 Mantegazza <mantegazza-AT-ill.fr>.
1699
1717
1700 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
1718 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
1701 history-search via readline (like C-p/C-n). I'd wanted this for a
1719 history-search via readline (like C-p/C-n). I'd wanted this for a
1702 long time, but only recently found out how to do it. For users
1720 long time, but only recently found out how to do it. For users
1703 who already have their ipythonrc files made and want this, just
1721 who already have their ipythonrc files made and want this, just
1704 add:
1722 add:
1705
1723
1706 readline_parse_and_bind "\e[A": history-search-backward
1724 readline_parse_and_bind "\e[A": history-search-backward
1707 readline_parse_and_bind "\e[B": history-search-forward
1725 readline_parse_and_bind "\e[B": history-search-forward
1708
1726
1709 2005-03-18 Fernando Perez <fperez@colorado.edu>
1727 2005-03-18 Fernando Perez <fperez@colorado.edu>
1710
1728
1711 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
1729 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
1712 LSString and SList classes which allow transparent conversions
1730 LSString and SList classes which allow transparent conversions
1713 between list mode and whitespace-separated string.
1731 between list mode and whitespace-separated string.
1714 (magic_r): Fix recursion problem in %r.
1732 (magic_r): Fix recursion problem in %r.
1715
1733
1716 * IPython/genutils.py (LSString): New class to be used for
1734 * IPython/genutils.py (LSString): New class to be used for
1717 automatic storage of the results of all alias/system calls in _o
1735 automatic storage of the results of all alias/system calls in _o
1718 and _e (stdout/err). These provide a .l/.list attribute which
1736 and _e (stdout/err). These provide a .l/.list attribute which
1719 does automatic splitting on newlines. This means that for most
1737 does automatic splitting on newlines. This means that for most
1720 uses, you'll never need to do capturing of output with %sc/%sx
1738 uses, you'll never need to do capturing of output with %sc/%sx
1721 anymore, since ipython keeps this always done for you. Note that
1739 anymore, since ipython keeps this always done for you. Note that
1722 only the LAST results are stored, the _o/e variables are
1740 only the LAST results are stored, the _o/e variables are
1723 overwritten on each call. If you need to save their contents
1741 overwritten on each call. If you need to save their contents
1724 further, simply bind them to any other name.
1742 further, simply bind them to any other name.
1725
1743
1726 2005-03-17 Fernando Perez <fperez@colorado.edu>
1744 2005-03-17 Fernando Perez <fperez@colorado.edu>
1727
1745
1728 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
1746 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
1729 prompt namespace handling.
1747 prompt namespace handling.
1730
1748
1731 2005-03-16 Fernando Perez <fperez@colorado.edu>
1749 2005-03-16 Fernando Perez <fperez@colorado.edu>
1732
1750
1733 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
1751 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
1734 classic prompts to be '>>> ' (final space was missing, and it
1752 classic prompts to be '>>> ' (final space was missing, and it
1735 trips the emacs python mode).
1753 trips the emacs python mode).
1736 (BasePrompt.__str__): Added safe support for dynamic prompt
1754 (BasePrompt.__str__): Added safe support for dynamic prompt
1737 strings. Now you can set your prompt string to be '$x', and the
1755 strings. Now you can set your prompt string to be '$x', and the
1738 value of x will be printed from your interactive namespace. The
1756 value of x will be printed from your interactive namespace. The
1739 interpolation syntax includes the full Itpl support, so
1757 interpolation syntax includes the full Itpl support, so
1740 ${foo()+x+bar()} is a valid prompt string now, and the function
1758 ${foo()+x+bar()} is a valid prompt string now, and the function
1741 calls will be made at runtime.
1759 calls will be made at runtime.
1742
1760
1743 2005-03-15 Fernando Perez <fperez@colorado.edu>
1761 2005-03-15 Fernando Perez <fperez@colorado.edu>
1744
1762
1745 * IPython/Magic.py (magic_history): renamed %hist to %history, to
1763 * IPython/Magic.py (magic_history): renamed %hist to %history, to
1746 avoid name clashes in pylab. %hist still works, it just forwards
1764 avoid name clashes in pylab. %hist still works, it just forwards
1747 the call to %history.
1765 the call to %history.
1748
1766
1749 2005-03-02 *** Released version 0.6.12
1767 2005-03-02 *** Released version 0.6.12
1750
1768
1751 2005-03-02 Fernando Perez <fperez@colorado.edu>
1769 2005-03-02 Fernando Perez <fperez@colorado.edu>
1752
1770
1753 * IPython/iplib.py (handle_magic): log magic calls properly as
1771 * IPython/iplib.py (handle_magic): log magic calls properly as
1754 ipmagic() function calls.
1772 ipmagic() function calls.
1755
1773
1756 * IPython/Magic.py (magic_time): Improved %time to support
1774 * IPython/Magic.py (magic_time): Improved %time to support
1757 statements and provide wall-clock as well as CPU time.
1775 statements and provide wall-clock as well as CPU time.
1758
1776
1759 2005-02-27 Fernando Perez <fperez@colorado.edu>
1777 2005-02-27 Fernando Perez <fperez@colorado.edu>
1760
1778
1761 * IPython/hooks.py: New hooks module, to expose user-modifiable
1779 * IPython/hooks.py: New hooks module, to expose user-modifiable
1762 IPython functionality in a clean manner. For now only the editor
1780 IPython functionality in a clean manner. For now only the editor
1763 hook is actually written, and other thigns which I intend to turn
1781 hook is actually written, and other thigns which I intend to turn
1764 into proper hooks aren't yet there. The display and prefilter
1782 into proper hooks aren't yet there. The display and prefilter
1765 stuff, for example, should be hooks. But at least now the
1783 stuff, for example, should be hooks. But at least now the
1766 framework is in place, and the rest can be moved here with more
1784 framework is in place, and the rest can be moved here with more
1767 time later. IPython had had a .hooks variable for a long time for
1785 time later. IPython had had a .hooks variable for a long time for
1768 this purpose, but I'd never actually used it for anything.
1786 this purpose, but I'd never actually used it for anything.
1769
1787
1770 2005-02-26 Fernando Perez <fperez@colorado.edu>
1788 2005-02-26 Fernando Perez <fperez@colorado.edu>
1771
1789
1772 * IPython/ipmaker.py (make_IPython): make the default ipython
1790 * IPython/ipmaker.py (make_IPython): make the default ipython
1773 directory be called _ipython under win32, to follow more the
1791 directory be called _ipython under win32, to follow more the
1774 naming peculiarities of that platform (where buggy software like
1792 naming peculiarities of that platform (where buggy software like
1775 Visual Sourcesafe breaks with .named directories). Reported by
1793 Visual Sourcesafe breaks with .named directories). Reported by
1776 Ville Vainio.
1794 Ville Vainio.
1777
1795
1778 2005-02-23 Fernando Perez <fperez@colorado.edu>
1796 2005-02-23 Fernando Perez <fperez@colorado.edu>
1779
1797
1780 * IPython/iplib.py (InteractiveShell.__init__): removed a few
1798 * IPython/iplib.py (InteractiveShell.__init__): removed a few
1781 auto_aliases for win32 which were causing problems. Users can
1799 auto_aliases for win32 which were causing problems. Users can
1782 define the ones they personally like.
1800 define the ones they personally like.
1783
1801
1784 2005-02-21 Fernando Perez <fperez@colorado.edu>
1802 2005-02-21 Fernando Perez <fperez@colorado.edu>
1785
1803
1786 * IPython/Magic.py (magic_time): new magic to time execution of
1804 * IPython/Magic.py (magic_time): new magic to time execution of
1787 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
1805 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
1788
1806
1789 2005-02-19 Fernando Perez <fperez@colorado.edu>
1807 2005-02-19 Fernando Perez <fperez@colorado.edu>
1790
1808
1791 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
1809 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
1792 into keys (for prompts, for example).
1810 into keys (for prompts, for example).
1793
1811
1794 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
1812 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
1795 prompts in case users want them. This introduces a small behavior
1813 prompts in case users want them. This introduces a small behavior
1796 change: ipython does not automatically add a space to all prompts
1814 change: ipython does not automatically add a space to all prompts
1797 anymore. To get the old prompts with a space, users should add it
1815 anymore. To get the old prompts with a space, users should add it
1798 manually to their ipythonrc file, so for example prompt_in1 should
1816 manually to their ipythonrc file, so for example prompt_in1 should
1799 now read 'In [\#]: ' instead of 'In [\#]:'.
1817 now read 'In [\#]: ' instead of 'In [\#]:'.
1800 (BasePrompt.__init__): New option prompts_pad_left (only in rc
1818 (BasePrompt.__init__): New option prompts_pad_left (only in rc
1801 file) to control left-padding of secondary prompts.
1819 file) to control left-padding of secondary prompts.
1802
1820
1803 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
1821 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
1804 the profiler can't be imported. Fix for Debian, which removed
1822 the profiler can't be imported. Fix for Debian, which removed
1805 profile.py because of License issues. I applied a slightly
1823 profile.py because of License issues. I applied a slightly
1806 modified version of the original Debian patch at
1824 modified version of the original Debian patch at
1807 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
1825 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
1808
1826
1809 2005-02-17 Fernando Perez <fperez@colorado.edu>
1827 2005-02-17 Fernando Perez <fperez@colorado.edu>
1810
1828
1811 * IPython/genutils.py (native_line_ends): Fix bug which would
1829 * IPython/genutils.py (native_line_ends): Fix bug which would
1812 cause improper line-ends under win32 b/c I was not opening files
1830 cause improper line-ends under win32 b/c I was not opening files
1813 in binary mode. Bug report and fix thanks to Ville.
1831 in binary mode. Bug report and fix thanks to Ville.
1814
1832
1815 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
1833 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
1816 trying to catch spurious foo[1] autocalls. My fix actually broke
1834 trying to catch spurious foo[1] autocalls. My fix actually broke
1817 ',/' autoquote/call with explicit escape (bad regexp).
1835 ',/' autoquote/call with explicit escape (bad regexp).
1818
1836
1819 2005-02-15 *** Released version 0.6.11
1837 2005-02-15 *** Released version 0.6.11
1820
1838
1821 2005-02-14 Fernando Perez <fperez@colorado.edu>
1839 2005-02-14 Fernando Perez <fperez@colorado.edu>
1822
1840
1823 * IPython/background_jobs.py: New background job management
1841 * IPython/background_jobs.py: New background job management
1824 subsystem. This is implemented via a new set of classes, and
1842 subsystem. This is implemented via a new set of classes, and
1825 IPython now provides a builtin 'jobs' object for background job
1843 IPython now provides a builtin 'jobs' object for background job
1826 execution. A convenience %bg magic serves as a lightweight
1844 execution. A convenience %bg magic serves as a lightweight
1827 frontend for starting the more common type of calls. This was
1845 frontend for starting the more common type of calls. This was
1828 inspired by discussions with B. Granger and the BackgroundCommand
1846 inspired by discussions with B. Granger and the BackgroundCommand
1829 class described in the book Python Scripting for Computational
1847 class described in the book Python Scripting for Computational
1830 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
1848 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
1831 (although ultimately no code from this text was used, as IPython's
1849 (although ultimately no code from this text was used, as IPython's
1832 system is a separate implementation).
1850 system is a separate implementation).
1833
1851
1834 * IPython/iplib.py (MagicCompleter.python_matches): add new option
1852 * IPython/iplib.py (MagicCompleter.python_matches): add new option
1835 to control the completion of single/double underscore names
1853 to control the completion of single/double underscore names
1836 separately. As documented in the example ipytonrc file, the
1854 separately. As documented in the example ipytonrc file, the
1837 readline_omit__names variable can now be set to 2, to omit even
1855 readline_omit__names variable can now be set to 2, to omit even
1838 single underscore names. Thanks to a patch by Brian Wong
1856 single underscore names. Thanks to a patch by Brian Wong
1839 <BrianWong-AT-AirgoNetworks.Com>.
1857 <BrianWong-AT-AirgoNetworks.Com>.
1840 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
1858 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
1841 be autocalled as foo([1]) if foo were callable. A problem for
1859 be autocalled as foo([1]) if foo were callable. A problem for
1842 things which are both callable and implement __getitem__.
1860 things which are both callable and implement __getitem__.
1843 (init_readline): Fix autoindentation for win32. Thanks to a patch
1861 (init_readline): Fix autoindentation for win32. Thanks to a patch
1844 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
1862 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
1845
1863
1846 2005-02-12 Fernando Perez <fperez@colorado.edu>
1864 2005-02-12 Fernando Perez <fperez@colorado.edu>
1847
1865
1848 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
1866 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
1849 which I had written long ago to sort out user error messages which
1867 which I had written long ago to sort out user error messages which
1850 may occur during startup. This seemed like a good idea initially,
1868 may occur during startup. This seemed like a good idea initially,
1851 but it has proven a disaster in retrospect. I don't want to
1869 but it has proven a disaster in retrospect. I don't want to
1852 change much code for now, so my fix is to set the internal 'debug'
1870 change much code for now, so my fix is to set the internal 'debug'
1853 flag to true everywhere, whose only job was precisely to control
1871 flag to true everywhere, whose only job was precisely to control
1854 this subsystem. This closes issue 28 (as well as avoiding all
1872 this subsystem. This closes issue 28 (as well as avoiding all
1855 sorts of strange hangups which occur from time to time).
1873 sorts of strange hangups which occur from time to time).
1856
1874
1857 2005-02-07 Fernando Perez <fperez@colorado.edu>
1875 2005-02-07 Fernando Perez <fperez@colorado.edu>
1858
1876
1859 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
1877 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
1860 previous call produced a syntax error.
1878 previous call produced a syntax error.
1861
1879
1862 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1880 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1863 classes without constructor.
1881 classes without constructor.
1864
1882
1865 2005-02-06 Fernando Perez <fperez@colorado.edu>
1883 2005-02-06 Fernando Perez <fperez@colorado.edu>
1866
1884
1867 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
1885 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
1868 completions with the results of each matcher, so we return results
1886 completions with the results of each matcher, so we return results
1869 to the user from all namespaces. This breaks with ipython
1887 to the user from all namespaces. This breaks with ipython
1870 tradition, but I think it's a nicer behavior. Now you get all
1888 tradition, but I think it's a nicer behavior. Now you get all
1871 possible completions listed, from all possible namespaces (python,
1889 possible completions listed, from all possible namespaces (python,
1872 filesystem, magics...) After a request by John Hunter
1890 filesystem, magics...) After a request by John Hunter
1873 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1891 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1874
1892
1875 2005-02-05 Fernando Perez <fperez@colorado.edu>
1893 2005-02-05 Fernando Perez <fperez@colorado.edu>
1876
1894
1877 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
1895 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
1878 the call had quote characters in it (the quotes were stripped).
1896 the call had quote characters in it (the quotes were stripped).
1879
1897
1880 2005-01-31 Fernando Perez <fperez@colorado.edu>
1898 2005-01-31 Fernando Perez <fperez@colorado.edu>
1881
1899
1882 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
1900 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
1883 Itpl.itpl() to make the code more robust against psyco
1901 Itpl.itpl() to make the code more robust against psyco
1884 optimizations.
1902 optimizations.
1885
1903
1886 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
1904 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
1887 of causing an exception. Quicker, cleaner.
1905 of causing an exception. Quicker, cleaner.
1888
1906
1889 2005-01-28 Fernando Perez <fperez@colorado.edu>
1907 2005-01-28 Fernando Perez <fperez@colorado.edu>
1890
1908
1891 * scripts/ipython_win_post_install.py (install): hardcode
1909 * scripts/ipython_win_post_install.py (install): hardcode
1892 sys.prefix+'python.exe' as the executable path. It turns out that
1910 sys.prefix+'python.exe' as the executable path. It turns out that
1893 during the post-installation run, sys.executable resolves to the
1911 during the post-installation run, sys.executable resolves to the
1894 name of the binary installer! I should report this as a distutils
1912 name of the binary installer! I should report this as a distutils
1895 bug, I think. I updated the .10 release with this tiny fix, to
1913 bug, I think. I updated the .10 release with this tiny fix, to
1896 avoid annoying the lists further.
1914 avoid annoying the lists further.
1897
1915
1898 2005-01-27 *** Released version 0.6.10
1916 2005-01-27 *** Released version 0.6.10
1899
1917
1900 2005-01-27 Fernando Perez <fperez@colorado.edu>
1918 2005-01-27 Fernando Perez <fperez@colorado.edu>
1901
1919
1902 * IPython/numutils.py (norm): Added 'inf' as optional name for
1920 * IPython/numutils.py (norm): Added 'inf' as optional name for
1903 L-infinity norm, included references to mathworld.com for vector
1921 L-infinity norm, included references to mathworld.com for vector
1904 norm definitions.
1922 norm definitions.
1905 (amin/amax): added amin/amax for array min/max. Similar to what
1923 (amin/amax): added amin/amax for array min/max. Similar to what
1906 pylab ships with after the recent reorganization of names.
1924 pylab ships with after the recent reorganization of names.
1907 (spike/spike_odd): removed deprecated spike/spike_odd functions.
1925 (spike/spike_odd): removed deprecated spike/spike_odd functions.
1908
1926
1909 * ipython.el: committed Alex's recent fixes and improvements.
1927 * ipython.el: committed Alex's recent fixes and improvements.
1910 Tested with python-mode from CVS, and it looks excellent. Since
1928 Tested with python-mode from CVS, and it looks excellent. Since
1911 python-mode hasn't released anything in a while, I'm temporarily
1929 python-mode hasn't released anything in a while, I'm temporarily
1912 putting a copy of today's CVS (v 4.70) of python-mode in:
1930 putting a copy of today's CVS (v 4.70) of python-mode in:
1913 http://ipython.scipy.org/tmp/python-mode.el
1931 http://ipython.scipy.org/tmp/python-mode.el
1914
1932
1915 * scripts/ipython_win_post_install.py (install): Win32 fix to use
1933 * scripts/ipython_win_post_install.py (install): Win32 fix to use
1916 sys.executable for the executable name, instead of assuming it's
1934 sys.executable for the executable name, instead of assuming it's
1917 called 'python.exe' (the post-installer would have produced broken
1935 called 'python.exe' (the post-installer would have produced broken
1918 setups on systems with a differently named python binary).
1936 setups on systems with a differently named python binary).
1919
1937
1920 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
1938 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
1921 references to os.linesep, to make the code more
1939 references to os.linesep, to make the code more
1922 platform-independent. This is also part of the win32 coloring
1940 platform-independent. This is also part of the win32 coloring
1923 fixes.
1941 fixes.
1924
1942
1925 * IPython/genutils.py (page_dumb): Remove attempts to chop long
1943 * IPython/genutils.py (page_dumb): Remove attempts to chop long
1926 lines, which actually cause coloring bugs because the length of
1944 lines, which actually cause coloring bugs because the length of
1927 the line is very difficult to correctly compute with embedded
1945 the line is very difficult to correctly compute with embedded
1928 escapes. This was the source of all the coloring problems under
1946 escapes. This was the source of all the coloring problems under
1929 Win32. I think that _finally_, Win32 users have a properly
1947 Win32. I think that _finally_, Win32 users have a properly
1930 working ipython in all respects. This would never have happened
1948 working ipython in all respects. This would never have happened
1931 if not for Gary Bishop and Viktor Ransmayr's great help and work.
1949 if not for Gary Bishop and Viktor Ransmayr's great help and work.
1932
1950
1933 2005-01-26 *** Released version 0.6.9
1951 2005-01-26 *** Released version 0.6.9
1934
1952
1935 2005-01-25 Fernando Perez <fperez@colorado.edu>
1953 2005-01-25 Fernando Perez <fperez@colorado.edu>
1936
1954
1937 * setup.py: finally, we have a true Windows installer, thanks to
1955 * setup.py: finally, we have a true Windows installer, thanks to
1938 the excellent work of Viktor Ransmayr
1956 the excellent work of Viktor Ransmayr
1939 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
1957 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
1940 Windows users. The setup routine is quite a bit cleaner thanks to
1958 Windows users. The setup routine is quite a bit cleaner thanks to
1941 this, and the post-install script uses the proper functions to
1959 this, and the post-install script uses the proper functions to
1942 allow a clean de-installation using the standard Windows Control
1960 allow a clean de-installation using the standard Windows Control
1943 Panel.
1961 Panel.
1944
1962
1945 * IPython/genutils.py (get_home_dir): changed to use the $HOME
1963 * IPython/genutils.py (get_home_dir): changed to use the $HOME
1946 environment variable under all OSes (including win32) if
1964 environment variable under all OSes (including win32) if
1947 available. This will give consistency to win32 users who have set
1965 available. This will give consistency to win32 users who have set
1948 this variable for any reason. If os.environ['HOME'] fails, the
1966 this variable for any reason. If os.environ['HOME'] fails, the
1949 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
1967 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
1950
1968
1951 2005-01-24 Fernando Perez <fperez@colorado.edu>
1969 2005-01-24 Fernando Perez <fperez@colorado.edu>
1952
1970
1953 * IPython/numutils.py (empty_like): add empty_like(), similar to
1971 * IPython/numutils.py (empty_like): add empty_like(), similar to
1954 zeros_like() but taking advantage of the new empty() Numeric routine.
1972 zeros_like() but taking advantage of the new empty() Numeric routine.
1955
1973
1956 2005-01-23 *** Released version 0.6.8
1974 2005-01-23 *** Released version 0.6.8
1957
1975
1958 2005-01-22 Fernando Perez <fperez@colorado.edu>
1976 2005-01-22 Fernando Perez <fperez@colorado.edu>
1959
1977
1960 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
1978 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
1961 automatic show() calls. After discussing things with JDH, it
1979 automatic show() calls. After discussing things with JDH, it
1962 turns out there are too many corner cases where this can go wrong.
1980 turns out there are too many corner cases where this can go wrong.
1963 It's best not to try to be 'too smart', and simply have ipython
1981 It's best not to try to be 'too smart', and simply have ipython
1964 reproduce as much as possible the default behavior of a normal
1982 reproduce as much as possible the default behavior of a normal
1965 python shell.
1983 python shell.
1966
1984
1967 * IPython/iplib.py (InteractiveShell.__init__): Modified the
1985 * IPython/iplib.py (InteractiveShell.__init__): Modified the
1968 line-splitting regexp and _prefilter() to avoid calling getattr()
1986 line-splitting regexp and _prefilter() to avoid calling getattr()
1969 on assignments. This closes
1987 on assignments. This closes
1970 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
1988 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
1971 readline uses getattr(), so a simple <TAB> keypress is still
1989 readline uses getattr(), so a simple <TAB> keypress is still
1972 enough to trigger getattr() calls on an object.
1990 enough to trigger getattr() calls on an object.
1973
1991
1974 2005-01-21 Fernando Perez <fperez@colorado.edu>
1992 2005-01-21 Fernando Perez <fperez@colorado.edu>
1975
1993
1976 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
1994 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
1977 docstring under pylab so it doesn't mask the original.
1995 docstring under pylab so it doesn't mask the original.
1978
1996
1979 2005-01-21 *** Released version 0.6.7
1997 2005-01-21 *** Released version 0.6.7
1980
1998
1981 2005-01-21 Fernando Perez <fperez@colorado.edu>
1999 2005-01-21 Fernando Perez <fperez@colorado.edu>
1982
2000
1983 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
2001 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
1984 signal handling for win32 users in multithreaded mode.
2002 signal handling for win32 users in multithreaded mode.
1985
2003
1986 2005-01-17 Fernando Perez <fperez@colorado.edu>
2004 2005-01-17 Fernando Perez <fperez@colorado.edu>
1987
2005
1988 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
2006 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1989 instances with no __init__. After a crash report by Norbert Nemec
2007 instances with no __init__. After a crash report by Norbert Nemec
1990 <Norbert-AT-nemec-online.de>.
2008 <Norbert-AT-nemec-online.de>.
1991
2009
1992 2005-01-14 Fernando Perez <fperez@colorado.edu>
2010 2005-01-14 Fernando Perez <fperez@colorado.edu>
1993
2011
1994 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
2012 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
1995 names for verbose exceptions, when multiple dotted names and the
2013 names for verbose exceptions, when multiple dotted names and the
1996 'parent' object were present on the same line.
2014 'parent' object were present on the same line.
1997
2015
1998 2005-01-11 Fernando Perez <fperez@colorado.edu>
2016 2005-01-11 Fernando Perez <fperez@colorado.edu>
1999
2017
2000 * IPython/genutils.py (flag_calls): new utility to trap and flag
2018 * IPython/genutils.py (flag_calls): new utility to trap and flag
2001 calls in functions. I need it to clean up matplotlib support.
2019 calls in functions. I need it to clean up matplotlib support.
2002 Also removed some deprecated code in genutils.
2020 Also removed some deprecated code in genutils.
2003
2021
2004 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
2022 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
2005 that matplotlib scripts called with %run, which don't call show()
2023 that matplotlib scripts called with %run, which don't call show()
2006 themselves, still have their plotting windows open.
2024 themselves, still have their plotting windows open.
2007
2025
2008 2005-01-05 Fernando Perez <fperez@colorado.edu>
2026 2005-01-05 Fernando Perez <fperez@colorado.edu>
2009
2027
2010 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
2028 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
2011 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
2029 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
2012
2030
2013 2004-12-19 Fernando Perez <fperez@colorado.edu>
2031 2004-12-19 Fernando Perez <fperez@colorado.edu>
2014
2032
2015 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
2033 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
2016 parent_runcode, which was an eyesore. The same result can be
2034 parent_runcode, which was an eyesore. The same result can be
2017 obtained with Python's regular superclass mechanisms.
2035 obtained with Python's regular superclass mechanisms.
2018
2036
2019 2004-12-17 Fernando Perez <fperez@colorado.edu>
2037 2004-12-17 Fernando Perez <fperez@colorado.edu>
2020
2038
2021 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
2039 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
2022 reported by Prabhu.
2040 reported by Prabhu.
2023 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
2041 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
2024 sys.stderr) instead of explicitly calling sys.stderr. This helps
2042 sys.stderr) instead of explicitly calling sys.stderr. This helps
2025 maintain our I/O abstractions clean, for future GUI embeddings.
2043 maintain our I/O abstractions clean, for future GUI embeddings.
2026
2044
2027 * IPython/genutils.py (info): added new utility for sys.stderr
2045 * IPython/genutils.py (info): added new utility for sys.stderr
2028 unified info message handling (thin wrapper around warn()).
2046 unified info message handling (thin wrapper around warn()).
2029
2047
2030 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
2048 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
2031 composite (dotted) names on verbose exceptions.
2049 composite (dotted) names on verbose exceptions.
2032 (VerboseTB.nullrepr): harden against another kind of errors which
2050 (VerboseTB.nullrepr): harden against another kind of errors which
2033 Python's inspect module can trigger, and which were crashing
2051 Python's inspect module can trigger, and which were crashing
2034 IPython. Thanks to a report by Marco Lombardi
2052 IPython. Thanks to a report by Marco Lombardi
2035 <mlombard-AT-ma010192.hq.eso.org>.
2053 <mlombard-AT-ma010192.hq.eso.org>.
2036
2054
2037 2004-12-13 *** Released version 0.6.6
2055 2004-12-13 *** Released version 0.6.6
2038
2056
2039 2004-12-12 Fernando Perez <fperez@colorado.edu>
2057 2004-12-12 Fernando Perez <fperez@colorado.edu>
2040
2058
2041 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
2059 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
2042 generated by pygtk upon initialization if it was built without
2060 generated by pygtk upon initialization if it was built without
2043 threads (for matplotlib users). After a crash reported by
2061 threads (for matplotlib users). After a crash reported by
2044 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
2062 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
2045
2063
2046 * IPython/ipmaker.py (make_IPython): fix small bug in the
2064 * IPython/ipmaker.py (make_IPython): fix small bug in the
2047 import_some parameter for multiple imports.
2065 import_some parameter for multiple imports.
2048
2066
2049 * IPython/iplib.py (ipmagic): simplified the interface of
2067 * IPython/iplib.py (ipmagic): simplified the interface of
2050 ipmagic() to take a single string argument, just as it would be
2068 ipmagic() to take a single string argument, just as it would be
2051 typed at the IPython cmd line.
2069 typed at the IPython cmd line.
2052 (ipalias): Added new ipalias() with an interface identical to
2070 (ipalias): Added new ipalias() with an interface identical to
2053 ipmagic(). This completes exposing a pure python interface to the
2071 ipmagic(). This completes exposing a pure python interface to the
2054 alias and magic system, which can be used in loops or more complex
2072 alias and magic system, which can be used in loops or more complex
2055 code where IPython's automatic line mangling is not active.
2073 code where IPython's automatic line mangling is not active.
2056
2074
2057 * IPython/genutils.py (timing): changed interface of timing to
2075 * IPython/genutils.py (timing): changed interface of timing to
2058 simply run code once, which is the most common case. timings()
2076 simply run code once, which is the most common case. timings()
2059 remains unchanged, for the cases where you want multiple runs.
2077 remains unchanged, for the cases where you want multiple runs.
2060
2078
2061 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
2079 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
2062 bug where Python2.2 crashes with exec'ing code which does not end
2080 bug where Python2.2 crashes with exec'ing code which does not end
2063 in a single newline. Python 2.3 is OK, so I hadn't noticed this
2081 in a single newline. Python 2.3 is OK, so I hadn't noticed this
2064 before.
2082 before.
2065
2083
2066 2004-12-10 Fernando Perez <fperez@colorado.edu>
2084 2004-12-10 Fernando Perez <fperez@colorado.edu>
2067
2085
2068 * IPython/Magic.py (Magic.magic_prun): changed name of option from
2086 * IPython/Magic.py (Magic.magic_prun): changed name of option from
2069 -t to -T, to accomodate the new -t flag in %run (the %run and
2087 -t to -T, to accomodate the new -t flag in %run (the %run and
2070 %prun options are kind of intermixed, and it's not easy to change
2088 %prun options are kind of intermixed, and it's not easy to change
2071 this with the limitations of python's getopt).
2089 this with the limitations of python's getopt).
2072
2090
2073 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
2091 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
2074 the execution of scripts. It's not as fine-tuned as timeit.py,
2092 the execution of scripts. It's not as fine-tuned as timeit.py,
2075 but it works from inside ipython (and under 2.2, which lacks
2093 but it works from inside ipython (and under 2.2, which lacks
2076 timeit.py). Optionally a number of runs > 1 can be given for
2094 timeit.py). Optionally a number of runs > 1 can be given for
2077 timing very short-running code.
2095 timing very short-running code.
2078
2096
2079 * IPython/genutils.py (uniq_stable): new routine which returns a
2097 * IPython/genutils.py (uniq_stable): new routine which returns a
2080 list of unique elements in any iterable, but in stable order of
2098 list of unique elements in any iterable, but in stable order of
2081 appearance. I needed this for the ultraTB fixes, and it's a handy
2099 appearance. I needed this for the ultraTB fixes, and it's a handy
2082 utility.
2100 utility.
2083
2101
2084 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
2102 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
2085 dotted names in Verbose exceptions. This had been broken since
2103 dotted names in Verbose exceptions. This had been broken since
2086 the very start, now x.y will properly be printed in a Verbose
2104 the very start, now x.y will properly be printed in a Verbose
2087 traceback, instead of x being shown and y appearing always as an
2105 traceback, instead of x being shown and y appearing always as an
2088 'undefined global'. Getting this to work was a bit tricky,
2106 'undefined global'. Getting this to work was a bit tricky,
2089 because by default python tokenizers are stateless. Saved by
2107 because by default python tokenizers are stateless. Saved by
2090 python's ability to easily add a bit of state to an arbitrary
2108 python's ability to easily add a bit of state to an arbitrary
2091 function (without needing to build a full-blown callable object).
2109 function (without needing to build a full-blown callable object).
2092
2110
2093 Also big cleanup of this code, which had horrendous runtime
2111 Also big cleanup of this code, which had horrendous runtime
2094 lookups of zillions of attributes for colorization. Moved all
2112 lookups of zillions of attributes for colorization. Moved all
2095 this code into a few templates, which make it cleaner and quicker.
2113 this code into a few templates, which make it cleaner and quicker.
2096
2114
2097 Printout quality was also improved for Verbose exceptions: one
2115 Printout quality was also improved for Verbose exceptions: one
2098 variable per line, and memory addresses are printed (this can be
2116 variable per line, and memory addresses are printed (this can be
2099 quite handy in nasty debugging situations, which is what Verbose
2117 quite handy in nasty debugging situations, which is what Verbose
2100 is for).
2118 is for).
2101
2119
2102 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
2120 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
2103 the command line as scripts to be loaded by embedded instances.
2121 the command line as scripts to be loaded by embedded instances.
2104 Doing so has the potential for an infinite recursion if there are
2122 Doing so has the potential for an infinite recursion if there are
2105 exceptions thrown in the process. This fixes a strange crash
2123 exceptions thrown in the process. This fixes a strange crash
2106 reported by Philippe MULLER <muller-AT-irit.fr>.
2124 reported by Philippe MULLER <muller-AT-irit.fr>.
2107
2125
2108 2004-12-09 Fernando Perez <fperez@colorado.edu>
2126 2004-12-09 Fernando Perez <fperez@colorado.edu>
2109
2127
2110 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
2128 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
2111 to reflect new names in matplotlib, which now expose the
2129 to reflect new names in matplotlib, which now expose the
2112 matlab-compatible interface via a pylab module instead of the
2130 matlab-compatible interface via a pylab module instead of the
2113 'matlab' name. The new code is backwards compatible, so users of
2131 'matlab' name. The new code is backwards compatible, so users of
2114 all matplotlib versions are OK. Patch by J. Hunter.
2132 all matplotlib versions are OK. Patch by J. Hunter.
2115
2133
2116 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
2134 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
2117 of __init__ docstrings for instances (class docstrings are already
2135 of __init__ docstrings for instances (class docstrings are already
2118 automatically printed). Instances with customized docstrings
2136 automatically printed). Instances with customized docstrings
2119 (indep. of the class) are also recognized and all 3 separate
2137 (indep. of the class) are also recognized and all 3 separate
2120 docstrings are printed (instance, class, constructor). After some
2138 docstrings are printed (instance, class, constructor). After some
2121 comments/suggestions by J. Hunter.
2139 comments/suggestions by J. Hunter.
2122
2140
2123 2004-12-05 Fernando Perez <fperez@colorado.edu>
2141 2004-12-05 Fernando Perez <fperez@colorado.edu>
2124
2142
2125 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
2143 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
2126 warnings when tab-completion fails and triggers an exception.
2144 warnings when tab-completion fails and triggers an exception.
2127
2145
2128 2004-12-03 Fernando Perez <fperez@colorado.edu>
2146 2004-12-03 Fernando Perez <fperez@colorado.edu>
2129
2147
2130 * IPython/Magic.py (magic_prun): Fix bug where an exception would
2148 * IPython/Magic.py (magic_prun): Fix bug where an exception would
2131 be triggered when using 'run -p'. An incorrect option flag was
2149 be triggered when using 'run -p'. An incorrect option flag was
2132 being set ('d' instead of 'D').
2150 being set ('d' instead of 'D').
2133 (manpage): fix missing escaped \- sign.
2151 (manpage): fix missing escaped \- sign.
2134
2152
2135 2004-11-30 *** Released version 0.6.5
2153 2004-11-30 *** Released version 0.6.5
2136
2154
2137 2004-11-30 Fernando Perez <fperez@colorado.edu>
2155 2004-11-30 Fernando Perez <fperez@colorado.edu>
2138
2156
2139 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
2157 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
2140 setting with -d option.
2158 setting with -d option.
2141
2159
2142 * setup.py (docfiles): Fix problem where the doc glob I was using
2160 * setup.py (docfiles): Fix problem where the doc glob I was using
2143 was COMPLETELY BROKEN. It was giving the right files by pure
2161 was COMPLETELY BROKEN. It was giving the right files by pure
2144 accident, but failed once I tried to include ipython.el. Note:
2162 accident, but failed once I tried to include ipython.el. Note:
2145 glob() does NOT allow you to do exclusion on multiple endings!
2163 glob() does NOT allow you to do exclusion on multiple endings!
2146
2164
2147 2004-11-29 Fernando Perez <fperez@colorado.edu>
2165 2004-11-29 Fernando Perez <fperez@colorado.edu>
2148
2166
2149 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
2167 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
2150 the manpage as the source. Better formatting & consistency.
2168 the manpage as the source. Better formatting & consistency.
2151
2169
2152 * IPython/Magic.py (magic_run): Added new -d option, to run
2170 * IPython/Magic.py (magic_run): Added new -d option, to run
2153 scripts under the control of the python pdb debugger. Note that
2171 scripts under the control of the python pdb debugger. Note that
2154 this required changing the %prun option -d to -D, to avoid a clash
2172 this required changing the %prun option -d to -D, to avoid a clash
2155 (since %run must pass options to %prun, and getopt is too dumb to
2173 (since %run must pass options to %prun, and getopt is too dumb to
2156 handle options with string values with embedded spaces). Thanks
2174 handle options with string values with embedded spaces). Thanks
2157 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
2175 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
2158 (magic_who_ls): added type matching to %who and %whos, so that one
2176 (magic_who_ls): added type matching to %who and %whos, so that one
2159 can filter their output to only include variables of certain
2177 can filter their output to only include variables of certain
2160 types. Another suggestion by Matthew.
2178 types. Another suggestion by Matthew.
2161 (magic_whos): Added memory summaries in kb and Mb for arrays.
2179 (magic_whos): Added memory summaries in kb and Mb for arrays.
2162 (magic_who): Improve formatting (break lines every 9 vars).
2180 (magic_who): Improve formatting (break lines every 9 vars).
2163
2181
2164 2004-11-28 Fernando Perez <fperez@colorado.edu>
2182 2004-11-28 Fernando Perez <fperez@colorado.edu>
2165
2183
2166 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
2184 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
2167 cache when empty lines were present.
2185 cache when empty lines were present.
2168
2186
2169 2004-11-24 Fernando Perez <fperez@colorado.edu>
2187 2004-11-24 Fernando Perez <fperez@colorado.edu>
2170
2188
2171 * IPython/usage.py (__doc__): document the re-activated threading
2189 * IPython/usage.py (__doc__): document the re-activated threading
2172 options for WX and GTK.
2190 options for WX and GTK.
2173
2191
2174 2004-11-23 Fernando Perez <fperez@colorado.edu>
2192 2004-11-23 Fernando Perez <fperez@colorado.edu>
2175
2193
2176 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
2194 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
2177 the -wthread and -gthread options, along with a new -tk one to try
2195 the -wthread and -gthread options, along with a new -tk one to try
2178 and coordinate Tk threading with wx/gtk. The tk support is very
2196 and coordinate Tk threading with wx/gtk. The tk support is very
2179 platform dependent, since it seems to require Tcl and Tk to be
2197 platform dependent, since it seems to require Tcl and Tk to be
2180 built with threads (Fedora1/2 appears NOT to have it, but in
2198 built with threads (Fedora1/2 appears NOT to have it, but in
2181 Prabhu's Debian boxes it works OK). But even with some Tk
2199 Prabhu's Debian boxes it works OK). But even with some Tk
2182 limitations, this is a great improvement.
2200 limitations, this is a great improvement.
2183
2201
2184 * IPython/Prompts.py (prompt_specials_color): Added \t for time
2202 * IPython/Prompts.py (prompt_specials_color): Added \t for time
2185 info in user prompts. Patch by Prabhu.
2203 info in user prompts. Patch by Prabhu.
2186
2204
2187 2004-11-18 Fernando Perez <fperez@colorado.edu>
2205 2004-11-18 Fernando Perez <fperez@colorado.edu>
2188
2206
2189 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
2207 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
2190 EOFErrors and bail, to avoid infinite loops if a non-terminating
2208 EOFErrors and bail, to avoid infinite loops if a non-terminating
2191 file is fed into ipython. Patch submitted in issue 19 by user,
2209 file is fed into ipython. Patch submitted in issue 19 by user,
2192 many thanks.
2210 many thanks.
2193
2211
2194 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
2212 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
2195 autoquote/parens in continuation prompts, which can cause lots of
2213 autoquote/parens in continuation prompts, which can cause lots of
2196 problems. Closes roundup issue 20.
2214 problems. Closes roundup issue 20.
2197
2215
2198 2004-11-17 Fernando Perez <fperez@colorado.edu>
2216 2004-11-17 Fernando Perez <fperez@colorado.edu>
2199
2217
2200 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
2218 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
2201 reported as debian bug #280505. I'm not sure my local changelog
2219 reported as debian bug #280505. I'm not sure my local changelog
2202 entry has the proper debian format (Jack?).
2220 entry has the proper debian format (Jack?).
2203
2221
2204 2004-11-08 *** Released version 0.6.4
2222 2004-11-08 *** Released version 0.6.4
2205
2223
2206 2004-11-08 Fernando Perez <fperez@colorado.edu>
2224 2004-11-08 Fernando Perez <fperez@colorado.edu>
2207
2225
2208 * IPython/iplib.py (init_readline): Fix exit message for Windows
2226 * IPython/iplib.py (init_readline): Fix exit message for Windows
2209 when readline is active. Thanks to a report by Eric Jones
2227 when readline is active. Thanks to a report by Eric Jones
2210 <eric-AT-enthought.com>.
2228 <eric-AT-enthought.com>.
2211
2229
2212 2004-11-07 Fernando Perez <fperez@colorado.edu>
2230 2004-11-07 Fernando Perez <fperez@colorado.edu>
2213
2231
2214 * IPython/genutils.py (page): Add a trap for OSError exceptions,
2232 * IPython/genutils.py (page): Add a trap for OSError exceptions,
2215 sometimes seen by win2k/cygwin users.
2233 sometimes seen by win2k/cygwin users.
2216
2234
2217 2004-11-06 Fernando Perez <fperez@colorado.edu>
2235 2004-11-06 Fernando Perez <fperez@colorado.edu>
2218
2236
2219 * IPython/iplib.py (interact): Change the handling of %Exit from
2237 * IPython/iplib.py (interact): Change the handling of %Exit from
2220 trying to propagate a SystemExit to an internal ipython flag.
2238 trying to propagate a SystemExit to an internal ipython flag.
2221 This is less elegant than using Python's exception mechanism, but
2239 This is less elegant than using Python's exception mechanism, but
2222 I can't get that to work reliably with threads, so under -pylab
2240 I can't get that to work reliably with threads, so under -pylab
2223 %Exit was hanging IPython. Cross-thread exception handling is
2241 %Exit was hanging IPython. Cross-thread exception handling is
2224 really a bitch. Thaks to a bug report by Stephen Walton
2242 really a bitch. Thaks to a bug report by Stephen Walton
2225 <stephen.walton-AT-csun.edu>.
2243 <stephen.walton-AT-csun.edu>.
2226
2244
2227 2004-11-04 Fernando Perez <fperez@colorado.edu>
2245 2004-11-04 Fernando Perez <fperez@colorado.edu>
2228
2246
2229 * IPython/iplib.py (raw_input_original): store a pointer to the
2247 * IPython/iplib.py (raw_input_original): store a pointer to the
2230 true raw_input to harden against code which can modify it
2248 true raw_input to harden against code which can modify it
2231 (wx.py.PyShell does this and would otherwise crash ipython).
2249 (wx.py.PyShell does this and would otherwise crash ipython).
2232 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
2250 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
2233
2251
2234 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
2252 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
2235 Ctrl-C problem, which does not mess up the input line.
2253 Ctrl-C problem, which does not mess up the input line.
2236
2254
2237 2004-11-03 Fernando Perez <fperez@colorado.edu>
2255 2004-11-03 Fernando Perez <fperez@colorado.edu>
2238
2256
2239 * IPython/Release.py: Changed licensing to BSD, in all files.
2257 * IPython/Release.py: Changed licensing to BSD, in all files.
2240 (name): lowercase name for tarball/RPM release.
2258 (name): lowercase name for tarball/RPM release.
2241
2259
2242 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
2260 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
2243 use throughout ipython.
2261 use throughout ipython.
2244
2262
2245 * IPython/Magic.py (Magic._ofind): Switch to using the new
2263 * IPython/Magic.py (Magic._ofind): Switch to using the new
2246 OInspect.getdoc() function.
2264 OInspect.getdoc() function.
2247
2265
2248 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
2266 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
2249 of the line currently being canceled via Ctrl-C. It's extremely
2267 of the line currently being canceled via Ctrl-C. It's extremely
2250 ugly, but I don't know how to do it better (the problem is one of
2268 ugly, but I don't know how to do it better (the problem is one of
2251 handling cross-thread exceptions).
2269 handling cross-thread exceptions).
2252
2270
2253 2004-10-28 Fernando Perez <fperez@colorado.edu>
2271 2004-10-28 Fernando Perez <fperez@colorado.edu>
2254
2272
2255 * IPython/Shell.py (signal_handler): add signal handlers to trap
2273 * IPython/Shell.py (signal_handler): add signal handlers to trap
2256 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
2274 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
2257 report by Francesc Alted.
2275 report by Francesc Alted.
2258
2276
2259 2004-10-21 Fernando Perez <fperez@colorado.edu>
2277 2004-10-21 Fernando Perez <fperez@colorado.edu>
2260
2278
2261 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
2279 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
2262 to % for pysh syntax extensions.
2280 to % for pysh syntax extensions.
2263
2281
2264 2004-10-09 Fernando Perez <fperez@colorado.edu>
2282 2004-10-09 Fernando Perez <fperez@colorado.edu>
2265
2283
2266 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
2284 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
2267 arrays to print a more useful summary, without calling str(arr).
2285 arrays to print a more useful summary, without calling str(arr).
2268 This avoids the problem of extremely lengthy computations which
2286 This avoids the problem of extremely lengthy computations which
2269 occur if arr is large, and appear to the user as a system lockup
2287 occur if arr is large, and appear to the user as a system lockup
2270 with 100% cpu activity. After a suggestion by Kristian Sandberg
2288 with 100% cpu activity. After a suggestion by Kristian Sandberg
2271 <Kristian.Sandberg@colorado.edu>.
2289 <Kristian.Sandberg@colorado.edu>.
2272 (Magic.__init__): fix bug in global magic escapes not being
2290 (Magic.__init__): fix bug in global magic escapes not being
2273 correctly set.
2291 correctly set.
2274
2292
2275 2004-10-08 Fernando Perez <fperez@colorado.edu>
2293 2004-10-08 Fernando Perez <fperez@colorado.edu>
2276
2294
2277 * IPython/Magic.py (__license__): change to absolute imports of
2295 * IPython/Magic.py (__license__): change to absolute imports of
2278 ipython's own internal packages, to start adapting to the absolute
2296 ipython's own internal packages, to start adapting to the absolute
2279 import requirement of PEP-328.
2297 import requirement of PEP-328.
2280
2298
2281 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
2299 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
2282 files, and standardize author/license marks through the Release
2300 files, and standardize author/license marks through the Release
2283 module instead of having per/file stuff (except for files with
2301 module instead of having per/file stuff (except for files with
2284 particular licenses, like the MIT/PSF-licensed codes).
2302 particular licenses, like the MIT/PSF-licensed codes).
2285
2303
2286 * IPython/Debugger.py: remove dead code for python 2.1
2304 * IPython/Debugger.py: remove dead code for python 2.1
2287
2305
2288 2004-10-04 Fernando Perez <fperez@colorado.edu>
2306 2004-10-04 Fernando Perez <fperez@colorado.edu>
2289
2307
2290 * IPython/iplib.py (ipmagic): New function for accessing magics
2308 * IPython/iplib.py (ipmagic): New function for accessing magics
2291 via a normal python function call.
2309 via a normal python function call.
2292
2310
2293 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
2311 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
2294 from '@' to '%', to accomodate the new @decorator syntax of python
2312 from '@' to '%', to accomodate the new @decorator syntax of python
2295 2.4.
2313 2.4.
2296
2314
2297 2004-09-29 Fernando Perez <fperez@colorado.edu>
2315 2004-09-29 Fernando Perez <fperez@colorado.edu>
2298
2316
2299 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
2317 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
2300 matplotlib.use to prevent running scripts which try to switch
2318 matplotlib.use to prevent running scripts which try to switch
2301 interactive backends from within ipython. This will just crash
2319 interactive backends from within ipython. This will just crash
2302 the python interpreter, so we can't allow it (but a detailed error
2320 the python interpreter, so we can't allow it (but a detailed error
2303 is given to the user).
2321 is given to the user).
2304
2322
2305 2004-09-28 Fernando Perez <fperez@colorado.edu>
2323 2004-09-28 Fernando Perez <fperez@colorado.edu>
2306
2324
2307 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
2325 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
2308 matplotlib-related fixes so that using @run with non-matplotlib
2326 matplotlib-related fixes so that using @run with non-matplotlib
2309 scripts doesn't pop up spurious plot windows. This requires
2327 scripts doesn't pop up spurious plot windows. This requires
2310 matplotlib >= 0.63, where I had to make some changes as well.
2328 matplotlib >= 0.63, where I had to make some changes as well.
2311
2329
2312 * IPython/ipmaker.py (make_IPython): update version requirement to
2330 * IPython/ipmaker.py (make_IPython): update version requirement to
2313 python 2.2.
2331 python 2.2.
2314
2332
2315 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
2333 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
2316 banner arg for embedded customization.
2334 banner arg for embedded customization.
2317
2335
2318 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
2336 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
2319 explicit uses of __IP as the IPython's instance name. Now things
2337 explicit uses of __IP as the IPython's instance name. Now things
2320 are properly handled via the shell.name value. The actual code
2338 are properly handled via the shell.name value. The actual code
2321 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
2339 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
2322 is much better than before. I'll clean things completely when the
2340 is much better than before. I'll clean things completely when the
2323 magic stuff gets a real overhaul.
2341 magic stuff gets a real overhaul.
2324
2342
2325 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
2343 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
2326 minor changes to debian dir.
2344 minor changes to debian dir.
2327
2345
2328 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
2346 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
2329 pointer to the shell itself in the interactive namespace even when
2347 pointer to the shell itself in the interactive namespace even when
2330 a user-supplied dict is provided. This is needed for embedding
2348 a user-supplied dict is provided. This is needed for embedding
2331 purposes (found by tests with Michel Sanner).
2349 purposes (found by tests with Michel Sanner).
2332
2350
2333 2004-09-27 Fernando Perez <fperez@colorado.edu>
2351 2004-09-27 Fernando Perez <fperez@colorado.edu>
2334
2352
2335 * IPython/UserConfig/ipythonrc: remove []{} from
2353 * IPython/UserConfig/ipythonrc: remove []{} from
2336 readline_remove_delims, so that things like [modname.<TAB> do
2354 readline_remove_delims, so that things like [modname.<TAB> do
2337 proper completion. This disables [].TAB, but that's a less common
2355 proper completion. This disables [].TAB, but that's a less common
2338 case than module names in list comprehensions, for example.
2356 case than module names in list comprehensions, for example.
2339 Thanks to a report by Andrea Riciputi.
2357 Thanks to a report by Andrea Riciputi.
2340
2358
2341 2004-09-09 Fernando Perez <fperez@colorado.edu>
2359 2004-09-09 Fernando Perez <fperez@colorado.edu>
2342
2360
2343 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
2361 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
2344 blocking problems in win32 and osx. Fix by John.
2362 blocking problems in win32 and osx. Fix by John.
2345
2363
2346 2004-09-08 Fernando Perez <fperez@colorado.edu>
2364 2004-09-08 Fernando Perez <fperez@colorado.edu>
2347
2365
2348 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
2366 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
2349 for Win32 and OSX. Fix by John Hunter.
2367 for Win32 and OSX. Fix by John Hunter.
2350
2368
2351 2004-08-30 *** Released version 0.6.3
2369 2004-08-30 *** Released version 0.6.3
2352
2370
2353 2004-08-30 Fernando Perez <fperez@colorado.edu>
2371 2004-08-30 Fernando Perez <fperez@colorado.edu>
2354
2372
2355 * setup.py (isfile): Add manpages to list of dependent files to be
2373 * setup.py (isfile): Add manpages to list of dependent files to be
2356 updated.
2374 updated.
2357
2375
2358 2004-08-27 Fernando Perez <fperez@colorado.edu>
2376 2004-08-27 Fernando Perez <fperez@colorado.edu>
2359
2377
2360 * IPython/Shell.py (start): I've disabled -wthread and -gthread
2378 * IPython/Shell.py (start): I've disabled -wthread and -gthread
2361 for now. They don't really work with standalone WX/GTK code
2379 for now. They don't really work with standalone WX/GTK code
2362 (though matplotlib IS working fine with both of those backends).
2380 (though matplotlib IS working fine with both of those backends).
2363 This will neeed much more testing. I disabled most things with
2381 This will neeed much more testing. I disabled most things with
2364 comments, so turning it back on later should be pretty easy.
2382 comments, so turning it back on later should be pretty easy.
2365
2383
2366 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
2384 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
2367 autocalling of expressions like r'foo', by modifying the line
2385 autocalling of expressions like r'foo', by modifying the line
2368 split regexp. Closes
2386 split regexp. Closes
2369 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
2387 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
2370 Riley <ipythonbugs-AT-sabi.net>.
2388 Riley <ipythonbugs-AT-sabi.net>.
2371 (InteractiveShell.mainloop): honor --nobanner with banner
2389 (InteractiveShell.mainloop): honor --nobanner with banner
2372 extensions.
2390 extensions.
2373
2391
2374 * IPython/Shell.py: Significant refactoring of all classes, so
2392 * IPython/Shell.py: Significant refactoring of all classes, so
2375 that we can really support ALL matplotlib backends and threading
2393 that we can really support ALL matplotlib backends and threading
2376 models (John spotted a bug with Tk which required this). Now we
2394 models (John spotted a bug with Tk which required this). Now we
2377 should support single-threaded, WX-threads and GTK-threads, both
2395 should support single-threaded, WX-threads and GTK-threads, both
2378 for generic code and for matplotlib.
2396 for generic code and for matplotlib.
2379
2397
2380 * IPython/ipmaker.py (__call__): Changed -mpthread option to
2398 * IPython/ipmaker.py (__call__): Changed -mpthread option to
2381 -pylab, to simplify things for users. Will also remove the pylab
2399 -pylab, to simplify things for users. Will also remove the pylab
2382 profile, since now all of matplotlib configuration is directly
2400 profile, since now all of matplotlib configuration is directly
2383 handled here. This also reduces startup time.
2401 handled here. This also reduces startup time.
2384
2402
2385 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
2403 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
2386 shell wasn't being correctly called. Also in IPShellWX.
2404 shell wasn't being correctly called. Also in IPShellWX.
2387
2405
2388 * IPython/iplib.py (InteractiveShell.__init__): Added option to
2406 * IPython/iplib.py (InteractiveShell.__init__): Added option to
2389 fine-tune banner.
2407 fine-tune banner.
2390
2408
2391 * IPython/numutils.py (spike): Deprecate these spike functions,
2409 * IPython/numutils.py (spike): Deprecate these spike functions,
2392 delete (long deprecated) gnuplot_exec handler.
2410 delete (long deprecated) gnuplot_exec handler.
2393
2411
2394 2004-08-26 Fernando Perez <fperez@colorado.edu>
2412 2004-08-26 Fernando Perez <fperez@colorado.edu>
2395
2413
2396 * ipython.1: Update for threading options, plus some others which
2414 * ipython.1: Update for threading options, plus some others which
2397 were missing.
2415 were missing.
2398
2416
2399 * IPython/ipmaker.py (__call__): Added -wthread option for
2417 * IPython/ipmaker.py (__call__): Added -wthread option for
2400 wxpython thread handling. Make sure threading options are only
2418 wxpython thread handling. Make sure threading options are only
2401 valid at the command line.
2419 valid at the command line.
2402
2420
2403 * scripts/ipython: moved shell selection into a factory function
2421 * scripts/ipython: moved shell selection into a factory function
2404 in Shell.py, to keep the starter script to a minimum.
2422 in Shell.py, to keep the starter script to a minimum.
2405
2423
2406 2004-08-25 Fernando Perez <fperez@colorado.edu>
2424 2004-08-25 Fernando Perez <fperez@colorado.edu>
2407
2425
2408 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
2426 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
2409 John. Along with some recent changes he made to matplotlib, the
2427 John. Along with some recent changes he made to matplotlib, the
2410 next versions of both systems should work very well together.
2428 next versions of both systems should work very well together.
2411
2429
2412 2004-08-24 Fernando Perez <fperez@colorado.edu>
2430 2004-08-24 Fernando Perez <fperez@colorado.edu>
2413
2431
2414 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
2432 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
2415 tried to switch the profiling to using hotshot, but I'm getting
2433 tried to switch the profiling to using hotshot, but I'm getting
2416 strange errors from prof.runctx() there. I may be misreading the
2434 strange errors from prof.runctx() there. I may be misreading the
2417 docs, but it looks weird. For now the profiling code will
2435 docs, but it looks weird. For now the profiling code will
2418 continue to use the standard profiler.
2436 continue to use the standard profiler.
2419
2437
2420 2004-08-23 Fernando Perez <fperez@colorado.edu>
2438 2004-08-23 Fernando Perez <fperez@colorado.edu>
2421
2439
2422 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
2440 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
2423 threaded shell, by John Hunter. It's not quite ready yet, but
2441 threaded shell, by John Hunter. It's not quite ready yet, but
2424 close.
2442 close.
2425
2443
2426 2004-08-22 Fernando Perez <fperez@colorado.edu>
2444 2004-08-22 Fernando Perez <fperez@colorado.edu>
2427
2445
2428 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
2446 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
2429 in Magic and ultraTB.
2447 in Magic and ultraTB.
2430
2448
2431 * ipython.1: document threading options in manpage.
2449 * ipython.1: document threading options in manpage.
2432
2450
2433 * scripts/ipython: Changed name of -thread option to -gthread,
2451 * scripts/ipython: Changed name of -thread option to -gthread,
2434 since this is GTK specific. I want to leave the door open for a
2452 since this is GTK specific. I want to leave the door open for a
2435 -wthread option for WX, which will most likely be necessary. This
2453 -wthread option for WX, which will most likely be necessary. This
2436 change affects usage and ipmaker as well.
2454 change affects usage and ipmaker as well.
2437
2455
2438 * IPython/Shell.py (matplotlib_shell): Add a factory function to
2456 * IPython/Shell.py (matplotlib_shell): Add a factory function to
2439 handle the matplotlib shell issues. Code by John Hunter
2457 handle the matplotlib shell issues. Code by John Hunter
2440 <jdhunter-AT-nitace.bsd.uchicago.edu>.
2458 <jdhunter-AT-nitace.bsd.uchicago.edu>.
2441 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
2459 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
2442 broken (and disabled for end users) for now, but it puts the
2460 broken (and disabled for end users) for now, but it puts the
2443 infrastructure in place.
2461 infrastructure in place.
2444
2462
2445 2004-08-21 Fernando Perez <fperez@colorado.edu>
2463 2004-08-21 Fernando Perez <fperez@colorado.edu>
2446
2464
2447 * ipythonrc-pylab: Add matplotlib support.
2465 * ipythonrc-pylab: Add matplotlib support.
2448
2466
2449 * matplotlib_config.py: new files for matplotlib support, part of
2467 * matplotlib_config.py: new files for matplotlib support, part of
2450 the pylab profile.
2468 the pylab profile.
2451
2469
2452 * IPython/usage.py (__doc__): documented the threading options.
2470 * IPython/usage.py (__doc__): documented the threading options.
2453
2471
2454 2004-08-20 Fernando Perez <fperez@colorado.edu>
2472 2004-08-20 Fernando Perez <fperez@colorado.edu>
2455
2473
2456 * ipython: Modified the main calling routine to handle the -thread
2474 * ipython: Modified the main calling routine to handle the -thread
2457 and -mpthread options. This needs to be done as a top-level hack,
2475 and -mpthread options. This needs to be done as a top-level hack,
2458 because it determines which class to instantiate for IPython
2476 because it determines which class to instantiate for IPython
2459 itself.
2477 itself.
2460
2478
2461 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
2479 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
2462 classes to support multithreaded GTK operation without blocking,
2480 classes to support multithreaded GTK operation without blocking,
2463 and matplotlib with all backends. This is a lot of still very
2481 and matplotlib with all backends. This is a lot of still very
2464 experimental code, and threads are tricky. So it may still have a
2482 experimental code, and threads are tricky. So it may still have a
2465 few rough edges... This code owes a lot to
2483 few rough edges... This code owes a lot to
2466 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
2484 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
2467 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
2485 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
2468 to John Hunter for all the matplotlib work.
2486 to John Hunter for all the matplotlib work.
2469
2487
2470 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
2488 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
2471 options for gtk thread and matplotlib support.
2489 options for gtk thread and matplotlib support.
2472
2490
2473 2004-08-16 Fernando Perez <fperez@colorado.edu>
2491 2004-08-16 Fernando Perez <fperez@colorado.edu>
2474
2492
2475 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
2493 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
2476 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
2494 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
2477 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
2495 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
2478
2496
2479 2004-08-11 Fernando Perez <fperez@colorado.edu>
2497 2004-08-11 Fernando Perez <fperez@colorado.edu>
2480
2498
2481 * setup.py (isfile): Fix build so documentation gets updated for
2499 * setup.py (isfile): Fix build so documentation gets updated for
2482 rpms (it was only done for .tgz builds).
2500 rpms (it was only done for .tgz builds).
2483
2501
2484 2004-08-10 Fernando Perez <fperez@colorado.edu>
2502 2004-08-10 Fernando Perez <fperez@colorado.edu>
2485
2503
2486 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
2504 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
2487
2505
2488 * iplib.py : Silence syntax error exceptions in tab-completion.
2506 * iplib.py : Silence syntax error exceptions in tab-completion.
2489
2507
2490 2004-08-05 Fernando Perez <fperez@colorado.edu>
2508 2004-08-05 Fernando Perez <fperez@colorado.edu>
2491
2509
2492 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
2510 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
2493 'color off' mark for continuation prompts. This was causing long
2511 'color off' mark for continuation prompts. This was causing long
2494 continuation lines to mis-wrap.
2512 continuation lines to mis-wrap.
2495
2513
2496 2004-08-01 Fernando Perez <fperez@colorado.edu>
2514 2004-08-01 Fernando Perez <fperez@colorado.edu>
2497
2515
2498 * IPython/ipmaker.py (make_IPython): Allow the shell class used
2516 * IPython/ipmaker.py (make_IPython): Allow the shell class used
2499 for building ipython to be a parameter. All this is necessary
2517 for building ipython to be a parameter. All this is necessary
2500 right now to have a multithreaded version, but this insane
2518 right now to have a multithreaded version, but this insane
2501 non-design will be cleaned up soon. For now, it's a hack that
2519 non-design will be cleaned up soon. For now, it's a hack that
2502 works.
2520 works.
2503
2521
2504 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
2522 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
2505 args in various places. No bugs so far, but it's a dangerous
2523 args in various places. No bugs so far, but it's a dangerous
2506 practice.
2524 practice.
2507
2525
2508 2004-07-31 Fernando Perez <fperez@colorado.edu>
2526 2004-07-31 Fernando Perez <fperez@colorado.edu>
2509
2527
2510 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
2528 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
2511 fix completion of files with dots in their names under most
2529 fix completion of files with dots in their names under most
2512 profiles (pysh was OK because the completion order is different).
2530 profiles (pysh was OK because the completion order is different).
2513
2531
2514 2004-07-27 Fernando Perez <fperez@colorado.edu>
2532 2004-07-27 Fernando Perez <fperez@colorado.edu>
2515
2533
2516 * IPython/iplib.py (InteractiveShell.__init__): build dict of
2534 * IPython/iplib.py (InteractiveShell.__init__): build dict of
2517 keywords manually, b/c the one in keyword.py was removed in python
2535 keywords manually, b/c the one in keyword.py was removed in python
2518 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
2536 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
2519 This is NOT a bug under python 2.3 and earlier.
2537 This is NOT a bug under python 2.3 and earlier.
2520
2538
2521 2004-07-26 Fernando Perez <fperez@colorado.edu>
2539 2004-07-26 Fernando Perez <fperez@colorado.edu>
2522
2540
2523 * IPython/ultraTB.py (VerboseTB.text): Add another
2541 * IPython/ultraTB.py (VerboseTB.text): Add another
2524 linecache.checkcache() call to try to prevent inspect.py from
2542 linecache.checkcache() call to try to prevent inspect.py from
2525 crashing under python 2.3. I think this fixes
2543 crashing under python 2.3. I think this fixes
2526 http://www.scipy.net/roundup/ipython/issue17.
2544 http://www.scipy.net/roundup/ipython/issue17.
2527
2545
2528 2004-07-26 *** Released version 0.6.2
2546 2004-07-26 *** Released version 0.6.2
2529
2547
2530 2004-07-26 Fernando Perez <fperez@colorado.edu>
2548 2004-07-26 Fernando Perez <fperez@colorado.edu>
2531
2549
2532 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
2550 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
2533 fail for any number.
2551 fail for any number.
2534 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
2552 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
2535 empty bookmarks.
2553 empty bookmarks.
2536
2554
2537 2004-07-26 *** Released version 0.6.1
2555 2004-07-26 *** Released version 0.6.1
2538
2556
2539 2004-07-26 Fernando Perez <fperez@colorado.edu>
2557 2004-07-26 Fernando Perez <fperez@colorado.edu>
2540
2558
2541 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
2559 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
2542
2560
2543 * IPython/iplib.py (protect_filename): Applied Ville's patch for
2561 * IPython/iplib.py (protect_filename): Applied Ville's patch for
2544 escaping '()[]{}' in filenames.
2562 escaping '()[]{}' in filenames.
2545
2563
2546 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
2564 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
2547 Python 2.2 users who lack a proper shlex.split.
2565 Python 2.2 users who lack a proper shlex.split.
2548
2566
2549 2004-07-19 Fernando Perez <fperez@colorado.edu>
2567 2004-07-19 Fernando Perez <fperez@colorado.edu>
2550
2568
2551 * IPython/iplib.py (InteractiveShell.init_readline): Add support
2569 * IPython/iplib.py (InteractiveShell.init_readline): Add support
2552 for reading readline's init file. I follow the normal chain:
2570 for reading readline's init file. I follow the normal chain:
2553 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
2571 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
2554 report by Mike Heeter. This closes
2572 report by Mike Heeter. This closes
2555 http://www.scipy.net/roundup/ipython/issue16.
2573 http://www.scipy.net/roundup/ipython/issue16.
2556
2574
2557 2004-07-18 Fernando Perez <fperez@colorado.edu>
2575 2004-07-18 Fernando Perez <fperez@colorado.edu>
2558
2576
2559 * IPython/iplib.py (__init__): Add better handling of '\' under
2577 * IPython/iplib.py (__init__): Add better handling of '\' under
2560 Win32 for filenames. After a patch by Ville.
2578 Win32 for filenames. After a patch by Ville.
2561
2579
2562 2004-07-17 Fernando Perez <fperez@colorado.edu>
2580 2004-07-17 Fernando Perez <fperez@colorado.edu>
2563
2581
2564 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2582 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2565 autocalling would be triggered for 'foo is bar' if foo is
2583 autocalling would be triggered for 'foo is bar' if foo is
2566 callable. I also cleaned up the autocall detection code to use a
2584 callable. I also cleaned up the autocall detection code to use a
2567 regexp, which is faster. Bug reported by Alexander Schmolck.
2585 regexp, which is faster. Bug reported by Alexander Schmolck.
2568
2586
2569 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
2587 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
2570 '?' in them would confuse the help system. Reported by Alex
2588 '?' in them would confuse the help system. Reported by Alex
2571 Schmolck.
2589 Schmolck.
2572
2590
2573 2004-07-16 Fernando Perez <fperez@colorado.edu>
2591 2004-07-16 Fernando Perez <fperez@colorado.edu>
2574
2592
2575 * IPython/GnuplotInteractive.py (__all__): added plot2.
2593 * IPython/GnuplotInteractive.py (__all__): added plot2.
2576
2594
2577 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
2595 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
2578 plotting dictionaries, lists or tuples of 1d arrays.
2596 plotting dictionaries, lists or tuples of 1d arrays.
2579
2597
2580 * IPython/Magic.py (Magic.magic_hist): small clenaups and
2598 * IPython/Magic.py (Magic.magic_hist): small clenaups and
2581 optimizations.
2599 optimizations.
2582
2600
2583 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
2601 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
2584 the information which was there from Janko's original IPP code:
2602 the information which was there from Janko's original IPP code:
2585
2603
2586 03.05.99 20:53 porto.ifm.uni-kiel.de
2604 03.05.99 20:53 porto.ifm.uni-kiel.de
2587 --Started changelog.
2605 --Started changelog.
2588 --make clear do what it say it does
2606 --make clear do what it say it does
2589 --added pretty output of lines from inputcache
2607 --added pretty output of lines from inputcache
2590 --Made Logger a mixin class, simplifies handling of switches
2608 --Made Logger a mixin class, simplifies handling of switches
2591 --Added own completer class. .string<TAB> expands to last history
2609 --Added own completer class. .string<TAB> expands to last history
2592 line which starts with string. The new expansion is also present
2610 line which starts with string. The new expansion is also present
2593 with Ctrl-r from the readline library. But this shows, who this
2611 with Ctrl-r from the readline library. But this shows, who this
2594 can be done for other cases.
2612 can be done for other cases.
2595 --Added convention that all shell functions should accept a
2613 --Added convention that all shell functions should accept a
2596 parameter_string This opens the door for different behaviour for
2614 parameter_string This opens the door for different behaviour for
2597 each function. @cd is a good example of this.
2615 each function. @cd is a good example of this.
2598
2616
2599 04.05.99 12:12 porto.ifm.uni-kiel.de
2617 04.05.99 12:12 porto.ifm.uni-kiel.de
2600 --added logfile rotation
2618 --added logfile rotation
2601 --added new mainloop method which freezes first the namespace
2619 --added new mainloop method which freezes first the namespace
2602
2620
2603 07.05.99 21:24 porto.ifm.uni-kiel.de
2621 07.05.99 21:24 porto.ifm.uni-kiel.de
2604 --added the docreader classes. Now there is a help system.
2622 --added the docreader classes. Now there is a help system.
2605 -This is only a first try. Currently it's not easy to put new
2623 -This is only a first try. Currently it's not easy to put new
2606 stuff in the indices. But this is the way to go. Info would be
2624 stuff in the indices. But this is the way to go. Info would be
2607 better, but HTML is every where and not everybody has an info
2625 better, but HTML is every where and not everybody has an info
2608 system installed and it's not so easy to change html-docs to info.
2626 system installed and it's not so easy to change html-docs to info.
2609 --added global logfile option
2627 --added global logfile option
2610 --there is now a hook for object inspection method pinfo needs to
2628 --there is now a hook for object inspection method pinfo needs to
2611 be provided for this. Can be reached by two '??'.
2629 be provided for this. Can be reached by two '??'.
2612
2630
2613 08.05.99 20:51 porto.ifm.uni-kiel.de
2631 08.05.99 20:51 porto.ifm.uni-kiel.de
2614 --added a README
2632 --added a README
2615 --bug in rc file. Something has changed so functions in the rc
2633 --bug in rc file. Something has changed so functions in the rc
2616 file need to reference the shell and not self. Not clear if it's a
2634 file need to reference the shell and not self. Not clear if it's a
2617 bug or feature.
2635 bug or feature.
2618 --changed rc file for new behavior
2636 --changed rc file for new behavior
2619
2637
2620 2004-07-15 Fernando Perez <fperez@colorado.edu>
2638 2004-07-15 Fernando Perez <fperez@colorado.edu>
2621
2639
2622 * IPython/Logger.py (Logger.log): fixed recent bug where the input
2640 * IPython/Logger.py (Logger.log): fixed recent bug where the input
2623 cache was falling out of sync in bizarre manners when multi-line
2641 cache was falling out of sync in bizarre manners when multi-line
2624 input was present. Minor optimizations and cleanup.
2642 input was present. Minor optimizations and cleanup.
2625
2643
2626 (Logger): Remove old Changelog info for cleanup. This is the
2644 (Logger): Remove old Changelog info for cleanup. This is the
2627 information which was there from Janko's original code:
2645 information which was there from Janko's original code:
2628
2646
2629 Changes to Logger: - made the default log filename a parameter
2647 Changes to Logger: - made the default log filename a parameter
2630
2648
2631 - put a check for lines beginning with !@? in log(). Needed
2649 - put a check for lines beginning with !@? in log(). Needed
2632 (even if the handlers properly log their lines) for mid-session
2650 (even if the handlers properly log their lines) for mid-session
2633 logging activation to work properly. Without this, lines logged
2651 logging activation to work properly. Without this, lines logged
2634 in mid session, which get read from the cache, would end up
2652 in mid session, which get read from the cache, would end up
2635 'bare' (with !@? in the open) in the log. Now they are caught
2653 'bare' (with !@? in the open) in the log. Now they are caught
2636 and prepended with a #.
2654 and prepended with a #.
2637
2655
2638 * IPython/iplib.py (InteractiveShell.init_readline): added check
2656 * IPython/iplib.py (InteractiveShell.init_readline): added check
2639 in case MagicCompleter fails to be defined, so we don't crash.
2657 in case MagicCompleter fails to be defined, so we don't crash.
2640
2658
2641 2004-07-13 Fernando Perez <fperez@colorado.edu>
2659 2004-07-13 Fernando Perez <fperez@colorado.edu>
2642
2660
2643 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
2661 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
2644 of EPS if the requested filename ends in '.eps'.
2662 of EPS if the requested filename ends in '.eps'.
2645
2663
2646 2004-07-04 Fernando Perez <fperez@colorado.edu>
2664 2004-07-04 Fernando Perez <fperez@colorado.edu>
2647
2665
2648 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
2666 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
2649 escaping of quotes when calling the shell.
2667 escaping of quotes when calling the shell.
2650
2668
2651 2004-07-02 Fernando Perez <fperez@colorado.edu>
2669 2004-07-02 Fernando Perez <fperez@colorado.edu>
2652
2670
2653 * IPython/Prompts.py (CachedOutput.update): Fix problem with
2671 * IPython/Prompts.py (CachedOutput.update): Fix problem with
2654 gettext not working because we were clobbering '_'. Fixes
2672 gettext not working because we were clobbering '_'. Fixes
2655 http://www.scipy.net/roundup/ipython/issue6.
2673 http://www.scipy.net/roundup/ipython/issue6.
2656
2674
2657 2004-07-01 Fernando Perez <fperez@colorado.edu>
2675 2004-07-01 Fernando Perez <fperez@colorado.edu>
2658
2676
2659 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
2677 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
2660 into @cd. Patch by Ville.
2678 into @cd. Patch by Ville.
2661
2679
2662 * IPython/iplib.py (InteractiveShell.post_config_initialization):
2680 * IPython/iplib.py (InteractiveShell.post_config_initialization):
2663 new function to store things after ipmaker runs. Patch by Ville.
2681 new function to store things after ipmaker runs. Patch by Ville.
2664 Eventually this will go away once ipmaker is removed and the class
2682 Eventually this will go away once ipmaker is removed and the class
2665 gets cleaned up, but for now it's ok. Key functionality here is
2683 gets cleaned up, but for now it's ok. Key functionality here is
2666 the addition of the persistent storage mechanism, a dict for
2684 the addition of the persistent storage mechanism, a dict for
2667 keeping data across sessions (for now just bookmarks, but more can
2685 keeping data across sessions (for now just bookmarks, but more can
2668 be implemented later).
2686 be implemented later).
2669
2687
2670 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
2688 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
2671 persistent across sections. Patch by Ville, I modified it
2689 persistent across sections. Patch by Ville, I modified it
2672 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
2690 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
2673 added a '-l' option to list all bookmarks.
2691 added a '-l' option to list all bookmarks.
2674
2692
2675 * IPython/iplib.py (InteractiveShell.atexit_operations): new
2693 * IPython/iplib.py (InteractiveShell.atexit_operations): new
2676 center for cleanup. Registered with atexit.register(). I moved
2694 center for cleanup. Registered with atexit.register(). I moved
2677 here the old exit_cleanup(). After a patch by Ville.
2695 here the old exit_cleanup(). After a patch by Ville.
2678
2696
2679 * IPython/Magic.py (get_py_filename): added '~' to the accepted
2697 * IPython/Magic.py (get_py_filename): added '~' to the accepted
2680 characters in the hacked shlex_split for python 2.2.
2698 characters in the hacked shlex_split for python 2.2.
2681
2699
2682 * IPython/iplib.py (file_matches): more fixes to filenames with
2700 * IPython/iplib.py (file_matches): more fixes to filenames with
2683 whitespace in them. It's not perfect, but limitations in python's
2701 whitespace in them. It's not perfect, but limitations in python's
2684 readline make it impossible to go further.
2702 readline make it impossible to go further.
2685
2703
2686 2004-06-29 Fernando Perez <fperez@colorado.edu>
2704 2004-06-29 Fernando Perez <fperez@colorado.edu>
2687
2705
2688 * IPython/iplib.py (file_matches): escape whitespace correctly in
2706 * IPython/iplib.py (file_matches): escape whitespace correctly in
2689 filename completions. Bug reported by Ville.
2707 filename completions. Bug reported by Ville.
2690
2708
2691 2004-06-28 Fernando Perez <fperez@colorado.edu>
2709 2004-06-28 Fernando Perez <fperez@colorado.edu>
2692
2710
2693 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
2711 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
2694 the history file will be called 'history-PROFNAME' (or just
2712 the history file will be called 'history-PROFNAME' (or just
2695 'history' if no profile is loaded). I was getting annoyed at
2713 'history' if no profile is loaded). I was getting annoyed at
2696 getting my Numerical work history clobbered by pysh sessions.
2714 getting my Numerical work history clobbered by pysh sessions.
2697
2715
2698 * IPython/iplib.py (InteractiveShell.__init__): Internal
2716 * IPython/iplib.py (InteractiveShell.__init__): Internal
2699 getoutputerror() function so that we can honor the system_verbose
2717 getoutputerror() function so that we can honor the system_verbose
2700 flag for _all_ system calls. I also added escaping of #
2718 flag for _all_ system calls. I also added escaping of #
2701 characters here to avoid confusing Itpl.
2719 characters here to avoid confusing Itpl.
2702
2720
2703 * IPython/Magic.py (shlex_split): removed call to shell in
2721 * IPython/Magic.py (shlex_split): removed call to shell in
2704 parse_options and replaced it with shlex.split(). The annoying
2722 parse_options and replaced it with shlex.split(). The annoying
2705 part was that in Python 2.2, shlex.split() doesn't exist, so I had
2723 part was that in Python 2.2, shlex.split() doesn't exist, so I had
2706 to backport it from 2.3, with several frail hacks (the shlex
2724 to backport it from 2.3, with several frail hacks (the shlex
2707 module is rather limited in 2.2). Thanks to a suggestion by Ville
2725 module is rather limited in 2.2). Thanks to a suggestion by Ville
2708 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
2726 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
2709 problem.
2727 problem.
2710
2728
2711 (Magic.magic_system_verbose): new toggle to print the actual
2729 (Magic.magic_system_verbose): new toggle to print the actual
2712 system calls made by ipython. Mainly for debugging purposes.
2730 system calls made by ipython. Mainly for debugging purposes.
2713
2731
2714 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
2732 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
2715 doesn't support persistence. Reported (and fix suggested) by
2733 doesn't support persistence. Reported (and fix suggested) by
2716 Travis Caldwell <travis_caldwell2000@yahoo.com>.
2734 Travis Caldwell <travis_caldwell2000@yahoo.com>.
2717
2735
2718 2004-06-26 Fernando Perez <fperez@colorado.edu>
2736 2004-06-26 Fernando Perez <fperez@colorado.edu>
2719
2737
2720 * IPython/Logger.py (Logger.log): fix to handle correctly empty
2738 * IPython/Logger.py (Logger.log): fix to handle correctly empty
2721 continue prompts.
2739 continue prompts.
2722
2740
2723 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
2741 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
2724 function (basically a big docstring) and a few more things here to
2742 function (basically a big docstring) and a few more things here to
2725 speedup startup. pysh.py is now very lightweight. We want because
2743 speedup startup. pysh.py is now very lightweight. We want because
2726 it gets execfile'd, while InterpreterExec gets imported, so
2744 it gets execfile'd, while InterpreterExec gets imported, so
2727 byte-compilation saves time.
2745 byte-compilation saves time.
2728
2746
2729 2004-06-25 Fernando Perez <fperez@colorado.edu>
2747 2004-06-25 Fernando Perez <fperez@colorado.edu>
2730
2748
2731 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
2749 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
2732 -NUM', which was recently broken.
2750 -NUM', which was recently broken.
2733
2751
2734 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
2752 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
2735 in multi-line input (but not !!, which doesn't make sense there).
2753 in multi-line input (but not !!, which doesn't make sense there).
2736
2754
2737 * IPython/UserConfig/ipythonrc: made autoindent on by default.
2755 * IPython/UserConfig/ipythonrc: made autoindent on by default.
2738 It's just too useful, and people can turn it off in the less
2756 It's just too useful, and people can turn it off in the less
2739 common cases where it's a problem.
2757 common cases where it's a problem.
2740
2758
2741 2004-06-24 Fernando Perez <fperez@colorado.edu>
2759 2004-06-24 Fernando Perez <fperez@colorado.edu>
2742
2760
2743 * IPython/iplib.py (InteractiveShell._prefilter): big change -
2761 * IPython/iplib.py (InteractiveShell._prefilter): big change -
2744 special syntaxes (like alias calling) is now allied in multi-line
2762 special syntaxes (like alias calling) is now allied in multi-line
2745 input. This is still _very_ experimental, but it's necessary for
2763 input. This is still _very_ experimental, but it's necessary for
2746 efficient shell usage combining python looping syntax with system
2764 efficient shell usage combining python looping syntax with system
2747 calls. For now it's restricted to aliases, I don't think it
2765 calls. For now it's restricted to aliases, I don't think it
2748 really even makes sense to have this for magics.
2766 really even makes sense to have this for magics.
2749
2767
2750 2004-06-23 Fernando Perez <fperez@colorado.edu>
2768 2004-06-23 Fernando Perez <fperez@colorado.edu>
2751
2769
2752 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
2770 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
2753 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
2771 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
2754
2772
2755 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
2773 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
2756 extensions under Windows (after code sent by Gary Bishop). The
2774 extensions under Windows (after code sent by Gary Bishop). The
2757 extensions considered 'executable' are stored in IPython's rc
2775 extensions considered 'executable' are stored in IPython's rc
2758 structure as win_exec_ext.
2776 structure as win_exec_ext.
2759
2777
2760 * IPython/genutils.py (shell): new function, like system() but
2778 * IPython/genutils.py (shell): new function, like system() but
2761 without return value. Very useful for interactive shell work.
2779 without return value. Very useful for interactive shell work.
2762
2780
2763 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
2781 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
2764 delete aliases.
2782 delete aliases.
2765
2783
2766 * IPython/iplib.py (InteractiveShell.alias_table_update): make
2784 * IPython/iplib.py (InteractiveShell.alias_table_update): make
2767 sure that the alias table doesn't contain python keywords.
2785 sure that the alias table doesn't contain python keywords.
2768
2786
2769 2004-06-21 Fernando Perez <fperez@colorado.edu>
2787 2004-06-21 Fernando Perez <fperez@colorado.edu>
2770
2788
2771 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
2789 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
2772 non-existent items are found in $PATH. Reported by Thorsten.
2790 non-existent items are found in $PATH. Reported by Thorsten.
2773
2791
2774 2004-06-20 Fernando Perez <fperez@colorado.edu>
2792 2004-06-20 Fernando Perez <fperez@colorado.edu>
2775
2793
2776 * IPython/iplib.py (complete): modified the completer so that the
2794 * IPython/iplib.py (complete): modified the completer so that the
2777 order of priorities can be easily changed at runtime.
2795 order of priorities can be easily changed at runtime.
2778
2796
2779 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
2797 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
2780 Modified to auto-execute all lines beginning with '~', '/' or '.'.
2798 Modified to auto-execute all lines beginning with '~', '/' or '.'.
2781
2799
2782 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
2800 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
2783 expand Python variables prepended with $ in all system calls. The
2801 expand Python variables prepended with $ in all system calls. The
2784 same was done to InteractiveShell.handle_shell_escape. Now all
2802 same was done to InteractiveShell.handle_shell_escape. Now all
2785 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
2803 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
2786 expansion of python variables and expressions according to the
2804 expansion of python variables and expressions according to the
2787 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
2805 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
2788
2806
2789 Though PEP-215 has been rejected, a similar (but simpler) one
2807 Though PEP-215 has been rejected, a similar (but simpler) one
2790 seems like it will go into Python 2.4, PEP-292 -
2808 seems like it will go into Python 2.4, PEP-292 -
2791 http://www.python.org/peps/pep-0292.html.
2809 http://www.python.org/peps/pep-0292.html.
2792
2810
2793 I'll keep the full syntax of PEP-215, since IPython has since the
2811 I'll keep the full syntax of PEP-215, since IPython has since the
2794 start used Ka-Ping Yee's reference implementation discussed there
2812 start used Ka-Ping Yee's reference implementation discussed there
2795 (Itpl), and I actually like the powerful semantics it offers.
2813 (Itpl), and I actually like the powerful semantics it offers.
2796
2814
2797 In order to access normal shell variables, the $ has to be escaped
2815 In order to access normal shell variables, the $ has to be escaped
2798 via an extra $. For example:
2816 via an extra $. For example:
2799
2817
2800 In [7]: PATH='a python variable'
2818 In [7]: PATH='a python variable'
2801
2819
2802 In [8]: !echo $PATH
2820 In [8]: !echo $PATH
2803 a python variable
2821 a python variable
2804
2822
2805 In [9]: !echo $$PATH
2823 In [9]: !echo $$PATH
2806 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2824 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2807
2825
2808 (Magic.parse_options): escape $ so the shell doesn't evaluate
2826 (Magic.parse_options): escape $ so the shell doesn't evaluate
2809 things prematurely.
2827 things prematurely.
2810
2828
2811 * IPython/iplib.py (InteractiveShell.call_alias): added the
2829 * IPython/iplib.py (InteractiveShell.call_alias): added the
2812 ability for aliases to expand python variables via $.
2830 ability for aliases to expand python variables via $.
2813
2831
2814 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
2832 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
2815 system, now there's a @rehash/@rehashx pair of magics. These work
2833 system, now there's a @rehash/@rehashx pair of magics. These work
2816 like the csh rehash command, and can be invoked at any time. They
2834 like the csh rehash command, and can be invoked at any time. They
2817 build a table of aliases to everything in the user's $PATH
2835 build a table of aliases to everything in the user's $PATH
2818 (@rehash uses everything, @rehashx is slower but only adds
2836 (@rehash uses everything, @rehashx is slower but only adds
2819 executable files). With this, the pysh.py-based shell profile can
2837 executable files). With this, the pysh.py-based shell profile can
2820 now simply call rehash upon startup, and full access to all
2838 now simply call rehash upon startup, and full access to all
2821 programs in the user's path is obtained.
2839 programs in the user's path is obtained.
2822
2840
2823 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
2841 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
2824 functionality is now fully in place. I removed the old dynamic
2842 functionality is now fully in place. I removed the old dynamic
2825 code generation based approach, in favor of a much lighter one
2843 code generation based approach, in favor of a much lighter one
2826 based on a simple dict. The advantage is that this allows me to
2844 based on a simple dict. The advantage is that this allows me to
2827 now have thousands of aliases with negligible cost (unthinkable
2845 now have thousands of aliases with negligible cost (unthinkable
2828 with the old system).
2846 with the old system).
2829
2847
2830 2004-06-19 Fernando Perez <fperez@colorado.edu>
2848 2004-06-19 Fernando Perez <fperez@colorado.edu>
2831
2849
2832 * IPython/iplib.py (__init__): extended MagicCompleter class to
2850 * IPython/iplib.py (__init__): extended MagicCompleter class to
2833 also complete (last in priority) on user aliases.
2851 also complete (last in priority) on user aliases.
2834
2852
2835 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
2853 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
2836 call to eval.
2854 call to eval.
2837 (ItplNS.__init__): Added a new class which functions like Itpl,
2855 (ItplNS.__init__): Added a new class which functions like Itpl,
2838 but allows configuring the namespace for the evaluation to occur
2856 but allows configuring the namespace for the evaluation to occur
2839 in.
2857 in.
2840
2858
2841 2004-06-18 Fernando Perez <fperez@colorado.edu>
2859 2004-06-18 Fernando Perez <fperez@colorado.edu>
2842
2860
2843 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
2861 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
2844 better message when 'exit' or 'quit' are typed (a common newbie
2862 better message when 'exit' or 'quit' are typed (a common newbie
2845 confusion).
2863 confusion).
2846
2864
2847 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
2865 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
2848 check for Windows users.
2866 check for Windows users.
2849
2867
2850 * IPython/iplib.py (InteractiveShell.user_setup): removed
2868 * IPython/iplib.py (InteractiveShell.user_setup): removed
2851 disabling of colors for Windows. I'll test at runtime and issue a
2869 disabling of colors for Windows. I'll test at runtime and issue a
2852 warning if Gary's readline isn't found, as to nudge users to
2870 warning if Gary's readline isn't found, as to nudge users to
2853 download it.
2871 download it.
2854
2872
2855 2004-06-16 Fernando Perez <fperez@colorado.edu>
2873 2004-06-16 Fernando Perez <fperez@colorado.edu>
2856
2874
2857 * IPython/genutils.py (Stream.__init__): changed to print errors
2875 * IPython/genutils.py (Stream.__init__): changed to print errors
2858 to sys.stderr. I had a circular dependency here. Now it's
2876 to sys.stderr. I had a circular dependency here. Now it's
2859 possible to run ipython as IDLE's shell (consider this pre-alpha,
2877 possible to run ipython as IDLE's shell (consider this pre-alpha,
2860 since true stdout things end up in the starting terminal instead
2878 since true stdout things end up in the starting terminal instead
2861 of IDLE's out).
2879 of IDLE's out).
2862
2880
2863 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
2881 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
2864 users who haven't # updated their prompt_in2 definitions. Remove
2882 users who haven't # updated their prompt_in2 definitions. Remove
2865 eventually.
2883 eventually.
2866 (multiple_replace): added credit to original ASPN recipe.
2884 (multiple_replace): added credit to original ASPN recipe.
2867
2885
2868 2004-06-15 Fernando Perez <fperez@colorado.edu>
2886 2004-06-15 Fernando Perez <fperez@colorado.edu>
2869
2887
2870 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
2888 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
2871 list of auto-defined aliases.
2889 list of auto-defined aliases.
2872
2890
2873 2004-06-13 Fernando Perez <fperez@colorado.edu>
2891 2004-06-13 Fernando Perez <fperez@colorado.edu>
2874
2892
2875 * setup.py (scriptfiles): Don't trigger win_post_install unless an
2893 * setup.py (scriptfiles): Don't trigger win_post_install unless an
2876 install was really requested (so setup.py can be used for other
2894 install was really requested (so setup.py can be used for other
2877 things under Windows).
2895 things under Windows).
2878
2896
2879 2004-06-10 Fernando Perez <fperez@colorado.edu>
2897 2004-06-10 Fernando Perez <fperez@colorado.edu>
2880
2898
2881 * IPython/Logger.py (Logger.create_log): Manually remove any old
2899 * IPython/Logger.py (Logger.create_log): Manually remove any old
2882 backup, since os.remove may fail under Windows. Fixes bug
2900 backup, since os.remove may fail under Windows. Fixes bug
2883 reported by Thorsten.
2901 reported by Thorsten.
2884
2902
2885 2004-06-09 Fernando Perez <fperez@colorado.edu>
2903 2004-06-09 Fernando Perez <fperez@colorado.edu>
2886
2904
2887 * examples/example-embed.py: fixed all references to %n (replaced
2905 * examples/example-embed.py: fixed all references to %n (replaced
2888 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
2906 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
2889 for all examples and the manual as well.
2907 for all examples and the manual as well.
2890
2908
2891 2004-06-08 Fernando Perez <fperez@colorado.edu>
2909 2004-06-08 Fernando Perez <fperez@colorado.edu>
2892
2910
2893 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
2911 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
2894 alignment and color management. All 3 prompt subsystems now
2912 alignment and color management. All 3 prompt subsystems now
2895 inherit from BasePrompt.
2913 inherit from BasePrompt.
2896
2914
2897 * tools/release: updates for windows installer build and tag rpms
2915 * tools/release: updates for windows installer build and tag rpms
2898 with python version (since paths are fixed).
2916 with python version (since paths are fixed).
2899
2917
2900 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
2918 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
2901 which will become eventually obsolete. Also fixed the default
2919 which will become eventually obsolete. Also fixed the default
2902 prompt_in2 to use \D, so at least new users start with the correct
2920 prompt_in2 to use \D, so at least new users start with the correct
2903 defaults.
2921 defaults.
2904 WARNING: Users with existing ipythonrc files will need to apply
2922 WARNING: Users with existing ipythonrc files will need to apply
2905 this fix manually!
2923 this fix manually!
2906
2924
2907 * setup.py: make windows installer (.exe). This is finally the
2925 * setup.py: make windows installer (.exe). This is finally the
2908 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
2926 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
2909 which I hadn't included because it required Python 2.3 (or recent
2927 which I hadn't included because it required Python 2.3 (or recent
2910 distutils).
2928 distutils).
2911
2929
2912 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
2930 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
2913 usage of new '\D' escape.
2931 usage of new '\D' escape.
2914
2932
2915 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
2933 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
2916 lacks os.getuid())
2934 lacks os.getuid())
2917 (CachedOutput.set_colors): Added the ability to turn coloring
2935 (CachedOutput.set_colors): Added the ability to turn coloring
2918 on/off with @colors even for manually defined prompt colors. It
2936 on/off with @colors even for manually defined prompt colors. It
2919 uses a nasty global, but it works safely and via the generic color
2937 uses a nasty global, but it works safely and via the generic color
2920 handling mechanism.
2938 handling mechanism.
2921 (Prompt2.__init__): Introduced new escape '\D' for continuation
2939 (Prompt2.__init__): Introduced new escape '\D' for continuation
2922 prompts. It represents the counter ('\#') as dots.
2940 prompts. It represents the counter ('\#') as dots.
2923 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
2941 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
2924 need to update their ipythonrc files and replace '%n' with '\D' in
2942 need to update their ipythonrc files and replace '%n' with '\D' in
2925 their prompt_in2 settings everywhere. Sorry, but there's
2943 their prompt_in2 settings everywhere. Sorry, but there's
2926 otherwise no clean way to get all prompts to properly align. The
2944 otherwise no clean way to get all prompts to properly align. The
2927 ipythonrc shipped with IPython has been updated.
2945 ipythonrc shipped with IPython has been updated.
2928
2946
2929 2004-06-07 Fernando Perez <fperez@colorado.edu>
2947 2004-06-07 Fernando Perez <fperez@colorado.edu>
2930
2948
2931 * setup.py (isfile): Pass local_icons option to latex2html, so the
2949 * setup.py (isfile): Pass local_icons option to latex2html, so the
2932 resulting HTML file is self-contained. Thanks to
2950 resulting HTML file is self-contained. Thanks to
2933 dryice-AT-liu.com.cn for the tip.
2951 dryice-AT-liu.com.cn for the tip.
2934
2952
2935 * pysh.py: I created a new profile 'shell', which implements a
2953 * pysh.py: I created a new profile 'shell', which implements a
2936 _rudimentary_ IPython-based shell. This is in NO WAY a realy
2954 _rudimentary_ IPython-based shell. This is in NO WAY a realy
2937 system shell, nor will it become one anytime soon. It's mainly
2955 system shell, nor will it become one anytime soon. It's mainly
2938 meant to illustrate the use of the new flexible bash-like prompts.
2956 meant to illustrate the use of the new flexible bash-like prompts.
2939 I guess it could be used by hardy souls for true shell management,
2957 I guess it could be used by hardy souls for true shell management,
2940 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
2958 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
2941 profile. This uses the InterpreterExec extension provided by
2959 profile. This uses the InterpreterExec extension provided by
2942 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
2960 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
2943
2961
2944 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
2962 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
2945 auto-align itself with the length of the previous input prompt
2963 auto-align itself with the length of the previous input prompt
2946 (taking into account the invisible color escapes).
2964 (taking into account the invisible color escapes).
2947 (CachedOutput.__init__): Large restructuring of this class. Now
2965 (CachedOutput.__init__): Large restructuring of this class. Now
2948 all three prompts (primary1, primary2, output) are proper objects,
2966 all three prompts (primary1, primary2, output) are proper objects,
2949 managed by the 'parent' CachedOutput class. The code is still a
2967 managed by the 'parent' CachedOutput class. The code is still a
2950 bit hackish (all prompts share state via a pointer to the cache),
2968 bit hackish (all prompts share state via a pointer to the cache),
2951 but it's overall far cleaner than before.
2969 but it's overall far cleaner than before.
2952
2970
2953 * IPython/genutils.py (getoutputerror): modified to add verbose,
2971 * IPython/genutils.py (getoutputerror): modified to add verbose,
2954 debug and header options. This makes the interface of all getout*
2972 debug and header options. This makes the interface of all getout*
2955 functions uniform.
2973 functions uniform.
2956 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
2974 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
2957
2975
2958 * IPython/Magic.py (Magic.default_option): added a function to
2976 * IPython/Magic.py (Magic.default_option): added a function to
2959 allow registering default options for any magic command. This
2977 allow registering default options for any magic command. This
2960 makes it easy to have profiles which customize the magics globally
2978 makes it easy to have profiles which customize the magics globally
2961 for a certain use. The values set through this function are
2979 for a certain use. The values set through this function are
2962 picked up by the parse_options() method, which all magics should
2980 picked up by the parse_options() method, which all magics should
2963 use to parse their options.
2981 use to parse their options.
2964
2982
2965 * IPython/genutils.py (warn): modified the warnings framework to
2983 * IPython/genutils.py (warn): modified the warnings framework to
2966 use the Term I/O class. I'm trying to slowly unify all of
2984 use the Term I/O class. I'm trying to slowly unify all of
2967 IPython's I/O operations to pass through Term.
2985 IPython's I/O operations to pass through Term.
2968
2986
2969 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
2987 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
2970 the secondary prompt to correctly match the length of the primary
2988 the secondary prompt to correctly match the length of the primary
2971 one for any prompt. Now multi-line code will properly line up
2989 one for any prompt. Now multi-line code will properly line up
2972 even for path dependent prompts, such as the new ones available
2990 even for path dependent prompts, such as the new ones available
2973 via the prompt_specials.
2991 via the prompt_specials.
2974
2992
2975 2004-06-06 Fernando Perez <fperez@colorado.edu>
2993 2004-06-06 Fernando Perez <fperez@colorado.edu>
2976
2994
2977 * IPython/Prompts.py (prompt_specials): Added the ability to have
2995 * IPython/Prompts.py (prompt_specials): Added the ability to have
2978 bash-like special sequences in the prompts, which get
2996 bash-like special sequences in the prompts, which get
2979 automatically expanded. Things like hostname, current working
2997 automatically expanded. Things like hostname, current working
2980 directory and username are implemented already, but it's easy to
2998 directory and username are implemented already, but it's easy to
2981 add more in the future. Thanks to a patch by W.J. van der Laan
2999 add more in the future. Thanks to a patch by W.J. van der Laan
2982 <gnufnork-AT-hetdigitalegat.nl>
3000 <gnufnork-AT-hetdigitalegat.nl>
2983 (prompt_specials): Added color support for prompt strings, so
3001 (prompt_specials): Added color support for prompt strings, so
2984 users can define arbitrary color setups for their prompts.
3002 users can define arbitrary color setups for their prompts.
2985
3003
2986 2004-06-05 Fernando Perez <fperez@colorado.edu>
3004 2004-06-05 Fernando Perez <fperez@colorado.edu>
2987
3005
2988 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
3006 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
2989 code to load Gary Bishop's readline and configure it
3007 code to load Gary Bishop's readline and configure it
2990 automatically. Thanks to Gary for help on this.
3008 automatically. Thanks to Gary for help on this.
2991
3009
2992 2004-06-01 Fernando Perez <fperez@colorado.edu>
3010 2004-06-01 Fernando Perez <fperez@colorado.edu>
2993
3011
2994 * IPython/Logger.py (Logger.create_log): fix bug for logging
3012 * IPython/Logger.py (Logger.create_log): fix bug for logging
2995 with no filename (previous fix was incomplete).
3013 with no filename (previous fix was incomplete).
2996
3014
2997 2004-05-25 Fernando Perez <fperez@colorado.edu>
3015 2004-05-25 Fernando Perez <fperez@colorado.edu>
2998
3016
2999 * IPython/Magic.py (Magic.parse_options): fix bug where naked
3017 * IPython/Magic.py (Magic.parse_options): fix bug where naked
3000 parens would get passed to the shell.
3018 parens would get passed to the shell.
3001
3019
3002 2004-05-20 Fernando Perez <fperez@colorado.edu>
3020 2004-05-20 Fernando Perez <fperez@colorado.edu>
3003
3021
3004 * IPython/Magic.py (Magic.magic_prun): changed default profile
3022 * IPython/Magic.py (Magic.magic_prun): changed default profile
3005 sort order to 'time' (the more common profiling need).
3023 sort order to 'time' (the more common profiling need).
3006
3024
3007 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
3025 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
3008 so that source code shown is guaranteed in sync with the file on
3026 so that source code shown is guaranteed in sync with the file on
3009 disk (also changed in psource). Similar fix to the one for
3027 disk (also changed in psource). Similar fix to the one for
3010 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
3028 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
3011 <yann.ledu-AT-noos.fr>.
3029 <yann.ledu-AT-noos.fr>.
3012
3030
3013 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
3031 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
3014 with a single option would not be correctly parsed. Closes
3032 with a single option would not be correctly parsed. Closes
3015 http://www.scipy.net/roundup/ipython/issue14. This bug had been
3033 http://www.scipy.net/roundup/ipython/issue14. This bug had been
3016 introduced in 0.6.0 (on 2004-05-06).
3034 introduced in 0.6.0 (on 2004-05-06).
3017
3035
3018 2004-05-13 *** Released version 0.6.0
3036 2004-05-13 *** Released version 0.6.0
3019
3037
3020 2004-05-13 Fernando Perez <fperez@colorado.edu>
3038 2004-05-13 Fernando Perez <fperez@colorado.edu>
3021
3039
3022 * debian/: Added debian/ directory to CVS, so that debian support
3040 * debian/: Added debian/ directory to CVS, so that debian support
3023 is publicly accessible. The debian package is maintained by Jack
3041 is publicly accessible. The debian package is maintained by Jack
3024 Moffit <jack-AT-xiph.org>.
3042 Moffit <jack-AT-xiph.org>.
3025
3043
3026 * Documentation: included the notes about an ipython-based system
3044 * Documentation: included the notes about an ipython-based system
3027 shell (the hypothetical 'pysh') into the new_design.pdf document,
3045 shell (the hypothetical 'pysh') into the new_design.pdf document,
3028 so that these ideas get distributed to users along with the
3046 so that these ideas get distributed to users along with the
3029 official documentation.
3047 official documentation.
3030
3048
3031 2004-05-10 Fernando Perez <fperez@colorado.edu>
3049 2004-05-10 Fernando Perez <fperez@colorado.edu>
3032
3050
3033 * IPython/Logger.py (Logger.create_log): fix recently introduced
3051 * IPython/Logger.py (Logger.create_log): fix recently introduced
3034 bug (misindented line) where logstart would fail when not given an
3052 bug (misindented line) where logstart would fail when not given an
3035 explicit filename.
3053 explicit filename.
3036
3054
3037 2004-05-09 Fernando Perez <fperez@colorado.edu>
3055 2004-05-09 Fernando Perez <fperez@colorado.edu>
3038
3056
3039 * IPython/Magic.py (Magic.parse_options): skip system call when
3057 * IPython/Magic.py (Magic.parse_options): skip system call when
3040 there are no options to look for. Faster, cleaner for the common
3058 there are no options to look for. Faster, cleaner for the common
3041 case.
3059 case.
3042
3060
3043 * Documentation: many updates to the manual: describing Windows
3061 * Documentation: many updates to the manual: describing Windows
3044 support better, Gnuplot updates, credits, misc small stuff. Also
3062 support better, Gnuplot updates, credits, misc small stuff. Also
3045 updated the new_design doc a bit.
3063 updated the new_design doc a bit.
3046
3064
3047 2004-05-06 *** Released version 0.6.0.rc1
3065 2004-05-06 *** Released version 0.6.0.rc1
3048
3066
3049 2004-05-06 Fernando Perez <fperez@colorado.edu>
3067 2004-05-06 Fernando Perez <fperez@colorado.edu>
3050
3068
3051 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
3069 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
3052 operations to use the vastly more efficient list/''.join() method.
3070 operations to use the vastly more efficient list/''.join() method.
3053 (FormattedTB.text): Fix
3071 (FormattedTB.text): Fix
3054 http://www.scipy.net/roundup/ipython/issue12 - exception source
3072 http://www.scipy.net/roundup/ipython/issue12 - exception source
3055 extract not updated after reload. Thanks to Mike Salib
3073 extract not updated after reload. Thanks to Mike Salib
3056 <msalib-AT-mit.edu> for pinning the source of the problem.
3074 <msalib-AT-mit.edu> for pinning the source of the problem.
3057 Fortunately, the solution works inside ipython and doesn't require
3075 Fortunately, the solution works inside ipython and doesn't require
3058 any changes to python proper.
3076 any changes to python proper.
3059
3077
3060 * IPython/Magic.py (Magic.parse_options): Improved to process the
3078 * IPython/Magic.py (Magic.parse_options): Improved to process the
3061 argument list as a true shell would (by actually using the
3079 argument list as a true shell would (by actually using the
3062 underlying system shell). This way, all @magics automatically get
3080 underlying system shell). This way, all @magics automatically get
3063 shell expansion for variables. Thanks to a comment by Alex
3081 shell expansion for variables. Thanks to a comment by Alex
3064 Schmolck.
3082 Schmolck.
3065
3083
3066 2004-04-04 Fernando Perez <fperez@colorado.edu>
3084 2004-04-04 Fernando Perez <fperez@colorado.edu>
3067
3085
3068 * IPython/iplib.py (InteractiveShell.interact): Added a special
3086 * IPython/iplib.py (InteractiveShell.interact): Added a special
3069 trap for a debugger quit exception, which is basically impossible
3087 trap for a debugger quit exception, which is basically impossible
3070 to handle by normal mechanisms, given what pdb does to the stack.
3088 to handle by normal mechanisms, given what pdb does to the stack.
3071 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
3089 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
3072
3090
3073 2004-04-03 Fernando Perez <fperez@colorado.edu>
3091 2004-04-03 Fernando Perez <fperez@colorado.edu>
3074
3092
3075 * IPython/genutils.py (Term): Standardized the names of the Term
3093 * IPython/genutils.py (Term): Standardized the names of the Term
3076 class streams to cin/cout/cerr, following C++ naming conventions
3094 class streams to cin/cout/cerr, following C++ naming conventions
3077 (I can't use in/out/err because 'in' is not a valid attribute
3095 (I can't use in/out/err because 'in' is not a valid attribute
3078 name).
3096 name).
3079
3097
3080 * IPython/iplib.py (InteractiveShell.interact): don't increment
3098 * IPython/iplib.py (InteractiveShell.interact): don't increment
3081 the prompt if there's no user input. By Daniel 'Dang' Griffith
3099 the prompt if there's no user input. By Daniel 'Dang' Griffith
3082 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
3100 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
3083 Francois Pinard.
3101 Francois Pinard.
3084
3102
3085 2004-04-02 Fernando Perez <fperez@colorado.edu>
3103 2004-04-02 Fernando Perez <fperez@colorado.edu>
3086
3104
3087 * IPython/genutils.py (Stream.__init__): Modified to survive at
3105 * IPython/genutils.py (Stream.__init__): Modified to survive at
3088 least importing in contexts where stdin/out/err aren't true file
3106 least importing in contexts where stdin/out/err aren't true file
3089 objects, such as PyCrust (they lack fileno() and mode). However,
3107 objects, such as PyCrust (they lack fileno() and mode). However,
3090 the recovery facilities which rely on these things existing will
3108 the recovery facilities which rely on these things existing will
3091 not work.
3109 not work.
3092
3110
3093 2004-04-01 Fernando Perez <fperez@colorado.edu>
3111 2004-04-01 Fernando Perez <fperez@colorado.edu>
3094
3112
3095 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
3113 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
3096 use the new getoutputerror() function, so it properly
3114 use the new getoutputerror() function, so it properly
3097 distinguishes stdout/err.
3115 distinguishes stdout/err.
3098
3116
3099 * IPython/genutils.py (getoutputerror): added a function to
3117 * IPython/genutils.py (getoutputerror): added a function to
3100 capture separately the standard output and error of a command.
3118 capture separately the standard output and error of a command.
3101 After a comment from dang on the mailing lists. This code is
3119 After a comment from dang on the mailing lists. This code is
3102 basically a modified version of commands.getstatusoutput(), from
3120 basically a modified version of commands.getstatusoutput(), from
3103 the standard library.
3121 the standard library.
3104
3122
3105 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
3123 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
3106 '!!' as a special syntax (shorthand) to access @sx.
3124 '!!' as a special syntax (shorthand) to access @sx.
3107
3125
3108 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
3126 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
3109 command and return its output as a list split on '\n'.
3127 command and return its output as a list split on '\n'.
3110
3128
3111 2004-03-31 Fernando Perez <fperez@colorado.edu>
3129 2004-03-31 Fernando Perez <fperez@colorado.edu>
3112
3130
3113 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
3131 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
3114 method to dictionaries used as FakeModule instances if they lack
3132 method to dictionaries used as FakeModule instances if they lack
3115 it. At least pydoc in python2.3 breaks for runtime-defined
3133 it. At least pydoc in python2.3 breaks for runtime-defined
3116 functions without this hack. At some point I need to _really_
3134 functions without this hack. At some point I need to _really_
3117 understand what FakeModule is doing, because it's a gross hack.
3135 understand what FakeModule is doing, because it's a gross hack.
3118 But it solves Arnd's problem for now...
3136 But it solves Arnd's problem for now...
3119
3137
3120 2004-02-27 Fernando Perez <fperez@colorado.edu>
3138 2004-02-27 Fernando Perez <fperez@colorado.edu>
3121
3139
3122 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
3140 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
3123 mode would behave erratically. Also increased the number of
3141 mode would behave erratically. Also increased the number of
3124 possible logs in rotate mod to 999. Thanks to Rod Holland
3142 possible logs in rotate mod to 999. Thanks to Rod Holland
3125 <rhh@StructureLABS.com> for the report and fixes.
3143 <rhh@StructureLABS.com> for the report and fixes.
3126
3144
3127 2004-02-26 Fernando Perez <fperez@colorado.edu>
3145 2004-02-26 Fernando Perez <fperez@colorado.edu>
3128
3146
3129 * IPython/genutils.py (page): Check that the curses module really
3147 * IPython/genutils.py (page): Check that the curses module really
3130 has the initscr attribute before trying to use it. For some
3148 has the initscr attribute before trying to use it. For some
3131 reason, the Solaris curses module is missing this. I think this
3149 reason, the Solaris curses module is missing this. I think this
3132 should be considered a Solaris python bug, but I'm not sure.
3150 should be considered a Solaris python bug, but I'm not sure.
3133
3151
3134 2004-01-17 Fernando Perez <fperez@colorado.edu>
3152 2004-01-17 Fernando Perez <fperez@colorado.edu>
3135
3153
3136 * IPython/genutils.py (Stream.__init__): Changes to try to make
3154 * IPython/genutils.py (Stream.__init__): Changes to try to make
3137 ipython robust against stdin/out/err being closed by the user.
3155 ipython robust against stdin/out/err being closed by the user.
3138 This is 'user error' (and blocks a normal python session, at least
3156 This is 'user error' (and blocks a normal python session, at least
3139 the stdout case). However, Ipython should be able to survive such
3157 the stdout case). However, Ipython should be able to survive such
3140 instances of abuse as gracefully as possible. To simplify the
3158 instances of abuse as gracefully as possible. To simplify the
3141 coding and maintain compatibility with Gary Bishop's Term
3159 coding and maintain compatibility with Gary Bishop's Term
3142 contributions, I've made use of classmethods for this. I think
3160 contributions, I've made use of classmethods for this. I think
3143 this introduces a dependency on python 2.2.
3161 this introduces a dependency on python 2.2.
3144
3162
3145 2004-01-13 Fernando Perez <fperez@colorado.edu>
3163 2004-01-13 Fernando Perez <fperez@colorado.edu>
3146
3164
3147 * IPython/numutils.py (exp_safe): simplified the code a bit and
3165 * IPython/numutils.py (exp_safe): simplified the code a bit and
3148 removed the need for importing the kinds module altogether.
3166 removed the need for importing the kinds module altogether.
3149
3167
3150 2004-01-06 Fernando Perez <fperez@colorado.edu>
3168 2004-01-06 Fernando Perez <fperez@colorado.edu>
3151
3169
3152 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
3170 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
3153 a magic function instead, after some community feedback. No
3171 a magic function instead, after some community feedback. No
3154 special syntax will exist for it, but its name is deliberately
3172 special syntax will exist for it, but its name is deliberately
3155 very short.
3173 very short.
3156
3174
3157 2003-12-20 Fernando Perez <fperez@colorado.edu>
3175 2003-12-20 Fernando Perez <fperez@colorado.edu>
3158
3176
3159 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
3177 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
3160 new functionality, to automagically assign the result of a shell
3178 new functionality, to automagically assign the result of a shell
3161 command to a variable. I'll solicit some community feedback on
3179 command to a variable. I'll solicit some community feedback on
3162 this before making it permanent.
3180 this before making it permanent.
3163
3181
3164 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
3182 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
3165 requested about callables for which inspect couldn't obtain a
3183 requested about callables for which inspect couldn't obtain a
3166 proper argspec. Thanks to a crash report sent by Etienne
3184 proper argspec. Thanks to a crash report sent by Etienne
3167 Posthumus <etienne-AT-apple01.cs.vu.nl>.
3185 Posthumus <etienne-AT-apple01.cs.vu.nl>.
3168
3186
3169 2003-12-09 Fernando Perez <fperez@colorado.edu>
3187 2003-12-09 Fernando Perez <fperez@colorado.edu>
3170
3188
3171 * IPython/genutils.py (page): patch for the pager to work across
3189 * IPython/genutils.py (page): patch for the pager to work across
3172 various versions of Windows. By Gary Bishop.
3190 various versions of Windows. By Gary Bishop.
3173
3191
3174 2003-12-04 Fernando Perez <fperez@colorado.edu>
3192 2003-12-04 Fernando Perez <fperez@colorado.edu>
3175
3193
3176 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
3194 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
3177 Gnuplot.py version 1.7, whose internal names changed quite a bit.
3195 Gnuplot.py version 1.7, whose internal names changed quite a bit.
3178 While I tested this and it looks ok, there may still be corner
3196 While I tested this and it looks ok, there may still be corner
3179 cases I've missed.
3197 cases I've missed.
3180
3198
3181 2003-12-01 Fernando Perez <fperez@colorado.edu>
3199 2003-12-01 Fernando Perez <fperez@colorado.edu>
3182
3200
3183 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
3201 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
3184 where a line like 'p,q=1,2' would fail because the automagic
3202 where a line like 'p,q=1,2' would fail because the automagic
3185 system would be triggered for @p.
3203 system would be triggered for @p.
3186
3204
3187 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
3205 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
3188 cleanups, code unmodified.
3206 cleanups, code unmodified.
3189
3207
3190 * IPython/genutils.py (Term): added a class for IPython to handle
3208 * IPython/genutils.py (Term): added a class for IPython to handle
3191 output. In most cases it will just be a proxy for stdout/err, but
3209 output. In most cases it will just be a proxy for stdout/err, but
3192 having this allows modifications to be made for some platforms,
3210 having this allows modifications to be made for some platforms,
3193 such as handling color escapes under Windows. All of this code
3211 such as handling color escapes under Windows. All of this code
3194 was contributed by Gary Bishop, with minor modifications by me.
3212 was contributed by Gary Bishop, with minor modifications by me.
3195 The actual changes affect many files.
3213 The actual changes affect many files.
3196
3214
3197 2003-11-30 Fernando Perez <fperez@colorado.edu>
3215 2003-11-30 Fernando Perez <fperez@colorado.edu>
3198
3216
3199 * IPython/iplib.py (file_matches): new completion code, courtesy
3217 * IPython/iplib.py (file_matches): new completion code, courtesy
3200 of Jeff Collins. This enables filename completion again under
3218 of Jeff Collins. This enables filename completion again under
3201 python 2.3, which disabled it at the C level.
3219 python 2.3, which disabled it at the C level.
3202
3220
3203 2003-11-11 Fernando Perez <fperez@colorado.edu>
3221 2003-11-11 Fernando Perez <fperez@colorado.edu>
3204
3222
3205 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
3223 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
3206 for Numeric.array(map(...)), but often convenient.
3224 for Numeric.array(map(...)), but often convenient.
3207
3225
3208 2003-11-05 Fernando Perez <fperez@colorado.edu>
3226 2003-11-05 Fernando Perez <fperez@colorado.edu>
3209
3227
3210 * IPython/numutils.py (frange): Changed a call from int() to
3228 * IPython/numutils.py (frange): Changed a call from int() to
3211 int(round()) to prevent a problem reported with arange() in the
3229 int(round()) to prevent a problem reported with arange() in the
3212 numpy list.
3230 numpy list.
3213
3231
3214 2003-10-06 Fernando Perez <fperez@colorado.edu>
3232 2003-10-06 Fernando Perez <fperez@colorado.edu>
3215
3233
3216 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
3234 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
3217 prevent crashes if sys lacks an argv attribute (it happens with
3235 prevent crashes if sys lacks an argv attribute (it happens with
3218 embedded interpreters which build a bare-bones sys module).
3236 embedded interpreters which build a bare-bones sys module).
3219 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
3237 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
3220
3238
3221 2003-09-24 Fernando Perez <fperez@colorado.edu>
3239 2003-09-24 Fernando Perez <fperez@colorado.edu>
3222
3240
3223 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
3241 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
3224 to protect against poorly written user objects where __getattr__
3242 to protect against poorly written user objects where __getattr__
3225 raises exceptions other than AttributeError. Thanks to a bug
3243 raises exceptions other than AttributeError. Thanks to a bug
3226 report by Oliver Sander <osander-AT-gmx.de>.
3244 report by Oliver Sander <osander-AT-gmx.de>.
3227
3245
3228 * IPython/FakeModule.py (FakeModule.__repr__): this method was
3246 * IPython/FakeModule.py (FakeModule.__repr__): this method was
3229 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
3247 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
3230
3248
3231 2003-09-09 Fernando Perez <fperez@colorado.edu>
3249 2003-09-09 Fernando Perez <fperez@colorado.edu>
3232
3250
3233 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
3251 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
3234 unpacking a list whith a callable as first element would
3252 unpacking a list whith a callable as first element would
3235 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
3253 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
3236 Collins.
3254 Collins.
3237
3255
3238 2003-08-25 *** Released version 0.5.0
3256 2003-08-25 *** Released version 0.5.0
3239
3257
3240 2003-08-22 Fernando Perez <fperez@colorado.edu>
3258 2003-08-22 Fernando Perez <fperez@colorado.edu>
3241
3259
3242 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
3260 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
3243 improperly defined user exceptions. Thanks to feedback from Mark
3261 improperly defined user exceptions. Thanks to feedback from Mark
3244 Russell <mrussell-AT-verio.net>.
3262 Russell <mrussell-AT-verio.net>.
3245
3263
3246 2003-08-20 Fernando Perez <fperez@colorado.edu>
3264 2003-08-20 Fernando Perez <fperez@colorado.edu>
3247
3265
3248 * IPython/OInspect.py (Inspector.pinfo): changed String Form
3266 * IPython/OInspect.py (Inspector.pinfo): changed String Form
3249 printing so that it would print multi-line string forms starting
3267 printing so that it would print multi-line string forms starting
3250 with a new line. This way the formatting is better respected for
3268 with a new line. This way the formatting is better respected for
3251 objects which work hard to make nice string forms.
3269 objects which work hard to make nice string forms.
3252
3270
3253 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
3271 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
3254 autocall would overtake data access for objects with both
3272 autocall would overtake data access for objects with both
3255 __getitem__ and __call__.
3273 __getitem__ and __call__.
3256
3274
3257 2003-08-19 *** Released version 0.5.0-rc1
3275 2003-08-19 *** Released version 0.5.0-rc1
3258
3276
3259 2003-08-19 Fernando Perez <fperez@colorado.edu>
3277 2003-08-19 Fernando Perez <fperez@colorado.edu>
3260
3278
3261 * IPython/deep_reload.py (load_tail): single tiny change here
3279 * IPython/deep_reload.py (load_tail): single tiny change here
3262 seems to fix the long-standing bug of dreload() failing to work
3280 seems to fix the long-standing bug of dreload() failing to work
3263 for dotted names. But this module is pretty tricky, so I may have
3281 for dotted names. But this module is pretty tricky, so I may have
3264 missed some subtlety. Needs more testing!.
3282 missed some subtlety. Needs more testing!.
3265
3283
3266 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
3284 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
3267 exceptions which have badly implemented __str__ methods.
3285 exceptions which have badly implemented __str__ methods.
3268 (VerboseTB.text): harden against inspect.getinnerframes crashing,
3286 (VerboseTB.text): harden against inspect.getinnerframes crashing,
3269 which I've been getting reports about from Python 2.3 users. I
3287 which I've been getting reports about from Python 2.3 users. I
3270 wish I had a simple test case to reproduce the problem, so I could
3288 wish I had a simple test case to reproduce the problem, so I could
3271 either write a cleaner workaround or file a bug report if
3289 either write a cleaner workaround or file a bug report if
3272 necessary.
3290 necessary.
3273
3291
3274 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
3292 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
3275 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
3293 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
3276 a bug report by Tjabo Kloppenburg.
3294 a bug report by Tjabo Kloppenburg.
3277
3295
3278 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
3296 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
3279 crashes. Wrapped the pdb call in a blanket try/except, since pdb
3297 crashes. Wrapped the pdb call in a blanket try/except, since pdb
3280 seems rather unstable. Thanks to a bug report by Tjabo
3298 seems rather unstable. Thanks to a bug report by Tjabo
3281 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
3299 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
3282
3300
3283 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
3301 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
3284 this out soon because of the critical fixes in the inner loop for
3302 this out soon because of the critical fixes in the inner loop for
3285 generators.
3303 generators.
3286
3304
3287 * IPython/Magic.py (Magic.getargspec): removed. This (and
3305 * IPython/Magic.py (Magic.getargspec): removed. This (and
3288 _get_def) have been obsoleted by OInspect for a long time, I
3306 _get_def) have been obsoleted by OInspect for a long time, I
3289 hadn't noticed that they were dead code.
3307 hadn't noticed that they were dead code.
3290 (Magic._ofind): restored _ofind functionality for a few literals
3308 (Magic._ofind): restored _ofind functionality for a few literals
3291 (those in ["''",'""','[]','{}','()']). But it won't work anymore
3309 (those in ["''",'""','[]','{}','()']). But it won't work anymore
3292 for things like "hello".capitalize?, since that would require a
3310 for things like "hello".capitalize?, since that would require a
3293 potentially dangerous eval() again.
3311 potentially dangerous eval() again.
3294
3312
3295 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
3313 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
3296 logic a bit more to clean up the escapes handling and minimize the
3314 logic a bit more to clean up the escapes handling and minimize the
3297 use of _ofind to only necessary cases. The interactive 'feel' of
3315 use of _ofind to only necessary cases. The interactive 'feel' of
3298 IPython should have improved quite a bit with the changes in
3316 IPython should have improved quite a bit with the changes in
3299 _prefilter and _ofind (besides being far safer than before).
3317 _prefilter and _ofind (besides being far safer than before).
3300
3318
3301 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
3319 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
3302 obscure, never reported). Edit would fail to find the object to
3320 obscure, never reported). Edit would fail to find the object to
3303 edit under some circumstances.
3321 edit under some circumstances.
3304 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
3322 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
3305 which were causing double-calling of generators. Those eval calls
3323 which were causing double-calling of generators. Those eval calls
3306 were _very_ dangerous, since code with side effects could be
3324 were _very_ dangerous, since code with side effects could be
3307 triggered. As they say, 'eval is evil'... These were the
3325 triggered. As they say, 'eval is evil'... These were the
3308 nastiest evals in IPython. Besides, _ofind is now far simpler,
3326 nastiest evals in IPython. Besides, _ofind is now far simpler,
3309 and it should also be quite a bit faster. Its use of inspect is
3327 and it should also be quite a bit faster. Its use of inspect is
3310 also safer, so perhaps some of the inspect-related crashes I've
3328 also safer, so perhaps some of the inspect-related crashes I've
3311 seen lately with Python 2.3 might be taken care of. That will
3329 seen lately with Python 2.3 might be taken care of. That will
3312 need more testing.
3330 need more testing.
3313
3331
3314 2003-08-17 Fernando Perez <fperez@colorado.edu>
3332 2003-08-17 Fernando Perez <fperez@colorado.edu>
3315
3333
3316 * IPython/iplib.py (InteractiveShell._prefilter): significant
3334 * IPython/iplib.py (InteractiveShell._prefilter): significant
3317 simplifications to the logic for handling user escapes. Faster
3335 simplifications to the logic for handling user escapes. Faster
3318 and simpler code.
3336 and simpler code.
3319
3337
3320 2003-08-14 Fernando Perez <fperez@colorado.edu>
3338 2003-08-14 Fernando Perez <fperez@colorado.edu>
3321
3339
3322 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
3340 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
3323 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
3341 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
3324 but it should be quite a bit faster. And the recursive version
3342 but it should be quite a bit faster. And the recursive version
3325 generated O(log N) intermediate storage for all rank>1 arrays,
3343 generated O(log N) intermediate storage for all rank>1 arrays,
3326 even if they were contiguous.
3344 even if they were contiguous.
3327 (l1norm): Added this function.
3345 (l1norm): Added this function.
3328 (norm): Added this function for arbitrary norms (including
3346 (norm): Added this function for arbitrary norms (including
3329 l-infinity). l1 and l2 are still special cases for convenience
3347 l-infinity). l1 and l2 are still special cases for convenience
3330 and speed.
3348 and speed.
3331
3349
3332 2003-08-03 Fernando Perez <fperez@colorado.edu>
3350 2003-08-03 Fernando Perez <fperez@colorado.edu>
3333
3351
3334 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
3352 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
3335 exceptions, which now raise PendingDeprecationWarnings in Python
3353 exceptions, which now raise PendingDeprecationWarnings in Python
3336 2.3. There were some in Magic and some in Gnuplot2.
3354 2.3. There were some in Magic and some in Gnuplot2.
3337
3355
3338 2003-06-30 Fernando Perez <fperez@colorado.edu>
3356 2003-06-30 Fernando Perez <fperez@colorado.edu>
3339
3357
3340 * IPython/genutils.py (page): modified to call curses only for
3358 * IPython/genutils.py (page): modified to call curses only for
3341 terminals where TERM=='xterm'. After problems under many other
3359 terminals where TERM=='xterm'. After problems under many other
3342 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
3360 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
3343
3361
3344 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
3362 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
3345 would be triggered when readline was absent. This was just an old
3363 would be triggered when readline was absent. This was just an old
3346 debugging statement I'd forgotten to take out.
3364 debugging statement I'd forgotten to take out.
3347
3365
3348 2003-06-20 Fernando Perez <fperez@colorado.edu>
3366 2003-06-20 Fernando Perez <fperez@colorado.edu>
3349
3367
3350 * IPython/genutils.py (clock): modified to return only user time
3368 * IPython/genutils.py (clock): modified to return only user time
3351 (not counting system time), after a discussion on scipy. While
3369 (not counting system time), after a discussion on scipy. While
3352 system time may be a useful quantity occasionally, it may much
3370 system time may be a useful quantity occasionally, it may much
3353 more easily be skewed by occasional swapping or other similar
3371 more easily be skewed by occasional swapping or other similar
3354 activity.
3372 activity.
3355
3373
3356 2003-06-05 Fernando Perez <fperez@colorado.edu>
3374 2003-06-05 Fernando Perez <fperez@colorado.edu>
3357
3375
3358 * IPython/numutils.py (identity): new function, for building
3376 * IPython/numutils.py (identity): new function, for building
3359 arbitrary rank Kronecker deltas (mostly backwards compatible with
3377 arbitrary rank Kronecker deltas (mostly backwards compatible with
3360 Numeric.identity)
3378 Numeric.identity)
3361
3379
3362 2003-06-03 Fernando Perez <fperez@colorado.edu>
3380 2003-06-03 Fernando Perez <fperez@colorado.edu>
3363
3381
3364 * IPython/iplib.py (InteractiveShell.handle_magic): protect
3382 * IPython/iplib.py (InteractiveShell.handle_magic): protect
3365 arguments passed to magics with spaces, to allow trailing '\' to
3383 arguments passed to magics with spaces, to allow trailing '\' to
3366 work normally (mainly for Windows users).
3384 work normally (mainly for Windows users).
3367
3385
3368 2003-05-29 Fernando Perez <fperez@colorado.edu>
3386 2003-05-29 Fernando Perez <fperez@colorado.edu>
3369
3387
3370 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
3388 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
3371 instead of pydoc.help. This fixes a bizarre behavior where
3389 instead of pydoc.help. This fixes a bizarre behavior where
3372 printing '%s' % locals() would trigger the help system. Now
3390 printing '%s' % locals() would trigger the help system. Now
3373 ipython behaves like normal python does.
3391 ipython behaves like normal python does.
3374
3392
3375 Note that if one does 'from pydoc import help', the bizarre
3393 Note that if one does 'from pydoc import help', the bizarre
3376 behavior returns, but this will also happen in normal python, so
3394 behavior returns, but this will also happen in normal python, so
3377 it's not an ipython bug anymore (it has to do with how pydoc.help
3395 it's not an ipython bug anymore (it has to do with how pydoc.help
3378 is implemented).
3396 is implemented).
3379
3397
3380 2003-05-22 Fernando Perez <fperez@colorado.edu>
3398 2003-05-22 Fernando Perez <fperez@colorado.edu>
3381
3399
3382 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
3400 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
3383 return [] instead of None when nothing matches, also match to end
3401 return [] instead of None when nothing matches, also match to end
3384 of line. Patch by Gary Bishop.
3402 of line. Patch by Gary Bishop.
3385
3403
3386 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
3404 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
3387 protection as before, for files passed on the command line. This
3405 protection as before, for files passed on the command line. This
3388 prevents the CrashHandler from kicking in if user files call into
3406 prevents the CrashHandler from kicking in if user files call into
3389 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
3407 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
3390 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
3408 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
3391
3409
3392 2003-05-20 *** Released version 0.4.0
3410 2003-05-20 *** Released version 0.4.0
3393
3411
3394 2003-05-20 Fernando Perez <fperez@colorado.edu>
3412 2003-05-20 Fernando Perez <fperez@colorado.edu>
3395
3413
3396 * setup.py: added support for manpages. It's a bit hackish b/c of
3414 * setup.py: added support for manpages. It's a bit hackish b/c of
3397 a bug in the way the bdist_rpm distutils target handles gzipped
3415 a bug in the way the bdist_rpm distutils target handles gzipped
3398 manpages, but it works. After a patch by Jack.
3416 manpages, but it works. After a patch by Jack.
3399
3417
3400 2003-05-19 Fernando Perez <fperez@colorado.edu>
3418 2003-05-19 Fernando Perez <fperez@colorado.edu>
3401
3419
3402 * IPython/numutils.py: added a mockup of the kinds module, since
3420 * IPython/numutils.py: added a mockup of the kinds module, since
3403 it was recently removed from Numeric. This way, numutils will
3421 it was recently removed from Numeric. This way, numutils will
3404 work for all users even if they are missing kinds.
3422 work for all users even if they are missing kinds.
3405
3423
3406 * IPython/Magic.py (Magic._ofind): Harden against an inspect
3424 * IPython/Magic.py (Magic._ofind): Harden against an inspect
3407 failure, which can occur with SWIG-wrapped extensions. After a
3425 failure, which can occur with SWIG-wrapped extensions. After a
3408 crash report from Prabhu.
3426 crash report from Prabhu.
3409
3427
3410 2003-05-16 Fernando Perez <fperez@colorado.edu>
3428 2003-05-16 Fernando Perez <fperez@colorado.edu>
3411
3429
3412 * IPython/iplib.py (InteractiveShell.excepthook): New method to
3430 * IPython/iplib.py (InteractiveShell.excepthook): New method to
3413 protect ipython from user code which may call directly
3431 protect ipython from user code which may call directly
3414 sys.excepthook (this looks like an ipython crash to the user, even
3432 sys.excepthook (this looks like an ipython crash to the user, even
3415 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3433 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3416 This is especially important to help users of WxWindows, but may
3434 This is especially important to help users of WxWindows, but may
3417 also be useful in other cases.
3435 also be useful in other cases.
3418
3436
3419 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
3437 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
3420 an optional tb_offset to be specified, and to preserve exception
3438 an optional tb_offset to be specified, and to preserve exception
3421 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3439 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3422
3440
3423 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
3441 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
3424
3442
3425 2003-05-15 Fernando Perez <fperez@colorado.edu>
3443 2003-05-15 Fernando Perez <fperez@colorado.edu>
3426
3444
3427 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
3445 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
3428 installing for a new user under Windows.
3446 installing for a new user under Windows.
3429
3447
3430 2003-05-12 Fernando Perez <fperez@colorado.edu>
3448 2003-05-12 Fernando Perez <fperez@colorado.edu>
3431
3449
3432 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
3450 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
3433 handler for Emacs comint-based lines. Currently it doesn't do
3451 handler for Emacs comint-based lines. Currently it doesn't do
3434 much (but importantly, it doesn't update the history cache). In
3452 much (but importantly, it doesn't update the history cache). In
3435 the future it may be expanded if Alex needs more functionality
3453 the future it may be expanded if Alex needs more functionality
3436 there.
3454 there.
3437
3455
3438 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
3456 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
3439 info to crash reports.
3457 info to crash reports.
3440
3458
3441 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
3459 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
3442 just like Python's -c. Also fixed crash with invalid -color
3460 just like Python's -c. Also fixed crash with invalid -color
3443 option value at startup. Thanks to Will French
3461 option value at startup. Thanks to Will French
3444 <wfrench-AT-bestweb.net> for the bug report.
3462 <wfrench-AT-bestweb.net> for the bug report.
3445
3463
3446 2003-05-09 Fernando Perez <fperez@colorado.edu>
3464 2003-05-09 Fernando Perez <fperez@colorado.edu>
3447
3465
3448 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
3466 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
3449 to EvalDict (it's a mapping, after all) and simplified its code
3467 to EvalDict (it's a mapping, after all) and simplified its code
3450 quite a bit, after a nice discussion on c.l.py where Gustavo
3468 quite a bit, after a nice discussion on c.l.py where Gustavo
3451 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
3469 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
3452
3470
3453 2003-04-30 Fernando Perez <fperez@colorado.edu>
3471 2003-04-30 Fernando Perez <fperez@colorado.edu>
3454
3472
3455 * IPython/genutils.py (timings_out): modified it to reduce its
3473 * IPython/genutils.py (timings_out): modified it to reduce its
3456 overhead in the common reps==1 case.
3474 overhead in the common reps==1 case.
3457
3475
3458 2003-04-29 Fernando Perez <fperez@colorado.edu>
3476 2003-04-29 Fernando Perez <fperez@colorado.edu>
3459
3477
3460 * IPython/genutils.py (timings_out): Modified to use the resource
3478 * IPython/genutils.py (timings_out): Modified to use the resource
3461 module, which avoids the wraparound problems of time.clock().
3479 module, which avoids the wraparound problems of time.clock().
3462
3480
3463 2003-04-17 *** Released version 0.2.15pre4
3481 2003-04-17 *** Released version 0.2.15pre4
3464
3482
3465 2003-04-17 Fernando Perez <fperez@colorado.edu>
3483 2003-04-17 Fernando Perez <fperez@colorado.edu>
3466
3484
3467 * setup.py (scriptfiles): Split windows-specific stuff over to a
3485 * setup.py (scriptfiles): Split windows-specific stuff over to a
3468 separate file, in an attempt to have a Windows GUI installer.
3486 separate file, in an attempt to have a Windows GUI installer.
3469 That didn't work, but part of the groundwork is done.
3487 That didn't work, but part of the groundwork is done.
3470
3488
3471 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
3489 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
3472 indent/unindent with 4 spaces. Particularly useful in combination
3490 indent/unindent with 4 spaces. Particularly useful in combination
3473 with the new auto-indent option.
3491 with the new auto-indent option.
3474
3492
3475 2003-04-16 Fernando Perez <fperez@colorado.edu>
3493 2003-04-16 Fernando Perez <fperez@colorado.edu>
3476
3494
3477 * IPython/Magic.py: various replacements of self.rc for
3495 * IPython/Magic.py: various replacements of self.rc for
3478 self.shell.rc. A lot more remains to be done to fully disentangle
3496 self.shell.rc. A lot more remains to be done to fully disentangle
3479 this class from the main Shell class.
3497 this class from the main Shell class.
3480
3498
3481 * IPython/GnuplotRuntime.py: added checks for mouse support so
3499 * IPython/GnuplotRuntime.py: added checks for mouse support so
3482 that we don't try to enable it if the current gnuplot doesn't
3500 that we don't try to enable it if the current gnuplot doesn't
3483 really support it. Also added checks so that we don't try to
3501 really support it. Also added checks so that we don't try to
3484 enable persist under Windows (where Gnuplot doesn't recognize the
3502 enable persist under Windows (where Gnuplot doesn't recognize the
3485 option).
3503 option).
3486
3504
3487 * IPython/iplib.py (InteractiveShell.interact): Added optional
3505 * IPython/iplib.py (InteractiveShell.interact): Added optional
3488 auto-indenting code, after a patch by King C. Shu
3506 auto-indenting code, after a patch by King C. Shu
3489 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
3507 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
3490 get along well with pasting indented code. If I ever figure out
3508 get along well with pasting indented code. If I ever figure out
3491 how to make that part go well, it will become on by default.
3509 how to make that part go well, it will become on by default.
3492
3510
3493 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
3511 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
3494 crash ipython if there was an unmatched '%' in the user's prompt
3512 crash ipython if there was an unmatched '%' in the user's prompt
3495 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3513 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3496
3514
3497 * IPython/iplib.py (InteractiveShell.interact): removed the
3515 * IPython/iplib.py (InteractiveShell.interact): removed the
3498 ability to ask the user whether he wants to crash or not at the
3516 ability to ask the user whether he wants to crash or not at the
3499 'last line' exception handler. Calling functions at that point
3517 'last line' exception handler. Calling functions at that point
3500 changes the stack, and the error reports would have incorrect
3518 changes the stack, and the error reports would have incorrect
3501 tracebacks.
3519 tracebacks.
3502
3520
3503 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
3521 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
3504 pass through a peger a pretty-printed form of any object. After a
3522 pass through a peger a pretty-printed form of any object. After a
3505 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
3523 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
3506
3524
3507 2003-04-14 Fernando Perez <fperez@colorado.edu>
3525 2003-04-14 Fernando Perez <fperez@colorado.edu>
3508
3526
3509 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
3527 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
3510 all files in ~ would be modified at first install (instead of
3528 all files in ~ would be modified at first install (instead of
3511 ~/.ipython). This could be potentially disastrous, as the
3529 ~/.ipython). This could be potentially disastrous, as the
3512 modification (make line-endings native) could damage binary files.
3530 modification (make line-endings native) could damage binary files.
3513
3531
3514 2003-04-10 Fernando Perez <fperez@colorado.edu>
3532 2003-04-10 Fernando Perez <fperez@colorado.edu>
3515
3533
3516 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
3534 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
3517 handle only lines which are invalid python. This now means that
3535 handle only lines which are invalid python. This now means that
3518 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
3536 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
3519 for the bug report.
3537 for the bug report.
3520
3538
3521 2003-04-01 Fernando Perez <fperez@colorado.edu>
3539 2003-04-01 Fernando Perez <fperez@colorado.edu>
3522
3540
3523 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
3541 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
3524 where failing to set sys.last_traceback would crash pdb.pm().
3542 where failing to set sys.last_traceback would crash pdb.pm().
3525 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
3543 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
3526 report.
3544 report.
3527
3545
3528 2003-03-25 Fernando Perez <fperez@colorado.edu>
3546 2003-03-25 Fernando Perez <fperez@colorado.edu>
3529
3547
3530 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
3548 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
3531 before printing it (it had a lot of spurious blank lines at the
3549 before printing it (it had a lot of spurious blank lines at the
3532 end).
3550 end).
3533
3551
3534 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
3552 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
3535 output would be sent 21 times! Obviously people don't use this
3553 output would be sent 21 times! Obviously people don't use this
3536 too often, or I would have heard about it.
3554 too often, or I would have heard about it.
3537
3555
3538 2003-03-24 Fernando Perez <fperez@colorado.edu>
3556 2003-03-24 Fernando Perez <fperez@colorado.edu>
3539
3557
3540 * setup.py (scriptfiles): renamed the data_files parameter from
3558 * setup.py (scriptfiles): renamed the data_files parameter from
3541 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
3559 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
3542 for the patch.
3560 for the patch.
3543
3561
3544 2003-03-20 Fernando Perez <fperez@colorado.edu>
3562 2003-03-20 Fernando Perez <fperez@colorado.edu>
3545
3563
3546 * IPython/genutils.py (error): added error() and fatal()
3564 * IPython/genutils.py (error): added error() and fatal()
3547 functions.
3565 functions.
3548
3566
3549 2003-03-18 *** Released version 0.2.15pre3
3567 2003-03-18 *** Released version 0.2.15pre3
3550
3568
3551 2003-03-18 Fernando Perez <fperez@colorado.edu>
3569 2003-03-18 Fernando Perez <fperez@colorado.edu>
3552
3570
3553 * setupext/install_data_ext.py
3571 * setupext/install_data_ext.py
3554 (install_data_ext.initialize_options): Class contributed by Jack
3572 (install_data_ext.initialize_options): Class contributed by Jack
3555 Moffit for fixing the old distutils hack. He is sending this to
3573 Moffit for fixing the old distutils hack. He is sending this to
3556 the distutils folks so in the future we may not need it as a
3574 the distutils folks so in the future we may not need it as a
3557 private fix.
3575 private fix.
3558
3576
3559 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
3577 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
3560 changes for Debian packaging. See his patch for full details.
3578 changes for Debian packaging. See his patch for full details.
3561 The old distutils hack of making the ipythonrc* files carry a
3579 The old distutils hack of making the ipythonrc* files carry a
3562 bogus .py extension is gone, at last. Examples were moved to a
3580 bogus .py extension is gone, at last. Examples were moved to a
3563 separate subdir under doc/, and the separate executable scripts
3581 separate subdir under doc/, and the separate executable scripts
3564 now live in their own directory. Overall a great cleanup. The
3582 now live in their own directory. Overall a great cleanup. The
3565 manual was updated to use the new files, and setup.py has been
3583 manual was updated to use the new files, and setup.py has been
3566 fixed for this setup.
3584 fixed for this setup.
3567
3585
3568 * IPython/PyColorize.py (Parser.usage): made non-executable and
3586 * IPython/PyColorize.py (Parser.usage): made non-executable and
3569 created a pycolor wrapper around it to be included as a script.
3587 created a pycolor wrapper around it to be included as a script.
3570
3588
3571 2003-03-12 *** Released version 0.2.15pre2
3589 2003-03-12 *** Released version 0.2.15pre2
3572
3590
3573 2003-03-12 Fernando Perez <fperez@colorado.edu>
3591 2003-03-12 Fernando Perez <fperez@colorado.edu>
3574
3592
3575 * IPython/ColorANSI.py (make_color_table): Finally fixed the
3593 * IPython/ColorANSI.py (make_color_table): Finally fixed the
3576 long-standing problem with garbage characters in some terminals.
3594 long-standing problem with garbage characters in some terminals.
3577 The issue was really that the \001 and \002 escapes must _only_ be
3595 The issue was really that the \001 and \002 escapes must _only_ be
3578 passed to input prompts (which call readline), but _never_ to
3596 passed to input prompts (which call readline), but _never_ to
3579 normal text to be printed on screen. I changed ColorANSI to have
3597 normal text to be printed on screen. I changed ColorANSI to have
3580 two classes: TermColors and InputTermColors, each with the
3598 two classes: TermColors and InputTermColors, each with the
3581 appropriate escapes for input prompts or normal text. The code in
3599 appropriate escapes for input prompts or normal text. The code in
3582 Prompts.py got slightly more complicated, but this very old and
3600 Prompts.py got slightly more complicated, but this very old and
3583 annoying bug is finally fixed.
3601 annoying bug is finally fixed.
3584
3602
3585 All the credit for nailing down the real origin of this problem
3603 All the credit for nailing down the real origin of this problem
3586 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
3604 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
3587 *Many* thanks to him for spending quite a bit of effort on this.
3605 *Many* thanks to him for spending quite a bit of effort on this.
3588
3606
3589 2003-03-05 *** Released version 0.2.15pre1
3607 2003-03-05 *** Released version 0.2.15pre1
3590
3608
3591 2003-03-03 Fernando Perez <fperez@colorado.edu>
3609 2003-03-03 Fernando Perez <fperez@colorado.edu>
3592
3610
3593 * IPython/FakeModule.py: Moved the former _FakeModule to a
3611 * IPython/FakeModule.py: Moved the former _FakeModule to a
3594 separate file, because it's also needed by Magic (to fix a similar
3612 separate file, because it's also needed by Magic (to fix a similar
3595 pickle-related issue in @run).
3613 pickle-related issue in @run).
3596
3614
3597 2003-03-02 Fernando Perez <fperez@colorado.edu>
3615 2003-03-02 Fernando Perez <fperez@colorado.edu>
3598
3616
3599 * IPython/Magic.py (Magic.magic_autocall): new magic to control
3617 * IPython/Magic.py (Magic.magic_autocall): new magic to control
3600 the autocall option at runtime.
3618 the autocall option at runtime.
3601 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
3619 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
3602 across Magic.py to start separating Magic from InteractiveShell.
3620 across Magic.py to start separating Magic from InteractiveShell.
3603 (Magic._ofind): Fixed to return proper namespace for dotted
3621 (Magic._ofind): Fixed to return proper namespace for dotted
3604 names. Before, a dotted name would always return 'not currently
3622 names. Before, a dotted name would always return 'not currently
3605 defined', because it would find the 'parent'. s.x would be found,
3623 defined', because it would find the 'parent'. s.x would be found,
3606 but since 'x' isn't defined by itself, it would get confused.
3624 but since 'x' isn't defined by itself, it would get confused.
3607 (Magic.magic_run): Fixed pickling problems reported by Ralf
3625 (Magic.magic_run): Fixed pickling problems reported by Ralf
3608 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
3626 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
3609 that I'd used when Mike Heeter reported similar issues at the
3627 that I'd used when Mike Heeter reported similar issues at the
3610 top-level, but now for @run. It boils down to injecting the
3628 top-level, but now for @run. It boils down to injecting the
3611 namespace where code is being executed with something that looks
3629 namespace where code is being executed with something that looks
3612 enough like a module to fool pickle.dump(). Since a pickle stores
3630 enough like a module to fool pickle.dump(). Since a pickle stores
3613 a named reference to the importing module, we need this for
3631 a named reference to the importing module, we need this for
3614 pickles to save something sensible.
3632 pickles to save something sensible.
3615
3633
3616 * IPython/ipmaker.py (make_IPython): added an autocall option.
3634 * IPython/ipmaker.py (make_IPython): added an autocall option.
3617
3635
3618 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
3636 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
3619 the auto-eval code. Now autocalling is an option, and the code is
3637 the auto-eval code. Now autocalling is an option, and the code is
3620 also vastly safer. There is no more eval() involved at all.
3638 also vastly safer. There is no more eval() involved at all.
3621
3639
3622 2003-03-01 Fernando Perez <fperez@colorado.edu>
3640 2003-03-01 Fernando Perez <fperez@colorado.edu>
3623
3641
3624 * IPython/Magic.py (Magic._ofind): Changed interface to return a
3642 * IPython/Magic.py (Magic._ofind): Changed interface to return a
3625 dict with named keys instead of a tuple.
3643 dict with named keys instead of a tuple.
3626
3644
3627 * IPython: Started using CVS for IPython as of 0.2.15pre1.
3645 * IPython: Started using CVS for IPython as of 0.2.15pre1.
3628
3646
3629 * setup.py (make_shortcut): Fixed message about directories
3647 * setup.py (make_shortcut): Fixed message about directories
3630 created during Windows installation (the directories were ok, just
3648 created during Windows installation (the directories were ok, just
3631 the printed message was misleading). Thanks to Chris Liechti
3649 the printed message was misleading). Thanks to Chris Liechti
3632 <cliechti-AT-gmx.net> for the heads up.
3650 <cliechti-AT-gmx.net> for the heads up.
3633
3651
3634 2003-02-21 Fernando Perez <fperez@colorado.edu>
3652 2003-02-21 Fernando Perez <fperez@colorado.edu>
3635
3653
3636 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
3654 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
3637 of ValueError exception when checking for auto-execution. This
3655 of ValueError exception when checking for auto-execution. This
3638 one is raised by things like Numeric arrays arr.flat when the
3656 one is raised by things like Numeric arrays arr.flat when the
3639 array is non-contiguous.
3657 array is non-contiguous.
3640
3658
3641 2003-01-31 Fernando Perez <fperez@colorado.edu>
3659 2003-01-31 Fernando Perez <fperez@colorado.edu>
3642
3660
3643 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
3661 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
3644 not return any value at all (even though the command would get
3662 not return any value at all (even though the command would get
3645 executed).
3663 executed).
3646 (xsys): Flush stdout right after printing the command to ensure
3664 (xsys): Flush stdout right after printing the command to ensure
3647 proper ordering of commands and command output in the total
3665 proper ordering of commands and command output in the total
3648 output.
3666 output.
3649 (SystemExec/xsys/bq): Switched the names of xsys/bq and
3667 (SystemExec/xsys/bq): Switched the names of xsys/bq and
3650 system/getoutput as defaults. The old ones are kept for
3668 system/getoutput as defaults. The old ones are kept for
3651 compatibility reasons, so no code which uses this library needs
3669 compatibility reasons, so no code which uses this library needs
3652 changing.
3670 changing.
3653
3671
3654 2003-01-27 *** Released version 0.2.14
3672 2003-01-27 *** Released version 0.2.14
3655
3673
3656 2003-01-25 Fernando Perez <fperez@colorado.edu>
3674 2003-01-25 Fernando Perez <fperez@colorado.edu>
3657
3675
3658 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
3676 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
3659 functions defined in previous edit sessions could not be re-edited
3677 functions defined in previous edit sessions could not be re-edited
3660 (because the temp files were immediately removed). Now temp files
3678 (because the temp files were immediately removed). Now temp files
3661 are removed only at IPython's exit.
3679 are removed only at IPython's exit.
3662 (Magic.magic_run): Improved @run to perform shell-like expansions
3680 (Magic.magic_run): Improved @run to perform shell-like expansions
3663 on its arguments (~users and $VARS). With this, @run becomes more
3681 on its arguments (~users and $VARS). With this, @run becomes more
3664 like a normal command-line.
3682 like a normal command-line.
3665
3683
3666 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
3684 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
3667 bugs related to embedding and cleaned up that code. A fairly
3685 bugs related to embedding and cleaned up that code. A fairly
3668 important one was the impossibility to access the global namespace
3686 important one was the impossibility to access the global namespace
3669 through the embedded IPython (only local variables were visible).
3687 through the embedded IPython (only local variables were visible).
3670
3688
3671 2003-01-14 Fernando Perez <fperez@colorado.edu>
3689 2003-01-14 Fernando Perez <fperez@colorado.edu>
3672
3690
3673 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
3691 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
3674 auto-calling to be a bit more conservative. Now it doesn't get
3692 auto-calling to be a bit more conservative. Now it doesn't get
3675 triggered if any of '!=()<>' are in the rest of the input line, to
3693 triggered if any of '!=()<>' are in the rest of the input line, to
3676 allow comparing callables. Thanks to Alex for the heads up.
3694 allow comparing callables. Thanks to Alex for the heads up.
3677
3695
3678 2003-01-07 Fernando Perez <fperez@colorado.edu>
3696 2003-01-07 Fernando Perez <fperez@colorado.edu>
3679
3697
3680 * IPython/genutils.py (page): fixed estimation of the number of
3698 * IPython/genutils.py (page): fixed estimation of the number of
3681 lines in a string to be paged to simply count newlines. This
3699 lines in a string to be paged to simply count newlines. This
3682 prevents over-guessing due to embedded escape sequences. A better
3700 prevents over-guessing due to embedded escape sequences. A better
3683 long-term solution would involve stripping out the control chars
3701 long-term solution would involve stripping out the control chars
3684 for the count, but it's potentially so expensive I just don't
3702 for the count, but it's potentially so expensive I just don't
3685 think it's worth doing.
3703 think it's worth doing.
3686
3704
3687 2002-12-19 *** Released version 0.2.14pre50
3705 2002-12-19 *** Released version 0.2.14pre50
3688
3706
3689 2002-12-19 Fernando Perez <fperez@colorado.edu>
3707 2002-12-19 Fernando Perez <fperez@colorado.edu>
3690
3708
3691 * tools/release (version): Changed release scripts to inform
3709 * tools/release (version): Changed release scripts to inform
3692 Andrea and build a NEWS file with a list of recent changes.
3710 Andrea and build a NEWS file with a list of recent changes.
3693
3711
3694 * IPython/ColorANSI.py (__all__): changed terminal detection
3712 * IPython/ColorANSI.py (__all__): changed terminal detection
3695 code. Seems to work better for xterms without breaking
3713 code. Seems to work better for xterms without breaking
3696 konsole. Will need more testing to determine if WinXP and Mac OSX
3714 konsole. Will need more testing to determine if WinXP and Mac OSX
3697 also work ok.
3715 also work ok.
3698
3716
3699 2002-12-18 *** Released version 0.2.14pre49
3717 2002-12-18 *** Released version 0.2.14pre49
3700
3718
3701 2002-12-18 Fernando Perez <fperez@colorado.edu>
3719 2002-12-18 Fernando Perez <fperez@colorado.edu>
3702
3720
3703 * Docs: added new info about Mac OSX, from Andrea.
3721 * Docs: added new info about Mac OSX, from Andrea.
3704
3722
3705 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
3723 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
3706 allow direct plotting of python strings whose format is the same
3724 allow direct plotting of python strings whose format is the same
3707 of gnuplot data files.
3725 of gnuplot data files.
3708
3726
3709 2002-12-16 Fernando Perez <fperez@colorado.edu>
3727 2002-12-16 Fernando Perez <fperez@colorado.edu>
3710
3728
3711 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
3729 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
3712 value of exit question to be acknowledged.
3730 value of exit question to be acknowledged.
3713
3731
3714 2002-12-03 Fernando Perez <fperez@colorado.edu>
3732 2002-12-03 Fernando Perez <fperez@colorado.edu>
3715
3733
3716 * IPython/ipmaker.py: removed generators, which had been added
3734 * IPython/ipmaker.py: removed generators, which had been added
3717 by mistake in an earlier debugging run. This was causing trouble
3735 by mistake in an earlier debugging run. This was causing trouble
3718 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
3736 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
3719 for pointing this out.
3737 for pointing this out.
3720
3738
3721 2002-11-17 Fernando Perez <fperez@colorado.edu>
3739 2002-11-17 Fernando Perez <fperez@colorado.edu>
3722
3740
3723 * Manual: updated the Gnuplot section.
3741 * Manual: updated the Gnuplot section.
3724
3742
3725 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
3743 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
3726 a much better split of what goes in Runtime and what goes in
3744 a much better split of what goes in Runtime and what goes in
3727 Interactive.
3745 Interactive.
3728
3746
3729 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
3747 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
3730 being imported from iplib.
3748 being imported from iplib.
3731
3749
3732 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
3750 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
3733 for command-passing. Now the global Gnuplot instance is called
3751 for command-passing. Now the global Gnuplot instance is called
3734 'gp' instead of 'g', which was really a far too fragile and
3752 'gp' instead of 'g', which was really a far too fragile and
3735 common name.
3753 common name.
3736
3754
3737 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
3755 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
3738 bounding boxes generated by Gnuplot for square plots.
3756 bounding boxes generated by Gnuplot for square plots.
3739
3757
3740 * IPython/genutils.py (popkey): new function added. I should
3758 * IPython/genutils.py (popkey): new function added. I should
3741 suggest this on c.l.py as a dict method, it seems useful.
3759 suggest this on c.l.py as a dict method, it seems useful.
3742
3760
3743 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
3761 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
3744 to transparently handle PostScript generation. MUCH better than
3762 to transparently handle PostScript generation. MUCH better than
3745 the previous plot_eps/replot_eps (which I removed now). The code
3763 the previous plot_eps/replot_eps (which I removed now). The code
3746 is also fairly clean and well documented now (including
3764 is also fairly clean and well documented now (including
3747 docstrings).
3765 docstrings).
3748
3766
3749 2002-11-13 Fernando Perez <fperez@colorado.edu>
3767 2002-11-13 Fernando Perez <fperez@colorado.edu>
3750
3768
3751 * IPython/Magic.py (Magic.magic_edit): fixed docstring
3769 * IPython/Magic.py (Magic.magic_edit): fixed docstring
3752 (inconsistent with options).
3770 (inconsistent with options).
3753
3771
3754 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
3772 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
3755 manually disabled, I don't know why. Fixed it.
3773 manually disabled, I don't know why. Fixed it.
3756 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
3774 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
3757 eps output.
3775 eps output.
3758
3776
3759 2002-11-12 Fernando Perez <fperez@colorado.edu>
3777 2002-11-12 Fernando Perez <fperez@colorado.edu>
3760
3778
3761 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
3779 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
3762 don't propagate up to caller. Fixes crash reported by François
3780 don't propagate up to caller. Fixes crash reported by François
3763 Pinard.
3781 Pinard.
3764
3782
3765 2002-11-09 Fernando Perez <fperez@colorado.edu>
3783 2002-11-09 Fernando Perez <fperez@colorado.edu>
3766
3784
3767 * IPython/ipmaker.py (make_IPython): fixed problem with writing
3785 * IPython/ipmaker.py (make_IPython): fixed problem with writing
3768 history file for new users.
3786 history file for new users.
3769 (make_IPython): fixed bug where initial install would leave the
3787 (make_IPython): fixed bug where initial install would leave the
3770 user running in the .ipython dir.
3788 user running in the .ipython dir.
3771 (make_IPython): fixed bug where config dir .ipython would be
3789 (make_IPython): fixed bug where config dir .ipython would be
3772 created regardless of the given -ipythondir option. Thanks to Cory
3790 created regardless of the given -ipythondir option. Thanks to Cory
3773 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
3791 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
3774
3792
3775 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
3793 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
3776 type confirmations. Will need to use it in all of IPython's code
3794 type confirmations. Will need to use it in all of IPython's code
3777 consistently.
3795 consistently.
3778
3796
3779 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
3797 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
3780 context to print 31 lines instead of the default 5. This will make
3798 context to print 31 lines instead of the default 5. This will make
3781 the crash reports extremely detailed in case the problem is in
3799 the crash reports extremely detailed in case the problem is in
3782 libraries I don't have access to.
3800 libraries I don't have access to.
3783
3801
3784 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
3802 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
3785 line of defense' code to still crash, but giving users fair
3803 line of defense' code to still crash, but giving users fair
3786 warning. I don't want internal errors to go unreported: if there's
3804 warning. I don't want internal errors to go unreported: if there's
3787 an internal problem, IPython should crash and generate a full
3805 an internal problem, IPython should crash and generate a full
3788 report.
3806 report.
3789
3807
3790 2002-11-08 Fernando Perez <fperez@colorado.edu>
3808 2002-11-08 Fernando Perez <fperez@colorado.edu>
3791
3809
3792 * IPython/iplib.py (InteractiveShell.interact): added code to trap
3810 * IPython/iplib.py (InteractiveShell.interact): added code to trap
3793 otherwise uncaught exceptions which can appear if people set
3811 otherwise uncaught exceptions which can appear if people set
3794 sys.stdout to something badly broken. Thanks to a crash report
3812 sys.stdout to something badly broken. Thanks to a crash report
3795 from henni-AT-mail.brainbot.com.
3813 from henni-AT-mail.brainbot.com.
3796
3814
3797 2002-11-04 Fernando Perez <fperez@colorado.edu>
3815 2002-11-04 Fernando Perez <fperez@colorado.edu>
3798
3816
3799 * IPython/iplib.py (InteractiveShell.interact): added
3817 * IPython/iplib.py (InteractiveShell.interact): added
3800 __IPYTHON__active to the builtins. It's a flag which goes on when
3818 __IPYTHON__active to the builtins. It's a flag which goes on when
3801 the interaction starts and goes off again when it stops. This
3819 the interaction starts and goes off again when it stops. This
3802 allows embedding code to detect being inside IPython. Before this
3820 allows embedding code to detect being inside IPython. Before this
3803 was done via __IPYTHON__, but that only shows that an IPython
3821 was done via __IPYTHON__, but that only shows that an IPython
3804 instance has been created.
3822 instance has been created.
3805
3823
3806 * IPython/Magic.py (Magic.magic_env): I realized that in a
3824 * IPython/Magic.py (Magic.magic_env): I realized that in a
3807 UserDict, instance.data holds the data as a normal dict. So I
3825 UserDict, instance.data holds the data as a normal dict. So I
3808 modified @env to return os.environ.data instead of rebuilding a
3826 modified @env to return os.environ.data instead of rebuilding a
3809 dict by hand.
3827 dict by hand.
3810
3828
3811 2002-11-02 Fernando Perez <fperez@colorado.edu>
3829 2002-11-02 Fernando Perez <fperez@colorado.edu>
3812
3830
3813 * IPython/genutils.py (warn): changed so that level 1 prints no
3831 * IPython/genutils.py (warn): changed so that level 1 prints no
3814 header. Level 2 is now the default (with 'WARNING' header, as
3832 header. Level 2 is now the default (with 'WARNING' header, as
3815 before). I think I tracked all places where changes were needed in
3833 before). I think I tracked all places where changes were needed in
3816 IPython, but outside code using the old level numbering may have
3834 IPython, but outside code using the old level numbering may have
3817 broken.
3835 broken.
3818
3836
3819 * IPython/iplib.py (InteractiveShell.runcode): added this to
3837 * IPython/iplib.py (InteractiveShell.runcode): added this to
3820 handle the tracebacks in SystemExit traps correctly. The previous
3838 handle the tracebacks in SystemExit traps correctly. The previous
3821 code (through interact) was printing more of the stack than
3839 code (through interact) was printing more of the stack than
3822 necessary, showing IPython internal code to the user.
3840 necessary, showing IPython internal code to the user.
3823
3841
3824 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
3842 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
3825 default. Now that the default at the confirmation prompt is yes,
3843 default. Now that the default at the confirmation prompt is yes,
3826 it's not so intrusive. François' argument that ipython sessions
3844 it's not so intrusive. François' argument that ipython sessions
3827 tend to be complex enough not to lose them from an accidental C-d,
3845 tend to be complex enough not to lose them from an accidental C-d,
3828 is a valid one.
3846 is a valid one.
3829
3847
3830 * IPython/iplib.py (InteractiveShell.interact): added a
3848 * IPython/iplib.py (InteractiveShell.interact): added a
3831 showtraceback() call to the SystemExit trap, and modified the exit
3849 showtraceback() call to the SystemExit trap, and modified the exit
3832 confirmation to have yes as the default.
3850 confirmation to have yes as the default.
3833
3851
3834 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
3852 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
3835 this file. It's been gone from the code for a long time, this was
3853 this file. It's been gone from the code for a long time, this was
3836 simply leftover junk.
3854 simply leftover junk.
3837
3855
3838 2002-11-01 Fernando Perez <fperez@colorado.edu>
3856 2002-11-01 Fernando Perez <fperez@colorado.edu>
3839
3857
3840 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
3858 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
3841 added. If set, IPython now traps EOF and asks for
3859 added. If set, IPython now traps EOF and asks for
3842 confirmation. After a request by François Pinard.
3860 confirmation. After a request by François Pinard.
3843
3861
3844 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
3862 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
3845 of @abort, and with a new (better) mechanism for handling the
3863 of @abort, and with a new (better) mechanism for handling the
3846 exceptions.
3864 exceptions.
3847
3865
3848 2002-10-27 Fernando Perez <fperez@colorado.edu>
3866 2002-10-27 Fernando Perez <fperez@colorado.edu>
3849
3867
3850 * IPython/usage.py (__doc__): updated the --help information and
3868 * IPython/usage.py (__doc__): updated the --help information and
3851 the ipythonrc file to indicate that -log generates
3869 the ipythonrc file to indicate that -log generates
3852 ./ipython.log. Also fixed the corresponding info in @logstart.
3870 ./ipython.log. Also fixed the corresponding info in @logstart.
3853 This and several other fixes in the manuals thanks to reports by
3871 This and several other fixes in the manuals thanks to reports by
3854 François Pinard <pinard-AT-iro.umontreal.ca>.
3872 François Pinard <pinard-AT-iro.umontreal.ca>.
3855
3873
3856 * IPython/Logger.py (Logger.switch_log): Fixed error message to
3874 * IPython/Logger.py (Logger.switch_log): Fixed error message to
3857 refer to @logstart (instead of @log, which doesn't exist).
3875 refer to @logstart (instead of @log, which doesn't exist).
3858
3876
3859 * IPython/iplib.py (InteractiveShell._prefilter): fixed
3877 * IPython/iplib.py (InteractiveShell._prefilter): fixed
3860 AttributeError crash. Thanks to Christopher Armstrong
3878 AttributeError crash. Thanks to Christopher Armstrong
3861 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
3879 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
3862 introduced recently (in 0.2.14pre37) with the fix to the eval
3880 introduced recently (in 0.2.14pre37) with the fix to the eval
3863 problem mentioned below.
3881 problem mentioned below.
3864
3882
3865 2002-10-17 Fernando Perez <fperez@colorado.edu>
3883 2002-10-17 Fernando Perez <fperez@colorado.edu>
3866
3884
3867 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
3885 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
3868 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
3886 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
3869
3887
3870 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
3888 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
3871 this function to fix a problem reported by Alex Schmolck. He saw
3889 this function to fix a problem reported by Alex Schmolck. He saw
3872 it with list comprehensions and generators, which were getting
3890 it with list comprehensions and generators, which were getting
3873 called twice. The real problem was an 'eval' call in testing for
3891 called twice. The real problem was an 'eval' call in testing for
3874 automagic which was evaluating the input line silently.
3892 automagic which was evaluating the input line silently.
3875
3893
3876 This is a potentially very nasty bug, if the input has side
3894 This is a potentially very nasty bug, if the input has side
3877 effects which must not be repeated. The code is much cleaner now,
3895 effects which must not be repeated. The code is much cleaner now,
3878 without any blanket 'except' left and with a regexp test for
3896 without any blanket 'except' left and with a regexp test for
3879 actual function names.
3897 actual function names.
3880
3898
3881 But an eval remains, which I'm not fully comfortable with. I just
3899 But an eval remains, which I'm not fully comfortable with. I just
3882 don't know how to find out if an expression could be a callable in
3900 don't know how to find out if an expression could be a callable in
3883 the user's namespace without doing an eval on the string. However
3901 the user's namespace without doing an eval on the string. However
3884 that string is now much more strictly checked so that no code
3902 that string is now much more strictly checked so that no code
3885 slips by, so the eval should only happen for things that can
3903 slips by, so the eval should only happen for things that can
3886 really be only function/method names.
3904 really be only function/method names.
3887
3905
3888 2002-10-15 Fernando Perez <fperez@colorado.edu>
3906 2002-10-15 Fernando Perez <fperez@colorado.edu>
3889
3907
3890 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
3908 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
3891 OSX information to main manual, removed README_Mac_OSX file from
3909 OSX information to main manual, removed README_Mac_OSX file from
3892 distribution. Also updated credits for recent additions.
3910 distribution. Also updated credits for recent additions.
3893
3911
3894 2002-10-10 Fernando Perez <fperez@colorado.edu>
3912 2002-10-10 Fernando Perez <fperez@colorado.edu>
3895
3913
3896 * README_Mac_OSX: Added a README for Mac OSX users for fixing
3914 * README_Mac_OSX: Added a README for Mac OSX users for fixing
3897 terminal-related issues. Many thanks to Andrea Riciputi
3915 terminal-related issues. Many thanks to Andrea Riciputi
3898 <andrea.riciputi-AT-libero.it> for writing it.
3916 <andrea.riciputi-AT-libero.it> for writing it.
3899
3917
3900 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
3918 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
3901 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3919 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3902
3920
3903 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
3921 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
3904 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
3922 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
3905 <syver-en-AT-online.no> who both submitted patches for this problem.
3923 <syver-en-AT-online.no> who both submitted patches for this problem.
3906
3924
3907 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
3925 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
3908 global embedding to make sure that things don't overwrite user
3926 global embedding to make sure that things don't overwrite user
3909 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
3927 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
3910
3928
3911 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
3929 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
3912 compatibility. Thanks to Hayden Callow
3930 compatibility. Thanks to Hayden Callow
3913 <h.callow-AT-elec.canterbury.ac.nz>
3931 <h.callow-AT-elec.canterbury.ac.nz>
3914
3932
3915 2002-10-04 Fernando Perez <fperez@colorado.edu>
3933 2002-10-04 Fernando Perez <fperez@colorado.edu>
3916
3934
3917 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
3935 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
3918 Gnuplot.File objects.
3936 Gnuplot.File objects.
3919
3937
3920 2002-07-23 Fernando Perez <fperez@colorado.edu>
3938 2002-07-23 Fernando Perez <fperez@colorado.edu>
3921
3939
3922 * IPython/genutils.py (timing): Added timings() and timing() for
3940 * IPython/genutils.py (timing): Added timings() and timing() for
3923 quick access to the most commonly needed data, the execution
3941 quick access to the most commonly needed data, the execution
3924 times. Old timing() renamed to timings_out().
3942 times. Old timing() renamed to timings_out().
3925
3943
3926 2002-07-18 Fernando Perez <fperez@colorado.edu>
3944 2002-07-18 Fernando Perez <fperez@colorado.edu>
3927
3945
3928 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
3946 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
3929 bug with nested instances disrupting the parent's tab completion.
3947 bug with nested instances disrupting the parent's tab completion.
3930
3948
3931 * IPython/iplib.py (all_completions): Added Alex Schmolck's
3949 * IPython/iplib.py (all_completions): Added Alex Schmolck's
3932 all_completions code to begin the emacs integration.
3950 all_completions code to begin the emacs integration.
3933
3951
3934 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
3952 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
3935 argument to allow titling individual arrays when plotting.
3953 argument to allow titling individual arrays when plotting.
3936
3954
3937 2002-07-15 Fernando Perez <fperez@colorado.edu>
3955 2002-07-15 Fernando Perez <fperez@colorado.edu>
3938
3956
3939 * setup.py (make_shortcut): changed to retrieve the value of
3957 * setup.py (make_shortcut): changed to retrieve the value of
3940 'Program Files' directory from the registry (this value changes in
3958 'Program Files' directory from the registry (this value changes in
3941 non-english versions of Windows). Thanks to Thomas Fanslau
3959 non-english versions of Windows). Thanks to Thomas Fanslau
3942 <tfanslau-AT-gmx.de> for the report.
3960 <tfanslau-AT-gmx.de> for the report.
3943
3961
3944 2002-07-10 Fernando Perez <fperez@colorado.edu>
3962 2002-07-10 Fernando Perez <fperez@colorado.edu>
3945
3963
3946 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
3964 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
3947 a bug in pdb, which crashes if a line with only whitespace is
3965 a bug in pdb, which crashes if a line with only whitespace is
3948 entered. Bug report submitted to sourceforge.
3966 entered. Bug report submitted to sourceforge.
3949
3967
3950 2002-07-09 Fernando Perez <fperez@colorado.edu>
3968 2002-07-09 Fernando Perez <fperez@colorado.edu>
3951
3969
3952 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
3970 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
3953 reporting exceptions (it's a bug in inspect.py, I just set a
3971 reporting exceptions (it's a bug in inspect.py, I just set a
3954 workaround).
3972 workaround).
3955
3973
3956 2002-07-08 Fernando Perez <fperez@colorado.edu>
3974 2002-07-08 Fernando Perez <fperez@colorado.edu>
3957
3975
3958 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
3976 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
3959 __IPYTHON__ in __builtins__ to show up in user_ns.
3977 __IPYTHON__ in __builtins__ to show up in user_ns.
3960
3978
3961 2002-07-03 Fernando Perez <fperez@colorado.edu>
3979 2002-07-03 Fernando Perez <fperez@colorado.edu>
3962
3980
3963 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
3981 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
3964 name from @gp_set_instance to @gp_set_default.
3982 name from @gp_set_instance to @gp_set_default.
3965
3983
3966 * IPython/ipmaker.py (make_IPython): default editor value set to
3984 * IPython/ipmaker.py (make_IPython): default editor value set to
3967 '0' (a string), to match the rc file. Otherwise will crash when
3985 '0' (a string), to match the rc file. Otherwise will crash when
3968 .strip() is called on it.
3986 .strip() is called on it.
3969
3987
3970
3988
3971 2002-06-28 Fernando Perez <fperez@colorado.edu>
3989 2002-06-28 Fernando Perez <fperez@colorado.edu>
3972
3990
3973 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
3991 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
3974 of files in current directory when a file is executed via
3992 of files in current directory when a file is executed via
3975 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
3993 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
3976
3994
3977 * setup.py (manfiles): fix for rpm builds, submitted by RA
3995 * setup.py (manfiles): fix for rpm builds, submitted by RA
3978 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
3996 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
3979
3997
3980 * IPython/ipmaker.py (make_IPython): fixed lookup of default
3998 * IPython/ipmaker.py (make_IPython): fixed lookup of default
3981 editor when set to '0'. Problem was, '0' evaluates to True (it's a
3999 editor when set to '0'. Problem was, '0' evaluates to True (it's a
3982 string!). A. Schmolck caught this one.
4000 string!). A. Schmolck caught this one.
3983
4001
3984 2002-06-27 Fernando Perez <fperez@colorado.edu>
4002 2002-06-27 Fernando Perez <fperez@colorado.edu>
3985
4003
3986 * IPython/ipmaker.py (make_IPython): fixed bug when running user
4004 * IPython/ipmaker.py (make_IPython): fixed bug when running user
3987 defined files at the cmd line. __name__ wasn't being set to
4005 defined files at the cmd line. __name__ wasn't being set to
3988 __main__.
4006 __main__.
3989
4007
3990 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
4008 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
3991 regular lists and tuples besides Numeric arrays.
4009 regular lists and tuples besides Numeric arrays.
3992
4010
3993 * IPython/Prompts.py (CachedOutput.__call__): Added output
4011 * IPython/Prompts.py (CachedOutput.__call__): Added output
3994 supression for input ending with ';'. Similar to Mathematica and
4012 supression for input ending with ';'. Similar to Mathematica and
3995 Matlab. The _* vars and Out[] list are still updated, just like
4013 Matlab. The _* vars and Out[] list are still updated, just like
3996 Mathematica behaves.
4014 Mathematica behaves.
3997
4015
3998 2002-06-25 Fernando Perez <fperez@colorado.edu>
4016 2002-06-25 Fernando Perez <fperez@colorado.edu>
3999
4017
4000 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
4018 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
4001 .ini extensions for profiels under Windows.
4019 .ini extensions for profiels under Windows.
4002
4020
4003 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
4021 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
4004 string form. Fix contributed by Alexander Schmolck
4022 string form. Fix contributed by Alexander Schmolck
4005 <a.schmolck-AT-gmx.net>
4023 <a.schmolck-AT-gmx.net>
4006
4024
4007 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
4025 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
4008 pre-configured Gnuplot instance.
4026 pre-configured Gnuplot instance.
4009
4027
4010 2002-06-21 Fernando Perez <fperez@colorado.edu>
4028 2002-06-21 Fernando Perez <fperez@colorado.edu>
4011
4029
4012 * IPython/numutils.py (exp_safe): new function, works around the
4030 * IPython/numutils.py (exp_safe): new function, works around the
4013 underflow problems in Numeric.
4031 underflow problems in Numeric.
4014 (log2): New fn. Safe log in base 2: returns exact integer answer
4032 (log2): New fn. Safe log in base 2: returns exact integer answer
4015 for exact integer powers of 2.
4033 for exact integer powers of 2.
4016
4034
4017 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
4035 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
4018 properly.
4036 properly.
4019
4037
4020 2002-06-20 Fernando Perez <fperez@colorado.edu>
4038 2002-06-20 Fernando Perez <fperez@colorado.edu>
4021
4039
4022 * IPython/genutils.py (timing): new function like
4040 * IPython/genutils.py (timing): new function like
4023 Mathematica's. Similar to time_test, but returns more info.
4041 Mathematica's. Similar to time_test, but returns more info.
4024
4042
4025 2002-06-18 Fernando Perez <fperez@colorado.edu>
4043 2002-06-18 Fernando Perez <fperez@colorado.edu>
4026
4044
4027 * IPython/Magic.py (Magic.magic_save): modified @save and @r
4045 * IPython/Magic.py (Magic.magic_save): modified @save and @r
4028 according to Mike Heeter's suggestions.
4046 according to Mike Heeter's suggestions.
4029
4047
4030 2002-06-16 Fernando Perez <fperez@colorado.edu>
4048 2002-06-16 Fernando Perez <fperez@colorado.edu>
4031
4049
4032 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
4050 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
4033 system. GnuplotMagic is gone as a user-directory option. New files
4051 system. GnuplotMagic is gone as a user-directory option. New files
4034 make it easier to use all the gnuplot stuff both from external
4052 make it easier to use all the gnuplot stuff both from external
4035 programs as well as from IPython. Had to rewrite part of
4053 programs as well as from IPython. Had to rewrite part of
4036 hardcopy() b/c of a strange bug: often the ps files simply don't
4054 hardcopy() b/c of a strange bug: often the ps files simply don't
4037 get created, and require a repeat of the command (often several
4055 get created, and require a repeat of the command (often several
4038 times).
4056 times).
4039
4057
4040 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
4058 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
4041 resolve output channel at call time, so that if sys.stderr has
4059 resolve output channel at call time, so that if sys.stderr has
4042 been redirected by user this gets honored.
4060 been redirected by user this gets honored.
4043
4061
4044 2002-06-13 Fernando Perez <fperez@colorado.edu>
4062 2002-06-13 Fernando Perez <fperez@colorado.edu>
4045
4063
4046 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
4064 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
4047 IPShell. Kept a copy with the old names to avoid breaking people's
4065 IPShell. Kept a copy with the old names to avoid breaking people's
4048 embedded code.
4066 embedded code.
4049
4067
4050 * IPython/ipython: simplified it to the bare minimum after
4068 * IPython/ipython: simplified it to the bare minimum after
4051 Holger's suggestions. Added info about how to use it in
4069 Holger's suggestions. Added info about how to use it in
4052 PYTHONSTARTUP.
4070 PYTHONSTARTUP.
4053
4071
4054 * IPython/Shell.py (IPythonShell): changed the options passing
4072 * IPython/Shell.py (IPythonShell): changed the options passing
4055 from a string with funky %s replacements to a straight list. Maybe
4073 from a string with funky %s replacements to a straight list. Maybe
4056 a bit more typing, but it follows sys.argv conventions, so there's
4074 a bit more typing, but it follows sys.argv conventions, so there's
4057 less special-casing to remember.
4075 less special-casing to remember.
4058
4076
4059 2002-06-12 Fernando Perez <fperez@colorado.edu>
4077 2002-06-12 Fernando Perez <fperez@colorado.edu>
4060
4078
4061 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
4079 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
4062 command. Thanks to a suggestion by Mike Heeter.
4080 command. Thanks to a suggestion by Mike Heeter.
4063 (Magic.magic_pfile): added behavior to look at filenames if given
4081 (Magic.magic_pfile): added behavior to look at filenames if given
4064 arg is not a defined object.
4082 arg is not a defined object.
4065 (Magic.magic_save): New @save function to save code snippets. Also
4083 (Magic.magic_save): New @save function to save code snippets. Also
4066 a Mike Heeter idea.
4084 a Mike Heeter idea.
4067
4085
4068 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
4086 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
4069 plot() and replot(). Much more convenient now, especially for
4087 plot() and replot(). Much more convenient now, especially for
4070 interactive use.
4088 interactive use.
4071
4089
4072 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
4090 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
4073 filenames.
4091 filenames.
4074
4092
4075 2002-06-02 Fernando Perez <fperez@colorado.edu>
4093 2002-06-02 Fernando Perez <fperez@colorado.edu>
4076
4094
4077 * IPython/Struct.py (Struct.__init__): modified to admit
4095 * IPython/Struct.py (Struct.__init__): modified to admit
4078 initialization via another struct.
4096 initialization via another struct.
4079
4097
4080 * IPython/genutils.py (SystemExec.__init__): New stateful
4098 * IPython/genutils.py (SystemExec.__init__): New stateful
4081 interface to xsys and bq. Useful for writing system scripts.
4099 interface to xsys and bq. Useful for writing system scripts.
4082
4100
4083 2002-05-30 Fernando Perez <fperez@colorado.edu>
4101 2002-05-30 Fernando Perez <fperez@colorado.edu>
4084
4102
4085 * MANIFEST.in: Changed docfile selection to exclude all the lyx
4103 * MANIFEST.in: Changed docfile selection to exclude all the lyx
4086 documents. This will make the user download smaller (it's getting
4104 documents. This will make the user download smaller (it's getting
4087 too big).
4105 too big).
4088
4106
4089 2002-05-29 Fernando Perez <fperez@colorado.edu>
4107 2002-05-29 Fernando Perez <fperez@colorado.edu>
4090
4108
4091 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
4109 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
4092 fix problems with shelve and pickle. Seems to work, but I don't
4110 fix problems with shelve and pickle. Seems to work, but I don't
4093 know if corner cases break it. Thanks to Mike Heeter
4111 know if corner cases break it. Thanks to Mike Heeter
4094 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
4112 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
4095
4113
4096 2002-05-24 Fernando Perez <fperez@colorado.edu>
4114 2002-05-24 Fernando Perez <fperez@colorado.edu>
4097
4115
4098 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
4116 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
4099 macros having broken.
4117 macros having broken.
4100
4118
4101 2002-05-21 Fernando Perez <fperez@colorado.edu>
4119 2002-05-21 Fernando Perez <fperez@colorado.edu>
4102
4120
4103 * IPython/Magic.py (Magic.magic_logstart): fixed recently
4121 * IPython/Magic.py (Magic.magic_logstart): fixed recently
4104 introduced logging bug: all history before logging started was
4122 introduced logging bug: all history before logging started was
4105 being written one character per line! This came from the redesign
4123 being written one character per line! This came from the redesign
4106 of the input history as a special list which slices to strings,
4124 of the input history as a special list which slices to strings,
4107 not to lists.
4125 not to lists.
4108
4126
4109 2002-05-20 Fernando Perez <fperez@colorado.edu>
4127 2002-05-20 Fernando Perez <fperez@colorado.edu>
4110
4128
4111 * IPython/Prompts.py (CachedOutput.__init__): made the color table
4129 * IPython/Prompts.py (CachedOutput.__init__): made the color table
4112 be an attribute of all classes in this module. The design of these
4130 be an attribute of all classes in this module. The design of these
4113 classes needs some serious overhauling.
4131 classes needs some serious overhauling.
4114
4132
4115 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
4133 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
4116 which was ignoring '_' in option names.
4134 which was ignoring '_' in option names.
4117
4135
4118 * IPython/ultraTB.py (FormattedTB.__init__): Changed
4136 * IPython/ultraTB.py (FormattedTB.__init__): Changed
4119 'Verbose_novars' to 'Context' and made it the new default. It's a
4137 'Verbose_novars' to 'Context' and made it the new default. It's a
4120 bit more readable and also safer than verbose.
4138 bit more readable and also safer than verbose.
4121
4139
4122 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
4140 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
4123 triple-quoted strings.
4141 triple-quoted strings.
4124
4142
4125 * IPython/OInspect.py (__all__): new module exposing the object
4143 * IPython/OInspect.py (__all__): new module exposing the object
4126 introspection facilities. Now the corresponding magics are dummy
4144 introspection facilities. Now the corresponding magics are dummy
4127 wrappers around this. Having this module will make it much easier
4145 wrappers around this. Having this module will make it much easier
4128 to put these functions into our modified pdb.
4146 to put these functions into our modified pdb.
4129 This new object inspector system uses the new colorizing module,
4147 This new object inspector system uses the new colorizing module,
4130 so source code and other things are nicely syntax highlighted.
4148 so source code and other things are nicely syntax highlighted.
4131
4149
4132 2002-05-18 Fernando Perez <fperez@colorado.edu>
4150 2002-05-18 Fernando Perez <fperez@colorado.edu>
4133
4151
4134 * IPython/ColorANSI.py: Split the coloring tools into a separate
4152 * IPython/ColorANSI.py: Split the coloring tools into a separate
4135 module so I can use them in other code easier (they were part of
4153 module so I can use them in other code easier (they were part of
4136 ultraTB).
4154 ultraTB).
4137
4155
4138 2002-05-17 Fernando Perez <fperez@colorado.edu>
4156 2002-05-17 Fernando Perez <fperez@colorado.edu>
4139
4157
4140 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
4158 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
4141 fixed it to set the global 'g' also to the called instance, as
4159 fixed it to set the global 'g' also to the called instance, as
4142 long as 'g' was still a gnuplot instance (so it doesn't overwrite
4160 long as 'g' was still a gnuplot instance (so it doesn't overwrite
4143 user's 'g' variables).
4161 user's 'g' variables).
4144
4162
4145 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
4163 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
4146 global variables (aliases to _ih,_oh) so that users which expect
4164 global variables (aliases to _ih,_oh) so that users which expect
4147 In[5] or Out[7] to work aren't unpleasantly surprised.
4165 In[5] or Out[7] to work aren't unpleasantly surprised.
4148 (InputList.__getslice__): new class to allow executing slices of
4166 (InputList.__getslice__): new class to allow executing slices of
4149 input history directly. Very simple class, complements the use of
4167 input history directly. Very simple class, complements the use of
4150 macros.
4168 macros.
4151
4169
4152 2002-05-16 Fernando Perez <fperez@colorado.edu>
4170 2002-05-16 Fernando Perez <fperez@colorado.edu>
4153
4171
4154 * setup.py (docdirbase): make doc directory be just doc/IPython
4172 * setup.py (docdirbase): make doc directory be just doc/IPython
4155 without version numbers, it will reduce clutter for users.
4173 without version numbers, it will reduce clutter for users.
4156
4174
4157 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
4175 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
4158 execfile call to prevent possible memory leak. See for details:
4176 execfile call to prevent possible memory leak. See for details:
4159 http://mail.python.org/pipermail/python-list/2002-February/088476.html
4177 http://mail.python.org/pipermail/python-list/2002-February/088476.html
4160
4178
4161 2002-05-15 Fernando Perez <fperez@colorado.edu>
4179 2002-05-15 Fernando Perez <fperez@colorado.edu>
4162
4180
4163 * IPython/Magic.py (Magic.magic_psource): made the object
4181 * IPython/Magic.py (Magic.magic_psource): made the object
4164 introspection names be more standard: pdoc, pdef, pfile and
4182 introspection names be more standard: pdoc, pdef, pfile and
4165 psource. They all print/page their output, and it makes
4183 psource. They all print/page their output, and it makes
4166 remembering them easier. Kept old names for compatibility as
4184 remembering them easier. Kept old names for compatibility as
4167 aliases.
4185 aliases.
4168
4186
4169 2002-05-14 Fernando Perez <fperez@colorado.edu>
4187 2002-05-14 Fernando Perez <fperez@colorado.edu>
4170
4188
4171 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
4189 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
4172 what the mouse problem was. The trick is to use gnuplot with temp
4190 what the mouse problem was. The trick is to use gnuplot with temp
4173 files and NOT with pipes (for data communication), because having
4191 files and NOT with pipes (for data communication), because having
4174 both pipes and the mouse on is bad news.
4192 both pipes and the mouse on is bad news.
4175
4193
4176 2002-05-13 Fernando Perez <fperez@colorado.edu>
4194 2002-05-13 Fernando Perez <fperez@colorado.edu>
4177
4195
4178 * IPython/Magic.py (Magic._ofind): fixed namespace order search
4196 * IPython/Magic.py (Magic._ofind): fixed namespace order search
4179 bug. Information would be reported about builtins even when
4197 bug. Information would be reported about builtins even when
4180 user-defined functions overrode them.
4198 user-defined functions overrode them.
4181
4199
4182 2002-05-11 Fernando Perez <fperez@colorado.edu>
4200 2002-05-11 Fernando Perez <fperez@colorado.edu>
4183
4201
4184 * IPython/__init__.py (__all__): removed FlexCompleter from
4202 * IPython/__init__.py (__all__): removed FlexCompleter from
4185 __all__ so that things don't fail in platforms without readline.
4203 __all__ so that things don't fail in platforms without readline.
4186
4204
4187 2002-05-10 Fernando Perez <fperez@colorado.edu>
4205 2002-05-10 Fernando Perez <fperez@colorado.edu>
4188
4206
4189 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
4207 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
4190 it requires Numeric, effectively making Numeric a dependency for
4208 it requires Numeric, effectively making Numeric a dependency for
4191 IPython.
4209 IPython.
4192
4210
4193 * Released 0.2.13
4211 * Released 0.2.13
4194
4212
4195 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
4213 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
4196 profiler interface. Now all the major options from the profiler
4214 profiler interface. Now all the major options from the profiler
4197 module are directly supported in IPython, both for single
4215 module are directly supported in IPython, both for single
4198 expressions (@prun) and for full programs (@run -p).
4216 expressions (@prun) and for full programs (@run -p).
4199
4217
4200 2002-05-09 Fernando Perez <fperez@colorado.edu>
4218 2002-05-09 Fernando Perez <fperez@colorado.edu>
4201
4219
4202 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
4220 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
4203 magic properly formatted for screen.
4221 magic properly formatted for screen.
4204
4222
4205 * setup.py (make_shortcut): Changed things to put pdf version in
4223 * setup.py (make_shortcut): Changed things to put pdf version in
4206 doc/ instead of doc/manual (had to change lyxport a bit).
4224 doc/ instead of doc/manual (had to change lyxport a bit).
4207
4225
4208 * IPython/Magic.py (Profile.string_stats): made profile runs go
4226 * IPython/Magic.py (Profile.string_stats): made profile runs go
4209 through pager (they are long and a pager allows searching, saving,
4227 through pager (they are long and a pager allows searching, saving,
4210 etc.)
4228 etc.)
4211
4229
4212 2002-05-08 Fernando Perez <fperez@colorado.edu>
4230 2002-05-08 Fernando Perez <fperez@colorado.edu>
4213
4231
4214 * Released 0.2.12
4232 * Released 0.2.12
4215
4233
4216 2002-05-06 Fernando Perez <fperez@colorado.edu>
4234 2002-05-06 Fernando Perez <fperez@colorado.edu>
4217
4235
4218 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
4236 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
4219 introduced); 'hist n1 n2' was broken.
4237 introduced); 'hist n1 n2' was broken.
4220 (Magic.magic_pdb): added optional on/off arguments to @pdb
4238 (Magic.magic_pdb): added optional on/off arguments to @pdb
4221 (Magic.magic_run): added option -i to @run, which executes code in
4239 (Magic.magic_run): added option -i to @run, which executes code in
4222 the IPython namespace instead of a clean one. Also added @irun as
4240 the IPython namespace instead of a clean one. Also added @irun as
4223 an alias to @run -i.
4241 an alias to @run -i.
4224
4242
4225 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
4243 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
4226 fixed (it didn't really do anything, the namespaces were wrong).
4244 fixed (it didn't really do anything, the namespaces were wrong).
4227
4245
4228 * IPython/Debugger.py (__init__): Added workaround for python 2.1
4246 * IPython/Debugger.py (__init__): Added workaround for python 2.1
4229
4247
4230 * IPython/__init__.py (__all__): Fixed package namespace, now
4248 * IPython/__init__.py (__all__): Fixed package namespace, now
4231 'import IPython' does give access to IPython.<all> as
4249 'import IPython' does give access to IPython.<all> as
4232 expected. Also renamed __release__ to Release.
4250 expected. Also renamed __release__ to Release.
4233
4251
4234 * IPython/Debugger.py (__license__): created new Pdb class which
4252 * IPython/Debugger.py (__license__): created new Pdb class which
4235 functions like a drop-in for the normal pdb.Pdb but does NOT
4253 functions like a drop-in for the normal pdb.Pdb but does NOT
4236 import readline by default. This way it doesn't muck up IPython's
4254 import readline by default. This way it doesn't muck up IPython's
4237 readline handling, and now tab-completion finally works in the
4255 readline handling, and now tab-completion finally works in the
4238 debugger -- sort of. It completes things globally visible, but the
4256 debugger -- sort of. It completes things globally visible, but the
4239 completer doesn't track the stack as pdb walks it. That's a bit
4257 completer doesn't track the stack as pdb walks it. That's a bit
4240 tricky, and I'll have to implement it later.
4258 tricky, and I'll have to implement it later.
4241
4259
4242 2002-05-05 Fernando Perez <fperez@colorado.edu>
4260 2002-05-05 Fernando Perez <fperez@colorado.edu>
4243
4261
4244 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
4262 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
4245 magic docstrings when printed via ? (explicit \'s were being
4263 magic docstrings when printed via ? (explicit \'s were being
4246 printed).
4264 printed).
4247
4265
4248 * IPython/ipmaker.py (make_IPython): fixed namespace
4266 * IPython/ipmaker.py (make_IPython): fixed namespace
4249 identification bug. Now variables loaded via logs or command-line
4267 identification bug. Now variables loaded via logs or command-line
4250 files are recognized in the interactive namespace by @who.
4268 files are recognized in the interactive namespace by @who.
4251
4269
4252 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
4270 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
4253 log replay system stemming from the string form of Structs.
4271 log replay system stemming from the string form of Structs.
4254
4272
4255 * IPython/Magic.py (Macro.__init__): improved macros to properly
4273 * IPython/Magic.py (Macro.__init__): improved macros to properly
4256 handle magic commands in them.
4274 handle magic commands in them.
4257 (Magic.magic_logstart): usernames are now expanded so 'logstart
4275 (Magic.magic_logstart): usernames are now expanded so 'logstart
4258 ~/mylog' now works.
4276 ~/mylog' now works.
4259
4277
4260 * IPython/iplib.py (complete): fixed bug where paths starting with
4278 * IPython/iplib.py (complete): fixed bug where paths starting with
4261 '/' would be completed as magic names.
4279 '/' would be completed as magic names.
4262
4280
4263 2002-05-04 Fernando Perez <fperez@colorado.edu>
4281 2002-05-04 Fernando Perez <fperez@colorado.edu>
4264
4282
4265 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
4283 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
4266 allow running full programs under the profiler's control.
4284 allow running full programs under the profiler's control.
4267
4285
4268 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
4286 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
4269 mode to report exceptions verbosely but without formatting
4287 mode to report exceptions verbosely but without formatting
4270 variables. This addresses the issue of ipython 'freezing' (it's
4288 variables. This addresses the issue of ipython 'freezing' (it's
4271 not frozen, but caught in an expensive formatting loop) when huge
4289 not frozen, but caught in an expensive formatting loop) when huge
4272 variables are in the context of an exception.
4290 variables are in the context of an exception.
4273 (VerboseTB.text): Added '--->' markers at line where exception was
4291 (VerboseTB.text): Added '--->' markers at line where exception was
4274 triggered. Much clearer to read, especially in NoColor modes.
4292 triggered. Much clearer to read, especially in NoColor modes.
4275
4293
4276 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
4294 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
4277 implemented in reverse when changing to the new parse_options().
4295 implemented in reverse when changing to the new parse_options().
4278
4296
4279 2002-05-03 Fernando Perez <fperez@colorado.edu>
4297 2002-05-03 Fernando Perez <fperez@colorado.edu>
4280
4298
4281 * IPython/Magic.py (Magic.parse_options): new function so that
4299 * IPython/Magic.py (Magic.parse_options): new function so that
4282 magics can parse options easier.
4300 magics can parse options easier.
4283 (Magic.magic_prun): new function similar to profile.run(),
4301 (Magic.magic_prun): new function similar to profile.run(),
4284 suggested by Chris Hart.
4302 suggested by Chris Hart.
4285 (Magic.magic_cd): fixed behavior so that it only changes if
4303 (Magic.magic_cd): fixed behavior so that it only changes if
4286 directory actually is in history.
4304 directory actually is in history.
4287
4305
4288 * IPython/usage.py (__doc__): added information about potential
4306 * IPython/usage.py (__doc__): added information about potential
4289 slowness of Verbose exception mode when there are huge data
4307 slowness of Verbose exception mode when there are huge data
4290 structures to be formatted (thanks to Archie Paulson).
4308 structures to be formatted (thanks to Archie Paulson).
4291
4309
4292 * IPython/ipmaker.py (make_IPython): Changed default logging
4310 * IPython/ipmaker.py (make_IPython): Changed default logging
4293 (when simply called with -log) to use curr_dir/ipython.log in
4311 (when simply called with -log) to use curr_dir/ipython.log in
4294 rotate mode. Fixed crash which was occuring with -log before
4312 rotate mode. Fixed crash which was occuring with -log before
4295 (thanks to Jim Boyle).
4313 (thanks to Jim Boyle).
4296
4314
4297 2002-05-01 Fernando Perez <fperez@colorado.edu>
4315 2002-05-01 Fernando Perez <fperez@colorado.edu>
4298
4316
4299 * Released 0.2.11 for these fixes (mainly the ultraTB one which
4317 * Released 0.2.11 for these fixes (mainly the ultraTB one which
4300 was nasty -- though somewhat of a corner case).
4318 was nasty -- though somewhat of a corner case).
4301
4319
4302 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
4320 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
4303 text (was a bug).
4321 text (was a bug).
4304
4322
4305 2002-04-30 Fernando Perez <fperez@colorado.edu>
4323 2002-04-30 Fernando Perez <fperez@colorado.edu>
4306
4324
4307 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
4325 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
4308 a print after ^D or ^C from the user so that the In[] prompt
4326 a print after ^D or ^C from the user so that the In[] prompt
4309 doesn't over-run the gnuplot one.
4327 doesn't over-run the gnuplot one.
4310
4328
4311 2002-04-29 Fernando Perez <fperez@colorado.edu>
4329 2002-04-29 Fernando Perez <fperez@colorado.edu>
4312
4330
4313 * Released 0.2.10
4331 * Released 0.2.10
4314
4332
4315 * IPython/__release__.py (version): get date dynamically.
4333 * IPython/__release__.py (version): get date dynamically.
4316
4334
4317 * Misc. documentation updates thanks to Arnd's comments. Also ran
4335 * Misc. documentation updates thanks to Arnd's comments. Also ran
4318 a full spellcheck on the manual (hadn't been done in a while).
4336 a full spellcheck on the manual (hadn't been done in a while).
4319
4337
4320 2002-04-27 Fernando Perez <fperez@colorado.edu>
4338 2002-04-27 Fernando Perez <fperez@colorado.edu>
4321
4339
4322 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
4340 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
4323 starting a log in mid-session would reset the input history list.
4341 starting a log in mid-session would reset the input history list.
4324
4342
4325 2002-04-26 Fernando Perez <fperez@colorado.edu>
4343 2002-04-26 Fernando Perez <fperez@colorado.edu>
4326
4344
4327 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
4345 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
4328 all files were being included in an update. Now anything in
4346 all files were being included in an update. Now anything in
4329 UserConfig that matches [A-Za-z]*.py will go (this excludes
4347 UserConfig that matches [A-Za-z]*.py will go (this excludes
4330 __init__.py)
4348 __init__.py)
4331
4349
4332 2002-04-25 Fernando Perez <fperez@colorado.edu>
4350 2002-04-25 Fernando Perez <fperez@colorado.edu>
4333
4351
4334 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
4352 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
4335 to __builtins__ so that any form of embedded or imported code can
4353 to __builtins__ so that any form of embedded or imported code can
4336 test for being inside IPython.
4354 test for being inside IPython.
4337
4355
4338 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
4356 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
4339 changed to GnuplotMagic because it's now an importable module,
4357 changed to GnuplotMagic because it's now an importable module,
4340 this makes the name follow that of the standard Gnuplot module.
4358 this makes the name follow that of the standard Gnuplot module.
4341 GnuplotMagic can now be loaded at any time in mid-session.
4359 GnuplotMagic can now be loaded at any time in mid-session.
4342
4360
4343 2002-04-24 Fernando Perez <fperez@colorado.edu>
4361 2002-04-24 Fernando Perez <fperez@colorado.edu>
4344
4362
4345 * IPython/numutils.py: removed SIUnits. It doesn't properly set
4363 * IPython/numutils.py: removed SIUnits. It doesn't properly set
4346 the globals (IPython has its own namespace) and the
4364 the globals (IPython has its own namespace) and the
4347 PhysicalQuantity stuff is much better anyway.
4365 PhysicalQuantity stuff is much better anyway.
4348
4366
4349 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
4367 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
4350 embedding example to standard user directory for
4368 embedding example to standard user directory for
4351 distribution. Also put it in the manual.
4369 distribution. Also put it in the manual.
4352
4370
4353 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
4371 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
4354 instance as first argument (so it doesn't rely on some obscure
4372 instance as first argument (so it doesn't rely on some obscure
4355 hidden global).
4373 hidden global).
4356
4374
4357 * IPython/UserConfig/ipythonrc.py: put () back in accepted
4375 * IPython/UserConfig/ipythonrc.py: put () back in accepted
4358 delimiters. While it prevents ().TAB from working, it allows
4376 delimiters. While it prevents ().TAB from working, it allows
4359 completions in open (... expressions. This is by far a more common
4377 completions in open (... expressions. This is by far a more common
4360 case.
4378 case.
4361
4379
4362 2002-04-23 Fernando Perez <fperez@colorado.edu>
4380 2002-04-23 Fernando Perez <fperez@colorado.edu>
4363
4381
4364 * IPython/Extensions/InterpreterPasteInput.py: new
4382 * IPython/Extensions/InterpreterPasteInput.py: new
4365 syntax-processing module for pasting lines with >>> or ... at the
4383 syntax-processing module for pasting lines with >>> or ... at the
4366 start.
4384 start.
4367
4385
4368 * IPython/Extensions/PhysicalQ_Interactive.py
4386 * IPython/Extensions/PhysicalQ_Interactive.py
4369 (PhysicalQuantityInteractive.__int__): fixed to work with either
4387 (PhysicalQuantityInteractive.__int__): fixed to work with either
4370 Numeric or math.
4388 Numeric or math.
4371
4389
4372 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
4390 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
4373 provided profiles. Now we have:
4391 provided profiles. Now we have:
4374 -math -> math module as * and cmath with its own namespace.
4392 -math -> math module as * and cmath with its own namespace.
4375 -numeric -> Numeric as *, plus gnuplot & grace
4393 -numeric -> Numeric as *, plus gnuplot & grace
4376 -physics -> same as before
4394 -physics -> same as before
4377
4395
4378 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
4396 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
4379 user-defined magics wouldn't be found by @magic if they were
4397 user-defined magics wouldn't be found by @magic if they were
4380 defined as class methods. Also cleaned up the namespace search
4398 defined as class methods. Also cleaned up the namespace search
4381 logic and the string building (to use %s instead of many repeated
4399 logic and the string building (to use %s instead of many repeated
4382 string adds).
4400 string adds).
4383
4401
4384 * IPython/UserConfig/example-magic.py (magic_foo): updated example
4402 * IPython/UserConfig/example-magic.py (magic_foo): updated example
4385 of user-defined magics to operate with class methods (cleaner, in
4403 of user-defined magics to operate with class methods (cleaner, in
4386 line with the gnuplot code).
4404 line with the gnuplot code).
4387
4405
4388 2002-04-22 Fernando Perez <fperez@colorado.edu>
4406 2002-04-22 Fernando Perez <fperez@colorado.edu>
4389
4407
4390 * setup.py: updated dependency list so that manual is updated when
4408 * setup.py: updated dependency list so that manual is updated when
4391 all included files change.
4409 all included files change.
4392
4410
4393 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
4411 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
4394 the delimiter removal option (the fix is ugly right now).
4412 the delimiter removal option (the fix is ugly right now).
4395
4413
4396 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
4414 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
4397 all of the math profile (quicker loading, no conflict between
4415 all of the math profile (quicker loading, no conflict between
4398 g-9.8 and g-gnuplot).
4416 g-9.8 and g-gnuplot).
4399
4417
4400 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
4418 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
4401 name of post-mortem files to IPython_crash_report.txt.
4419 name of post-mortem files to IPython_crash_report.txt.
4402
4420
4403 * Cleanup/update of the docs. Added all the new readline info and
4421 * Cleanup/update of the docs. Added all the new readline info and
4404 formatted all lists as 'real lists'.
4422 formatted all lists as 'real lists'.
4405
4423
4406 * IPython/ipmaker.py (make_IPython): removed now-obsolete
4424 * IPython/ipmaker.py (make_IPython): removed now-obsolete
4407 tab-completion options, since the full readline parse_and_bind is
4425 tab-completion options, since the full readline parse_and_bind is
4408 now accessible.
4426 now accessible.
4409
4427
4410 * IPython/iplib.py (InteractiveShell.init_readline): Changed
4428 * IPython/iplib.py (InteractiveShell.init_readline): Changed
4411 handling of readline options. Now users can specify any string to
4429 handling of readline options. Now users can specify any string to
4412 be passed to parse_and_bind(), as well as the delimiters to be
4430 be passed to parse_and_bind(), as well as the delimiters to be
4413 removed.
4431 removed.
4414 (InteractiveShell.__init__): Added __name__ to the global
4432 (InteractiveShell.__init__): Added __name__ to the global
4415 namespace so that things like Itpl which rely on its existence
4433 namespace so that things like Itpl which rely on its existence
4416 don't crash.
4434 don't crash.
4417 (InteractiveShell._prefilter): Defined the default with a _ so
4435 (InteractiveShell._prefilter): Defined the default with a _ so
4418 that prefilter() is easier to override, while the default one
4436 that prefilter() is easier to override, while the default one
4419 remains available.
4437 remains available.
4420
4438
4421 2002-04-18 Fernando Perez <fperez@colorado.edu>
4439 2002-04-18 Fernando Perez <fperez@colorado.edu>
4422
4440
4423 * Added information about pdb in the docs.
4441 * Added information about pdb in the docs.
4424
4442
4425 2002-04-17 Fernando Perez <fperez@colorado.edu>
4443 2002-04-17 Fernando Perez <fperez@colorado.edu>
4426
4444
4427 * IPython/ipmaker.py (make_IPython): added rc_override option to
4445 * IPython/ipmaker.py (make_IPython): added rc_override option to
4428 allow passing config options at creation time which may override
4446 allow passing config options at creation time which may override
4429 anything set in the config files or command line. This is
4447 anything set in the config files or command line. This is
4430 particularly useful for configuring embedded instances.
4448 particularly useful for configuring embedded instances.
4431
4449
4432 2002-04-15 Fernando Perez <fperez@colorado.edu>
4450 2002-04-15 Fernando Perez <fperez@colorado.edu>
4433
4451
4434 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
4452 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
4435 crash embedded instances because of the input cache falling out of
4453 crash embedded instances because of the input cache falling out of
4436 sync with the output counter.
4454 sync with the output counter.
4437
4455
4438 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
4456 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
4439 mode which calls pdb after an uncaught exception in IPython itself.
4457 mode which calls pdb after an uncaught exception in IPython itself.
4440
4458
4441 2002-04-14 Fernando Perez <fperez@colorado.edu>
4459 2002-04-14 Fernando Perez <fperez@colorado.edu>
4442
4460
4443 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
4461 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
4444 readline, fix it back after each call.
4462 readline, fix it back after each call.
4445
4463
4446 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
4464 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
4447 method to force all access via __call__(), which guarantees that
4465 method to force all access via __call__(), which guarantees that
4448 traceback references are properly deleted.
4466 traceback references are properly deleted.
4449
4467
4450 * IPython/Prompts.py (CachedOutput._display): minor fixes to
4468 * IPython/Prompts.py (CachedOutput._display): minor fixes to
4451 improve printing when pprint is in use.
4469 improve printing when pprint is in use.
4452
4470
4453 2002-04-13 Fernando Perez <fperez@colorado.edu>
4471 2002-04-13 Fernando Perez <fperez@colorado.edu>
4454
4472
4455 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
4473 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
4456 exceptions aren't caught anymore. If the user triggers one, he
4474 exceptions aren't caught anymore. If the user triggers one, he
4457 should know why he's doing it and it should go all the way up,
4475 should know why he's doing it and it should go all the way up,
4458 just like any other exception. So now @abort will fully kill the
4476 just like any other exception. So now @abort will fully kill the
4459 embedded interpreter and the embedding code (unless that happens
4477 embedded interpreter and the embedding code (unless that happens
4460 to catch SystemExit).
4478 to catch SystemExit).
4461
4479
4462 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
4480 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
4463 and a debugger() method to invoke the interactive pdb debugger
4481 and a debugger() method to invoke the interactive pdb debugger
4464 after printing exception information. Also added the corresponding
4482 after printing exception information. Also added the corresponding
4465 -pdb option and @pdb magic to control this feature, and updated
4483 -pdb option and @pdb magic to control this feature, and updated
4466 the docs. After a suggestion from Christopher Hart
4484 the docs. After a suggestion from Christopher Hart
4467 (hart-AT-caltech.edu).
4485 (hart-AT-caltech.edu).
4468
4486
4469 2002-04-12 Fernando Perez <fperez@colorado.edu>
4487 2002-04-12 Fernando Perez <fperez@colorado.edu>
4470
4488
4471 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
4489 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
4472 the exception handlers defined by the user (not the CrashHandler)
4490 the exception handlers defined by the user (not the CrashHandler)
4473 so that user exceptions don't trigger an ipython bug report.
4491 so that user exceptions don't trigger an ipython bug report.
4474
4492
4475 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
4493 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
4476 configurable (it should have always been so).
4494 configurable (it should have always been so).
4477
4495
4478 2002-03-26 Fernando Perez <fperez@colorado.edu>
4496 2002-03-26 Fernando Perez <fperez@colorado.edu>
4479
4497
4480 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
4498 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
4481 and there to fix embedding namespace issues. This should all be
4499 and there to fix embedding namespace issues. This should all be
4482 done in a more elegant way.
4500 done in a more elegant way.
4483
4501
4484 2002-03-25 Fernando Perez <fperez@colorado.edu>
4502 2002-03-25 Fernando Perez <fperez@colorado.edu>
4485
4503
4486 * IPython/genutils.py (get_home_dir): Try to make it work under
4504 * IPython/genutils.py (get_home_dir): Try to make it work under
4487 win9x also.
4505 win9x also.
4488
4506
4489 2002-03-20 Fernando Perez <fperez@colorado.edu>
4507 2002-03-20 Fernando Perez <fperez@colorado.edu>
4490
4508
4491 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
4509 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
4492 sys.displayhook untouched upon __init__.
4510 sys.displayhook untouched upon __init__.
4493
4511
4494 2002-03-19 Fernando Perez <fperez@colorado.edu>
4512 2002-03-19 Fernando Perez <fperez@colorado.edu>
4495
4513
4496 * Released 0.2.9 (for embedding bug, basically).
4514 * Released 0.2.9 (for embedding bug, basically).
4497
4515
4498 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
4516 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
4499 exceptions so that enclosing shell's state can be restored.
4517 exceptions so that enclosing shell's state can be restored.
4500
4518
4501 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
4519 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
4502 naming conventions in the .ipython/ dir.
4520 naming conventions in the .ipython/ dir.
4503
4521
4504 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
4522 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
4505 from delimiters list so filenames with - in them get expanded.
4523 from delimiters list so filenames with - in them get expanded.
4506
4524
4507 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
4525 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
4508 sys.displayhook not being properly restored after an embedded call.
4526 sys.displayhook not being properly restored after an embedded call.
4509
4527
4510 2002-03-18 Fernando Perez <fperez@colorado.edu>
4528 2002-03-18 Fernando Perez <fperez@colorado.edu>
4511
4529
4512 * Released 0.2.8
4530 * Released 0.2.8
4513
4531
4514 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
4532 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
4515 some files weren't being included in a -upgrade.
4533 some files weren't being included in a -upgrade.
4516 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
4534 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
4517 on' so that the first tab completes.
4535 on' so that the first tab completes.
4518 (InteractiveShell.handle_magic): fixed bug with spaces around
4536 (InteractiveShell.handle_magic): fixed bug with spaces around
4519 quotes breaking many magic commands.
4537 quotes breaking many magic commands.
4520
4538
4521 * setup.py: added note about ignoring the syntax error messages at
4539 * setup.py: added note about ignoring the syntax error messages at
4522 installation.
4540 installation.
4523
4541
4524 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
4542 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
4525 streamlining the gnuplot interface, now there's only one magic @gp.
4543 streamlining the gnuplot interface, now there's only one magic @gp.
4526
4544
4527 2002-03-17 Fernando Perez <fperez@colorado.edu>
4545 2002-03-17 Fernando Perez <fperez@colorado.edu>
4528
4546
4529 * IPython/UserConfig/magic_gnuplot.py: new name for the
4547 * IPython/UserConfig/magic_gnuplot.py: new name for the
4530 example-magic_pm.py file. Much enhanced system, now with a shell
4548 example-magic_pm.py file. Much enhanced system, now with a shell
4531 for communicating directly with gnuplot, one command at a time.
4549 for communicating directly with gnuplot, one command at a time.
4532
4550
4533 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
4551 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
4534 setting __name__=='__main__'.
4552 setting __name__=='__main__'.
4535
4553
4536 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
4554 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
4537 mini-shell for accessing gnuplot from inside ipython. Should
4555 mini-shell for accessing gnuplot from inside ipython. Should
4538 extend it later for grace access too. Inspired by Arnd's
4556 extend it later for grace access too. Inspired by Arnd's
4539 suggestion.
4557 suggestion.
4540
4558
4541 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
4559 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
4542 calling magic functions with () in their arguments. Thanks to Arnd
4560 calling magic functions with () in their arguments. Thanks to Arnd
4543 Baecker for pointing this to me.
4561 Baecker for pointing this to me.
4544
4562
4545 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
4563 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
4546 infinitely for integer or complex arrays (only worked with floats).
4564 infinitely for integer or complex arrays (only worked with floats).
4547
4565
4548 2002-03-16 Fernando Perez <fperez@colorado.edu>
4566 2002-03-16 Fernando Perez <fperez@colorado.edu>
4549
4567
4550 * setup.py: Merged setup and setup_windows into a single script
4568 * setup.py: Merged setup and setup_windows into a single script
4551 which properly handles things for windows users.
4569 which properly handles things for windows users.
4552
4570
4553 2002-03-15 Fernando Perez <fperez@colorado.edu>
4571 2002-03-15 Fernando Perez <fperez@colorado.edu>
4554
4572
4555 * Big change to the manual: now the magics are all automatically
4573 * Big change to the manual: now the magics are all automatically
4556 documented. This information is generated from their docstrings
4574 documented. This information is generated from their docstrings
4557 and put in a latex file included by the manual lyx file. This way
4575 and put in a latex file included by the manual lyx file. This way
4558 we get always up to date information for the magics. The manual
4576 we get always up to date information for the magics. The manual
4559 now also has proper version information, also auto-synced.
4577 now also has proper version information, also auto-synced.
4560
4578
4561 For this to work, an undocumented --magic_docstrings option was added.
4579 For this to work, an undocumented --magic_docstrings option was added.
4562
4580
4563 2002-03-13 Fernando Perez <fperez@colorado.edu>
4581 2002-03-13 Fernando Perez <fperez@colorado.edu>
4564
4582
4565 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
4583 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
4566 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
4584 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
4567
4585
4568 2002-03-12 Fernando Perez <fperez@colorado.edu>
4586 2002-03-12 Fernando Perez <fperez@colorado.edu>
4569
4587
4570 * IPython/ultraTB.py (TermColors): changed color escapes again to
4588 * IPython/ultraTB.py (TermColors): changed color escapes again to
4571 fix the (old, reintroduced) line-wrapping bug. Basically, if
4589 fix the (old, reintroduced) line-wrapping bug. Basically, if
4572 \001..\002 aren't given in the color escapes, lines get wrapped
4590 \001..\002 aren't given in the color escapes, lines get wrapped
4573 weirdly. But giving those screws up old xterms and emacs terms. So
4591 weirdly. But giving those screws up old xterms and emacs terms. So
4574 I added some logic for emacs terms to be ok, but I can't identify old
4592 I added some logic for emacs terms to be ok, but I can't identify old
4575 xterms separately ($TERM=='xterm' for many terminals, like konsole).
4593 xterms separately ($TERM=='xterm' for many terminals, like konsole).
4576
4594
4577 2002-03-10 Fernando Perez <fperez@colorado.edu>
4595 2002-03-10 Fernando Perez <fperez@colorado.edu>
4578
4596
4579 * IPython/usage.py (__doc__): Various documentation cleanups and
4597 * IPython/usage.py (__doc__): Various documentation cleanups and
4580 updates, both in usage docstrings and in the manual.
4598 updates, both in usage docstrings and in the manual.
4581
4599
4582 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
4600 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
4583 handling of caching. Set minimum acceptabe value for having a
4601 handling of caching. Set minimum acceptabe value for having a
4584 cache at 20 values.
4602 cache at 20 values.
4585
4603
4586 * IPython/iplib.py (InteractiveShell.user_setup): moved the
4604 * IPython/iplib.py (InteractiveShell.user_setup): moved the
4587 install_first_time function to a method, renamed it and added an
4605 install_first_time function to a method, renamed it and added an
4588 'upgrade' mode. Now people can update their config directory with
4606 'upgrade' mode. Now people can update their config directory with
4589 a simple command line switch (-upgrade, also new).
4607 a simple command line switch (-upgrade, also new).
4590
4608
4591 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
4609 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
4592 @file (convenient for automagic users under Python >= 2.2).
4610 @file (convenient for automagic users under Python >= 2.2).
4593 Removed @files (it seemed more like a plural than an abbrev. of
4611 Removed @files (it seemed more like a plural than an abbrev. of
4594 'file show').
4612 'file show').
4595
4613
4596 * IPython/iplib.py (install_first_time): Fixed crash if there were
4614 * IPython/iplib.py (install_first_time): Fixed crash if there were
4597 backup files ('~') in .ipython/ install directory.
4615 backup files ('~') in .ipython/ install directory.
4598
4616
4599 * IPython/ipmaker.py (make_IPython): fixes for new prompt
4617 * IPython/ipmaker.py (make_IPython): fixes for new prompt
4600 system. Things look fine, but these changes are fairly
4618 system. Things look fine, but these changes are fairly
4601 intrusive. Test them for a few days.
4619 intrusive. Test them for a few days.
4602
4620
4603 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
4621 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
4604 the prompts system. Now all in/out prompt strings are user
4622 the prompts system. Now all in/out prompt strings are user
4605 controllable. This is particularly useful for embedding, as one
4623 controllable. This is particularly useful for embedding, as one
4606 can tag embedded instances with particular prompts.
4624 can tag embedded instances with particular prompts.
4607
4625
4608 Also removed global use of sys.ps1/2, which now allows nested
4626 Also removed global use of sys.ps1/2, which now allows nested
4609 embeddings without any problems. Added command-line options for
4627 embeddings without any problems. Added command-line options for
4610 the prompt strings.
4628 the prompt strings.
4611
4629
4612 2002-03-08 Fernando Perez <fperez@colorado.edu>
4630 2002-03-08 Fernando Perez <fperez@colorado.edu>
4613
4631
4614 * IPython/UserConfig/example-embed-short.py (ipshell): added
4632 * IPython/UserConfig/example-embed-short.py (ipshell): added
4615 example file with the bare minimum code for embedding.
4633 example file with the bare minimum code for embedding.
4616
4634
4617 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
4635 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
4618 functionality for the embeddable shell to be activated/deactivated
4636 functionality for the embeddable shell to be activated/deactivated
4619 either globally or at each call.
4637 either globally or at each call.
4620
4638
4621 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
4639 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
4622 rewriting the prompt with '--->' for auto-inputs with proper
4640 rewriting the prompt with '--->' for auto-inputs with proper
4623 coloring. Now the previous UGLY hack in handle_auto() is gone, and
4641 coloring. Now the previous UGLY hack in handle_auto() is gone, and
4624 this is handled by the prompts class itself, as it should.
4642 this is handled by the prompts class itself, as it should.
4625
4643
4626 2002-03-05 Fernando Perez <fperez@colorado.edu>
4644 2002-03-05 Fernando Perez <fperez@colorado.edu>
4627
4645
4628 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
4646 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
4629 @logstart to avoid name clashes with the math log function.
4647 @logstart to avoid name clashes with the math log function.
4630
4648
4631 * Big updates to X/Emacs section of the manual.
4649 * Big updates to X/Emacs section of the manual.
4632
4650
4633 * Removed ipython_emacs. Milan explained to me how to pass
4651 * Removed ipython_emacs. Milan explained to me how to pass
4634 arguments to ipython through Emacs. Some day I'm going to end up
4652 arguments to ipython through Emacs. Some day I'm going to end up
4635 learning some lisp...
4653 learning some lisp...
4636
4654
4637 2002-03-04 Fernando Perez <fperez@colorado.edu>
4655 2002-03-04 Fernando Perez <fperez@colorado.edu>
4638
4656
4639 * IPython/ipython_emacs: Created script to be used as the
4657 * IPython/ipython_emacs: Created script to be used as the
4640 py-python-command Emacs variable so we can pass IPython
4658 py-python-command Emacs variable so we can pass IPython
4641 parameters. I can't figure out how to tell Emacs directly to pass
4659 parameters. I can't figure out how to tell Emacs directly to pass
4642 parameters to IPython, so a dummy shell script will do it.
4660 parameters to IPython, so a dummy shell script will do it.
4643
4661
4644 Other enhancements made for things to work better under Emacs'
4662 Other enhancements made for things to work better under Emacs'
4645 various types of terminals. Many thanks to Milan Zamazal
4663 various types of terminals. Many thanks to Milan Zamazal
4646 <pdm-AT-zamazal.org> for all the suggestions and pointers.
4664 <pdm-AT-zamazal.org> for all the suggestions and pointers.
4647
4665
4648 2002-03-01 Fernando Perez <fperez@colorado.edu>
4666 2002-03-01 Fernando Perez <fperez@colorado.edu>
4649
4667
4650 * IPython/ipmaker.py (make_IPython): added a --readline! option so
4668 * IPython/ipmaker.py (make_IPython): added a --readline! option so
4651 that loading of readline is now optional. This gives better
4669 that loading of readline is now optional. This gives better
4652 control to emacs users.
4670 control to emacs users.
4653
4671
4654 * IPython/ultraTB.py (__date__): Modified color escape sequences
4672 * IPython/ultraTB.py (__date__): Modified color escape sequences
4655 and now things work fine under xterm and in Emacs' term buffers
4673 and now things work fine under xterm and in Emacs' term buffers
4656 (though not shell ones). Well, in emacs you get colors, but all
4674 (though not shell ones). Well, in emacs you get colors, but all
4657 seem to be 'light' colors (no difference between dark and light
4675 seem to be 'light' colors (no difference between dark and light
4658 ones). But the garbage chars are gone, and also in xterms. It
4676 ones). But the garbage chars are gone, and also in xterms. It
4659 seems that now I'm using 'cleaner' ansi sequences.
4677 seems that now I'm using 'cleaner' ansi sequences.
4660
4678
4661 2002-02-21 Fernando Perez <fperez@colorado.edu>
4679 2002-02-21 Fernando Perez <fperez@colorado.edu>
4662
4680
4663 * Released 0.2.7 (mainly to publish the scoping fix).
4681 * Released 0.2.7 (mainly to publish the scoping fix).
4664
4682
4665 * IPython/Logger.py (Logger.logstate): added. A corresponding
4683 * IPython/Logger.py (Logger.logstate): added. A corresponding
4666 @logstate magic was created.
4684 @logstate magic was created.
4667
4685
4668 * IPython/Magic.py: fixed nested scoping problem under Python
4686 * IPython/Magic.py: fixed nested scoping problem under Python
4669 2.1.x (automagic wasn't working).
4687 2.1.x (automagic wasn't working).
4670
4688
4671 2002-02-20 Fernando Perez <fperez@colorado.edu>
4689 2002-02-20 Fernando Perez <fperez@colorado.edu>
4672
4690
4673 * Released 0.2.6.
4691 * Released 0.2.6.
4674
4692
4675 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
4693 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
4676 option so that logs can come out without any headers at all.
4694 option so that logs can come out without any headers at all.
4677
4695
4678 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
4696 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
4679 SciPy.
4697 SciPy.
4680
4698
4681 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
4699 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
4682 that embedded IPython calls don't require vars() to be explicitly
4700 that embedded IPython calls don't require vars() to be explicitly
4683 passed. Now they are extracted from the caller's frame (code
4701 passed. Now they are extracted from the caller's frame (code
4684 snatched from Eric Jones' weave). Added better documentation to
4702 snatched from Eric Jones' weave). Added better documentation to
4685 the section on embedding and the example file.
4703 the section on embedding and the example file.
4686
4704
4687 * IPython/genutils.py (page): Changed so that under emacs, it just
4705 * IPython/genutils.py (page): Changed so that under emacs, it just
4688 prints the string. You can then page up and down in the emacs
4706 prints the string. You can then page up and down in the emacs
4689 buffer itself. This is how the builtin help() works.
4707 buffer itself. This is how the builtin help() works.
4690
4708
4691 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
4709 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
4692 macro scoping: macros need to be executed in the user's namespace
4710 macro scoping: macros need to be executed in the user's namespace
4693 to work as if they had been typed by the user.
4711 to work as if they had been typed by the user.
4694
4712
4695 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
4713 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
4696 execute automatically (no need to type 'exec...'). They then
4714 execute automatically (no need to type 'exec...'). They then
4697 behave like 'true macros'. The printing system was also modified
4715 behave like 'true macros'. The printing system was also modified
4698 for this to work.
4716 for this to work.
4699
4717
4700 2002-02-19 Fernando Perez <fperez@colorado.edu>
4718 2002-02-19 Fernando Perez <fperez@colorado.edu>
4701
4719
4702 * IPython/genutils.py (page_file): new function for paging files
4720 * IPython/genutils.py (page_file): new function for paging files
4703 in an OS-independent way. Also necessary for file viewing to work
4721 in an OS-independent way. Also necessary for file viewing to work
4704 well inside Emacs buffers.
4722 well inside Emacs buffers.
4705 (page): Added checks for being in an emacs buffer.
4723 (page): Added checks for being in an emacs buffer.
4706 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
4724 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
4707 same bug in iplib.
4725 same bug in iplib.
4708
4726
4709 2002-02-18 Fernando Perez <fperez@colorado.edu>
4727 2002-02-18 Fernando Perez <fperez@colorado.edu>
4710
4728
4711 * IPython/iplib.py (InteractiveShell.init_readline): modified use
4729 * IPython/iplib.py (InteractiveShell.init_readline): modified use
4712 of readline so that IPython can work inside an Emacs buffer.
4730 of readline so that IPython can work inside an Emacs buffer.
4713
4731
4714 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
4732 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
4715 method signatures (they weren't really bugs, but it looks cleaner
4733 method signatures (they weren't really bugs, but it looks cleaner
4716 and keeps PyChecker happy).
4734 and keeps PyChecker happy).
4717
4735
4718 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
4736 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
4719 for implementing various user-defined hooks. Currently only
4737 for implementing various user-defined hooks. Currently only
4720 display is done.
4738 display is done.
4721
4739
4722 * IPython/Prompts.py (CachedOutput._display): changed display
4740 * IPython/Prompts.py (CachedOutput._display): changed display
4723 functions so that they can be dynamically changed by users easily.
4741 functions so that they can be dynamically changed by users easily.
4724
4742
4725 * IPython/Extensions/numeric_formats.py (num_display): added an
4743 * IPython/Extensions/numeric_formats.py (num_display): added an
4726 extension for printing NumPy arrays in flexible manners. It
4744 extension for printing NumPy arrays in flexible manners. It
4727 doesn't do anything yet, but all the structure is in
4745 doesn't do anything yet, but all the structure is in
4728 place. Ultimately the plan is to implement output format control
4746 place. Ultimately the plan is to implement output format control
4729 like in Octave.
4747 like in Octave.
4730
4748
4731 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
4749 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
4732 methods are found at run-time by all the automatic machinery.
4750 methods are found at run-time by all the automatic machinery.
4733
4751
4734 2002-02-17 Fernando Perez <fperez@colorado.edu>
4752 2002-02-17 Fernando Perez <fperez@colorado.edu>
4735
4753
4736 * setup_Windows.py (make_shortcut): documented. Cleaned up the
4754 * setup_Windows.py (make_shortcut): documented. Cleaned up the
4737 whole file a little.
4755 whole file a little.
4738
4756
4739 * ToDo: closed this document. Now there's a new_design.lyx
4757 * ToDo: closed this document. Now there's a new_design.lyx
4740 document for all new ideas. Added making a pdf of it for the
4758 document for all new ideas. Added making a pdf of it for the
4741 end-user distro.
4759 end-user distro.
4742
4760
4743 * IPython/Logger.py (Logger.switch_log): Created this to replace
4761 * IPython/Logger.py (Logger.switch_log): Created this to replace
4744 logon() and logoff(). It also fixes a nasty crash reported by
4762 logon() and logoff(). It also fixes a nasty crash reported by
4745 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
4763 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
4746
4764
4747 * IPython/iplib.py (complete): got auto-completion to work with
4765 * IPython/iplib.py (complete): got auto-completion to work with
4748 automagic (I had wanted this for a long time).
4766 automagic (I had wanted this for a long time).
4749
4767
4750 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
4768 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
4751 to @file, since file() is now a builtin and clashes with automagic
4769 to @file, since file() is now a builtin and clashes with automagic
4752 for @file.
4770 for @file.
4753
4771
4754 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
4772 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
4755 of this was previously in iplib, which had grown to more than 2000
4773 of this was previously in iplib, which had grown to more than 2000
4756 lines, way too long. No new functionality, but it makes managing
4774 lines, way too long. No new functionality, but it makes managing
4757 the code a bit easier.
4775 the code a bit easier.
4758
4776
4759 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
4777 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
4760 information to crash reports.
4778 information to crash reports.
4761
4779
4762 2002-02-12 Fernando Perez <fperez@colorado.edu>
4780 2002-02-12 Fernando Perez <fperez@colorado.edu>
4763
4781
4764 * Released 0.2.5.
4782 * Released 0.2.5.
4765
4783
4766 2002-02-11 Fernando Perez <fperez@colorado.edu>
4784 2002-02-11 Fernando Perez <fperez@colorado.edu>
4767
4785
4768 * Wrote a relatively complete Windows installer. It puts
4786 * Wrote a relatively complete Windows installer. It puts
4769 everything in place, creates Start Menu entries and fixes the
4787 everything in place, creates Start Menu entries and fixes the
4770 color issues. Nothing fancy, but it works.
4788 color issues. Nothing fancy, but it works.
4771
4789
4772 2002-02-10 Fernando Perez <fperez@colorado.edu>
4790 2002-02-10 Fernando Perez <fperez@colorado.edu>
4773
4791
4774 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
4792 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
4775 os.path.expanduser() call so that we can type @run ~/myfile.py and
4793 os.path.expanduser() call so that we can type @run ~/myfile.py and
4776 have thigs work as expected.
4794 have thigs work as expected.
4777
4795
4778 * IPython/genutils.py (page): fixed exception handling so things
4796 * IPython/genutils.py (page): fixed exception handling so things
4779 work both in Unix and Windows correctly. Quitting a pager triggers
4797 work both in Unix and Windows correctly. Quitting a pager triggers
4780 an IOError/broken pipe in Unix, and in windows not finding a pager
4798 an IOError/broken pipe in Unix, and in windows not finding a pager
4781 is also an IOError, so I had to actually look at the return value
4799 is also an IOError, so I had to actually look at the return value
4782 of the exception, not just the exception itself. Should be ok now.
4800 of the exception, not just the exception itself. Should be ok now.
4783
4801
4784 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
4802 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
4785 modified to allow case-insensitive color scheme changes.
4803 modified to allow case-insensitive color scheme changes.
4786
4804
4787 2002-02-09 Fernando Perez <fperez@colorado.edu>
4805 2002-02-09 Fernando Perez <fperez@colorado.edu>
4788
4806
4789 * IPython/genutils.py (native_line_ends): new function to leave
4807 * IPython/genutils.py (native_line_ends): new function to leave
4790 user config files with os-native line-endings.
4808 user config files with os-native line-endings.
4791
4809
4792 * README and manual updates.
4810 * README and manual updates.
4793
4811
4794 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
4812 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
4795 instead of StringType to catch Unicode strings.
4813 instead of StringType to catch Unicode strings.
4796
4814
4797 * IPython/genutils.py (filefind): fixed bug for paths with
4815 * IPython/genutils.py (filefind): fixed bug for paths with
4798 embedded spaces (very common in Windows).
4816 embedded spaces (very common in Windows).
4799
4817
4800 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
4818 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
4801 files under Windows, so that they get automatically associated
4819 files under Windows, so that they get automatically associated
4802 with a text editor. Windows makes it a pain to handle
4820 with a text editor. Windows makes it a pain to handle
4803 extension-less files.
4821 extension-less files.
4804
4822
4805 * IPython/iplib.py (InteractiveShell.init_readline): Made the
4823 * IPython/iplib.py (InteractiveShell.init_readline): Made the
4806 warning about readline only occur for Posix. In Windows there's no
4824 warning about readline only occur for Posix. In Windows there's no
4807 way to get readline, so why bother with the warning.
4825 way to get readline, so why bother with the warning.
4808
4826
4809 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
4827 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
4810 for __str__ instead of dir(self), since dir() changed in 2.2.
4828 for __str__ instead of dir(self), since dir() changed in 2.2.
4811
4829
4812 * Ported to Windows! Tested on XP, I suspect it should work fine
4830 * Ported to Windows! Tested on XP, I suspect it should work fine
4813 on NT/2000, but I don't think it will work on 98 et al. That
4831 on NT/2000, but I don't think it will work on 98 et al. That
4814 series of Windows is such a piece of junk anyway that I won't try
4832 series of Windows is such a piece of junk anyway that I won't try
4815 porting it there. The XP port was straightforward, showed a few
4833 porting it there. The XP port was straightforward, showed a few
4816 bugs here and there (fixed all), in particular some string
4834 bugs here and there (fixed all), in particular some string
4817 handling stuff which required considering Unicode strings (which
4835 handling stuff which required considering Unicode strings (which
4818 Windows uses). This is good, but hasn't been too tested :) No
4836 Windows uses). This is good, but hasn't been too tested :) No
4819 fancy installer yet, I'll put a note in the manual so people at
4837 fancy installer yet, I'll put a note in the manual so people at
4820 least make manually a shortcut.
4838 least make manually a shortcut.
4821
4839
4822 * IPython/iplib.py (Magic.magic_colors): Unified the color options
4840 * IPython/iplib.py (Magic.magic_colors): Unified the color options
4823 into a single one, "colors". This now controls both prompt and
4841 into a single one, "colors". This now controls both prompt and
4824 exception color schemes, and can be changed both at startup
4842 exception color schemes, and can be changed both at startup
4825 (either via command-line switches or via ipythonrc files) and at
4843 (either via command-line switches or via ipythonrc files) and at
4826 runtime, with @colors.
4844 runtime, with @colors.
4827 (Magic.magic_run): renamed @prun to @run and removed the old
4845 (Magic.magic_run): renamed @prun to @run and removed the old
4828 @run. The two were too similar to warrant keeping both.
4846 @run. The two were too similar to warrant keeping both.
4829
4847
4830 2002-02-03 Fernando Perez <fperez@colorado.edu>
4848 2002-02-03 Fernando Perez <fperez@colorado.edu>
4831
4849
4832 * IPython/iplib.py (install_first_time): Added comment on how to
4850 * IPython/iplib.py (install_first_time): Added comment on how to
4833 configure the color options for first-time users. Put a <return>
4851 configure the color options for first-time users. Put a <return>
4834 request at the end so that small-terminal users get a chance to
4852 request at the end so that small-terminal users get a chance to
4835 read the startup info.
4853 read the startup info.
4836
4854
4837 2002-01-23 Fernando Perez <fperez@colorado.edu>
4855 2002-01-23 Fernando Perez <fperez@colorado.edu>
4838
4856
4839 * IPython/iplib.py (CachedOutput.update): Changed output memory
4857 * IPython/iplib.py (CachedOutput.update): Changed output memory
4840 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
4858 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
4841 input history we still use _i. Did this b/c these variable are
4859 input history we still use _i. Did this b/c these variable are
4842 very commonly used in interactive work, so the less we need to
4860 very commonly used in interactive work, so the less we need to
4843 type the better off we are.
4861 type the better off we are.
4844 (Magic.magic_prun): updated @prun to better handle the namespaces
4862 (Magic.magic_prun): updated @prun to better handle the namespaces
4845 the file will run in, including a fix for __name__ not being set
4863 the file will run in, including a fix for __name__ not being set
4846 before.
4864 before.
4847
4865
4848 2002-01-20 Fernando Perez <fperez@colorado.edu>
4866 2002-01-20 Fernando Perez <fperez@colorado.edu>
4849
4867
4850 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
4868 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
4851 extra garbage for Python 2.2. Need to look more carefully into
4869 extra garbage for Python 2.2. Need to look more carefully into
4852 this later.
4870 this later.
4853
4871
4854 2002-01-19 Fernando Perez <fperez@colorado.edu>
4872 2002-01-19 Fernando Perez <fperez@colorado.edu>
4855
4873
4856 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
4874 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
4857 display SyntaxError exceptions properly formatted when they occur
4875 display SyntaxError exceptions properly formatted when they occur
4858 (they can be triggered by imported code).
4876 (they can be triggered by imported code).
4859
4877
4860 2002-01-18 Fernando Perez <fperez@colorado.edu>
4878 2002-01-18 Fernando Perez <fperez@colorado.edu>
4861
4879
4862 * IPython/iplib.py (InteractiveShell.safe_execfile): now
4880 * IPython/iplib.py (InteractiveShell.safe_execfile): now
4863 SyntaxError exceptions are reported nicely formatted, instead of
4881 SyntaxError exceptions are reported nicely formatted, instead of
4864 spitting out only offset information as before.
4882 spitting out only offset information as before.
4865 (Magic.magic_prun): Added the @prun function for executing
4883 (Magic.magic_prun): Added the @prun function for executing
4866 programs with command line args inside IPython.
4884 programs with command line args inside IPython.
4867
4885
4868 2002-01-16 Fernando Perez <fperez@colorado.edu>
4886 2002-01-16 Fernando Perez <fperez@colorado.edu>
4869
4887
4870 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
4888 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
4871 to *not* include the last item given in a range. This brings their
4889 to *not* include the last item given in a range. This brings their
4872 behavior in line with Python's slicing:
4890 behavior in line with Python's slicing:
4873 a[n1:n2] -> a[n1]...a[n2-1]
4891 a[n1:n2] -> a[n1]...a[n2-1]
4874 It may be a bit less convenient, but I prefer to stick to Python's
4892 It may be a bit less convenient, but I prefer to stick to Python's
4875 conventions *everywhere*, so users never have to wonder.
4893 conventions *everywhere*, so users never have to wonder.
4876 (Magic.magic_macro): Added @macro function to ease the creation of
4894 (Magic.magic_macro): Added @macro function to ease the creation of
4877 macros.
4895 macros.
4878
4896
4879 2002-01-05 Fernando Perez <fperez@colorado.edu>
4897 2002-01-05 Fernando Perez <fperez@colorado.edu>
4880
4898
4881 * Released 0.2.4.
4899 * Released 0.2.4.
4882
4900
4883 * IPython/iplib.py (Magic.magic_pdef):
4901 * IPython/iplib.py (Magic.magic_pdef):
4884 (InteractiveShell.safe_execfile): report magic lines and error
4902 (InteractiveShell.safe_execfile): report magic lines and error
4885 lines without line numbers so one can easily copy/paste them for
4903 lines without line numbers so one can easily copy/paste them for
4886 re-execution.
4904 re-execution.
4887
4905
4888 * Updated manual with recent changes.
4906 * Updated manual with recent changes.
4889
4907
4890 * IPython/iplib.py (Magic.magic_oinfo): added constructor
4908 * IPython/iplib.py (Magic.magic_oinfo): added constructor
4891 docstring printing when class? is called. Very handy for knowing
4909 docstring printing when class? is called. Very handy for knowing
4892 how to create class instances (as long as __init__ is well
4910 how to create class instances (as long as __init__ is well
4893 documented, of course :)
4911 documented, of course :)
4894 (Magic.magic_doc): print both class and constructor docstrings.
4912 (Magic.magic_doc): print both class and constructor docstrings.
4895 (Magic.magic_pdef): give constructor info if passed a class and
4913 (Magic.magic_pdef): give constructor info if passed a class and
4896 __call__ info for callable object instances.
4914 __call__ info for callable object instances.
4897
4915
4898 2002-01-04 Fernando Perez <fperez@colorado.edu>
4916 2002-01-04 Fernando Perez <fperez@colorado.edu>
4899
4917
4900 * Made deep_reload() off by default. It doesn't always work
4918 * Made deep_reload() off by default. It doesn't always work
4901 exactly as intended, so it's probably safer to have it off. It's
4919 exactly as intended, so it's probably safer to have it off. It's
4902 still available as dreload() anyway, so nothing is lost.
4920 still available as dreload() anyway, so nothing is lost.
4903
4921
4904 2002-01-02 Fernando Perez <fperez@colorado.edu>
4922 2002-01-02 Fernando Perez <fperez@colorado.edu>
4905
4923
4906 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
4924 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
4907 so I wanted an updated release).
4925 so I wanted an updated release).
4908
4926
4909 2001-12-27 Fernando Perez <fperez@colorado.edu>
4927 2001-12-27 Fernando Perez <fperez@colorado.edu>
4910
4928
4911 * IPython/iplib.py (InteractiveShell.interact): Added the original
4929 * IPython/iplib.py (InteractiveShell.interact): Added the original
4912 code from 'code.py' for this module in order to change the
4930 code from 'code.py' for this module in order to change the
4913 handling of a KeyboardInterrupt. This was necessary b/c otherwise
4931 handling of a KeyboardInterrupt. This was necessary b/c otherwise
4914 the history cache would break when the user hit Ctrl-C, and
4932 the history cache would break when the user hit Ctrl-C, and
4915 interact() offers no way to add any hooks to it.
4933 interact() offers no way to add any hooks to it.
4916
4934
4917 2001-12-23 Fernando Perez <fperez@colorado.edu>
4935 2001-12-23 Fernando Perez <fperez@colorado.edu>
4918
4936
4919 * setup.py: added check for 'MANIFEST' before trying to remove
4937 * setup.py: added check for 'MANIFEST' before trying to remove
4920 it. Thanks to Sean Reifschneider.
4938 it. Thanks to Sean Reifschneider.
4921
4939
4922 2001-12-22 Fernando Perez <fperez@colorado.edu>
4940 2001-12-22 Fernando Perez <fperez@colorado.edu>
4923
4941
4924 * Released 0.2.2.
4942 * Released 0.2.2.
4925
4943
4926 * Finished (reasonably) writing the manual. Later will add the
4944 * Finished (reasonably) writing the manual. Later will add the
4927 python-standard navigation stylesheets, but for the time being
4945 python-standard navigation stylesheets, but for the time being
4928 it's fairly complete. Distribution will include html and pdf
4946 it's fairly complete. Distribution will include html and pdf
4929 versions.
4947 versions.
4930
4948
4931 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
4949 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
4932 (MayaVi author).
4950 (MayaVi author).
4933
4951
4934 2001-12-21 Fernando Perez <fperez@colorado.edu>
4952 2001-12-21 Fernando Perez <fperez@colorado.edu>
4935
4953
4936 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
4954 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
4937 good public release, I think (with the manual and the distutils
4955 good public release, I think (with the manual and the distutils
4938 installer). The manual can use some work, but that can go
4956 installer). The manual can use some work, but that can go
4939 slowly. Otherwise I think it's quite nice for end users. Next
4957 slowly. Otherwise I think it's quite nice for end users. Next
4940 summer, rewrite the guts of it...
4958 summer, rewrite the guts of it...
4941
4959
4942 * Changed format of ipythonrc files to use whitespace as the
4960 * Changed format of ipythonrc files to use whitespace as the
4943 separator instead of an explicit '='. Cleaner.
4961 separator instead of an explicit '='. Cleaner.
4944
4962
4945 2001-12-20 Fernando Perez <fperez@colorado.edu>
4963 2001-12-20 Fernando Perez <fperez@colorado.edu>
4946
4964
4947 * Started a manual in LyX. For now it's just a quick merge of the
4965 * Started a manual in LyX. For now it's just a quick merge of the
4948 various internal docstrings and READMEs. Later it may grow into a
4966 various internal docstrings and READMEs. Later it may grow into a
4949 nice, full-blown manual.
4967 nice, full-blown manual.
4950
4968
4951 * Set up a distutils based installer. Installation should now be
4969 * Set up a distutils based installer. Installation should now be
4952 trivially simple for end-users.
4970 trivially simple for end-users.
4953
4971
4954 2001-12-11 Fernando Perez <fperez@colorado.edu>
4972 2001-12-11 Fernando Perez <fperez@colorado.edu>
4955
4973
4956 * Released 0.2.0. First public release, announced it at
4974 * Released 0.2.0. First public release, announced it at
4957 comp.lang.python. From now on, just bugfixes...
4975 comp.lang.python. From now on, just bugfixes...
4958
4976
4959 * Went through all the files, set copyright/license notices and
4977 * Went through all the files, set copyright/license notices and
4960 cleaned up things. Ready for release.
4978 cleaned up things. Ready for release.
4961
4979
4962 2001-12-10 Fernando Perez <fperez@colorado.edu>
4980 2001-12-10 Fernando Perez <fperez@colorado.edu>
4963
4981
4964 * Changed the first-time installer not to use tarfiles. It's more
4982 * Changed the first-time installer not to use tarfiles. It's more
4965 robust now and less unix-dependent. Also makes it easier for
4983 robust now and less unix-dependent. Also makes it easier for
4966 people to later upgrade versions.
4984 people to later upgrade versions.
4967
4985
4968 * Changed @exit to @abort to reflect the fact that it's pretty
4986 * Changed @exit to @abort to reflect the fact that it's pretty
4969 brutal (a sys.exit()). The difference between @abort and Ctrl-D
4987 brutal (a sys.exit()). The difference between @abort and Ctrl-D
4970 becomes significant only when IPyhton is embedded: in that case,
4988 becomes significant only when IPyhton is embedded: in that case,
4971 C-D closes IPython only, but @abort kills the enclosing program
4989 C-D closes IPython only, but @abort kills the enclosing program
4972 too (unless it had called IPython inside a try catching
4990 too (unless it had called IPython inside a try catching
4973 SystemExit).
4991 SystemExit).
4974
4992
4975 * Created Shell module which exposes the actuall IPython Shell
4993 * Created Shell module which exposes the actuall IPython Shell
4976 classes, currently the normal and the embeddable one. This at
4994 classes, currently the normal and the embeddable one. This at
4977 least offers a stable interface we won't need to change when
4995 least offers a stable interface we won't need to change when
4978 (later) the internals are rewritten. That rewrite will be confined
4996 (later) the internals are rewritten. That rewrite will be confined
4979 to iplib and ipmaker, but the Shell interface should remain as is.
4997 to iplib and ipmaker, but the Shell interface should remain as is.
4980
4998
4981 * Added embed module which offers an embeddable IPShell object,
4999 * Added embed module which offers an embeddable IPShell object,
4982 useful to fire up IPython *inside* a running program. Great for
5000 useful to fire up IPython *inside* a running program. Great for
4983 debugging or dynamical data analysis.
5001 debugging or dynamical data analysis.
4984
5002
4985 2001-12-08 Fernando Perez <fperez@colorado.edu>
5003 2001-12-08 Fernando Perez <fperez@colorado.edu>
4986
5004
4987 * Fixed small bug preventing seeing info from methods of defined
5005 * Fixed small bug preventing seeing info from methods of defined
4988 objects (incorrect namespace in _ofind()).
5006 objects (incorrect namespace in _ofind()).
4989
5007
4990 * Documentation cleanup. Moved the main usage docstrings to a
5008 * Documentation cleanup. Moved the main usage docstrings to a
4991 separate file, usage.py (cleaner to maintain, and hopefully in the
5009 separate file, usage.py (cleaner to maintain, and hopefully in the
4992 future some perlpod-like way of producing interactive, man and
5010 future some perlpod-like way of producing interactive, man and
4993 html docs out of it will be found).
5011 html docs out of it will be found).
4994
5012
4995 * Added @profile to see your profile at any time.
5013 * Added @profile to see your profile at any time.
4996
5014
4997 * Added @p as an alias for 'print'. It's especially convenient if
5015 * Added @p as an alias for 'print'. It's especially convenient if
4998 using automagic ('p x' prints x).
5016 using automagic ('p x' prints x).
4999
5017
5000 * Small cleanups and fixes after a pychecker run.
5018 * Small cleanups and fixes after a pychecker run.
5001
5019
5002 * Changed the @cd command to handle @cd - and @cd -<n> for
5020 * Changed the @cd command to handle @cd - and @cd -<n> for
5003 visiting any directory in _dh.
5021 visiting any directory in _dh.
5004
5022
5005 * Introduced _dh, a history of visited directories. @dhist prints
5023 * Introduced _dh, a history of visited directories. @dhist prints
5006 it out with numbers.
5024 it out with numbers.
5007
5025
5008 2001-12-07 Fernando Perez <fperez@colorado.edu>
5026 2001-12-07 Fernando Perez <fperez@colorado.edu>
5009
5027
5010 * Released 0.1.22
5028 * Released 0.1.22
5011
5029
5012 * Made initialization a bit more robust against invalid color
5030 * Made initialization a bit more robust against invalid color
5013 options in user input (exit, not traceback-crash).
5031 options in user input (exit, not traceback-crash).
5014
5032
5015 * Changed the bug crash reporter to write the report only in the
5033 * Changed the bug crash reporter to write the report only in the
5016 user's .ipython directory. That way IPython won't litter people's
5034 user's .ipython directory. That way IPython won't litter people's
5017 hard disks with crash files all over the place. Also print on
5035 hard disks with crash files all over the place. Also print on
5018 screen the necessary mail command.
5036 screen the necessary mail command.
5019
5037
5020 * With the new ultraTB, implemented LightBG color scheme for light
5038 * With the new ultraTB, implemented LightBG color scheme for light
5021 background terminals. A lot of people like white backgrounds, so I
5039 background terminals. A lot of people like white backgrounds, so I
5022 guess we should at least give them something readable.
5040 guess we should at least give them something readable.
5023
5041
5024 2001-12-06 Fernando Perez <fperez@colorado.edu>
5042 2001-12-06 Fernando Perez <fperez@colorado.edu>
5025
5043
5026 * Modified the structure of ultraTB. Now there's a proper class
5044 * Modified the structure of ultraTB. Now there's a proper class
5027 for tables of color schemes which allow adding schemes easily and
5045 for tables of color schemes which allow adding schemes easily and
5028 switching the active scheme without creating a new instance every
5046 switching the active scheme without creating a new instance every
5029 time (which was ridiculous). The syntax for creating new schemes
5047 time (which was ridiculous). The syntax for creating new schemes
5030 is also cleaner. I think ultraTB is finally done, with a clean
5048 is also cleaner. I think ultraTB is finally done, with a clean
5031 class structure. Names are also much cleaner (now there's proper
5049 class structure. Names are also much cleaner (now there's proper
5032 color tables, no need for every variable to also have 'color' in
5050 color tables, no need for every variable to also have 'color' in
5033 its name).
5051 its name).
5034
5052
5035 * Broke down genutils into separate files. Now genutils only
5053 * Broke down genutils into separate files. Now genutils only
5036 contains utility functions, and classes have been moved to their
5054 contains utility functions, and classes have been moved to their
5037 own files (they had enough independent functionality to warrant
5055 own files (they had enough independent functionality to warrant
5038 it): ConfigLoader, OutputTrap, Struct.
5056 it): ConfigLoader, OutputTrap, Struct.
5039
5057
5040 2001-12-05 Fernando Perez <fperez@colorado.edu>
5058 2001-12-05 Fernando Perez <fperez@colorado.edu>
5041
5059
5042 * IPython turns 21! Released version 0.1.21, as a candidate for
5060 * IPython turns 21! Released version 0.1.21, as a candidate for
5043 public consumption. If all goes well, release in a few days.
5061 public consumption. If all goes well, release in a few days.
5044
5062
5045 * Fixed path bug (files in Extensions/ directory wouldn't be found
5063 * Fixed path bug (files in Extensions/ directory wouldn't be found
5046 unless IPython/ was explicitly in sys.path).
5064 unless IPython/ was explicitly in sys.path).
5047
5065
5048 * Extended the FlexCompleter class as MagicCompleter to allow
5066 * Extended the FlexCompleter class as MagicCompleter to allow
5049 completion of @-starting lines.
5067 completion of @-starting lines.
5050
5068
5051 * Created __release__.py file as a central repository for release
5069 * Created __release__.py file as a central repository for release
5052 info that other files can read from.
5070 info that other files can read from.
5053
5071
5054 * Fixed small bug in logging: when logging was turned on in
5072 * Fixed small bug in logging: when logging was turned on in
5055 mid-session, old lines with special meanings (!@?) were being
5073 mid-session, old lines with special meanings (!@?) were being
5056 logged without the prepended comment, which is necessary since
5074 logged without the prepended comment, which is necessary since
5057 they are not truly valid python syntax. This should make session
5075 they are not truly valid python syntax. This should make session
5058 restores produce less errors.
5076 restores produce less errors.
5059
5077
5060 * The namespace cleanup forced me to make a FlexCompleter class
5078 * The namespace cleanup forced me to make a FlexCompleter class
5061 which is nothing but a ripoff of rlcompleter, but with selectable
5079 which is nothing but a ripoff of rlcompleter, but with selectable
5062 namespace (rlcompleter only works in __main__.__dict__). I'll try
5080 namespace (rlcompleter only works in __main__.__dict__). I'll try
5063 to submit a note to the authors to see if this change can be
5081 to submit a note to the authors to see if this change can be
5064 incorporated in future rlcompleter releases (Dec.6: done)
5082 incorporated in future rlcompleter releases (Dec.6: done)
5065
5083
5066 * More fixes to namespace handling. It was a mess! Now all
5084 * More fixes to namespace handling. It was a mess! Now all
5067 explicit references to __main__.__dict__ are gone (except when
5085 explicit references to __main__.__dict__ are gone (except when
5068 really needed) and everything is handled through the namespace
5086 really needed) and everything is handled through the namespace
5069 dicts in the IPython instance. We seem to be getting somewhere
5087 dicts in the IPython instance. We seem to be getting somewhere
5070 with this, finally...
5088 with this, finally...
5071
5089
5072 * Small documentation updates.
5090 * Small documentation updates.
5073
5091
5074 * Created the Extensions directory under IPython (with an
5092 * Created the Extensions directory under IPython (with an
5075 __init__.py). Put the PhysicalQ stuff there. This directory should
5093 __init__.py). Put the PhysicalQ stuff there. This directory should
5076 be used for all special-purpose extensions.
5094 be used for all special-purpose extensions.
5077
5095
5078 * File renaming:
5096 * File renaming:
5079 ipythonlib --> ipmaker
5097 ipythonlib --> ipmaker
5080 ipplib --> iplib
5098 ipplib --> iplib
5081 This makes a bit more sense in terms of what these files actually do.
5099 This makes a bit more sense in terms of what these files actually do.
5082
5100
5083 * Moved all the classes and functions in ipythonlib to ipplib, so
5101 * Moved all the classes and functions in ipythonlib to ipplib, so
5084 now ipythonlib only has make_IPython(). This will ease up its
5102 now ipythonlib only has make_IPython(). This will ease up its
5085 splitting in smaller functional chunks later.
5103 splitting in smaller functional chunks later.
5086
5104
5087 * Cleaned up (done, I think) output of @whos. Better column
5105 * Cleaned up (done, I think) output of @whos. Better column
5088 formatting, and now shows str(var) for as much as it can, which is
5106 formatting, and now shows str(var) for as much as it can, which is
5089 typically what one gets with a 'print var'.
5107 typically what one gets with a 'print var'.
5090
5108
5091 2001-12-04 Fernando Perez <fperez@colorado.edu>
5109 2001-12-04 Fernando Perez <fperez@colorado.edu>
5092
5110
5093 * Fixed namespace problems. Now builtin/IPyhton/user names get
5111 * Fixed namespace problems. Now builtin/IPyhton/user names get
5094 properly reported in their namespace. Internal namespace handling
5112 properly reported in their namespace. Internal namespace handling
5095 is finally getting decent (not perfect yet, but much better than
5113 is finally getting decent (not perfect yet, but much better than
5096 the ad-hoc mess we had).
5114 the ad-hoc mess we had).
5097
5115
5098 * Removed -exit option. If people just want to run a python
5116 * Removed -exit option. If people just want to run a python
5099 script, that's what the normal interpreter is for. Less
5117 script, that's what the normal interpreter is for. Less
5100 unnecessary options, less chances for bugs.
5118 unnecessary options, less chances for bugs.
5101
5119
5102 * Added a crash handler which generates a complete post-mortem if
5120 * Added a crash handler which generates a complete post-mortem if
5103 IPython crashes. This will help a lot in tracking bugs down the
5121 IPython crashes. This will help a lot in tracking bugs down the
5104 road.
5122 road.
5105
5123
5106 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
5124 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
5107 which were boud to functions being reassigned would bypass the
5125 which were boud to functions being reassigned would bypass the
5108 logger, breaking the sync of _il with the prompt counter. This
5126 logger, breaking the sync of _il with the prompt counter. This
5109 would then crash IPython later when a new line was logged.
5127 would then crash IPython later when a new line was logged.
5110
5128
5111 2001-12-02 Fernando Perez <fperez@colorado.edu>
5129 2001-12-02 Fernando Perez <fperez@colorado.edu>
5112
5130
5113 * Made IPython a package. This means people don't have to clutter
5131 * Made IPython a package. This means people don't have to clutter
5114 their sys.path with yet another directory. Changed the INSTALL
5132 their sys.path with yet another directory. Changed the INSTALL
5115 file accordingly.
5133 file accordingly.
5116
5134
5117 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
5135 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
5118 sorts its output (so @who shows it sorted) and @whos formats the
5136 sorts its output (so @who shows it sorted) and @whos formats the
5119 table according to the width of the first column. Nicer, easier to
5137 table according to the width of the first column. Nicer, easier to
5120 read. Todo: write a generic table_format() which takes a list of
5138 read. Todo: write a generic table_format() which takes a list of
5121 lists and prints it nicely formatted, with optional row/column
5139 lists and prints it nicely formatted, with optional row/column
5122 separators and proper padding and justification.
5140 separators and proper padding and justification.
5123
5141
5124 * Released 0.1.20
5142 * Released 0.1.20
5125
5143
5126 * Fixed bug in @log which would reverse the inputcache list (a
5144 * Fixed bug in @log which would reverse the inputcache list (a
5127 copy operation was missing).
5145 copy operation was missing).
5128
5146
5129 * Code cleanup. @config was changed to use page(). Better, since
5147 * Code cleanup. @config was changed to use page(). Better, since
5130 its output is always quite long.
5148 its output is always quite long.
5131
5149
5132 * Itpl is back as a dependency. I was having too many problems
5150 * Itpl is back as a dependency. I was having too many problems
5133 getting the parametric aliases to work reliably, and it's just
5151 getting the parametric aliases to work reliably, and it's just
5134 easier to code weird string operations with it than playing %()s
5152 easier to code weird string operations with it than playing %()s
5135 games. It's only ~6k, so I don't think it's too big a deal.
5153 games. It's only ~6k, so I don't think it's too big a deal.
5136
5154
5137 * Found (and fixed) a very nasty bug with history. !lines weren't
5155 * Found (and fixed) a very nasty bug with history. !lines weren't
5138 getting cached, and the out of sync caches would crash
5156 getting cached, and the out of sync caches would crash
5139 IPython. Fixed it by reorganizing the prefilter/handlers/logger
5157 IPython. Fixed it by reorganizing the prefilter/handlers/logger
5140 division of labor a bit better. Bug fixed, cleaner structure.
5158 division of labor a bit better. Bug fixed, cleaner structure.
5141
5159
5142 2001-12-01 Fernando Perez <fperez@colorado.edu>
5160 2001-12-01 Fernando Perez <fperez@colorado.edu>
5143
5161
5144 * Released 0.1.19
5162 * Released 0.1.19
5145
5163
5146 * Added option -n to @hist to prevent line number printing. Much
5164 * Added option -n to @hist to prevent line number printing. Much
5147 easier to copy/paste code this way.
5165 easier to copy/paste code this way.
5148
5166
5149 * Created global _il to hold the input list. Allows easy
5167 * Created global _il to hold the input list. Allows easy
5150 re-execution of blocks of code by slicing it (inspired by Janko's
5168 re-execution of blocks of code by slicing it (inspired by Janko's
5151 comment on 'macros').
5169 comment on 'macros').
5152
5170
5153 * Small fixes and doc updates.
5171 * Small fixes and doc updates.
5154
5172
5155 * Rewrote @history function (was @h). Renamed it to @hist, @h is
5173 * Rewrote @history function (was @h). Renamed it to @hist, @h is
5156 much too fragile with automagic. Handles properly multi-line
5174 much too fragile with automagic. Handles properly multi-line
5157 statements and takes parameters.
5175 statements and takes parameters.
5158
5176
5159 2001-11-30 Fernando Perez <fperez@colorado.edu>
5177 2001-11-30 Fernando Perez <fperez@colorado.edu>
5160
5178
5161 * Version 0.1.18 released.
5179 * Version 0.1.18 released.
5162
5180
5163 * Fixed nasty namespace bug in initial module imports.
5181 * Fixed nasty namespace bug in initial module imports.
5164
5182
5165 * Added copyright/license notes to all code files (except
5183 * Added copyright/license notes to all code files (except
5166 DPyGetOpt). For the time being, LGPL. That could change.
5184 DPyGetOpt). For the time being, LGPL. That could change.
5167
5185
5168 * Rewrote a much nicer README, updated INSTALL, cleaned up
5186 * Rewrote a much nicer README, updated INSTALL, cleaned up
5169 ipythonrc-* samples.
5187 ipythonrc-* samples.
5170
5188
5171 * Overall code/documentation cleanup. Basically ready for
5189 * Overall code/documentation cleanup. Basically ready for
5172 release. Only remaining thing: licence decision (LGPL?).
5190 release. Only remaining thing: licence decision (LGPL?).
5173
5191
5174 * Converted load_config to a class, ConfigLoader. Now recursion
5192 * Converted load_config to a class, ConfigLoader. Now recursion
5175 control is better organized. Doesn't include the same file twice.
5193 control is better organized. Doesn't include the same file twice.
5176
5194
5177 2001-11-29 Fernando Perez <fperez@colorado.edu>
5195 2001-11-29 Fernando Perez <fperez@colorado.edu>
5178
5196
5179 * Got input history working. Changed output history variables from
5197 * Got input history working. Changed output history variables from
5180 _p to _o so that _i is for input and _o for output. Just cleaner
5198 _p to _o so that _i is for input and _o for output. Just cleaner
5181 convention.
5199 convention.
5182
5200
5183 * Implemented parametric aliases. This pretty much allows the
5201 * Implemented parametric aliases. This pretty much allows the
5184 alias system to offer full-blown shell convenience, I think.
5202 alias system to offer full-blown shell convenience, I think.
5185
5203
5186 * Version 0.1.17 released, 0.1.18 opened.
5204 * Version 0.1.17 released, 0.1.18 opened.
5187
5205
5188 * dot_ipython/ipythonrc (alias): added documentation.
5206 * dot_ipython/ipythonrc (alias): added documentation.
5189 (xcolor): Fixed small bug (xcolors -> xcolor)
5207 (xcolor): Fixed small bug (xcolors -> xcolor)
5190
5208
5191 * Changed the alias system. Now alias is a magic command to define
5209 * Changed the alias system. Now alias is a magic command to define
5192 aliases just like the shell. Rationale: the builtin magics should
5210 aliases just like the shell. Rationale: the builtin magics should
5193 be there for things deeply connected to IPython's
5211 be there for things deeply connected to IPython's
5194 architecture. And this is a much lighter system for what I think
5212 architecture. And this is a much lighter system for what I think
5195 is the really important feature: allowing users to define quickly
5213 is the really important feature: allowing users to define quickly
5196 magics that will do shell things for them, so they can customize
5214 magics that will do shell things for them, so they can customize
5197 IPython easily to match their work habits. If someone is really
5215 IPython easily to match their work habits. If someone is really
5198 desperate to have another name for a builtin alias, they can
5216 desperate to have another name for a builtin alias, they can
5199 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
5217 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
5200 works.
5218 works.
5201
5219
5202 2001-11-28 Fernando Perez <fperez@colorado.edu>
5220 2001-11-28 Fernando Perez <fperez@colorado.edu>
5203
5221
5204 * Changed @file so that it opens the source file at the proper
5222 * Changed @file so that it opens the source file at the proper
5205 line. Since it uses less, if your EDITOR environment is
5223 line. Since it uses less, if your EDITOR environment is
5206 configured, typing v will immediately open your editor of choice
5224 configured, typing v will immediately open your editor of choice
5207 right at the line where the object is defined. Not as quick as
5225 right at the line where the object is defined. Not as quick as
5208 having a direct @edit command, but for all intents and purposes it
5226 having a direct @edit command, but for all intents and purposes it
5209 works. And I don't have to worry about writing @edit to deal with
5227 works. And I don't have to worry about writing @edit to deal with
5210 all the editors, less does that.
5228 all the editors, less does that.
5211
5229
5212 * Version 0.1.16 released, 0.1.17 opened.
5230 * Version 0.1.16 released, 0.1.17 opened.
5213
5231
5214 * Fixed some nasty bugs in the page/page_dumb combo that could
5232 * Fixed some nasty bugs in the page/page_dumb combo that could
5215 crash IPython.
5233 crash IPython.
5216
5234
5217 2001-11-27 Fernando Perez <fperez@colorado.edu>
5235 2001-11-27 Fernando Perez <fperez@colorado.edu>
5218
5236
5219 * Version 0.1.15 released, 0.1.16 opened.
5237 * Version 0.1.15 released, 0.1.16 opened.
5220
5238
5221 * Finally got ? and ?? to work for undefined things: now it's
5239 * Finally got ? and ?? to work for undefined things: now it's
5222 possible to type {}.get? and get information about the get method
5240 possible to type {}.get? and get information about the get method
5223 of dicts, or os.path? even if only os is defined (so technically
5241 of dicts, or os.path? even if only os is defined (so technically
5224 os.path isn't). Works at any level. For example, after import os,
5242 os.path isn't). Works at any level. For example, after import os,
5225 os?, os.path?, os.path.abspath? all work. This is great, took some
5243 os?, os.path?, os.path.abspath? all work. This is great, took some
5226 work in _ofind.
5244 work in _ofind.
5227
5245
5228 * Fixed more bugs with logging. The sanest way to do it was to add
5246 * Fixed more bugs with logging. The sanest way to do it was to add
5229 to @log a 'mode' parameter. Killed two in one shot (this mode
5247 to @log a 'mode' parameter. Killed two in one shot (this mode
5230 option was a request of Janko's). I think it's finally clean
5248 option was a request of Janko's). I think it's finally clean
5231 (famous last words).
5249 (famous last words).
5232
5250
5233 * Added a page_dumb() pager which does a decent job of paging on
5251 * Added a page_dumb() pager which does a decent job of paging on
5234 screen, if better things (like less) aren't available. One less
5252 screen, if better things (like less) aren't available. One less
5235 unix dependency (someday maybe somebody will port this to
5253 unix dependency (someday maybe somebody will port this to
5236 windows).
5254 windows).
5237
5255
5238 * Fixed problem in magic_log: would lock of logging out if log
5256 * Fixed problem in magic_log: would lock of logging out if log
5239 creation failed (because it would still think it had succeeded).
5257 creation failed (because it would still think it had succeeded).
5240
5258
5241 * Improved the page() function using curses to auto-detect screen
5259 * Improved the page() function using curses to auto-detect screen
5242 size. Now it can make a much better decision on whether to print
5260 size. Now it can make a much better decision on whether to print
5243 or page a string. Option screen_length was modified: a value 0
5261 or page a string. Option screen_length was modified: a value 0
5244 means auto-detect, and that's the default now.
5262 means auto-detect, and that's the default now.
5245
5263
5246 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
5264 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
5247 go out. I'll test it for a few days, then talk to Janko about
5265 go out. I'll test it for a few days, then talk to Janko about
5248 licences and announce it.
5266 licences and announce it.
5249
5267
5250 * Fixed the length of the auto-generated ---> prompt which appears
5268 * Fixed the length of the auto-generated ---> prompt which appears
5251 for auto-parens and auto-quotes. Getting this right isn't trivial,
5269 for auto-parens and auto-quotes. Getting this right isn't trivial,
5252 with all the color escapes, different prompt types and optional
5270 with all the color escapes, different prompt types and optional
5253 separators. But it seems to be working in all the combinations.
5271 separators. But it seems to be working in all the combinations.
5254
5272
5255 2001-11-26 Fernando Perez <fperez@colorado.edu>
5273 2001-11-26 Fernando Perez <fperez@colorado.edu>
5256
5274
5257 * Wrote a regexp filter to get option types from the option names
5275 * Wrote a regexp filter to get option types from the option names
5258 string. This eliminates the need to manually keep two duplicate
5276 string. This eliminates the need to manually keep two duplicate
5259 lists.
5277 lists.
5260
5278
5261 * Removed the unneeded check_option_names. Now options are handled
5279 * Removed the unneeded check_option_names. Now options are handled
5262 in a much saner manner and it's easy to visually check that things
5280 in a much saner manner and it's easy to visually check that things
5263 are ok.
5281 are ok.
5264
5282
5265 * Updated version numbers on all files I modified to carry a
5283 * Updated version numbers on all files I modified to carry a
5266 notice so Janko and Nathan have clear version markers.
5284 notice so Janko and Nathan have clear version markers.
5267
5285
5268 * Updated docstring for ultraTB with my changes. I should send
5286 * Updated docstring for ultraTB with my changes. I should send
5269 this to Nathan.
5287 this to Nathan.
5270
5288
5271 * Lots of small fixes. Ran everything through pychecker again.
5289 * Lots of small fixes. Ran everything through pychecker again.
5272
5290
5273 * Made loading of deep_reload an cmd line option. If it's not too
5291 * Made loading of deep_reload an cmd line option. If it's not too
5274 kosher, now people can just disable it. With -nodeep_reload it's
5292 kosher, now people can just disable it. With -nodeep_reload it's
5275 still available as dreload(), it just won't overwrite reload().
5293 still available as dreload(), it just won't overwrite reload().
5276
5294
5277 * Moved many options to the no| form (-opt and -noopt
5295 * Moved many options to the no| form (-opt and -noopt
5278 accepted). Cleaner.
5296 accepted). Cleaner.
5279
5297
5280 * Changed magic_log so that if called with no parameters, it uses
5298 * Changed magic_log so that if called with no parameters, it uses
5281 'rotate' mode. That way auto-generated logs aren't automatically
5299 'rotate' mode. That way auto-generated logs aren't automatically
5282 over-written. For normal logs, now a backup is made if it exists
5300 over-written. For normal logs, now a backup is made if it exists
5283 (only 1 level of backups). A new 'backup' mode was added to the
5301 (only 1 level of backups). A new 'backup' mode was added to the
5284 Logger class to support this. This was a request by Janko.
5302 Logger class to support this. This was a request by Janko.
5285
5303
5286 * Added @logoff/@logon to stop/restart an active log.
5304 * Added @logoff/@logon to stop/restart an active log.
5287
5305
5288 * Fixed a lot of bugs in log saving/replay. It was pretty
5306 * Fixed a lot of bugs in log saving/replay. It was pretty
5289 broken. Now special lines (!@,/) appear properly in the command
5307 broken. Now special lines (!@,/) appear properly in the command
5290 history after a log replay.
5308 history after a log replay.
5291
5309
5292 * Tried and failed to implement full session saving via pickle. My
5310 * Tried and failed to implement full session saving via pickle. My
5293 idea was to pickle __main__.__dict__, but modules can't be
5311 idea was to pickle __main__.__dict__, but modules can't be
5294 pickled. This would be a better alternative to replaying logs, but
5312 pickled. This would be a better alternative to replaying logs, but
5295 seems quite tricky to get to work. Changed -session to be called
5313 seems quite tricky to get to work. Changed -session to be called
5296 -logplay, which more accurately reflects what it does. And if we
5314 -logplay, which more accurately reflects what it does. And if we
5297 ever get real session saving working, -session is now available.
5315 ever get real session saving working, -session is now available.
5298
5316
5299 * Implemented color schemes for prompts also. As for tracebacks,
5317 * Implemented color schemes for prompts also. As for tracebacks,
5300 currently only NoColor and Linux are supported. But now the
5318 currently only NoColor and Linux are supported. But now the
5301 infrastructure is in place, based on a generic ColorScheme
5319 infrastructure is in place, based on a generic ColorScheme
5302 class. So writing and activating new schemes both for the prompts
5320 class. So writing and activating new schemes both for the prompts
5303 and the tracebacks should be straightforward.
5321 and the tracebacks should be straightforward.
5304
5322
5305 * Version 0.1.13 released, 0.1.14 opened.
5323 * Version 0.1.13 released, 0.1.14 opened.
5306
5324
5307 * Changed handling of options for output cache. Now counter is
5325 * Changed handling of options for output cache. Now counter is
5308 hardwired starting at 1 and one specifies the maximum number of
5326 hardwired starting at 1 and one specifies the maximum number of
5309 entries *in the outcache* (not the max prompt counter). This is
5327 entries *in the outcache* (not the max prompt counter). This is
5310 much better, since many statements won't increase the cache
5328 much better, since many statements won't increase the cache
5311 count. It also eliminated some confusing options, now there's only
5329 count. It also eliminated some confusing options, now there's only
5312 one: cache_size.
5330 one: cache_size.
5313
5331
5314 * Added 'alias' magic function and magic_alias option in the
5332 * Added 'alias' magic function and magic_alias option in the
5315 ipythonrc file. Now the user can easily define whatever names he
5333 ipythonrc file. Now the user can easily define whatever names he
5316 wants for the magic functions without having to play weird
5334 wants for the magic functions without having to play weird
5317 namespace games. This gives IPython a real shell-like feel.
5335 namespace games. This gives IPython a real shell-like feel.
5318
5336
5319 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
5337 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
5320 @ or not).
5338 @ or not).
5321
5339
5322 This was one of the last remaining 'visible' bugs (that I know
5340 This was one of the last remaining 'visible' bugs (that I know
5323 of). I think if I can clean up the session loading so it works
5341 of). I think if I can clean up the session loading so it works
5324 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
5342 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
5325 about licensing).
5343 about licensing).
5326
5344
5327 2001-11-25 Fernando Perez <fperez@colorado.edu>
5345 2001-11-25 Fernando Perez <fperez@colorado.edu>
5328
5346
5329 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
5347 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
5330 there's a cleaner distinction between what ? and ?? show.
5348 there's a cleaner distinction between what ? and ?? show.
5331
5349
5332 * Added screen_length option. Now the user can define his own
5350 * Added screen_length option. Now the user can define his own
5333 screen size for page() operations.
5351 screen size for page() operations.
5334
5352
5335 * Implemented magic shell-like functions with automatic code
5353 * Implemented magic shell-like functions with automatic code
5336 generation. Now adding another function is just a matter of adding
5354 generation. Now adding another function is just a matter of adding
5337 an entry to a dict, and the function is dynamically generated at
5355 an entry to a dict, and the function is dynamically generated at
5338 run-time. Python has some really cool features!
5356 run-time. Python has some really cool features!
5339
5357
5340 * Renamed many options to cleanup conventions a little. Now all
5358 * Renamed many options to cleanup conventions a little. Now all
5341 are lowercase, and only underscores where needed. Also in the code
5359 are lowercase, and only underscores where needed. Also in the code
5342 option name tables are clearer.
5360 option name tables are clearer.
5343
5361
5344 * Changed prompts a little. Now input is 'In [n]:' instead of
5362 * Changed prompts a little. Now input is 'In [n]:' instead of
5345 'In[n]:='. This allows it the numbers to be aligned with the
5363 'In[n]:='. This allows it the numbers to be aligned with the
5346 Out[n] numbers, and removes usage of ':=' which doesn't exist in
5364 Out[n] numbers, and removes usage of ':=' which doesn't exist in
5347 Python (it was a Mathematica thing). The '...' continuation prompt
5365 Python (it was a Mathematica thing). The '...' continuation prompt
5348 was also changed a little to align better.
5366 was also changed a little to align better.
5349
5367
5350 * Fixed bug when flushing output cache. Not all _p<n> variables
5368 * Fixed bug when flushing output cache. Not all _p<n> variables
5351 exist, so their deletion needs to be wrapped in a try:
5369 exist, so their deletion needs to be wrapped in a try:
5352
5370
5353 * Figured out how to properly use inspect.formatargspec() (it
5371 * Figured out how to properly use inspect.formatargspec() (it
5354 requires the args preceded by *). So I removed all the code from
5372 requires the args preceded by *). So I removed all the code from
5355 _get_pdef in Magic, which was just replicating that.
5373 _get_pdef in Magic, which was just replicating that.
5356
5374
5357 * Added test to prefilter to allow redefining magic function names
5375 * Added test to prefilter to allow redefining magic function names
5358 as variables. This is ok, since the @ form is always available,
5376 as variables. This is ok, since the @ form is always available,
5359 but whe should allow the user to define a variable called 'ls' if
5377 but whe should allow the user to define a variable called 'ls' if
5360 he needs it.
5378 he needs it.
5361
5379
5362 * Moved the ToDo information from README into a separate ToDo.
5380 * Moved the ToDo information from README into a separate ToDo.
5363
5381
5364 * General code cleanup and small bugfixes. I think it's close to a
5382 * General code cleanup and small bugfixes. I think it's close to a
5365 state where it can be released, obviously with a big 'beta'
5383 state where it can be released, obviously with a big 'beta'
5366 warning on it.
5384 warning on it.
5367
5385
5368 * Got the magic function split to work. Now all magics are defined
5386 * Got the magic function split to work. Now all magics are defined
5369 in a separate class. It just organizes things a bit, and now
5387 in a separate class. It just organizes things a bit, and now
5370 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
5388 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
5371 was too long).
5389 was too long).
5372
5390
5373 * Changed @clear to @reset to avoid potential confusions with
5391 * Changed @clear to @reset to avoid potential confusions with
5374 the shell command clear. Also renamed @cl to @clear, which does
5392 the shell command clear. Also renamed @cl to @clear, which does
5375 exactly what people expect it to from their shell experience.
5393 exactly what people expect it to from their shell experience.
5376
5394
5377 Added a check to the @reset command (since it's so
5395 Added a check to the @reset command (since it's so
5378 destructive, it's probably a good idea to ask for confirmation).
5396 destructive, it's probably a good idea to ask for confirmation).
5379 But now reset only works for full namespace resetting. Since the
5397 But now reset only works for full namespace resetting. Since the
5380 del keyword is already there for deleting a few specific
5398 del keyword is already there for deleting a few specific
5381 variables, I don't see the point of having a redundant magic
5399 variables, I don't see the point of having a redundant magic
5382 function for the same task.
5400 function for the same task.
5383
5401
5384 2001-11-24 Fernando Perez <fperez@colorado.edu>
5402 2001-11-24 Fernando Perez <fperez@colorado.edu>
5385
5403
5386 * Updated the builtin docs (esp. the ? ones).
5404 * Updated the builtin docs (esp. the ? ones).
5387
5405
5388 * Ran all the code through pychecker. Not terribly impressed with
5406 * Ran all the code through pychecker. Not terribly impressed with
5389 it: lots of spurious warnings and didn't really find anything of
5407 it: lots of spurious warnings and didn't really find anything of
5390 substance (just a few modules being imported and not used).
5408 substance (just a few modules being imported and not used).
5391
5409
5392 * Implemented the new ultraTB functionality into IPython. New
5410 * Implemented the new ultraTB functionality into IPython. New
5393 option: xcolors. This chooses color scheme. xmode now only selects
5411 option: xcolors. This chooses color scheme. xmode now only selects
5394 between Plain and Verbose. Better orthogonality.
5412 between Plain and Verbose. Better orthogonality.
5395
5413
5396 * Large rewrite of ultraTB. Much cleaner now, with a separation of
5414 * Large rewrite of ultraTB. Much cleaner now, with a separation of
5397 mode and color scheme for the exception handlers. Now it's
5415 mode and color scheme for the exception handlers. Now it's
5398 possible to have the verbose traceback with no coloring.
5416 possible to have the verbose traceback with no coloring.
5399
5417
5400 2001-11-23 Fernando Perez <fperez@colorado.edu>
5418 2001-11-23 Fernando Perez <fperez@colorado.edu>
5401
5419
5402 * Version 0.1.12 released, 0.1.13 opened.
5420 * Version 0.1.12 released, 0.1.13 opened.
5403
5421
5404 * Removed option to set auto-quote and auto-paren escapes by
5422 * Removed option to set auto-quote and auto-paren escapes by
5405 user. The chances of breaking valid syntax are just too high. If
5423 user. The chances of breaking valid syntax are just too high. If
5406 someone *really* wants, they can always dig into the code.
5424 someone *really* wants, they can always dig into the code.
5407
5425
5408 * Made prompt separators configurable.
5426 * Made prompt separators configurable.
5409
5427
5410 2001-11-22 Fernando Perez <fperez@colorado.edu>
5428 2001-11-22 Fernando Perez <fperez@colorado.edu>
5411
5429
5412 * Small bugfixes in many places.
5430 * Small bugfixes in many places.
5413
5431
5414 * Removed the MyCompleter class from ipplib. It seemed redundant
5432 * Removed the MyCompleter class from ipplib. It seemed redundant
5415 with the C-p,C-n history search functionality. Less code to
5433 with the C-p,C-n history search functionality. Less code to
5416 maintain.
5434 maintain.
5417
5435
5418 * Moved all the original ipython.py code into ipythonlib.py. Right
5436 * Moved all the original ipython.py code into ipythonlib.py. Right
5419 now it's just one big dump into a function called make_IPython, so
5437 now it's just one big dump into a function called make_IPython, so
5420 no real modularity has been gained. But at least it makes the
5438 no real modularity has been gained. But at least it makes the
5421 wrapper script tiny, and since ipythonlib is a module, it gets
5439 wrapper script tiny, and since ipythonlib is a module, it gets
5422 compiled and startup is much faster.
5440 compiled and startup is much faster.
5423
5441
5424 This is a reasobably 'deep' change, so we should test it for a
5442 This is a reasobably 'deep' change, so we should test it for a
5425 while without messing too much more with the code.
5443 while without messing too much more with the code.
5426
5444
5427 2001-11-21 Fernando Perez <fperez@colorado.edu>
5445 2001-11-21 Fernando Perez <fperez@colorado.edu>
5428
5446
5429 * Version 0.1.11 released, 0.1.12 opened for further work.
5447 * Version 0.1.11 released, 0.1.12 opened for further work.
5430
5448
5431 * Removed dependency on Itpl. It was only needed in one place. It
5449 * Removed dependency on Itpl. It was only needed in one place. It
5432 would be nice if this became part of python, though. It makes life
5450 would be nice if this became part of python, though. It makes life
5433 *a lot* easier in some cases.
5451 *a lot* easier in some cases.
5434
5452
5435 * Simplified the prefilter code a bit. Now all handlers are
5453 * Simplified the prefilter code a bit. Now all handlers are
5436 expected to explicitly return a value (at least a blank string).
5454 expected to explicitly return a value (at least a blank string).
5437
5455
5438 * Heavy edits in ipplib. Removed the help system altogether. Now
5456 * Heavy edits in ipplib. Removed the help system altogether. Now
5439 obj?/?? is used for inspecting objects, a magic @doc prints
5457 obj?/?? is used for inspecting objects, a magic @doc prints
5440 docstrings, and full-blown Python help is accessed via the 'help'
5458 docstrings, and full-blown Python help is accessed via the 'help'
5441 keyword. This cleans up a lot of code (less to maintain) and does
5459 keyword. This cleans up a lot of code (less to maintain) and does
5442 the job. Since 'help' is now a standard Python component, might as
5460 the job. Since 'help' is now a standard Python component, might as
5443 well use it and remove duplicate functionality.
5461 well use it and remove duplicate functionality.
5444
5462
5445 Also removed the option to use ipplib as a standalone program. By
5463 Also removed the option to use ipplib as a standalone program. By
5446 now it's too dependent on other parts of IPython to function alone.
5464 now it's too dependent on other parts of IPython to function alone.
5447
5465
5448 * Fixed bug in genutils.pager. It would crash if the pager was
5466 * Fixed bug in genutils.pager. It would crash if the pager was
5449 exited immediately after opening (broken pipe).
5467 exited immediately after opening (broken pipe).
5450
5468
5451 * Trimmed down the VerboseTB reporting a little. The header is
5469 * Trimmed down the VerboseTB reporting a little. The header is
5452 much shorter now and the repeated exception arguments at the end
5470 much shorter now and the repeated exception arguments at the end
5453 have been removed. For interactive use the old header seemed a bit
5471 have been removed. For interactive use the old header seemed a bit
5454 excessive.
5472 excessive.
5455
5473
5456 * Fixed small bug in output of @whos for variables with multi-word
5474 * Fixed small bug in output of @whos for variables with multi-word
5457 types (only first word was displayed).
5475 types (only first word was displayed).
5458
5476
5459 2001-11-17 Fernando Perez <fperez@colorado.edu>
5477 2001-11-17 Fernando Perez <fperez@colorado.edu>
5460
5478
5461 * Version 0.1.10 released, 0.1.11 opened for further work.
5479 * Version 0.1.10 released, 0.1.11 opened for further work.
5462
5480
5463 * Modified dirs and friends. dirs now *returns* the stack (not
5481 * Modified dirs and friends. dirs now *returns* the stack (not
5464 prints), so one can manipulate it as a variable. Convenient to
5482 prints), so one can manipulate it as a variable. Convenient to
5465 travel along many directories.
5483 travel along many directories.
5466
5484
5467 * Fixed bug in magic_pdef: would only work with functions with
5485 * Fixed bug in magic_pdef: would only work with functions with
5468 arguments with default values.
5486 arguments with default values.
5469
5487
5470 2001-11-14 Fernando Perez <fperez@colorado.edu>
5488 2001-11-14 Fernando Perez <fperez@colorado.edu>
5471
5489
5472 * Added the PhysicsInput stuff to dot_ipython so it ships as an
5490 * Added the PhysicsInput stuff to dot_ipython so it ships as an
5473 example with IPython. Various other minor fixes and cleanups.
5491 example with IPython. Various other minor fixes and cleanups.
5474
5492
5475 * Version 0.1.9 released, 0.1.10 opened for further work.
5493 * Version 0.1.9 released, 0.1.10 opened for further work.
5476
5494
5477 * Added sys.path to the list of directories searched in the
5495 * Added sys.path to the list of directories searched in the
5478 execfile= option. It used to be the current directory and the
5496 execfile= option. It used to be the current directory and the
5479 user's IPYTHONDIR only.
5497 user's IPYTHONDIR only.
5480
5498
5481 2001-11-13 Fernando Perez <fperez@colorado.edu>
5499 2001-11-13 Fernando Perez <fperez@colorado.edu>
5482
5500
5483 * Reinstated the raw_input/prefilter separation that Janko had
5501 * Reinstated the raw_input/prefilter separation that Janko had
5484 initially. This gives a more convenient setup for extending the
5502 initially. This gives a more convenient setup for extending the
5485 pre-processor from the outside: raw_input always gets a string,
5503 pre-processor from the outside: raw_input always gets a string,
5486 and prefilter has to process it. We can then redefine prefilter
5504 and prefilter has to process it. We can then redefine prefilter
5487 from the outside and implement extensions for special
5505 from the outside and implement extensions for special
5488 purposes.
5506 purposes.
5489
5507
5490 Today I got one for inputting PhysicalQuantity objects
5508 Today I got one for inputting PhysicalQuantity objects
5491 (from Scientific) without needing any function calls at
5509 (from Scientific) without needing any function calls at
5492 all. Extremely convenient, and it's all done as a user-level
5510 all. Extremely convenient, and it's all done as a user-level
5493 extension (no IPython code was touched). Now instead of:
5511 extension (no IPython code was touched). Now instead of:
5494 a = PhysicalQuantity(4.2,'m/s**2')
5512 a = PhysicalQuantity(4.2,'m/s**2')
5495 one can simply say
5513 one can simply say
5496 a = 4.2 m/s**2
5514 a = 4.2 m/s**2
5497 or even
5515 or even
5498 a = 4.2 m/s^2
5516 a = 4.2 m/s^2
5499
5517
5500 I use this, but it's also a proof of concept: IPython really is
5518 I use this, but it's also a proof of concept: IPython really is
5501 fully user-extensible, even at the level of the parsing of the
5519 fully user-extensible, even at the level of the parsing of the
5502 command line. It's not trivial, but it's perfectly doable.
5520 command line. It's not trivial, but it's perfectly doable.
5503
5521
5504 * Added 'add_flip' method to inclusion conflict resolver. Fixes
5522 * Added 'add_flip' method to inclusion conflict resolver. Fixes
5505 the problem of modules being loaded in the inverse order in which
5523 the problem of modules being loaded in the inverse order in which
5506 they were defined in
5524 they were defined in
5507
5525
5508 * Version 0.1.8 released, 0.1.9 opened for further work.
5526 * Version 0.1.8 released, 0.1.9 opened for further work.
5509
5527
5510 * Added magics pdef, source and file. They respectively show the
5528 * Added magics pdef, source and file. They respectively show the
5511 definition line ('prototype' in C), source code and full python
5529 definition line ('prototype' in C), source code and full python
5512 file for any callable object. The object inspector oinfo uses
5530 file for any callable object. The object inspector oinfo uses
5513 these to show the same information.
5531 these to show the same information.
5514
5532
5515 * Version 0.1.7 released, 0.1.8 opened for further work.
5533 * Version 0.1.7 released, 0.1.8 opened for further work.
5516
5534
5517 * Separated all the magic functions into a class called Magic. The
5535 * Separated all the magic functions into a class called Magic. The
5518 InteractiveShell class was becoming too big for Xemacs to handle
5536 InteractiveShell class was becoming too big for Xemacs to handle
5519 (de-indenting a line would lock it up for 10 seconds while it
5537 (de-indenting a line would lock it up for 10 seconds while it
5520 backtracked on the whole class!)
5538 backtracked on the whole class!)
5521
5539
5522 FIXME: didn't work. It can be done, but right now namespaces are
5540 FIXME: didn't work. It can be done, but right now namespaces are
5523 all messed up. Do it later (reverted it for now, so at least
5541 all messed up. Do it later (reverted it for now, so at least
5524 everything works as before).
5542 everything works as before).
5525
5543
5526 * Got the object introspection system (magic_oinfo) working! I
5544 * Got the object introspection system (magic_oinfo) working! I
5527 think this is pretty much ready for release to Janko, so he can
5545 think this is pretty much ready for release to Janko, so he can
5528 test it for a while and then announce it. Pretty much 100% of what
5546 test it for a while and then announce it. Pretty much 100% of what
5529 I wanted for the 'phase 1' release is ready. Happy, tired.
5547 I wanted for the 'phase 1' release is ready. Happy, tired.
5530
5548
5531 2001-11-12 Fernando Perez <fperez@colorado.edu>
5549 2001-11-12 Fernando Perez <fperez@colorado.edu>
5532
5550
5533 * Version 0.1.6 released, 0.1.7 opened for further work.
5551 * Version 0.1.6 released, 0.1.7 opened for further work.
5534
5552
5535 * Fixed bug in printing: it used to test for truth before
5553 * Fixed bug in printing: it used to test for truth before
5536 printing, so 0 wouldn't print. Now checks for None.
5554 printing, so 0 wouldn't print. Now checks for None.
5537
5555
5538 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
5556 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
5539 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
5557 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
5540 reaches by hand into the outputcache. Think of a better way to do
5558 reaches by hand into the outputcache. Think of a better way to do
5541 this later.
5559 this later.
5542
5560
5543 * Various small fixes thanks to Nathan's comments.
5561 * Various small fixes thanks to Nathan's comments.
5544
5562
5545 * Changed magic_pprint to magic_Pprint. This way it doesn't
5563 * Changed magic_pprint to magic_Pprint. This way it doesn't
5546 collide with pprint() and the name is consistent with the command
5564 collide with pprint() and the name is consistent with the command
5547 line option.
5565 line option.
5548
5566
5549 * Changed prompt counter behavior to be fully like
5567 * Changed prompt counter behavior to be fully like
5550 Mathematica's. That is, even input that doesn't return a result
5568 Mathematica's. That is, even input that doesn't return a result
5551 raises the prompt counter. The old behavior was kind of confusing
5569 raises the prompt counter. The old behavior was kind of confusing
5552 (getting the same prompt number several times if the operation
5570 (getting the same prompt number several times if the operation
5553 didn't return a result).
5571 didn't return a result).
5554
5572
5555 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
5573 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
5556
5574
5557 * Fixed -Classic mode (wasn't working anymore).
5575 * Fixed -Classic mode (wasn't working anymore).
5558
5576
5559 * Added colored prompts using Nathan's new code. Colors are
5577 * Added colored prompts using Nathan's new code. Colors are
5560 currently hardwired, they can be user-configurable. For
5578 currently hardwired, they can be user-configurable. For
5561 developers, they can be chosen in file ipythonlib.py, at the
5579 developers, they can be chosen in file ipythonlib.py, at the
5562 beginning of the CachedOutput class def.
5580 beginning of the CachedOutput class def.
5563
5581
5564 2001-11-11 Fernando Perez <fperez@colorado.edu>
5582 2001-11-11 Fernando Perez <fperez@colorado.edu>
5565
5583
5566 * Version 0.1.5 released, 0.1.6 opened for further work.
5584 * Version 0.1.5 released, 0.1.6 opened for further work.
5567
5585
5568 * Changed magic_env to *return* the environment as a dict (not to
5586 * Changed magic_env to *return* the environment as a dict (not to
5569 print it). This way it prints, but it can also be processed.
5587 print it). This way it prints, but it can also be processed.
5570
5588
5571 * Added Verbose exception reporting to interactive
5589 * Added Verbose exception reporting to interactive
5572 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
5590 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
5573 traceback. Had to make some changes to the ultraTB file. This is
5591 traceback. Had to make some changes to the ultraTB file. This is
5574 probably the last 'big' thing in my mental todo list. This ties
5592 probably the last 'big' thing in my mental todo list. This ties
5575 in with the next entry:
5593 in with the next entry:
5576
5594
5577 * Changed -Xi and -Xf to a single -xmode option. Now all the user
5595 * Changed -Xi and -Xf to a single -xmode option. Now all the user
5578 has to specify is Plain, Color or Verbose for all exception
5596 has to specify is Plain, Color or Verbose for all exception
5579 handling.
5597 handling.
5580
5598
5581 * Removed ShellServices option. All this can really be done via
5599 * Removed ShellServices option. All this can really be done via
5582 the magic system. It's easier to extend, cleaner and has automatic
5600 the magic system. It's easier to extend, cleaner and has automatic
5583 namespace protection and documentation.
5601 namespace protection and documentation.
5584
5602
5585 2001-11-09 Fernando Perez <fperez@colorado.edu>
5603 2001-11-09 Fernando Perez <fperez@colorado.edu>
5586
5604
5587 * Fixed bug in output cache flushing (missing parameter to
5605 * Fixed bug in output cache flushing (missing parameter to
5588 __init__). Other small bugs fixed (found using pychecker).
5606 __init__). Other small bugs fixed (found using pychecker).
5589
5607
5590 * Version 0.1.4 opened for bugfixing.
5608 * Version 0.1.4 opened for bugfixing.
5591
5609
5592 2001-11-07 Fernando Perez <fperez@colorado.edu>
5610 2001-11-07 Fernando Perez <fperez@colorado.edu>
5593
5611
5594 * Version 0.1.3 released, mainly because of the raw_input bug.
5612 * Version 0.1.3 released, mainly because of the raw_input bug.
5595
5613
5596 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
5614 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
5597 and when testing for whether things were callable, a call could
5615 and when testing for whether things were callable, a call could
5598 actually be made to certain functions. They would get called again
5616 actually be made to certain functions. They would get called again
5599 once 'really' executed, with a resulting double call. A disaster
5617 once 'really' executed, with a resulting double call. A disaster
5600 in many cases (list.reverse() would never work!).
5618 in many cases (list.reverse() would never work!).
5601
5619
5602 * Removed prefilter() function, moved its code to raw_input (which
5620 * Removed prefilter() function, moved its code to raw_input (which
5603 after all was just a near-empty caller for prefilter). This saves
5621 after all was just a near-empty caller for prefilter). This saves
5604 a function call on every prompt, and simplifies the class a tiny bit.
5622 a function call on every prompt, and simplifies the class a tiny bit.
5605
5623
5606 * Fix _ip to __ip name in magic example file.
5624 * Fix _ip to __ip name in magic example file.
5607
5625
5608 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
5626 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
5609 work with non-gnu versions of tar.
5627 work with non-gnu versions of tar.
5610
5628
5611 2001-11-06 Fernando Perez <fperez@colorado.edu>
5629 2001-11-06 Fernando Perez <fperez@colorado.edu>
5612
5630
5613 * Version 0.1.2. Just to keep track of the recent changes.
5631 * Version 0.1.2. Just to keep track of the recent changes.
5614
5632
5615 * Fixed nasty bug in output prompt routine. It used to check 'if
5633 * Fixed nasty bug in output prompt routine. It used to check 'if
5616 arg != None...'. Problem is, this fails if arg implements a
5634 arg != None...'. Problem is, this fails if arg implements a
5617 special comparison (__cmp__) which disallows comparing to
5635 special comparison (__cmp__) which disallows comparing to
5618 None. Found it when trying to use the PhysicalQuantity module from
5636 None. Found it when trying to use the PhysicalQuantity module from
5619 ScientificPython.
5637 ScientificPython.
5620
5638
5621 2001-11-05 Fernando Perez <fperez@colorado.edu>
5639 2001-11-05 Fernando Perez <fperez@colorado.edu>
5622
5640
5623 * Also added dirs. Now the pushd/popd/dirs family functions
5641 * Also added dirs. Now the pushd/popd/dirs family functions
5624 basically like the shell, with the added convenience of going home
5642 basically like the shell, with the added convenience of going home
5625 when called with no args.
5643 when called with no args.
5626
5644
5627 * pushd/popd slightly modified to mimic shell behavior more
5645 * pushd/popd slightly modified to mimic shell behavior more
5628 closely.
5646 closely.
5629
5647
5630 * Added env,pushd,popd from ShellServices as magic functions. I
5648 * Added env,pushd,popd from ShellServices as magic functions. I
5631 think the cleanest will be to port all desired functions from
5649 think the cleanest will be to port all desired functions from
5632 ShellServices as magics and remove ShellServices altogether. This
5650 ShellServices as magics and remove ShellServices altogether. This
5633 will provide a single, clean way of adding functionality
5651 will provide a single, clean way of adding functionality
5634 (shell-type or otherwise) to IP.
5652 (shell-type or otherwise) to IP.
5635
5653
5636 2001-11-04 Fernando Perez <fperez@colorado.edu>
5654 2001-11-04 Fernando Perez <fperez@colorado.edu>
5637
5655
5638 * Added .ipython/ directory to sys.path. This way users can keep
5656 * Added .ipython/ directory to sys.path. This way users can keep
5639 customizations there and access them via import.
5657 customizations there and access them via import.
5640
5658
5641 2001-11-03 Fernando Perez <fperez@colorado.edu>
5659 2001-11-03 Fernando Perez <fperez@colorado.edu>
5642
5660
5643 * Opened version 0.1.1 for new changes.
5661 * Opened version 0.1.1 for new changes.
5644
5662
5645 * Changed version number to 0.1.0: first 'public' release, sent to
5663 * Changed version number to 0.1.0: first 'public' release, sent to
5646 Nathan and Janko.
5664 Nathan and Janko.
5647
5665
5648 * Lots of small fixes and tweaks.
5666 * Lots of small fixes and tweaks.
5649
5667
5650 * Minor changes to whos format. Now strings are shown, snipped if
5668 * Minor changes to whos format. Now strings are shown, snipped if
5651 too long.
5669 too long.
5652
5670
5653 * Changed ShellServices to work on __main__ so they show up in @who
5671 * Changed ShellServices to work on __main__ so they show up in @who
5654
5672
5655 * Help also works with ? at the end of a line:
5673 * Help also works with ? at the end of a line:
5656 ?sin and sin?
5674 ?sin and sin?
5657 both produce the same effect. This is nice, as often I use the
5675 both produce the same effect. This is nice, as often I use the
5658 tab-complete to find the name of a method, but I used to then have
5676 tab-complete to find the name of a method, but I used to then have
5659 to go to the beginning of the line to put a ? if I wanted more
5677 to go to the beginning of the line to put a ? if I wanted more
5660 info. Now I can just add the ? and hit return. Convenient.
5678 info. Now I can just add the ? and hit return. Convenient.
5661
5679
5662 2001-11-02 Fernando Perez <fperez@colorado.edu>
5680 2001-11-02 Fernando Perez <fperez@colorado.edu>
5663
5681
5664 * Python version check (>=2.1) added.
5682 * Python version check (>=2.1) added.
5665
5683
5666 * Added LazyPython documentation. At this point the docs are quite
5684 * Added LazyPython documentation. At this point the docs are quite
5667 a mess. A cleanup is in order.
5685 a mess. A cleanup is in order.
5668
5686
5669 * Auto-installer created. For some bizarre reason, the zipfiles
5687 * Auto-installer created. For some bizarre reason, the zipfiles
5670 module isn't working on my system. So I made a tar version
5688 module isn't working on my system. So I made a tar version
5671 (hopefully the command line options in various systems won't kill
5689 (hopefully the command line options in various systems won't kill
5672 me).
5690 me).
5673
5691
5674 * Fixes to Struct in genutils. Now all dictionary-like methods are
5692 * Fixes to Struct in genutils. Now all dictionary-like methods are
5675 protected (reasonably).
5693 protected (reasonably).
5676
5694
5677 * Added pager function to genutils and changed ? to print usage
5695 * Added pager function to genutils and changed ? to print usage
5678 note through it (it was too long).
5696 note through it (it was too long).
5679
5697
5680 * Added the LazyPython functionality. Works great! I changed the
5698 * Added the LazyPython functionality. Works great! I changed the
5681 auto-quote escape to ';', it's on home row and next to '. But
5699 auto-quote escape to ';', it's on home row and next to '. But
5682 both auto-quote and auto-paren (still /) escapes are command-line
5700 both auto-quote and auto-paren (still /) escapes are command-line
5683 parameters.
5701 parameters.
5684
5702
5685
5703
5686 2001-11-01 Fernando Perez <fperez@colorado.edu>
5704 2001-11-01 Fernando Perez <fperez@colorado.edu>
5687
5705
5688 * Version changed to 0.0.7. Fairly large change: configuration now
5706 * Version changed to 0.0.7. Fairly large change: configuration now
5689 is all stored in a directory, by default .ipython. There, all
5707 is all stored in a directory, by default .ipython. There, all
5690 config files have normal looking names (not .names)
5708 config files have normal looking names (not .names)
5691
5709
5692 * Version 0.0.6 Released first to Lucas and Archie as a test
5710 * Version 0.0.6 Released first to Lucas and Archie as a test
5693 run. Since it's the first 'semi-public' release, change version to
5711 run. Since it's the first 'semi-public' release, change version to
5694 > 0.0.6 for any changes now.
5712 > 0.0.6 for any changes now.
5695
5713
5696 * Stuff I had put in the ipplib.py changelog:
5714 * Stuff I had put in the ipplib.py changelog:
5697
5715
5698 Changes to InteractiveShell:
5716 Changes to InteractiveShell:
5699
5717
5700 - Made the usage message a parameter.
5718 - Made the usage message a parameter.
5701
5719
5702 - Require the name of the shell variable to be given. It's a bit
5720 - Require the name of the shell variable to be given. It's a bit
5703 of a hack, but allows the name 'shell' not to be hardwired in the
5721 of a hack, but allows the name 'shell' not to be hardwired in the
5704 magic (@) handler, which is problematic b/c it requires
5722 magic (@) handler, which is problematic b/c it requires
5705 polluting the global namespace with 'shell'. This in turn is
5723 polluting the global namespace with 'shell'. This in turn is
5706 fragile: if a user redefines a variable called shell, things
5724 fragile: if a user redefines a variable called shell, things
5707 break.
5725 break.
5708
5726
5709 - magic @: all functions available through @ need to be defined
5727 - magic @: all functions available through @ need to be defined
5710 as magic_<name>, even though they can be called simply as
5728 as magic_<name>, even though they can be called simply as
5711 @<name>. This allows the special command @magic to gather
5729 @<name>. This allows the special command @magic to gather
5712 information automatically about all existing magic functions,
5730 information automatically about all existing magic functions,
5713 even if they are run-time user extensions, by parsing the shell
5731 even if they are run-time user extensions, by parsing the shell
5714 instance __dict__ looking for special magic_ names.
5732 instance __dict__ looking for special magic_ names.
5715
5733
5716 - mainloop: added *two* local namespace parameters. This allows
5734 - mainloop: added *two* local namespace parameters. This allows
5717 the class to differentiate between parameters which were there
5735 the class to differentiate between parameters which were there
5718 before and after command line initialization was processed. This
5736 before and after command line initialization was processed. This
5719 way, later @who can show things loaded at startup by the
5737 way, later @who can show things loaded at startup by the
5720 user. This trick was necessary to make session saving/reloading
5738 user. This trick was necessary to make session saving/reloading
5721 really work: ideally after saving/exiting/reloading a session,
5739 really work: ideally after saving/exiting/reloading a session,
5722 *everything* should look the same, including the output of @who. I
5740 *everything* should look the same, including the output of @who. I
5723 was only able to make this work with this double namespace
5741 was only able to make this work with this double namespace
5724 trick.
5742 trick.
5725
5743
5726 - added a header to the logfile which allows (almost) full
5744 - added a header to the logfile which allows (almost) full
5727 session restoring.
5745 session restoring.
5728
5746
5729 - prepend lines beginning with @ or !, with a and log
5747 - prepend lines beginning with @ or !, with a and log
5730 them. Why? !lines: may be useful to know what you did @lines:
5748 them. Why? !lines: may be useful to know what you did @lines:
5731 they may affect session state. So when restoring a session, at
5749 they may affect session state. So when restoring a session, at
5732 least inform the user of their presence. I couldn't quite get
5750 least inform the user of their presence. I couldn't quite get
5733 them to properly re-execute, but at least the user is warned.
5751 them to properly re-execute, but at least the user is warned.
5734
5752
5735 * Started ChangeLog.
5753 * Started ChangeLog.
General Comments 0
You need to be logged in to leave comments. Login now