##// END OF EJS Templates
- Cleanup [1786], which went in with unfinished stuff by accident....
fperez -
Show More
@@ -1,363 +1,315 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Pdb debugger class.
4 4
5 5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 6 the command line completion of other programs which include this isn't
7 7 damaged.
8 8
9 9 In the future, this class will be expanded with improvements over the standard
10 10 pdb.
11 11
12 12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 13 changes. Licensing should therefore be under the standard Python terms. For
14 14 details on the PSF (Python Software Foundation) standard license, see:
15 15
16 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 22 # Since this file is essentially a modified copy of the pdb module which is
23 23 # part of the standard Python distribution, I assume that the proper procedure
24 24 # is to maintain its copyright as belonging to the Python Software Foundation
25 25 # (in addition to my own, for all new code).
26 26 #
27 27 # Copyright (C) 2001 Python Software Foundation, www.python.org
28 28 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
29 29 #
30 30 # Distributed under the terms of the BSD License. The full license is in
31 31 # the file COPYING, distributed as part of this software.
32 32 #
33 33 #*****************************************************************************
34 34
35 35 from IPython import Release
36 36 __author__ = '%s <%s>' % Release.authors['Fernando']
37 37 __license__ = 'Python'
38 38
39 39 import bdb
40 40 import cmd
41 41 import linecache
42 42 import os
43 43 import pdb
44 44 import sys
45 45
46 46 from IPython import PyColorize, ColorANSI
47 47 from IPython.genutils import Term
48 48 from IPython.excolors import ExceptionColors
49 49
50 50 def _file_lines(fname):
51 51 """Return the contents of a named file as a list of lines.
52 52
53 53 This function never raises an IOError exception: if the file can't be
54 54 read, it simply returns an empty list."""
55 55
56 56 try:
57 57 outfile = open(fname)
58 58 except IOError:
59 59 return []
60 60 else:
61 61 out = outfile.readlines()
62 62 outfile.close()
63 63 return out
64 64
65 65 class Pdb(pdb.Pdb):
66 66 """Modified Pdb class, does not load readline."""
67 67
68 # Ugly hack: we can't call the parent constructor, because it binds
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':
68 if sys.version[:3] >= '2.5':
73 69 def __init__(self,color_scheme='NoColor',completekey=None,
74 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 75 # IPython changes...
124
125 76 self.prompt = 'ipdb> ' # The default prompt is '(Pdb)'
126 77 self.aliases = {}
127 78
128 79 # Create color table: we copy the default one from the traceback
129 80 # module and add a few attributes needed for debugging
130 81 self.color_scheme_table = ExceptionColors.copy()
131 82
132 83 # shorthands
133 84 C = ColorANSI.TermColors
134 85 cst = self.color_scheme_table
135 86
136 87 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
137 88 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
138 89
139 90 cst['Linux'].colors.breakpoint_enabled = C.LightRed
140 91 cst['Linux'].colors.breakpoint_disabled = C.Red
141 92
142 93 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
143 94 cst['LightBG'].colors.breakpoint_disabled = C.Red
144 95
145 96 self.set_colors(color_scheme)
146
147 97
148 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 102 def __init__(self,color_scheme='NoColor'):
151 103 bdb.Bdb.__init__(self)
152 104 cmd.Cmd.__init__(self,completekey=None) # don't load readline
153 105 self.prompt = 'ipdb> ' # The default prompt is '(Pdb)'
154 106 self.aliases = {}
155 107
156 108 # These two lines are part of the py2.4 constructor, let's put them
157 109 # unconditionally here as they won't cause any problems in 2.3.
158 110 self.mainpyfile = ''
159 111 self._wait_for_mainpyfile = 0
160 112
161 113 # Read $HOME/.pdbrc and ./.pdbrc
162 114 try:
163 115 self.rcLines = _file_lines(os.path.join(os.environ['HOME'],
164 116 ".pdbrc"))
165 117 except KeyError:
166 118 self.rcLines = []
167 119 self.rcLines.extend(_file_lines(".pdbrc"))
168 120
169 121 # Create color table: we copy the default one from the traceback
170 122 # module and add a few attributes needed for debugging
171 123 self.color_scheme_table = ExceptionColors.copy()
172 124
173 125 # shorthands
174 126 C = ColorANSI.TermColors
175 127 cst = self.color_scheme_table
176 128
177 129 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
178 130 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
179 131
180 132 cst['Linux'].colors.breakpoint_enabled = C.LightRed
181 133 cst['Linux'].colors.breakpoint_disabled = C.Red
182 134
183 135 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
184 136 cst['LightBG'].colors.breakpoint_disabled = C.Red
185 137
186 138 self.set_colors(color_scheme)
187 139
188 140 def set_colors(self, scheme):
189 141 """Shorthand access to the color table scheme selector method."""
190 142 self.color_scheme_table.set_active_scheme(scheme)
191 143
192 144 def interaction(self, frame, traceback):
193 145 __IPYTHON__.set_completer_frame(frame)
194 146 pdb.Pdb.interaction(self, frame, traceback)
195 147
196 148 def do_up(self, arg):
197 149 pdb.Pdb.do_up(self, arg)
198 150 __IPYTHON__.set_completer_frame(self.curframe)
199 151 do_u = do_up
200 152
201 153 def do_down(self, arg):
202 154 pdb.Pdb.do_down(self, arg)
203 155 __IPYTHON__.set_completer_frame(self.curframe)
204 156 do_d = do_down
205 157
206 158 def postloop(self):
207 159 __IPYTHON__.set_completer_frame(None)
208 160
209 161 def print_stack_trace(self):
210 162 try:
211 163 for frame_lineno in self.stack:
212 164 self.print_stack_entry(frame_lineno, context = 5)
213 165 except KeyboardInterrupt:
214 166 pass
215 167
216 168 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
217 169 context = 3):
218 170 frame, lineno = frame_lineno
219 171 print >>Term.cout, self.format_stack_entry(frame_lineno, '', context)
220 172
221 173 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
222 174 import linecache, repr
223 175
224 176 ret = []
225 177
226 178 Colors = self.color_scheme_table.active_colors
227 179 ColorsNormal = Colors.Normal
228 180 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
229 181 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
230 182 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
231 183 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
232 184 ColorsNormal)
233 185
234 186 frame, lineno = frame_lineno
235 187
236 188 return_value = ''
237 189 if '__return__' in frame.f_locals:
238 190 rv = frame.f_locals['__return__']
239 191 #return_value += '->'
240 192 return_value += repr.repr(rv) + '\n'
241 193 ret.append(return_value)
242 194
243 195 #s = filename + '(' + `lineno` + ')'
244 196 filename = self.canonic(frame.f_code.co_filename)
245 197 link = tpl_link % filename
246 198
247 199 if frame.f_code.co_name:
248 200 func = frame.f_code.co_name
249 201 else:
250 202 func = "<lambda>"
251 203
252 204 call = ''
253 205 if func != '?':
254 206 if '__args__' in frame.f_locals:
255 207 args = repr.repr(frame.f_locals['__args__'])
256 208 else:
257 209 args = '()'
258 210 call = tpl_call % (func, args)
259 211
260 212 # The level info should be generated in the same format pdb uses, to
261 213 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
262 214 ret.append('> %s(%s)%s\n' % (link,lineno,call))
263 215
264 216 start = lineno - 1 - context//2
265 217 lines = linecache.getlines(filename)
266 218 start = max(start, 0)
267 219 start = min(start, len(lines) - context)
268 220 lines = lines[start : start + context]
269 221
270 222 for i,line in enumerate(lines):
271 223 show_arrow = (start + 1 + i == lineno)
272 224 ret.append(self.__format_line(tpl_line_em, filename,
273 225 start + 1 + i, line,
274 226 arrow = show_arrow) )
275 227
276 228 return ''.join(ret)
277 229
278 230 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
279 231 bp_mark = ""
280 232 bp_mark_color = ""
281 233
282 234 bp = None
283 235 if lineno in self.get_file_breaks(filename):
284 236 bps = self.get_breaks(filename, lineno)
285 237 bp = bps[-1]
286 238
287 239 if bp:
288 240 Colors = self.color_scheme_table.active_colors
289 241 bp_mark = str(bp.number)
290 242 bp_mark_color = Colors.breakpoint_enabled
291 243 if not bp.enabled:
292 244 bp_mark_color = Colors.breakpoint_disabled
293 245
294 246 numbers_width = 7
295 247 if arrow:
296 248 # This is the line with the error
297 249 pad = numbers_width - len(str(lineno)) - len(bp_mark)
298 250 if pad >= 3:
299 251 marker = '-'*(pad-3) + '-> '
300 252 elif pad == 2:
301 253 marker = '> '
302 254 elif pad == 1:
303 255 marker = '>'
304 256 else:
305 257 marker = ''
306 258 num = '%s%s' % (marker, str(lineno))
307 259 line = tpl_line % (bp_mark_color + bp_mark, num, line)
308 260 else:
309 261 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
310 262 line = tpl_line % (bp_mark_color + bp_mark, num, line)
311 263
312 264 return line
313 265
314 266 def do_list(self, arg):
315 267 self.lastcmd = 'list'
316 268 last = None
317 269 if arg:
318 270 try:
319 271 x = eval(arg, {}, {})
320 272 if type(x) == type(()):
321 273 first, last = x
322 274 first = int(first)
323 275 last = int(last)
324 276 if last < first:
325 277 # Assume it's a count
326 278 last = first + last
327 279 else:
328 280 first = max(1, int(x) - 5)
329 281 except:
330 282 print '*** Error in argument:', `arg`
331 283 return
332 284 elif self.lineno is None:
333 285 first = max(1, self.curframe.f_lineno - 5)
334 286 else:
335 287 first = self.lineno + 1
336 288 if last is None:
337 289 last = first + 10
338 290 filename = self.curframe.f_code.co_filename
339 291 try:
340 292 Colors = self.color_scheme_table.active_colors
341 293 ColorsNormal = Colors.Normal
342 294 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
343 295 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
344 296 src = []
345 297 for lineno in range(first, last+1):
346 298 line = linecache.getline(filename, lineno)
347 299 if not line:
348 300 break
349 301
350 302 if lineno == self.curframe.f_lineno:
351 303 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
352 304 else:
353 305 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
354 306
355 307 src.append(line)
356 308 self.lineno = lineno
357 309
358 310 print >>Term.cout, ''.join(src)
359 311
360 312 except KeyboardInterrupt:
361 313 pass
362 314
363 315 do_l = do_list
@@ -1,2990 +1,2991 b''
1 1 # -*- coding: utf-8 -*-
2 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 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 #****************************************************************************
15 15 # Modules and globals
16 16
17 17 from IPython import Release
18 18 __author__ = '%s <%s>\n%s <%s>' % \
19 19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 20 __license__ = Release.license
21 21
22 22 # Python standard modules
23 23 import __builtin__
24 24 import bdb
25 25 import inspect
26 26 import os
27 27 import pdb
28 28 import pydoc
29 29 import shlex
30 30 import sys
31 31 import re
32 32 import tempfile
33 33 import time
34 34 import cPickle as pickle
35 35 import textwrap
36 36 from cStringIO import StringIO
37 37 from getopt import getopt,GetoptError
38 38 from pprint import pprint, pformat
39 39
40 40 # profile isn't bundled by default in Debian for license reasons
41 41 try:
42 42 import profile,pstats
43 43 except ImportError:
44 44 profile = pstats = None
45 45
46 46 # Homebrewed
47 47 import IPython
48 48 from IPython import Debugger, OInspect, wildcard
49 49 from IPython.FakeModule import FakeModule
50 50 from IPython.Itpl import Itpl, itpl, printpl,itplns
51 51 from IPython.PyColorize import Parser
52 52 from IPython.ipstruct import Struct
53 53 from IPython.macro import Macro
54 54 from IPython.genutils import *
55 55 from IPython import platutils
56 56
57 57 #***************************************************************************
58 58 # Utility functions
59 59 def on_off(tag):
60 60 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
61 61 return ['OFF','ON'][tag]
62 62
63 63 class Bunch: pass
64 64
65 65 #***************************************************************************
66 66 # Main class implementing Magic functionality
67 67 class Magic:
68 68 """Magic functions for InteractiveShell.
69 69
70 70 Shell functions which can be reached as %function_name. All magic
71 71 functions should accept a string, which they can parse for their own
72 72 needs. This can make some functions easier to type, eg `%cd ../`
73 73 vs. `%cd("../")`
74 74
75 75 ALL definitions MUST begin with the prefix magic_. The user won't need it
76 76 at the command line, but it is is needed in the definition. """
77 77
78 78 # class globals
79 79 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
80 80 'Automagic is ON, % prefix NOT needed for magic functions.']
81 81
82 82 #......................................................................
83 83 # some utility functions
84 84
85 85 def __init__(self,shell):
86 86
87 87 self.options_table = {}
88 88 if profile is None:
89 89 self.magic_prun = self.profile_missing_notice
90 90 self.shell = shell
91 91
92 92 # namespace for holding state we may need
93 93 self._magic_state = Bunch()
94 94
95 95 def profile_missing_notice(self, *args, **kwargs):
96 96 error("""\
97 97 The profile module could not be found. If you are a Debian user,
98 98 it has been removed from the standard Debian package because of its non-free
99 99 license. To use profiling, please install"python2.3-profiler" from non-free.""")
100 100
101 101 def default_option(self,fn,optstr):
102 102 """Make an entry in the options_table for fn, with value optstr"""
103 103
104 104 if fn not in self.lsmagic():
105 105 error("%s is not a magic function" % fn)
106 106 self.options_table[fn] = optstr
107 107
108 108 def lsmagic(self):
109 109 """Return a list of currently available magic functions.
110 110
111 111 Gives a list of the bare names after mangling (['ls','cd', ...], not
112 112 ['magic_ls','magic_cd',...]"""
113 113
114 114 # FIXME. This needs a cleanup, in the way the magics list is built.
115 115
116 116 # magics in class definition
117 117 class_magic = lambda fn: fn.startswith('magic_') and \
118 118 callable(Magic.__dict__[fn])
119 119 # in instance namespace (run-time user additions)
120 120 inst_magic = lambda fn: fn.startswith('magic_') and \
121 121 callable(self.__dict__[fn])
122 122 # and bound magics by user (so they can access self):
123 123 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
124 124 callable(self.__class__.__dict__[fn])
125 125 magics = filter(class_magic,Magic.__dict__.keys()) + \
126 126 filter(inst_magic,self.__dict__.keys()) + \
127 127 filter(inst_bound_magic,self.__class__.__dict__.keys())
128 128 out = []
129 129 for fn in magics:
130 130 out.append(fn.replace('magic_','',1))
131 131 out.sort()
132 132 return out
133 133
134 134 def extract_input_slices(self,slices,raw=False):
135 135 """Return as a string a set of input history slices.
136 136
137 137 Inputs:
138 138
139 139 - slices: the set of slices is given as a list of strings (like
140 140 ['1','4:8','9'], since this function is for use by magic functions
141 141 which get their arguments as strings.
142 142
143 143 Optional inputs:
144 144
145 145 - raw(False): by default, the processed input is used. If this is
146 146 true, the raw input history is used instead.
147 147
148 148 Note that slices can be called with two notations:
149 149
150 150 N:M -> standard python form, means including items N...(M-1).
151 151
152 152 N-M -> include items N..M (closed endpoint)."""
153 153
154 154 if raw:
155 155 hist = self.shell.input_hist_raw
156 156 else:
157 157 hist = self.shell.input_hist
158 158
159 159 cmds = []
160 160 for chunk in slices:
161 161 if ':' in chunk:
162 162 ini,fin = map(int,chunk.split(':'))
163 163 elif '-' in chunk:
164 164 ini,fin = map(int,chunk.split('-'))
165 165 fin += 1
166 166 else:
167 167 ini = int(chunk)
168 168 fin = ini+1
169 169 cmds.append(hist[ini:fin])
170 170 return cmds
171 171
172 172 def _ofind(self,oname):
173 173 """Find an object in the available namespaces.
174 174
175 175 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
176 176
177 177 Has special code to detect magic functions.
178 178 """
179 179
180 180 oname = oname.strip()
181 181
182 182 # Namespaces to search in:
183 183 user_ns = self.shell.user_ns
184 184 internal_ns = self.shell.internal_ns
185 185 builtin_ns = __builtin__.__dict__
186 186 alias_ns = self.shell.alias_table
187 187
188 188 # Put them in a list. The order is important so that we find things in
189 189 # the same order that Python finds them.
190 190 namespaces = [ ('Interactive',user_ns),
191 191 ('IPython internal',internal_ns),
192 192 ('Python builtin',builtin_ns),
193 193 ('Alias',alias_ns),
194 194 ]
195 195
196 196 # initialize results to 'null'
197 197 found = 0; obj = None; ospace = None; ds = None;
198 198 ismagic = 0; isalias = 0; parent = None
199 199
200 200 # Look for the given name by splitting it in parts. If the head is
201 201 # found, then we look for all the remaining parts as members, and only
202 202 # declare success if we can find them all.
203 203 oname_parts = oname.split('.')
204 204 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
205 205 for nsname,ns in namespaces:
206 206 try:
207 207 obj = ns[oname_head]
208 208 except KeyError:
209 209 continue
210 210 else:
211 211 for part in oname_rest:
212 212 try:
213 213 parent = obj
214 214 obj = getattr(obj,part)
215 215 except:
216 216 # Blanket except b/c some badly implemented objects
217 217 # allow __getattr__ to raise exceptions other than
218 218 # AttributeError, which then crashes IPython.
219 219 break
220 220 else:
221 221 # If we finish the for loop (no break), we got all members
222 222 found = 1
223 223 ospace = nsname
224 224 if ns == alias_ns:
225 225 isalias = 1
226 226 break # namespace loop
227 227
228 228 # Try to see if it's magic
229 229 if not found:
230 230 if oname.startswith(self.shell.ESC_MAGIC):
231 231 oname = oname[1:]
232 232 obj = getattr(self,'magic_'+oname,None)
233 233 if obj is not None:
234 234 found = 1
235 235 ospace = 'IPython internal'
236 236 ismagic = 1
237 237
238 238 # Last try: special-case some literals like '', [], {}, etc:
239 239 if not found and oname_head in ["''",'""','[]','{}','()']:
240 240 obj = eval(oname_head)
241 241 found = 1
242 242 ospace = 'Interactive'
243 243
244 244 return {'found':found, 'obj':obj, 'namespace':ospace,
245 245 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
246 246
247 247 def arg_err(self,func):
248 248 """Print docstring if incorrect arguments were passed"""
249 249 print 'Error in arguments:'
250 250 print OInspect.getdoc(func)
251 251
252 252 def format_latex(self,strng):
253 253 """Format a string for latex inclusion."""
254 254
255 255 # Characters that need to be escaped for latex:
256 256 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
257 257 # Magic command names as headers:
258 258 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
259 259 re.MULTILINE)
260 260 # Magic commands
261 261 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
262 262 re.MULTILINE)
263 263 # Paragraph continue
264 264 par_re = re.compile(r'\\$',re.MULTILINE)
265 265
266 266 # The "\n" symbol
267 267 newline_re = re.compile(r'\\n')
268 268
269 269 # Now build the string for output:
270 270 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
271 271 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
272 272 strng)
273 273 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
274 274 strng = par_re.sub(r'\\\\',strng)
275 275 strng = escape_re.sub(r'\\\1',strng)
276 276 strng = newline_re.sub(r'\\textbackslash{}n',strng)
277 277 return strng
278 278
279 279 def format_screen(self,strng):
280 280 """Format a string for screen printing.
281 281
282 282 This removes some latex-type format codes."""
283 283 # Paragraph continue
284 284 par_re = re.compile(r'\\$',re.MULTILINE)
285 285 strng = par_re.sub('',strng)
286 286 return strng
287 287
288 288 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
289 289 """Parse options passed to an argument string.
290 290
291 291 The interface is similar to that of getopt(), but it returns back a
292 292 Struct with the options as keys and the stripped argument string still
293 293 as a string.
294 294
295 295 arg_str is quoted as a true sys.argv vector by using shlex.split.
296 296 This allows us to easily expand variables, glob files, quote
297 297 arguments, etc.
298 298
299 299 Options:
300 300 -mode: default 'string'. If given as 'list', the argument string is
301 301 returned as a list (split on whitespace) instead of a string.
302 302
303 303 -list_all: put all option values in lists. Normally only options
304 304 appearing more than once are put in a list."""
305 305
306 306 # inject default options at the beginning of the input line
307 307 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
308 308 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
309 309
310 310 mode = kw.get('mode','string')
311 311 if mode not in ['string','list']:
312 312 raise ValueError,'incorrect mode given: %s' % mode
313 313 # Get options
314 314 list_all = kw.get('list_all',0)
315 315
316 316 # Check if we have more than one argument to warrant extra processing:
317 317 odict = {} # Dictionary with options
318 318 args = arg_str.split()
319 319 if len(args) >= 1:
320 320 # If the list of inputs only has 0 or 1 thing in it, there's no
321 321 # need to look for options
322 322 argv = shlex.split(arg_str)
323 323 # Do regular option processing
324 324 try:
325 325 opts,args = getopt(argv,opt_str,*long_opts)
326 326 except GetoptError,e:
327 327 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
328 328 " ".join(long_opts)))
329 329 for o,a in opts:
330 330 if o.startswith('--'):
331 331 o = o[2:]
332 332 else:
333 333 o = o[1:]
334 334 try:
335 335 odict[o].append(a)
336 336 except AttributeError:
337 337 odict[o] = [odict[o],a]
338 338 except KeyError:
339 339 if list_all:
340 340 odict[o] = [a]
341 341 else:
342 342 odict[o] = a
343 343
344 344 # Prepare opts,args for return
345 345 opts = Struct(odict)
346 346 if mode == 'string':
347 347 args = ' '.join(args)
348 348
349 349 return opts,args
350 350
351 351 #......................................................................
352 352 # And now the actual magic functions
353 353
354 354 # Functions for IPython shell work (vars,funcs, config, etc)
355 355 def magic_lsmagic(self, parameter_s = ''):
356 356 """List currently available magic functions."""
357 357 mesc = self.shell.ESC_MAGIC
358 358 print 'Available magic functions:\n'+mesc+\
359 359 (' '+mesc).join(self.lsmagic())
360 360 print '\n' + Magic.auto_status[self.shell.rc.automagic]
361 361 return None
362 362
363 363 def magic_magic(self, parameter_s = ''):
364 364 """Print information about the magic function system."""
365 365
366 366 mode = ''
367 367 try:
368 368 if parameter_s.split()[0] == '-latex':
369 369 mode = 'latex'
370 370 if parameter_s.split()[0] == '-brief':
371 371 mode = 'brief'
372 372 except:
373 373 pass
374 374
375 375 magic_docs = []
376 376 for fname in self.lsmagic():
377 377 mname = 'magic_' + fname
378 378 for space in (Magic,self,self.__class__):
379 379 try:
380 380 fn = space.__dict__[mname]
381 381 except KeyError:
382 382 pass
383 383 else:
384 384 break
385 385 if mode == 'brief':
386 386 # only first line
387 387 fndoc = fn.__doc__.split('\n',1)[0]
388 388 else:
389 389 fndoc = fn.__doc__
390 390
391 391 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
392 392 fname,fndoc))
393 393 magic_docs = ''.join(magic_docs)
394 394
395 395 if mode == 'latex':
396 396 print self.format_latex(magic_docs)
397 397 return
398 398 else:
399 399 magic_docs = self.format_screen(magic_docs)
400 400 if mode == 'brief':
401 401 return magic_docs
402 402
403 403 outmsg = """
404 404 IPython's 'magic' functions
405 405 ===========================
406 406
407 407 The magic function system provides a series of functions which allow you to
408 408 control the behavior of IPython itself, plus a lot of system-type
409 409 features. All these functions are prefixed with a % character, but parameters
410 410 are given without parentheses or quotes.
411 411
412 412 NOTE: If you have 'automagic' enabled (via the command line option or with the
413 413 %automagic function), you don't need to type in the % explicitly. By default,
414 414 IPython ships with automagic on, so you should only rarely need the % escape.
415 415
416 416 Example: typing '%cd mydir' (without the quotes) changes you working directory
417 417 to 'mydir', if it exists.
418 418
419 419 You can define your own magic functions to extend the system. See the supplied
420 420 ipythonrc and example-magic.py files for details (in your ipython
421 421 configuration directory, typically $HOME/.ipython/).
422 422
423 423 You can also define your own aliased names for magic functions. In your
424 424 ipythonrc file, placing a line like:
425 425
426 426 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
427 427
428 428 will define %pf as a new name for %profile.
429 429
430 430 You can also call magics in code using the ipmagic() function, which IPython
431 431 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
432 432
433 433 For a list of the available magic functions, use %lsmagic. For a description
434 434 of any of them, type %magic_name?, e.g. '%cd?'.
435 435
436 436 Currently the magic system has the following functions:\n"""
437 437
438 438 mesc = self.shell.ESC_MAGIC
439 439 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
440 440 "\n\n%s%s\n\n%s" % (outmsg,
441 441 magic_docs,mesc,mesc,
442 442 (' '+mesc).join(self.lsmagic()),
443 443 Magic.auto_status[self.shell.rc.automagic] ) )
444 444
445 445 page(outmsg,screen_lines=self.shell.rc.screen_length)
446 446
447 447 def magic_automagic(self, parameter_s = ''):
448 448 """Make magic functions callable without having to type the initial %.
449 449
450 450 Toggles on/off (when off, you must call it as %automagic, of
451 451 course). Note that magic functions have lowest priority, so if there's
452 452 a variable whose name collides with that of a magic fn, automagic
453 453 won't work for that function (you get the variable instead). However,
454 454 if you delete the variable (del var), the previously shadowed magic
455 455 function becomes visible to automagic again."""
456 456
457 457 rc = self.shell.rc
458 458 rc.automagic = not rc.automagic
459 459 print '\n' + Magic.auto_status[rc.automagic]
460 460
461 461 def magic_autocall(self, parameter_s = ''):
462 462 """Make functions callable without having to type parentheses.
463 463
464 464 Usage:
465 465
466 466 %autocall [mode]
467 467
468 468 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
469 469 value is toggled on and off (remembering the previous state)."""
470 470
471 471 rc = self.shell.rc
472 472
473 473 if parameter_s:
474 474 arg = int(parameter_s)
475 475 else:
476 476 arg = 'toggle'
477 477
478 478 if not arg in (0,1,2,'toggle'):
479 479 error('Valid modes: (0->Off, 1->Smart, 2->Full')
480 480 return
481 481
482 482 if arg in (0,1,2):
483 483 rc.autocall = arg
484 484 else: # toggle
485 485 if rc.autocall:
486 486 self._magic_state.autocall_save = rc.autocall
487 487 rc.autocall = 0
488 488 else:
489 489 try:
490 490 rc.autocall = self._magic_state.autocall_save
491 491 except AttributeError:
492 492 rc.autocall = self._magic_state.autocall_save = 1
493 493
494 494 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
495 495
496 496 def magic_autoindent(self, parameter_s = ''):
497 497 """Toggle autoindent on/off (if available)."""
498 498
499 499 self.shell.set_autoindent()
500 500 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
501 501
502 502 def magic_system_verbose(self, parameter_s = ''):
503 503 """Toggle verbose printing of system calls on/off."""
504 504
505 505 self.shell.rc_set_toggle('system_verbose')
506 506 print "System verbose printing is:",\
507 507 ['OFF','ON'][self.shell.rc.system_verbose]
508 508
509 509 def magic_history(self, parameter_s = ''):
510 510 """Print input history (_i<n> variables), with most recent last.
511 511
512 512 %history -> print at most 40 inputs (some may be multi-line)\\
513 513 %history n -> print at most n inputs\\
514 514 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
515 515
516 516 Each input's number <n> is shown, and is accessible as the
517 517 automatically generated variable _i<n>. Multi-line statements are
518 518 printed starting at a new line for easy copy/paste.
519 519
520 520
521 521 Options:
522 522
523 523 -n: do NOT print line numbers. This is useful if you want to get a
524 524 printout of many lines which can be directly pasted into a text
525 525 editor.
526 526
527 527 This feature is only available if numbered prompts are in use.
528 528
529 529 -r: print the 'raw' history. IPython filters your input and
530 530 converts it all into valid Python source before executing it (things
531 531 like magics or aliases are turned into function calls, for
532 532 example). With this option, you'll see the unfiltered history
533 533 instead of the filtered version: '%cd /' will be seen as '%cd /'
534 534 instead of '_ip.magic("%cd /")'.
535 535 """
536 536
537 537 shell = self.shell
538 538 if not shell.outputcache.do_full_cache:
539 539 print 'This feature is only available if numbered prompts are in use.'
540 540 return
541 541 opts,args = self.parse_options(parameter_s,'nr',mode='list')
542 542
543 543 if opts.has_key('r'):
544 544 input_hist = shell.input_hist_raw
545 545 else:
546 546 input_hist = shell.input_hist
547 547
548 548 default_length = 40
549 549 if len(args) == 0:
550 550 final = len(input_hist)
551 551 init = max(1,final-default_length)
552 552 elif len(args) == 1:
553 553 final = len(input_hist)
554 554 init = max(1,final-int(args[0]))
555 555 elif len(args) == 2:
556 556 init,final = map(int,args)
557 557 else:
558 558 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
559 559 print self.magic_hist.__doc__
560 560 return
561 561 width = len(str(final))
562 562 line_sep = ['','\n']
563 563 print_nums = not opts.has_key('n')
564 564 for in_num in range(init,final):
565 565 inline = input_hist[in_num]
566 566 multiline = int(inline.count('\n') > 1)
567 567 if print_nums:
568 568 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
569 569 print inline,
570 570
571 571 def magic_hist(self, parameter_s=''):
572 572 """Alternate name for %history."""
573 573 return self.magic_history(parameter_s)
574 574
575 575 def magic_p(self, parameter_s=''):
576 576 """Just a short alias for Python's 'print'."""
577 577 exec 'print ' + parameter_s in self.shell.user_ns
578 578
579 579 def magic_r(self, parameter_s=''):
580 580 """Repeat previous input.
581 581
582 582 If given an argument, repeats the previous command which starts with
583 583 the same string, otherwise it just repeats the previous input.
584 584
585 585 Shell escaped commands (with ! as first character) are not recognized
586 586 by this system, only pure python code and magic commands.
587 587 """
588 588
589 589 start = parameter_s.strip()
590 590 esc_magic = self.shell.ESC_MAGIC
591 591 # Identify magic commands even if automagic is on (which means
592 592 # the in-memory version is different from that typed by the user).
593 593 if self.shell.rc.automagic:
594 594 start_magic = esc_magic+start
595 595 else:
596 596 start_magic = start
597 597 # Look through the input history in reverse
598 598 for n in range(len(self.shell.input_hist)-2,0,-1):
599 599 input = self.shell.input_hist[n]
600 600 # skip plain 'r' lines so we don't recurse to infinity
601 601 if input != '_ip.magic("r")\n' and \
602 602 (input.startswith(start) or input.startswith(start_magic)):
603 603 #print 'match',`input` # dbg
604 604 print 'Executing:',input,
605 605 self.shell.runlines(input)
606 606 return
607 607 print 'No previous input matching `%s` found.' % start
608 608
609 609 def magic_page(self, parameter_s=''):
610 610 """Pretty print the object and display it through a pager.
611 611
612 612 If no parameter is given, use _ (last output)."""
613 613 # After a function contributed by Olivier Aubert, slightly modified.
614 614
615 615 oname = parameter_s and parameter_s or '_'
616 616 info = self._ofind(oname)
617 617 if info['found']:
618 618 page(pformat(info['obj']))
619 619 else:
620 620 print 'Object `%s` not found' % oname
621 621
622 622 def magic_profile(self, parameter_s=''):
623 623 """Print your currently active IPyhton profile."""
624 624 if self.shell.rc.profile:
625 625 printpl('Current IPython profile: $self.shell.rc.profile.')
626 626 else:
627 627 print 'No profile active.'
628 628
629 629 def _inspect(self,meth,oname,**kw):
630 630 """Generic interface to the inspector system.
631 631
632 632 This function is meant to be called by pdef, pdoc & friends."""
633 633
634 634 oname = oname.strip()
635 635 info = Struct(self._ofind(oname))
636 636
637 637 if info.found:
638 638 # Get the docstring of the class property if it exists.
639 639 path = oname.split('.')
640 640 root = '.'.join(path[:-1])
641 641 if info.parent is not None:
642 642 try:
643 643 target = getattr(info.parent, '__class__')
644 644 # The object belongs to a class instance.
645 645 try:
646 646 target = getattr(target, path[-1])
647 647 # The class defines the object.
648 648 if isinstance(target, property):
649 649 oname = root + '.__class__.' + path[-1]
650 650 info = Struct(self._ofind(oname))
651 651 except AttributeError: pass
652 652 except AttributeError: pass
653 653
654 654 pmethod = getattr(self.shell.inspector,meth)
655 655 formatter = info.ismagic and self.format_screen or None
656 656 if meth == 'pdoc':
657 657 pmethod(info.obj,oname,formatter)
658 658 elif meth == 'pinfo':
659 659 pmethod(info.obj,oname,formatter,info,**kw)
660 660 else:
661 661 pmethod(info.obj,oname)
662 662 else:
663 663 print 'Object `%s` not found.' % oname
664 664 return 'not found' # so callers can take other action
665 665
666 666 def magic_pdef(self, parameter_s=''):
667 667 """Print the definition header for any callable object.
668 668
669 669 If the object is a class, print the constructor information."""
670 670 self._inspect('pdef',parameter_s)
671 671
672 672 def magic_pdoc(self, parameter_s=''):
673 673 """Print the docstring for an object.
674 674
675 675 If the given object is a class, it will print both the class and the
676 676 constructor docstrings."""
677 677 self._inspect('pdoc',parameter_s)
678 678
679 679 def magic_psource(self, parameter_s=''):
680 680 """Print (or run through pager) the source code for an object."""
681 681 self._inspect('psource',parameter_s)
682 682
683 683 def magic_pfile(self, parameter_s=''):
684 684 """Print (or run through pager) the file where an object is defined.
685 685
686 686 The file opens at the line where the object definition begins. IPython
687 687 will honor the environment variable PAGER if set, and otherwise will
688 688 do its best to print the file in a convenient form.
689 689
690 690 If the given argument is not an object currently defined, IPython will
691 691 try to interpret it as a filename (automatically adding a .py extension
692 692 if needed). You can thus use %pfile as a syntax highlighting code
693 693 viewer."""
694 694
695 695 # first interpret argument as an object name
696 696 out = self._inspect('pfile',parameter_s)
697 697 # if not, try the input as a filename
698 698 if out == 'not found':
699 699 try:
700 700 filename = get_py_filename(parameter_s)
701 701 except IOError,msg:
702 702 print msg
703 703 return
704 704 page(self.shell.inspector.format(file(filename).read()))
705 705
706 706 def magic_pinfo(self, parameter_s=''):
707 707 """Provide detailed information about an object.
708 708
709 709 '%pinfo object' is just a synonym for object? or ?object."""
710 710
711 711 #print 'pinfo par: <%s>' % parameter_s # dbg
712 712
713 713 # detail_level: 0 -> obj? , 1 -> obj??
714 714 detail_level = 0
715 715 # We need to detect if we got called as 'pinfo pinfo foo', which can
716 716 # happen if the user types 'pinfo foo?' at the cmd line.
717 717 pinfo,qmark1,oname,qmark2 = \
718 718 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
719 719 if pinfo or qmark1 or qmark2:
720 720 detail_level = 1
721 721 if "*" in oname:
722 722 self.magic_psearch(oname)
723 723 else:
724 724 self._inspect('pinfo',oname,detail_level=detail_level)
725 725
726 726 def magic_psearch(self, parameter_s=''):
727 727 """Search for object in namespaces by wildcard.
728 728
729 729 %psearch [options] PATTERN [OBJECT TYPE]
730 730
731 731 Note: ? can be used as a synonym for %psearch, at the beginning or at
732 732 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
733 733 rest of the command line must be unchanged (options come first), so
734 734 for example the following forms are equivalent
735 735
736 736 %psearch -i a* function
737 737 -i a* function?
738 738 ?-i a* function
739 739
740 740 Arguments:
741 741
742 742 PATTERN
743 743
744 744 where PATTERN is a string containing * as a wildcard similar to its
745 745 use in a shell. The pattern is matched in all namespaces on the
746 746 search path. By default objects starting with a single _ are not
747 747 matched, many IPython generated objects have a single
748 748 underscore. The default is case insensitive matching. Matching is
749 749 also done on the attributes of objects and not only on the objects
750 750 in a module.
751 751
752 752 [OBJECT TYPE]
753 753
754 754 Is the name of a python type from the types module. The name is
755 755 given in lowercase without the ending type, ex. StringType is
756 756 written string. By adding a type here only objects matching the
757 757 given type are matched. Using all here makes the pattern match all
758 758 types (this is the default).
759 759
760 760 Options:
761 761
762 762 -a: makes the pattern match even objects whose names start with a
763 763 single underscore. These names are normally ommitted from the
764 764 search.
765 765
766 766 -i/-c: make the pattern case insensitive/sensitive. If neither of
767 767 these options is given, the default is read from your ipythonrc
768 768 file. The option name which sets this value is
769 769 'wildcards_case_sensitive'. If this option is not specified in your
770 770 ipythonrc file, IPython's internal default is to do a case sensitive
771 771 search.
772 772
773 773 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
774 774 specifiy can be searched in any of the following namespaces:
775 775 'builtin', 'user', 'user_global','internal', 'alias', where
776 776 'builtin' and 'user' are the search defaults. Note that you should
777 777 not use quotes when specifying namespaces.
778 778
779 779 'Builtin' contains the python module builtin, 'user' contains all
780 780 user data, 'alias' only contain the shell aliases and no python
781 781 objects, 'internal' contains objects used by IPython. The
782 782 'user_global' namespace is only used by embedded IPython instances,
783 783 and it contains module-level globals. You can add namespaces to the
784 784 search with -s or exclude them with -e (these options can be given
785 785 more than once).
786 786
787 787 Examples:
788 788
789 789 %psearch a* -> objects beginning with an a
790 790 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
791 791 %psearch a* function -> all functions beginning with an a
792 792 %psearch re.e* -> objects beginning with an e in module re
793 793 %psearch r*.e* -> objects that start with e in modules starting in r
794 794 %psearch r*.* string -> all strings in modules beginning with r
795 795
796 796 Case sensitve search:
797 797
798 798 %psearch -c a* list all object beginning with lower case a
799 799
800 800 Show objects beginning with a single _:
801 801
802 802 %psearch -a _* list objects beginning with a single underscore"""
803 803
804 804 # default namespaces to be searched
805 805 def_search = ['user','builtin']
806 806
807 807 # Process options/args
808 808 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
809 809 opt = opts.get
810 810 shell = self.shell
811 811 psearch = shell.inspector.psearch
812 812
813 813 # select case options
814 814 if opts.has_key('i'):
815 815 ignore_case = True
816 816 elif opts.has_key('c'):
817 817 ignore_case = False
818 818 else:
819 819 ignore_case = not shell.rc.wildcards_case_sensitive
820 820
821 821 # Build list of namespaces to search from user options
822 822 def_search.extend(opt('s',[]))
823 823 ns_exclude = ns_exclude=opt('e',[])
824 824 ns_search = [nm for nm in def_search if nm not in ns_exclude]
825 825
826 826 # Call the actual search
827 827 try:
828 828 psearch(args,shell.ns_table,ns_search,
829 829 show_all=opt('a'),ignore_case=ignore_case)
830 830 except:
831 831 shell.showtraceback()
832 832
833 833 def magic_who_ls(self, parameter_s=''):
834 834 """Return a sorted list of all interactive variables.
835 835
836 836 If arguments are given, only variables of types matching these
837 837 arguments are returned."""
838 838
839 839 user_ns = self.shell.user_ns
840 840 internal_ns = self.shell.internal_ns
841 841 user_config_ns = self.shell.user_config_ns
842 842 out = []
843 843 typelist = parameter_s.split()
844 844
845 845 for i in user_ns:
846 846 if not (i.startswith('_') or i.startswith('_i')) \
847 847 and not (i in internal_ns or i in user_config_ns):
848 848 if typelist:
849 849 if type(user_ns[i]).__name__ in typelist:
850 850 out.append(i)
851 851 else:
852 852 out.append(i)
853 853 out.sort()
854 854 return out
855 855
856 856 def magic_who(self, parameter_s=''):
857 857 """Print all interactive variables, with some minimal formatting.
858 858
859 859 If any arguments are given, only variables whose type matches one of
860 860 these are printed. For example:
861 861
862 862 %who function str
863 863
864 864 will only list functions and strings, excluding all other types of
865 865 variables. To find the proper type names, simply use type(var) at a
866 866 command line to see how python prints type names. For example:
867 867
868 868 In [1]: type('hello')\\
869 869 Out[1]: <type 'str'>
870 870
871 871 indicates that the type name for strings is 'str'.
872 872
873 873 %who always excludes executed names loaded through your configuration
874 874 file and things which are internal to IPython.
875 875
876 876 This is deliberate, as typically you may load many modules and the
877 877 purpose of %who is to show you only what you've manually defined."""
878 878
879 879 varlist = self.magic_who_ls(parameter_s)
880 880 if not varlist:
881 881 print 'Interactive namespace is empty.'
882 882 return
883 883
884 884 # if we have variables, move on...
885 885
886 886 # stupid flushing problem: when prompts have no separators, stdout is
887 887 # getting lost. I'm starting to think this is a python bug. I'm having
888 888 # to force a flush with a print because even a sys.stdout.flush
889 889 # doesn't seem to do anything!
890 890
891 891 count = 0
892 892 for i in varlist:
893 893 print i+'\t',
894 894 count += 1
895 895 if count > 8:
896 896 count = 0
897 897 print
898 898 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
899 899
900 900 print # well, this does force a flush at the expense of an extra \n
901 901
902 902 def magic_whos(self, parameter_s=''):
903 903 """Like %who, but gives some extra information about each variable.
904 904
905 905 The same type filtering of %who can be applied here.
906 906
907 907 For all variables, the type is printed. Additionally it prints:
908 908
909 909 - For {},[],(): their length.
910 910
911 911 - For Numeric arrays, a summary with shape, number of elements,
912 912 typecode and size in memory.
913 913
914 914 - Everything else: a string representation, snipping their middle if
915 915 too long."""
916 916
917 917 varnames = self.magic_who_ls(parameter_s)
918 918 if not varnames:
919 919 print 'Interactive namespace is empty.'
920 920 return
921 921
922 922 # if we have variables, move on...
923 923
924 924 # for these types, show len() instead of data:
925 925 seq_types = [types.DictType,types.ListType,types.TupleType]
926 926
927 927 # for Numeric arrays, display summary info
928 928 try:
929 929 import Numeric
930 930 except ImportError:
931 931 array_type = None
932 932 else:
933 933 array_type = Numeric.ArrayType.__name__
934 934
935 935 # Find all variable names and types so we can figure out column sizes
936 936 get_vars = lambda i: self.shell.user_ns[i]
937 937 type_name = lambda v: type(v).__name__
938 938 varlist = map(get_vars,varnames)
939 939
940 940 typelist = []
941 941 for vv in varlist:
942 942 tt = type_name(vv)
943 943 if tt=='instance':
944 944 typelist.append(str(vv.__class__))
945 945 else:
946 946 typelist.append(tt)
947 947
948 948 # column labels and # of spaces as separator
949 949 varlabel = 'Variable'
950 950 typelabel = 'Type'
951 951 datalabel = 'Data/Info'
952 952 colsep = 3
953 953 # variable format strings
954 954 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
955 955 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
956 956 aformat = "%s: %s elems, type `%s`, %s bytes"
957 957 # find the size of the columns to format the output nicely
958 958 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
959 959 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
960 960 # table header
961 961 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
962 962 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
963 963 # and the table itself
964 964 kb = 1024
965 965 Mb = 1048576 # kb**2
966 966 for vname,var,vtype in zip(varnames,varlist,typelist):
967 967 print itpl(vformat),
968 968 if vtype in seq_types:
969 969 print len(var)
970 970 elif vtype==array_type:
971 971 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
972 972 vsize = Numeric.size(var)
973 973 vbytes = vsize*var.itemsize()
974 974 if vbytes < 100000:
975 975 print aformat % (vshape,vsize,var.typecode(),vbytes)
976 976 else:
977 977 print aformat % (vshape,vsize,var.typecode(),vbytes),
978 978 if vbytes < Mb:
979 979 print '(%s kb)' % (vbytes/kb,)
980 980 else:
981 981 print '(%s Mb)' % (vbytes/Mb,)
982 982 else:
983 983 vstr = str(var).replace('\n','\\n')
984 984 if len(vstr) < 50:
985 985 print vstr
986 986 else:
987 987 printpl(vfmt_short)
988 988
989 989 def magic_reset(self, parameter_s=''):
990 990 """Resets the namespace by removing all names defined by the user.
991 991
992 992 Input/Output history are left around in case you need them."""
993 993
994 994 ans = self.shell.ask_yes_no(
995 995 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
996 996 if not ans:
997 997 print 'Nothing done.'
998 998 return
999 999 user_ns = self.shell.user_ns
1000 1000 for i in self.magic_who_ls():
1001 1001 del(user_ns[i])
1002 1002
1003 1003 def magic_config(self,parameter_s=''):
1004 1004 """Show IPython's internal configuration."""
1005 1005
1006 1006 page('Current configuration structure:\n'+
1007 1007 pformat(self.shell.rc.dict()))
1008 1008
1009 1009 def magic_logstart(self,parameter_s=''):
1010 1010 """Start logging anywhere in a session.
1011 1011
1012 1012 %logstart [-o|-r|-t] [log_name [log_mode]]
1013 1013
1014 1014 If no name is given, it defaults to a file named 'ipython_log.py' in your
1015 1015 current directory, in 'rotate' mode (see below).
1016 1016
1017 1017 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1018 1018 history up to that point and then continues logging.
1019 1019
1020 1020 %logstart takes a second optional parameter: logging mode. This can be one
1021 1021 of (note that the modes are given unquoted):\\
1022 1022 append: well, that says it.\\
1023 1023 backup: rename (if exists) to name~ and start name.\\
1024 1024 global: single logfile in your home dir, appended to.\\
1025 1025 over : overwrite existing log.\\
1026 1026 rotate: create rotating logs name.1~, name.2~, etc.
1027 1027
1028 1028 Options:
1029 1029
1030 1030 -o: log also IPython's output. In this mode, all commands which
1031 1031 generate an Out[NN] prompt are recorded to the logfile, right after
1032 1032 their corresponding input line. The output lines are always
1033 1033 prepended with a '#[Out]# ' marker, so that the log remains valid
1034 1034 Python code.
1035 1035
1036 1036 Since this marker is always the same, filtering only the output from
1037 1037 a log is very easy, using for example a simple awk call:
1038 1038
1039 1039 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1040 1040
1041 1041 -r: log 'raw' input. Normally, IPython's logs contain the processed
1042 1042 input, so that user lines are logged in their final form, converted
1043 1043 into valid Python. For example, %Exit is logged as
1044 1044 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1045 1045 exactly as typed, with no transformations applied.
1046 1046
1047 1047 -t: put timestamps before each input line logged (these are put in
1048 1048 comments)."""
1049 1049
1050 1050 opts,par = self.parse_options(parameter_s,'ort')
1051 1051 log_output = 'o' in opts
1052 1052 log_raw_input = 'r' in opts
1053 1053 timestamp = 't' in opts
1054 1054
1055 1055 rc = self.shell.rc
1056 1056 logger = self.shell.logger
1057 1057
1058 1058 # if no args are given, the defaults set in the logger constructor by
1059 1059 # ipytohn remain valid
1060 1060 if par:
1061 1061 try:
1062 1062 logfname,logmode = par.split()
1063 1063 except:
1064 1064 logfname = par
1065 1065 logmode = 'backup'
1066 1066 else:
1067 1067 logfname = logger.logfname
1068 1068 logmode = logger.logmode
1069 1069 # put logfname into rc struct as if it had been called on the command
1070 1070 # line, so it ends up saved in the log header Save it in case we need
1071 1071 # to restore it...
1072 1072 old_logfile = rc.opts.get('logfile','')
1073 1073 if logfname:
1074 1074 logfname = os.path.expanduser(logfname)
1075 1075 rc.opts.logfile = logfname
1076 1076 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1077 1077 try:
1078 1078 started = logger.logstart(logfname,loghead,logmode,
1079 1079 log_output,timestamp,log_raw_input)
1080 1080 except:
1081 1081 rc.opts.logfile = old_logfile
1082 1082 warn("Couldn't start log: %s" % sys.exc_info()[1])
1083 1083 else:
1084 1084 # log input history up to this point, optionally interleaving
1085 1085 # output if requested
1086 1086
1087 1087 if timestamp:
1088 1088 # disable timestamping for the previous history, since we've
1089 1089 # lost those already (no time machine here).
1090 1090 logger.timestamp = False
1091 1091
1092 1092 if log_raw_input:
1093 1093 input_hist = self.shell.input_hist_raw
1094 1094 else:
1095 1095 input_hist = self.shell.input_hist
1096 1096
1097 1097 if log_output:
1098 1098 log_write = logger.log_write
1099 1099 output_hist = self.shell.output_hist
1100 1100 for n in range(1,len(input_hist)-1):
1101 1101 log_write(input_hist[n].rstrip())
1102 1102 if n in output_hist:
1103 1103 log_write(repr(output_hist[n]),'output')
1104 1104 else:
1105 1105 logger.log_write(input_hist[1:])
1106 1106 if timestamp:
1107 1107 # re-enable timestamping
1108 1108 logger.timestamp = True
1109 1109
1110 1110 print ('Activating auto-logging. '
1111 1111 'Current session state plus future input saved.')
1112 1112 logger.logstate()
1113 1113
1114 1114 def magic_logoff(self,parameter_s=''):
1115 1115 """Temporarily stop logging.
1116 1116
1117 1117 You must have previously started logging."""
1118 1118 self.shell.logger.switch_log(0)
1119 1119
1120 1120 def magic_logon(self,parameter_s=''):
1121 1121 """Restart logging.
1122 1122
1123 1123 This function is for restarting logging which you've temporarily
1124 1124 stopped with %logoff. For starting logging for the first time, you
1125 1125 must use the %logstart function, which allows you to specify an
1126 1126 optional log filename."""
1127 1127
1128 1128 self.shell.logger.switch_log(1)
1129 1129
1130 1130 def magic_logstate(self,parameter_s=''):
1131 1131 """Print the status of the logging system."""
1132 1132
1133 1133 self.shell.logger.logstate()
1134 1134
1135 1135 def magic_pdb(self, parameter_s=''):
1136 1136 """Control the calling of the pdb interactive debugger.
1137 1137
1138 1138 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1139 1139 argument it works as a toggle.
1140 1140
1141 1141 When an exception is triggered, IPython can optionally call the
1142 1142 interactive pdb debugger after the traceback printout. %pdb toggles
1143 1143 this feature on and off."""
1144 1144
1145 1145 par = parameter_s.strip().lower()
1146 1146
1147 1147 if par:
1148 1148 try:
1149 1149 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1150 1150 except KeyError:
1151 1151 print ('Incorrect argument. Use on/1, off/0, '
1152 1152 'or nothing for a toggle.')
1153 1153 return
1154 1154 else:
1155 1155 # toggle
1156 1156 new_pdb = not self.shell.InteractiveTB.call_pdb
1157 1157
1158 1158 # set on the shell
1159 1159 self.shell.call_pdb = new_pdb
1160 1160 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1161 1161
1162 1162 def magic_prun(self, parameter_s ='',user_mode=1,
1163 1163 opts=None,arg_lst=None,prog_ns=None):
1164 1164
1165 1165 """Run a statement through the python code profiler.
1166 1166
1167 1167 Usage:\\
1168 1168 %prun [options] statement
1169 1169
1170 1170 The given statement (which doesn't require quote marks) is run via the
1171 1171 python profiler in a manner similar to the profile.run() function.
1172 1172 Namespaces are internally managed to work correctly; profile.run
1173 1173 cannot be used in IPython because it makes certain assumptions about
1174 1174 namespaces which do not hold under IPython.
1175 1175
1176 1176 Options:
1177 1177
1178 1178 -l <limit>: you can place restrictions on what or how much of the
1179 1179 profile gets printed. The limit value can be:
1180 1180
1181 1181 * A string: only information for function names containing this string
1182 1182 is printed.
1183 1183
1184 1184 * An integer: only these many lines are printed.
1185 1185
1186 1186 * A float (between 0 and 1): this fraction of the report is printed
1187 1187 (for example, use a limit of 0.4 to see the topmost 40% only).
1188 1188
1189 1189 You can combine several limits with repeated use of the option. For
1190 1190 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1191 1191 information about class constructors.
1192 1192
1193 1193 -r: return the pstats.Stats object generated by the profiling. This
1194 1194 object has all the information about the profile in it, and you can
1195 1195 later use it for further analysis or in other functions.
1196 1196
1197 1197 Since magic functions have a particular form of calling which prevents
1198 1198 you from writing something like:\\
1199 1199 In [1]: p = %prun -r print 4 # invalid!\\
1200 1200 you must instead use IPython's automatic variables to assign this:\\
1201 1201 In [1]: %prun -r print 4 \\
1202 1202 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1203 1203 In [2]: stats = _
1204 1204
1205 1205 If you really need to assign this value via an explicit function call,
1206 1206 you can always tap directly into the true name of the magic function
1207 1207 by using the _ip.magic function:\\
1208 1208 In [3]: stats = _ip.magic('prun','-r print 4')
1209 1209
1210 1210 You can type _ip.magic? for more details.
1211 1211
1212 1212 -s <key>: sort profile by given key. You can provide more than one key
1213 1213 by using the option several times: '-s key1 -s key2 -s key3...'. The
1214 1214 default sorting key is 'time'.
1215 1215
1216 1216 The following is copied verbatim from the profile documentation
1217 1217 referenced below:
1218 1218
1219 1219 When more than one key is provided, additional keys are used as
1220 1220 secondary criteria when the there is equality in all keys selected
1221 1221 before them.
1222 1222
1223 1223 Abbreviations can be used for any key names, as long as the
1224 1224 abbreviation is unambiguous. The following are the keys currently
1225 1225 defined:
1226 1226
1227 1227 Valid Arg Meaning\\
1228 1228 "calls" call count\\
1229 1229 "cumulative" cumulative time\\
1230 1230 "file" file name\\
1231 1231 "module" file name\\
1232 1232 "pcalls" primitive call count\\
1233 1233 "line" line number\\
1234 1234 "name" function name\\
1235 1235 "nfl" name/file/line\\
1236 1236 "stdname" standard name\\
1237 1237 "time" internal time
1238 1238
1239 1239 Note that all sorts on statistics are in descending order (placing
1240 1240 most time consuming items first), where as name, file, and line number
1241 1241 searches are in ascending order (i.e., alphabetical). The subtle
1242 1242 distinction between "nfl" and "stdname" is that the standard name is a
1243 1243 sort of the name as printed, which means that the embedded line
1244 1244 numbers get compared in an odd way. For example, lines 3, 20, and 40
1245 1245 would (if the file names were the same) appear in the string order
1246 1246 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1247 1247 line numbers. In fact, sort_stats("nfl") is the same as
1248 1248 sort_stats("name", "file", "line").
1249 1249
1250 1250 -T <filename>: save profile results as shown on screen to a text
1251 1251 file. The profile is still shown on screen.
1252 1252
1253 1253 -D <filename>: save (via dump_stats) profile statistics to given
1254 1254 filename. This data is in a format understod by the pstats module, and
1255 1255 is generated by a call to the dump_stats() method of profile
1256 1256 objects. The profile is still shown on screen.
1257 1257
1258 1258 If you want to run complete programs under the profiler's control, use
1259 1259 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1260 1260 contains profiler specific options as described here.
1261 1261
1262 1262 You can read the complete documentation for the profile module with:\\
1263 1263 In [1]: import profile; profile.help() """
1264 1264
1265 1265 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1266 1266 # protect user quote marks
1267 1267 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1268 1268
1269 1269 if user_mode: # regular user call
1270 1270 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1271 1271 list_all=1)
1272 1272 namespace = self.shell.user_ns
1273 1273 else: # called to run a program by %run -p
1274 1274 try:
1275 1275 filename = get_py_filename(arg_lst[0])
1276 1276 except IOError,msg:
1277 1277 error(msg)
1278 1278 return
1279 1279
1280 1280 arg_str = 'execfile(filename,prog_ns)'
1281 1281 namespace = locals()
1282 1282
1283 1283 opts.merge(opts_def)
1284 1284
1285 1285 prof = profile.Profile()
1286 1286 try:
1287 1287 prof = prof.runctx(arg_str,namespace,namespace)
1288 1288 sys_exit = ''
1289 1289 except SystemExit:
1290 1290 sys_exit = """*** SystemExit exception caught in code being profiled."""
1291 1291
1292 1292 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1293 1293
1294 1294 lims = opts.l
1295 1295 if lims:
1296 1296 lims = [] # rebuild lims with ints/floats/strings
1297 1297 for lim in opts.l:
1298 1298 try:
1299 1299 lims.append(int(lim))
1300 1300 except ValueError:
1301 1301 try:
1302 1302 lims.append(float(lim))
1303 1303 except ValueError:
1304 1304 lims.append(lim)
1305 1305
1306 1306 # trap output
1307 1307 sys_stdout = sys.stdout
1308 1308 stdout_trap = StringIO()
1309 1309 try:
1310 1310 sys.stdout = stdout_trap
1311 1311 stats.print_stats(*lims)
1312 1312 finally:
1313 1313 sys.stdout = sys_stdout
1314 1314 output = stdout_trap.getvalue()
1315 1315 output = output.rstrip()
1316 1316
1317 1317 page(output,screen_lines=self.shell.rc.screen_length)
1318 1318 print sys_exit,
1319 1319
1320 1320 dump_file = opts.D[0]
1321 1321 text_file = opts.T[0]
1322 1322 if dump_file:
1323 1323 prof.dump_stats(dump_file)
1324 1324 print '\n*** Profile stats marshalled to file',\
1325 1325 `dump_file`+'.',sys_exit
1326 1326 if text_file:
1327 1327 file(text_file,'w').write(output)
1328 1328 print '\n*** Profile printout saved to text file',\
1329 1329 `text_file`+'.',sys_exit
1330 1330
1331 1331 if opts.has_key('r'):
1332 1332 return stats
1333 1333 else:
1334 1334 return None
1335 1335
1336 1336 def magic_run(self, parameter_s ='',runner=None):
1337 1337 """Run the named file inside IPython as a program.
1338 1338
1339 1339 Usage:\\
1340 1340 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1341 1341
1342 1342 Parameters after the filename are passed as command-line arguments to
1343 1343 the program (put in sys.argv). Then, control returns to IPython's
1344 1344 prompt.
1345 1345
1346 1346 This is similar to running at a system prompt:\\
1347 1347 $ python file args\\
1348 1348 but with the advantage of giving you IPython's tracebacks, and of
1349 1349 loading all variables into your interactive namespace for further use
1350 1350 (unless -p is used, see below).
1351 1351
1352 1352 The file is executed in a namespace initially consisting only of
1353 1353 __name__=='__main__' and sys.argv constructed as indicated. It thus
1354 1354 sees its environment as if it were being run as a stand-alone
1355 1355 program. But after execution, the IPython interactive namespace gets
1356 1356 updated with all variables defined in the program (except for __name__
1357 1357 and sys.argv). This allows for very convenient loading of code for
1358 1358 interactive work, while giving each program a 'clean sheet' to run in.
1359 1359
1360 1360 Options:
1361 1361
1362 1362 -n: __name__ is NOT set to '__main__', but to the running file's name
1363 1363 without extension (as python does under import). This allows running
1364 1364 scripts and reloading the definitions in them without calling code
1365 1365 protected by an ' if __name__ == "__main__" ' clause.
1366 1366
1367 1367 -i: run the file in IPython's namespace instead of an empty one. This
1368 1368 is useful if you are experimenting with code written in a text editor
1369 1369 which depends on variables defined interactively.
1370 1370
1371 1371 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1372 1372 being run. This is particularly useful if IPython is being used to
1373 1373 run unittests, which always exit with a sys.exit() call. In such
1374 1374 cases you are interested in the output of the test results, not in
1375 1375 seeing a traceback of the unittest module.
1376 1376
1377 1377 -t: print timing information at the end of the run. IPython will give
1378 1378 you an estimated CPU time consumption for your script, which under
1379 1379 Unix uses the resource module to avoid the wraparound problems of
1380 1380 time.clock(). Under Unix, an estimate of time spent on system tasks
1381 1381 is also given (for Windows platforms this is reported as 0.0).
1382 1382
1383 1383 If -t is given, an additional -N<N> option can be given, where <N>
1384 1384 must be an integer indicating how many times you want the script to
1385 1385 run. The final timing report will include total and per run results.
1386 1386
1387 1387 For example (testing the script uniq_stable.py):
1388 1388
1389 1389 In [1]: run -t uniq_stable
1390 1390
1391 1391 IPython CPU timings (estimated):\\
1392 1392 User : 0.19597 s.\\
1393 1393 System: 0.0 s.\\
1394 1394
1395 1395 In [2]: run -t -N5 uniq_stable
1396 1396
1397 1397 IPython CPU timings (estimated):\\
1398 1398 Total runs performed: 5\\
1399 1399 Times : Total Per run\\
1400 1400 User : 0.910862 s, 0.1821724 s.\\
1401 1401 System: 0.0 s, 0.0 s.
1402 1402
1403 1403 -d: run your program under the control of pdb, the Python debugger.
1404 1404 This allows you to execute your program step by step, watch variables,
1405 1405 etc. Internally, what IPython does is similar to calling:
1406 1406
1407 1407 pdb.run('execfile("YOURFILENAME")')
1408 1408
1409 1409 with a breakpoint set on line 1 of your file. You can change the line
1410 1410 number for this automatic breakpoint to be <N> by using the -bN option
1411 1411 (where N must be an integer). For example:
1412 1412
1413 1413 %run -d -b40 myscript
1414 1414
1415 1415 will set the first breakpoint at line 40 in myscript.py. Note that
1416 1416 the first breakpoint must be set on a line which actually does
1417 1417 something (not a comment or docstring) for it to stop execution.
1418 1418
1419 1419 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1420 1420 first enter 'c' (without qoutes) to start execution up to the first
1421 1421 breakpoint.
1422 1422
1423 1423 Entering 'help' gives information about the use of the debugger. You
1424 1424 can easily see pdb's full documentation with "import pdb;pdb.help()"
1425 1425 at a prompt.
1426 1426
1427 1427 -p: run program under the control of the Python profiler module (which
1428 1428 prints a detailed report of execution times, function calls, etc).
1429 1429
1430 1430 You can pass other options after -p which affect the behavior of the
1431 1431 profiler itself. See the docs for %prun for details.
1432 1432
1433 1433 In this mode, the program's variables do NOT propagate back to the
1434 1434 IPython interactive namespace (because they remain in the namespace
1435 1435 where the profiler executes them).
1436 1436
1437 1437 Internally this triggers a call to %prun, see its documentation for
1438 1438 details on the options available specifically for profiling."""
1439 1439
1440 1440 # get arguments and set sys.argv for program to be run.
1441 1441 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1442 1442 mode='list',list_all=1)
1443 1443
1444 1444 try:
1445 1445 filename = get_py_filename(arg_lst[0])
1446 1446 except IndexError:
1447 1447 warn('you must provide at least a filename.')
1448 1448 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1449 1449 return
1450 1450 except IOError,msg:
1451 1451 error(msg)
1452 1452 return
1453 1453
1454 1454 # Control the response to exit() calls made by the script being run
1455 1455 exit_ignore = opts.has_key('e')
1456 1456
1457 1457 # Make sure that the running script gets a proper sys.argv as if it
1458 1458 # were run from a system shell.
1459 1459 save_argv = sys.argv # save it for later restoring
1460 1460 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1461 1461
1462 1462 if opts.has_key('i'):
1463 1463 prog_ns = self.shell.user_ns
1464 1464 __name__save = self.shell.user_ns['__name__']
1465 1465 prog_ns['__name__'] = '__main__'
1466 1466 else:
1467 1467 if opts.has_key('n'):
1468 1468 name = os.path.splitext(os.path.basename(filename))[0]
1469 1469 else:
1470 1470 name = '__main__'
1471 1471 prog_ns = {'__name__':name}
1472 1472
1473 1473 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1474 1474 # set the __file__ global in the script's namespace
1475 1475 prog_ns['__file__'] = filename
1476 1476
1477 1477 # pickle fix. See iplib for an explanation. But we need to make sure
1478 1478 # that, if we overwrite __main__, we replace it at the end
1479 1479 if prog_ns['__name__'] == '__main__':
1480 1480 restore_main = sys.modules['__main__']
1481 1481 else:
1482 1482 restore_main = False
1483 1483
1484 1484 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1485 1485
1486 1486 stats = None
1487 1487 try:
1488 1488 if opts.has_key('p'):
1489 1489 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1490 1490 else:
1491 1491 if opts.has_key('d'):
1492 1492 deb = Debugger.Pdb(self.shell.rc.colors)
1493 1493 # reset Breakpoint state, which is moronically kept
1494 1494 # in a class
1495 1495 bdb.Breakpoint.next = 1
1496 1496 bdb.Breakpoint.bplist = {}
1497 1497 bdb.Breakpoint.bpbynumber = [None]
1498 1498 # Set an initial breakpoint to stop execution
1499 1499 maxtries = 10
1500 1500 bp = int(opts.get('b',[1])[0])
1501 1501 checkline = deb.checkline(filename,bp)
1502 1502 if not checkline:
1503 1503 for bp in range(bp+1,bp+maxtries+1):
1504 1504 if deb.checkline(filename,bp):
1505 1505 break
1506 1506 else:
1507 1507 msg = ("\nI failed to find a valid line to set "
1508 1508 "a breakpoint\n"
1509 1509 "after trying up to line: %s.\n"
1510 1510 "Please set a valid breakpoint manually "
1511 1511 "with the -b option." % bp)
1512 1512 error(msg)
1513 1513 return
1514 1514 # if we find a good linenumber, set the breakpoint
1515 1515 deb.do_break('%s:%s' % (filename,bp))
1516 1516 # Start file run
1517 1517 print "NOTE: Enter 'c' at the",
1518 1518 print "ipdb> prompt to start your script."
1519 1519 try:
1520 1520 deb.run('execfile("%s")' % filename,prog_ns)
1521 1521 except:
1522 1522 etype, value, tb = sys.exc_info()
1523 1523 # Skip three frames in the traceback: the %run one,
1524 1524 # one inside bdb.py, and the command-line typed by the
1525 1525 # user (run by exec in pdb itself).
1526 1526 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1527 1527 else:
1528 1528 if runner is None:
1529 1529 runner = self.shell.safe_execfile
1530 1530 if opts.has_key('t'):
1531 1531 try:
1532 1532 nruns = int(opts['N'][0])
1533 1533 if nruns < 1:
1534 1534 error('Number of runs must be >=1')
1535 1535 return
1536 1536 except (KeyError):
1537 1537 nruns = 1
1538 1538 if nruns == 1:
1539 1539 t0 = clock2()
1540 1540 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1541 1541 t1 = clock2()
1542 1542 t_usr = t1[0]-t0[0]
1543 1543 t_sys = t1[1]-t1[1]
1544 1544 print "\nIPython CPU timings (estimated):"
1545 1545 print " User : %10s s." % t_usr
1546 1546 print " System: %10s s." % t_sys
1547 1547 else:
1548 1548 runs = range(nruns)
1549 1549 t0 = clock2()
1550 1550 for nr in runs:
1551 1551 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1552 1552 t1 = clock2()
1553 1553 t_usr = t1[0]-t0[0]
1554 1554 t_sys = t1[1]-t1[1]
1555 1555 print "\nIPython CPU timings (estimated):"
1556 1556 print "Total runs performed:",nruns
1557 1557 print " Times : %10s %10s" % ('Total','Per run')
1558 1558 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1559 1559 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1560 1560
1561 1561 else:
1562 1562 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1563 1563 if opts.has_key('i'):
1564 1564 self.shell.user_ns['__name__'] = __name__save
1565 1565 else:
1566 1566 # update IPython interactive namespace
1567 1567 del prog_ns['__name__']
1568 1568 self.shell.user_ns.update(prog_ns)
1569 1569 finally:
1570 1570 sys.argv = save_argv
1571 1571 if restore_main:
1572 1572 sys.modules['__main__'] = restore_main
1573 1573 return stats
1574 1574
1575 1575 def magic_runlog(self, parameter_s =''):
1576 1576 """Run files as logs.
1577 1577
1578 1578 Usage:\\
1579 1579 %runlog file1 file2 ...
1580 1580
1581 1581 Run the named files (treating them as log files) in sequence inside
1582 1582 the interpreter, and return to the prompt. This is much slower than
1583 1583 %run because each line is executed in a try/except block, but it
1584 1584 allows running files with syntax errors in them.
1585 1585
1586 1586 Normally IPython will guess when a file is one of its own logfiles, so
1587 1587 you can typically use %run even for logs. This shorthand allows you to
1588 1588 force any file to be treated as a log file."""
1589 1589
1590 1590 for f in parameter_s.split():
1591 1591 self.shell.safe_execfile(f,self.shell.user_ns,
1592 1592 self.shell.user_ns,islog=1)
1593 1593
1594 1594 def magic_timeit(self, parameter_s =''):
1595 1595 """Time execution of a Python statement or expression
1596 1596
1597 1597 Usage:\\
1598 1598 %timeit [-n<N> -r<R> [-t|-c]] statement
1599 1599
1600 1600 Time execution of a Python statement or expression using the timeit
1601 1601 module.
1602 1602
1603 1603 Options:
1604 1604 -n<N>: execute the given statement <N> times in a loop. If this value
1605 1605 is not given, a fitting value is chosen.
1606 1606
1607 1607 -r<R>: repeat the loop iteration <R> times and take the best result.
1608 1608 Default: 3
1609 1609
1610 1610 -t: use time.time to measure the time, which is the default on Unix.
1611 1611 This function measures wall time.
1612 1612
1613 1613 -c: use time.clock to measure the time, which is the default on
1614 1614 Windows and measures wall time. On Unix, resource.getrusage is used
1615 1615 instead and returns the CPU user time.
1616 1616
1617 1617 -p<P>: use a precision of <P> digits to display the timing result.
1618 1618 Default: 3
1619 1619
1620 1620
1621 1621 Examples:\\
1622 1622 In [1]: %timeit pass
1623 1623 10000000 loops, best of 3: 53.3 ns per loop
1624 1624
1625 1625 In [2]: u = None
1626 1626
1627 1627 In [3]: %timeit u is None
1628 1628 10000000 loops, best of 3: 184 ns per loop
1629 1629
1630 1630 In [4]: %timeit -r 4 u == None
1631 1631 1000000 loops, best of 4: 242 ns per loop
1632 1632
1633 1633 In [5]: import time
1634 1634
1635 1635 In [6]: %timeit -n1 time.sleep(2)
1636 1636 1 loops, best of 3: 2 s per loop
1637 1637
1638 1638
1639 1639 The times reported by %timeit will be slightly higher than those reported
1640 1640 by the timeit.py script when variables are accessed. This is due to the
1641 1641 fact that %timeit executes the statement in the namespace of the shell,
1642 1642 compared with timeit.py, which uses a single setup statement to import
1643 1643 function or create variables. Generally, the bias does not matter as long
1644 1644 as results from timeit.py are not mixed with those from %timeit."""
1645 1645 import timeit
1646 1646 import math
1647 1647
1648 1648 units = ["s", "ms", "\xc2\xb5s", "ns"]
1649 1649 scaling = [1, 1e3, 1e6, 1e9]
1650 1650
1651 1651 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:')
1652 1652 if stmt == "":
1653 1653 return
1654 1654 timefunc = timeit.default_timer
1655 1655 number = int(getattr(opts, "n", 0))
1656 1656 repeat = int(getattr(opts, "r", timeit.default_repeat))
1657 1657 precision = int(getattr(opts, "p", 3))
1658 1658 if hasattr(opts, "t"):
1659 1659 timefunc = time.time
1660 1660 if hasattr(opts, "c"):
1661 1661 timefunc = clock
1662 1662
1663 1663 timer = timeit.Timer(timer=timefunc)
1664 1664 # this code has tight coupling to the inner workings of timeit.Timer,
1665 1665 # but is there a better way to achieve that the code stmt has access
1666 1666 # to the shell namespace?
1667 1667
1668 1668 src = timeit.template % {'stmt': timeit.reindent(stmt, 8), 'setup': "pass"}
1669 1669 code = compile(src, "<magic-timeit>", "exec")
1670 1670 ns = {}
1671 1671 exec code in self.shell.user_ns, ns
1672 1672 timer.inner = ns["inner"]
1673 1673
1674 1674 if number == 0:
1675 1675 # determine number so that 0.2 <= total time < 2.0
1676 1676 number = 1
1677 1677 for i in range(1, 10):
1678 1678 number *= 10
1679 1679 if timer.timeit(number) >= 0.2:
1680 1680 break
1681 1681
1682 1682 best = min(timer.repeat(repeat, number)) / number
1683 1683
1684 1684 if best > 0.0:
1685 1685 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1686 1686 else:
1687 1687 order = 3
1688 1688 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1689 1689 precision,
1690 1690 best * scaling[order],
1691 1691 units[order])
1692 1692
1693 1693 def magic_time(self,parameter_s = ''):
1694 1694 """Time execution of a Python statement or expression.
1695 1695
1696 1696 The CPU and wall clock times are printed, and the value of the
1697 1697 expression (if any) is returned. Note that under Win32, system time
1698 1698 is always reported as 0, since it can not be measured.
1699 1699
1700 1700 This function provides very basic timing functionality. In Python
1701 1701 2.3, the timeit module offers more control and sophistication, so this
1702 1702 could be rewritten to use it (patches welcome).
1703 1703
1704 1704 Some examples:
1705 1705
1706 1706 In [1]: time 2**128
1707 1707 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1708 1708 Wall time: 0.00
1709 1709 Out[1]: 340282366920938463463374607431768211456L
1710 1710
1711 1711 In [2]: n = 1000000
1712 1712
1713 1713 In [3]: time sum(range(n))
1714 1714 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1715 1715 Wall time: 1.37
1716 1716 Out[3]: 499999500000L
1717 1717
1718 1718 In [4]: time print 'hello world'
1719 1719 hello world
1720 1720 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1721 1721 Wall time: 0.00
1722 1722 """
1723 1723
1724 1724 # fail immediately if the given expression can't be compiled
1725 1725 try:
1726 1726 mode = 'eval'
1727 1727 code = compile(parameter_s,'<timed eval>',mode)
1728 1728 except SyntaxError:
1729 1729 mode = 'exec'
1730 1730 code = compile(parameter_s,'<timed exec>',mode)
1731 1731 # skew measurement as little as possible
1732 1732 glob = self.shell.user_ns
1733 1733 clk = clock2
1734 1734 wtime = time.time
1735 1735 # time execution
1736 1736 wall_st = wtime()
1737 1737 if mode=='eval':
1738 1738 st = clk()
1739 1739 out = eval(code,glob)
1740 1740 end = clk()
1741 1741 else:
1742 1742 st = clk()
1743 1743 exec code in glob
1744 1744 end = clk()
1745 1745 out = None
1746 1746 wall_end = wtime()
1747 1747 # Compute actual times and report
1748 1748 wall_time = wall_end-wall_st
1749 1749 cpu_user = end[0]-st[0]
1750 1750 cpu_sys = end[1]-st[1]
1751 1751 cpu_tot = cpu_user+cpu_sys
1752 1752 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1753 1753 (cpu_user,cpu_sys,cpu_tot)
1754 1754 print "Wall time: %.2f" % wall_time
1755 1755 return out
1756 1756
1757 1757 def magic_macro(self,parameter_s = ''):
1758 1758 """Define a set of input lines as a macro for future re-execution.
1759 1759
1760 1760 Usage:\\
1761 1761 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1762 1762
1763 1763 Options:
1764 1764
1765 1765 -r: use 'raw' input. By default, the 'processed' history is used,
1766 1766 so that magics are loaded in their transformed version to valid
1767 1767 Python. If this option is given, the raw input as typed as the
1768 1768 command line is used instead.
1769 1769
1770 1770 This will define a global variable called `name` which is a string
1771 1771 made of joining the slices and lines you specify (n1,n2,... numbers
1772 1772 above) from your input history into a single string. This variable
1773 1773 acts like an automatic function which re-executes those lines as if
1774 1774 you had typed them. You just type 'name' at the prompt and the code
1775 1775 executes.
1776 1776
1777 1777 The notation for indicating number ranges is: n1-n2 means 'use line
1778 1778 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1779 1779 using the lines numbered 5,6 and 7.
1780 1780
1781 1781 Note: as a 'hidden' feature, you can also use traditional python slice
1782 1782 notation, where N:M means numbers N through M-1.
1783 1783
1784 1784 For example, if your history contains (%hist prints it):
1785 1785
1786 1786 44: x=1\\
1787 1787 45: y=3\\
1788 1788 46: z=x+y\\
1789 1789 47: print x\\
1790 1790 48: a=5\\
1791 1791 49: print 'x',x,'y',y\\
1792 1792
1793 1793 you can create a macro with lines 44 through 47 (included) and line 49
1794 1794 called my_macro with:
1795 1795
1796 1796 In [51]: %macro my_macro 44-47 49
1797 1797
1798 1798 Now, typing `my_macro` (without quotes) will re-execute all this code
1799 1799 in one pass.
1800 1800
1801 1801 You don't need to give the line-numbers in order, and any given line
1802 1802 number can appear multiple times. You can assemble macros with any
1803 1803 lines from your input history in any order.
1804 1804
1805 1805 The macro is a simple object which holds its value in an attribute,
1806 1806 but IPython's display system checks for macros and executes them as
1807 1807 code instead of printing them when you type their name.
1808 1808
1809 1809 You can view a macro's contents by explicitly printing it with:
1810 1810
1811 1811 'print macro_name'.
1812 1812
1813 1813 For one-off cases which DON'T contain magic function calls in them you
1814 1814 can obtain similar results by explicitly executing slices from your
1815 1815 input history with:
1816 1816
1817 1817 In [60]: exec In[44:48]+In[49]"""
1818 1818
1819 1819 opts,args = self.parse_options(parameter_s,'r',mode='list')
1820 1820 name,ranges = args[0], args[1:]
1821 1821 #print 'rng',ranges # dbg
1822 1822 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1823 1823 macro = Macro(lines)
1824 1824 self.shell.user_ns.update({name:macro})
1825 1825 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1826 1826 print 'Macro contents:'
1827 1827 print macro,
1828 1828
1829 1829 def magic_save(self,parameter_s = ''):
1830 1830 """Save a set of lines to a given filename.
1831 1831
1832 1832 Usage:\\
1833 1833 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1834 1834
1835 1835 Options:
1836 1836
1837 1837 -r: use 'raw' input. By default, the 'processed' history is used,
1838 1838 so that magics are loaded in their transformed version to valid
1839 1839 Python. If this option is given, the raw input as typed as the
1840 1840 command line is used instead.
1841 1841
1842 1842 This function uses the same syntax as %macro for line extraction, but
1843 1843 instead of creating a macro it saves the resulting string to the
1844 1844 filename you specify.
1845 1845
1846 1846 It adds a '.py' extension to the file if you don't do so yourself, and
1847 1847 it asks for confirmation before overwriting existing files."""
1848 1848
1849 1849 opts,args = self.parse_options(parameter_s,'r',mode='list')
1850 1850 fname,ranges = args[0], args[1:]
1851 1851 if not fname.endswith('.py'):
1852 1852 fname += '.py'
1853 1853 if os.path.isfile(fname):
1854 1854 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1855 1855 if ans.lower() not in ['y','yes']:
1856 1856 print 'Operation cancelled.'
1857 1857 return
1858 1858 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1859 1859 f = file(fname,'w')
1860 1860 f.write(cmds)
1861 1861 f.close()
1862 1862 print 'The following commands were written to file `%s`:' % fname
1863 1863 print cmds
1864 1864
1865 1865 def _edit_macro(self,mname,macro):
1866 1866 """open an editor with the macro data in a file"""
1867 1867 filename = self.shell.mktempfile(macro.value)
1868 1868 self.shell.hooks.editor(filename)
1869 1869
1870 1870 # and make a new macro object, to replace the old one
1871 1871 mfile = open(filename)
1872 1872 mvalue = mfile.read()
1873 1873 mfile.close()
1874 1874 self.shell.user_ns[mname] = Macro(mvalue)
1875 1875
1876 1876 def magic_ed(self,parameter_s=''):
1877 1877 """Alias to %edit."""
1878 1878 return self.magic_edit(parameter_s)
1879 1879
1880 1880 def magic_edit(self,parameter_s='',last_call=['','']):
1881 1881 """Bring up an editor and execute the resulting code.
1882 1882
1883 1883 Usage:
1884 1884 %edit [options] [args]
1885 1885
1886 1886 %edit runs IPython's editor hook. The default version of this hook is
1887 1887 set to call the __IPYTHON__.rc.editor command. This is read from your
1888 1888 environment variable $EDITOR. If this isn't found, it will default to
1889 1889 vi under Linux/Unix and to notepad under Windows. See the end of this
1890 1890 docstring for how to change the editor hook.
1891 1891
1892 1892 You can also set the value of this editor via the command line option
1893 1893 '-editor' or in your ipythonrc file. This is useful if you wish to use
1894 1894 specifically for IPython an editor different from your typical default
1895 1895 (and for Windows users who typically don't set environment variables).
1896 1896
1897 1897 This command allows you to conveniently edit multi-line code right in
1898 1898 your IPython session.
1899 1899
1900 1900 If called without arguments, %edit opens up an empty editor with a
1901 1901 temporary file and will execute the contents of this file when you
1902 1902 close it (don't forget to save it!).
1903 1903
1904 1904
1905 1905 Options:
1906 1906
1907 1907 -n <number>: open the editor at a specified line number. By default,
1908 1908 the IPython editor hook uses the unix syntax 'editor +N filename', but
1909 1909 you can configure this by providing your own modified hook if your
1910 1910 favorite editor supports line-number specifications with a different
1911 1911 syntax.
1912 1912
1913 1913 -p: this will call the editor with the same data as the previous time
1914 1914 it was used, regardless of how long ago (in your current session) it
1915 1915 was.
1916 1916
1917 1917 -r: use 'raw' input. This option only applies to input taken from the
1918 1918 user's history. By default, the 'processed' history is used, so that
1919 1919 magics are loaded in their transformed version to valid Python. If
1920 1920 this option is given, the raw input as typed as the command line is
1921 1921 used instead. When you exit the editor, it will be executed by
1922 1922 IPython's own processor.
1923 1923
1924 1924 -x: do not execute the edited code immediately upon exit. This is
1925 1925 mainly useful if you are editing programs which need to be called with
1926 1926 command line arguments, which you can then do using %run.
1927 1927
1928 1928
1929 1929 Arguments:
1930 1930
1931 1931 If arguments are given, the following possibilites exist:
1932 1932
1933 1933 - The arguments are numbers or pairs of colon-separated numbers (like
1934 1934 1 4:8 9). These are interpreted as lines of previous input to be
1935 1935 loaded into the editor. The syntax is the same of the %macro command.
1936 1936
1937 1937 - If the argument doesn't start with a number, it is evaluated as a
1938 1938 variable and its contents loaded into the editor. You can thus edit
1939 1939 any string which contains python code (including the result of
1940 1940 previous edits).
1941 1941
1942 1942 - If the argument is the name of an object (other than a string),
1943 1943 IPython will try to locate the file where it was defined and open the
1944 1944 editor at the point where it is defined. You can use `%edit function`
1945 1945 to load an editor exactly at the point where 'function' is defined,
1946 1946 edit it and have the file be executed automatically.
1947 1947
1948 1948 If the object is a macro (see %macro for details), this opens up your
1949 1949 specified editor with a temporary file containing the macro's data.
1950 1950 Upon exit, the macro is reloaded with the contents of the file.
1951 1951
1952 1952 Note: opening at an exact line is only supported under Unix, and some
1953 1953 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1954 1954 '+NUMBER' parameter necessary for this feature. Good editors like
1955 1955 (X)Emacs, vi, jed, pico and joe all do.
1956 1956
1957 1957 - If the argument is not found as a variable, IPython will look for a
1958 1958 file with that name (adding .py if necessary) and load it into the
1959 1959 editor. It will execute its contents with execfile() when you exit,
1960 1960 loading any code in the file into your interactive namespace.
1961 1961
1962 1962 After executing your code, %edit will return as output the code you
1963 1963 typed in the editor (except when it was an existing file). This way
1964 1964 you can reload the code in further invocations of %edit as a variable,
1965 1965 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1966 1966 the output.
1967 1967
1968 1968 Note that %edit is also available through the alias %ed.
1969 1969
1970 1970 This is an example of creating a simple function inside the editor and
1971 1971 then modifying it. First, start up the editor:
1972 1972
1973 1973 In [1]: ed\\
1974 1974 Editing... done. Executing edited code...\\
1975 1975 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1976 1976
1977 1977 We can then call the function foo():
1978 1978
1979 1979 In [2]: foo()\\
1980 1980 foo() was defined in an editing session
1981 1981
1982 1982 Now we edit foo. IPython automatically loads the editor with the
1983 1983 (temporary) file where foo() was previously defined:
1984 1984
1985 1985 In [3]: ed foo\\
1986 1986 Editing... done. Executing edited code...
1987 1987
1988 1988 And if we call foo() again we get the modified version:
1989 1989
1990 1990 In [4]: foo()\\
1991 1991 foo() has now been changed!
1992 1992
1993 1993 Here is an example of how to edit a code snippet successive
1994 1994 times. First we call the editor:
1995 1995
1996 1996 In [8]: ed\\
1997 1997 Editing... done. Executing edited code...\\
1998 1998 hello\\
1999 1999 Out[8]: "print 'hello'\\n"
2000 2000
2001 2001 Now we call it again with the previous output (stored in _):
2002 2002
2003 2003 In [9]: ed _\\
2004 2004 Editing... done. Executing edited code...\\
2005 2005 hello world\\
2006 2006 Out[9]: "print 'hello world'\\n"
2007 2007
2008 2008 Now we call it with the output #8 (stored in _8, also as Out[8]):
2009 2009
2010 2010 In [10]: ed _8\\
2011 2011 Editing... done. Executing edited code...\\
2012 2012 hello again\\
2013 2013 Out[10]: "print 'hello again'\\n"
2014 2014
2015 2015
2016 2016 Changing the default editor hook:
2017 2017
2018 2018 If you wish to write your own editor hook, you can put it in a
2019 2019 configuration file which you load at startup time. The default hook
2020 2020 is defined in the IPython.hooks module, and you can use that as a
2021 2021 starting example for further modifications. That file also has
2022 2022 general instructions on how to set a new hook for use once you've
2023 2023 defined it."""
2024 2024
2025 2025 # FIXME: This function has become a convoluted mess. It needs a
2026 2026 # ground-up rewrite with clean, simple logic.
2027 2027
2028 2028 def make_filename(arg):
2029 2029 "Make a filename from the given args"
2030 2030 try:
2031 2031 filename = get_py_filename(arg)
2032 2032 except IOError:
2033 2033 if args.endswith('.py'):
2034 2034 filename = arg
2035 2035 else:
2036 2036 filename = None
2037 2037 return filename
2038 2038
2039 2039 # custom exceptions
2040 2040 class DataIsObject(Exception): pass
2041 2041
2042 2042 opts,args = self.parse_options(parameter_s,'prxn:')
2043 2043 # Set a few locals from the options for convenience:
2044 2044 opts_p = opts.has_key('p')
2045 2045 opts_r = opts.has_key('r')
2046 2046
2047 2047 # Default line number value
2048 2048 lineno = opts.get('n',None)
2049 2049
2050 2050 if opts_p:
2051 2051 args = '_%s' % last_call[0]
2052 2052 if not self.shell.user_ns.has_key(args):
2053 2053 args = last_call[1]
2054 2054
2055 2055 # use last_call to remember the state of the previous call, but don't
2056 2056 # let it be clobbered by successive '-p' calls.
2057 2057 try:
2058 2058 last_call[0] = self.shell.outputcache.prompt_count
2059 2059 if not opts_p:
2060 2060 last_call[1] = parameter_s
2061 2061 except:
2062 2062 pass
2063 2063
2064 2064 # by default this is done with temp files, except when the given
2065 2065 # arg is a filename
2066 2066 use_temp = 1
2067 2067
2068 2068 if re.match(r'\d',args):
2069 2069 # Mode where user specifies ranges of lines, like in %macro.
2070 2070 # This means that you can't edit files whose names begin with
2071 2071 # numbers this way. Tough.
2072 2072 ranges = args.split()
2073 2073 data = ''.join(self.extract_input_slices(ranges,opts_r))
2074 2074 elif args.endswith('.py'):
2075 2075 filename = make_filename(args)
2076 2076 data = ''
2077 2077 use_temp = 0
2078 2078 elif args:
2079 2079 try:
2080 2080 # Load the parameter given as a variable. If not a string,
2081 2081 # process it as an object instead (below)
2082 2082
2083 2083 #print '*** args',args,'type',type(args) # dbg
2084 2084 data = eval(args,self.shell.user_ns)
2085 2085 if not type(data) in StringTypes:
2086 2086 raise DataIsObject
2087 2087
2088 2088 except (NameError,SyntaxError):
2089 2089 # given argument is not a variable, try as a filename
2090 2090 filename = make_filename(args)
2091 2091 if filename is None:
2092 2092 warn("Argument given (%s) can't be found as a variable "
2093 2093 "or as a filename." % args)
2094 2094 return
2095 2095
2096 2096 data = ''
2097 2097 use_temp = 0
2098 2098 except DataIsObject:
2099 2099
2100 2100 # macros have a special edit function
2101 2101 if isinstance(data,Macro):
2102 2102 self._edit_macro(args,data)
2103 2103 return
2104 2104
2105 2105 # For objects, try to edit the file where they are defined
2106 2106 try:
2107 2107 filename = inspect.getabsfile(data)
2108 2108 datafile = 1
2109 2109 except TypeError:
2110 2110 filename = make_filename(args)
2111 2111 datafile = 1
2112 2112 warn('Could not find file where `%s` is defined.\n'
2113 2113 'Opening a file named `%s`' % (args,filename))
2114 2114 # Now, make sure we can actually read the source (if it was in
2115 2115 # a temp file it's gone by now).
2116 2116 if datafile:
2117 2117 try:
2118 2118 if lineno is None:
2119 2119 lineno = inspect.getsourcelines(data)[1]
2120 2120 except IOError:
2121 2121 filename = make_filename(args)
2122 2122 if filename is None:
2123 2123 warn('The file `%s` where `%s` was defined cannot '
2124 2124 'be read.' % (filename,data))
2125 2125 return
2126 2126 use_temp = 0
2127 2127 else:
2128 2128 data = ''
2129 2129
2130 2130 if use_temp:
2131 2131 filename = self.shell.mktempfile(data)
2132 2132 print 'IPython will make a temporary file named:',filename
2133 2133
2134 2134 # do actual editing here
2135 2135 print 'Editing...',
2136 2136 sys.stdout.flush()
2137 2137 self.shell.hooks.editor(filename,lineno)
2138 2138 if opts.has_key('x'): # -x prevents actual execution
2139 2139 print
2140 2140 else:
2141 2141 print 'done. Executing edited code...'
2142 2142 if opts_r:
2143 2143 self.shell.runlines(file_read(filename))
2144 2144 else:
2145 2145 self.shell.safe_execfile(filename,self.shell.user_ns)
2146 2146 if use_temp:
2147 2147 try:
2148 2148 return open(filename).read()
2149 2149 except IOError,msg:
2150 2150 if msg.filename == filename:
2151 2151 warn('File not found. Did you forget to save?')
2152 2152 return
2153 2153 else:
2154 2154 self.shell.showtraceback()
2155 2155
2156 2156 def magic_xmode(self,parameter_s = ''):
2157 2157 """Switch modes for the exception handlers.
2158 2158
2159 2159 Valid modes: Plain, Context and Verbose.
2160 2160
2161 2161 If called without arguments, acts as a toggle."""
2162 2162
2163 2163 def xmode_switch_err(name):
2164 2164 warn('Error changing %s exception modes.\n%s' %
2165 2165 (name,sys.exc_info()[1]))
2166 2166
2167 2167 shell = self.shell
2168 2168 new_mode = parameter_s.strip().capitalize()
2169 2169 try:
2170 2170 shell.InteractiveTB.set_mode(mode=new_mode)
2171 2171 print 'Exception reporting mode:',shell.InteractiveTB.mode
2172 2172 except:
2173 2173 xmode_switch_err('user')
2174 2174
2175 2175 # threaded shells use a special handler in sys.excepthook
2176 2176 if shell.isthreaded:
2177 2177 try:
2178 2178 shell.sys_excepthook.set_mode(mode=new_mode)
2179 2179 except:
2180 2180 xmode_switch_err('threaded')
2181 2181
2182 2182 def magic_colors(self,parameter_s = ''):
2183 2183 """Switch color scheme for prompts, info system and exception handlers.
2184 2184
2185 2185 Currently implemented schemes: NoColor, Linux, LightBG.
2186 2186
2187 2187 Color scheme names are not case-sensitive."""
2188 2188
2189 2189 def color_switch_err(name):
2190 2190 warn('Error changing %s color schemes.\n%s' %
2191 2191 (name,sys.exc_info()[1]))
2192 2192
2193 2193
2194 2194 new_scheme = parameter_s.strip()
2195 2195 if not new_scheme:
2196 2196 print 'You must specify a color scheme.'
2197 2197 return
2198 2198 import IPython.rlineimpl as readline
2199 2199 if not readline.have_readline:
2200 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 2202 You can find it at:
2203 http://sourceforge.net/projects/uncpythontools
2203 http://ipython.scipy.org/moin/PyReadline/Intro
2204 2204 Gary's readline needs the ctypes module, from:
2205 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 2208 Defaulting color scheme to 'NoColor'"""
2208 2209 new_scheme = 'NoColor'
2209 2210 warn(msg)
2210 2211 # local shortcut
2211 2212 shell = self.shell
2212 2213
2213 2214 # Set prompt colors
2214 2215 try:
2215 2216 shell.outputcache.set_colors(new_scheme)
2216 2217 except:
2217 2218 color_switch_err('prompt')
2218 2219 else:
2219 2220 shell.rc.colors = \
2220 2221 shell.outputcache.color_table.active_scheme_name
2221 2222 # Set exception colors
2222 2223 try:
2223 2224 shell.InteractiveTB.set_colors(scheme = new_scheme)
2224 2225 shell.SyntaxTB.set_colors(scheme = new_scheme)
2225 2226 except:
2226 2227 color_switch_err('exception')
2227 2228
2228 2229 # threaded shells use a verbose traceback in sys.excepthook
2229 2230 if shell.isthreaded:
2230 2231 try:
2231 2232 shell.sys_excepthook.set_colors(scheme=new_scheme)
2232 2233 except:
2233 2234 color_switch_err('system exception handler')
2234 2235
2235 2236 # Set info (for 'object?') colors
2236 2237 if shell.rc.color_info:
2237 2238 try:
2238 2239 shell.inspector.set_active_scheme(new_scheme)
2239 2240 except:
2240 2241 color_switch_err('object inspector')
2241 2242 else:
2242 2243 shell.inspector.set_active_scheme('NoColor')
2243 2244
2244 2245 def magic_color_info(self,parameter_s = ''):
2245 2246 """Toggle color_info.
2246 2247
2247 2248 The color_info configuration parameter controls whether colors are
2248 2249 used for displaying object details (by things like %psource, %pfile or
2249 2250 the '?' system). This function toggles this value with each call.
2250 2251
2251 2252 Note that unless you have a fairly recent pager (less works better
2252 2253 than more) in your system, using colored object information displays
2253 2254 will not work properly. Test it and see."""
2254 2255
2255 2256 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2256 2257 self.magic_colors(self.shell.rc.colors)
2257 2258 print 'Object introspection functions have now coloring:',
2258 2259 print ['OFF','ON'][self.shell.rc.color_info]
2259 2260
2260 2261 def magic_Pprint(self, parameter_s=''):
2261 2262 """Toggle pretty printing on/off."""
2262 2263
2263 2264 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2264 2265 print 'Pretty printing has been turned', \
2265 2266 ['OFF','ON'][self.shell.rc.pprint]
2266 2267
2267 2268 def magic_exit(self, parameter_s=''):
2268 2269 """Exit IPython, confirming if configured to do so.
2269 2270
2270 2271 You can configure whether IPython asks for confirmation upon exit by
2271 2272 setting the confirm_exit flag in the ipythonrc file."""
2272 2273
2273 2274 self.shell.exit()
2274 2275
2275 2276 def magic_quit(self, parameter_s=''):
2276 2277 """Exit IPython, confirming if configured to do so (like %exit)"""
2277 2278
2278 2279 self.shell.exit()
2279 2280
2280 2281 def magic_Exit(self, parameter_s=''):
2281 2282 """Exit IPython without confirmation."""
2282 2283
2283 2284 self.shell.exit_now = True
2284 2285
2285 2286 def magic_Quit(self, parameter_s=''):
2286 2287 """Exit IPython without confirmation (like %Exit)."""
2287 2288
2288 2289 self.shell.exit_now = True
2289 2290
2290 2291 #......................................................................
2291 2292 # Functions to implement unix shell-type things
2292 2293
2293 2294 def magic_alias(self, parameter_s = ''):
2294 2295 """Define an alias for a system command.
2295 2296
2296 2297 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2297 2298
2298 2299 Then, typing 'alias_name params' will execute the system command 'cmd
2299 2300 params' (from your underlying operating system).
2300 2301
2301 2302 Aliases have lower precedence than magic functions and Python normal
2302 2303 variables, so if 'foo' is both a Python variable and an alias, the
2303 2304 alias can not be executed until 'del foo' removes the Python variable.
2304 2305
2305 2306 You can use the %l specifier in an alias definition to represent the
2306 2307 whole line when the alias is called. For example:
2307 2308
2308 2309 In [2]: alias all echo "Input in brackets: <%l>"\\
2309 2310 In [3]: all hello world\\
2310 2311 Input in brackets: <hello world>
2311 2312
2312 2313 You can also define aliases with parameters using %s specifiers (one
2313 2314 per parameter):
2314 2315
2315 2316 In [1]: alias parts echo first %s second %s\\
2316 2317 In [2]: %parts A B\\
2317 2318 first A second B\\
2318 2319 In [3]: %parts A\\
2319 2320 Incorrect number of arguments: 2 expected.\\
2320 2321 parts is an alias to: 'echo first %s second %s'
2321 2322
2322 2323 Note that %l and %s are mutually exclusive. You can only use one or
2323 2324 the other in your aliases.
2324 2325
2325 2326 Aliases expand Python variables just like system calls using ! or !!
2326 2327 do: all expressions prefixed with '$' get expanded. For details of
2327 2328 the semantic rules, see PEP-215:
2328 2329 http://www.python.org/peps/pep-0215.html. This is the library used by
2329 2330 IPython for variable expansion. If you want to access a true shell
2330 2331 variable, an extra $ is necessary to prevent its expansion by IPython:
2331 2332
2332 2333 In [6]: alias show echo\\
2333 2334 In [7]: PATH='A Python string'\\
2334 2335 In [8]: show $PATH\\
2335 2336 A Python string\\
2336 2337 In [9]: show $$PATH\\
2337 2338 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2338 2339
2339 2340 You can use the alias facility to acess all of $PATH. See the %rehash
2340 2341 and %rehashx functions, which automatically create aliases for the
2341 2342 contents of your $PATH.
2342 2343
2343 2344 If called with no parameters, %alias prints the current alias table."""
2344 2345
2345 2346 par = parameter_s.strip()
2346 2347 if not par:
2347 2348 if self.shell.rc.automagic:
2348 2349 prechar = ''
2349 2350 else:
2350 2351 prechar = self.shell.ESC_MAGIC
2351 2352 #print 'Alias\t\tSystem Command\n'+'-'*30
2352 2353 atab = self.shell.alias_table
2353 2354 aliases = atab.keys()
2354 2355 aliases.sort()
2355 2356 res = []
2356 2357 for alias in aliases:
2357 2358 res.append((alias, atab[alias][1]))
2358 2359 print "Total number of aliases:",len(aliases)
2359 2360 return res
2360 2361 try:
2361 2362 alias,cmd = par.split(None,1)
2362 2363 except:
2363 2364 print OInspect.getdoc(self.magic_alias)
2364 2365 else:
2365 2366 nargs = cmd.count('%s')
2366 2367 if nargs>0 and cmd.find('%l')>=0:
2367 2368 error('The %s and %l specifiers are mutually exclusive '
2368 2369 'in alias definitions.')
2369 2370 else: # all looks OK
2370 2371 self.shell.alias_table[alias] = (nargs,cmd)
2371 2372 self.shell.alias_table_validate(verbose=0)
2372 2373 # end magic_alias
2373 2374
2374 2375 def magic_unalias(self, parameter_s = ''):
2375 2376 """Remove an alias"""
2376 2377
2377 2378 aname = parameter_s.strip()
2378 2379 if aname in self.shell.alias_table:
2379 2380 del self.shell.alias_table[aname]
2380 2381
2381 2382 def magic_rehash(self, parameter_s = ''):
2382 2383 """Update the alias table with all entries in $PATH.
2383 2384
2384 2385 This version does no checks on execute permissions or whether the
2385 2386 contents of $PATH are truly files (instead of directories or something
2386 2387 else). For such a safer (but slower) version, use %rehashx."""
2387 2388
2388 2389 # This function (and rehashx) manipulate the alias_table directly
2389 2390 # rather than calling magic_alias, for speed reasons. A rehash on a
2390 2391 # typical Linux box involves several thousand entries, so efficiency
2391 2392 # here is a top concern.
2392 2393
2393 2394 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2394 2395 alias_table = self.shell.alias_table
2395 2396 for pdir in path:
2396 2397 for ff in os.listdir(pdir):
2397 2398 # each entry in the alias table must be (N,name), where
2398 2399 # N is the number of positional arguments of the alias.
2399 2400 alias_table[ff] = (0,ff)
2400 2401 # Make sure the alias table doesn't contain keywords or builtins
2401 2402 self.shell.alias_table_validate()
2402 2403 # Call again init_auto_alias() so we get 'rm -i' and other modified
2403 2404 # aliases since %rehash will probably clobber them
2404 2405 self.shell.init_auto_alias()
2405 2406
2406 2407 def magic_rehashx(self, parameter_s = ''):
2407 2408 """Update the alias table with all executable files in $PATH.
2408 2409
2409 2410 This version explicitly checks that every entry in $PATH is a file
2410 2411 with execute access (os.X_OK), so it is much slower than %rehash.
2411 2412
2412 2413 Under Windows, it checks executability as a match agains a
2413 2414 '|'-separated string of extensions, stored in the IPython config
2414 2415 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2415 2416
2416 2417 path = [os.path.abspath(os.path.expanduser(p)) for p in
2417 2418 os.environ['PATH'].split(os.pathsep)]
2418 2419 path = filter(os.path.isdir,path)
2419 2420
2420 2421 alias_table = self.shell.alias_table
2421 2422 syscmdlist = []
2422 2423 if os.name == 'posix':
2423 2424 isexec = lambda fname:os.path.isfile(fname) and \
2424 2425 os.access(fname,os.X_OK)
2425 2426 else:
2426 2427
2427 2428 try:
2428 2429 winext = os.environ['pathext'].replace(';','|').replace('.','')
2429 2430 except KeyError:
2430 2431 winext = 'exe|com|bat'
2431 2432
2432 2433 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2433 2434 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2434 2435 savedir = os.getcwd()
2435 2436 try:
2436 2437 # write the whole loop for posix/Windows so we don't have an if in
2437 2438 # the innermost part
2438 2439 if os.name == 'posix':
2439 2440 for pdir in path:
2440 2441 os.chdir(pdir)
2441 2442 for ff in os.listdir(pdir):
2442 2443 if isexec(ff) and ff not in self.shell.no_alias:
2443 2444 # each entry in the alias table must be (N,name),
2444 2445 # where N is the number of positional arguments of the
2445 2446 # alias.
2446 2447 alias_table[ff] = (0,ff)
2447 2448 syscmdlist.append(ff)
2448 2449 else:
2449 2450 for pdir in path:
2450 2451 os.chdir(pdir)
2451 2452 for ff in os.listdir(pdir):
2452 2453 if isexec(ff) and os.path.splitext(ff)[0] not in self.shell.no_alias:
2453 2454 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2454 2455 syscmdlist.append(ff)
2455 2456 # Make sure the alias table doesn't contain keywords or builtins
2456 2457 self.shell.alias_table_validate()
2457 2458 # Call again init_auto_alias() so we get 'rm -i' and other
2458 2459 # modified aliases since %rehashx will probably clobber them
2459 2460 self.shell.init_auto_alias()
2460 2461 db = self.getapi().db
2461 2462 db['syscmdlist'] = syscmdlist
2462 2463 finally:
2463 2464 os.chdir(savedir)
2464 2465
2465 2466 def magic_pwd(self, parameter_s = ''):
2466 2467 """Return the current working directory path."""
2467 2468 return os.getcwd()
2468 2469
2469 2470 def magic_cd(self, parameter_s=''):
2470 2471 """Change the current working directory.
2471 2472
2472 2473 This command automatically maintains an internal list of directories
2473 2474 you visit during your IPython session, in the variable _dh. The
2474 2475 command %dhist shows this history nicely formatted.
2475 2476
2476 2477 Usage:
2477 2478
2478 2479 cd 'dir': changes to directory 'dir'.
2479 2480
2480 2481 cd -: changes to the last visited directory.
2481 2482
2482 2483 cd -<n>: changes to the n-th directory in the directory history.
2483 2484
2484 2485 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2485 2486 (note: cd <bookmark_name> is enough if there is no
2486 2487 directory <bookmark_name>, but a bookmark with the name exists.)
2487 2488
2488 2489 Options:
2489 2490
2490 2491 -q: quiet. Do not print the working directory after the cd command is
2491 2492 executed. By default IPython's cd command does print this directory,
2492 2493 since the default prompts do not display path information.
2493 2494
2494 2495 Note that !cd doesn't work for this purpose because the shell where
2495 2496 !command runs is immediately discarded after executing 'command'."""
2496 2497
2497 2498 parameter_s = parameter_s.strip()
2498 2499 #bkms = self.shell.persist.get("bookmarks",{})
2499 2500
2500 2501 numcd = re.match(r'(-)(\d+)$',parameter_s)
2501 2502 # jump in directory history by number
2502 2503 if numcd:
2503 2504 nn = int(numcd.group(2))
2504 2505 try:
2505 2506 ps = self.shell.user_ns['_dh'][nn]
2506 2507 except IndexError:
2507 2508 print 'The requested directory does not exist in history.'
2508 2509 return
2509 2510 else:
2510 2511 opts = {}
2511 2512 else:
2512 2513 #turn all non-space-escaping backslashes to slashes,
2513 2514 # for c:\windows\directory\names\
2514 2515 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2515 2516 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2516 2517 # jump to previous
2517 2518 if ps == '-':
2518 2519 try:
2519 2520 ps = self.shell.user_ns['_dh'][-2]
2520 2521 except IndexError:
2521 2522 print 'No previous directory to change to.'
2522 2523 return
2523 2524 # jump to bookmark if needed
2524 2525 else:
2525 2526 if not os.path.isdir(ps) or opts.has_key('b'):
2526 2527 bkms = self.db.get('bookmarks', {})
2527 2528
2528 2529 if bkms.has_key(ps):
2529 2530 target = bkms[ps]
2530 2531 print '(bookmark:%s) -> %s' % (ps,target)
2531 2532 ps = target
2532 2533 else:
2533 2534 if opts.has_key('b'):
2534 2535 error("Bookmark '%s' not found. "
2535 2536 "Use '%%bookmark -l' to see your bookmarks." % ps)
2536 2537 return
2537 2538
2538 2539 # at this point ps should point to the target dir
2539 2540 if ps:
2540 2541 try:
2541 2542 os.chdir(os.path.expanduser(ps))
2542 2543 ttitle = ("IPy:" + (
2543 2544 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2544 2545 platutils.set_term_title(ttitle)
2545 2546 except OSError:
2546 2547 print sys.exc_info()[1]
2547 2548 else:
2548 2549 self.shell.user_ns['_dh'].append(os.getcwd())
2549 2550 else:
2550 2551 os.chdir(self.shell.home_dir)
2551 2552 platutils.set_term_title("IPy:~")
2552 2553 self.shell.user_ns['_dh'].append(os.getcwd())
2553 2554 if not 'q' in opts:
2554 2555 print self.shell.user_ns['_dh'][-1]
2555 2556
2556 2557 def magic_dhist(self, parameter_s=''):
2557 2558 """Print your history of visited directories.
2558 2559
2559 2560 %dhist -> print full history\\
2560 2561 %dhist n -> print last n entries only\\
2561 2562 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2562 2563
2563 2564 This history is automatically maintained by the %cd command, and
2564 2565 always available as the global list variable _dh. You can use %cd -<n>
2565 2566 to go to directory number <n>."""
2566 2567
2567 2568 dh = self.shell.user_ns['_dh']
2568 2569 if parameter_s:
2569 2570 try:
2570 2571 args = map(int,parameter_s.split())
2571 2572 except:
2572 2573 self.arg_err(Magic.magic_dhist)
2573 2574 return
2574 2575 if len(args) == 1:
2575 2576 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2576 2577 elif len(args) == 2:
2577 2578 ini,fin = args
2578 2579 else:
2579 2580 self.arg_err(Magic.magic_dhist)
2580 2581 return
2581 2582 else:
2582 2583 ini,fin = 0,len(dh)
2583 2584 nlprint(dh,
2584 2585 header = 'Directory history (kept in _dh)',
2585 2586 start=ini,stop=fin)
2586 2587
2587 2588 def magic_env(self, parameter_s=''):
2588 2589 """List environment variables."""
2589 2590
2590 2591 return os.environ.data
2591 2592
2592 2593 def magic_pushd(self, parameter_s=''):
2593 2594 """Place the current dir on stack and change directory.
2594 2595
2595 2596 Usage:\\
2596 2597 %pushd ['dirname']
2597 2598
2598 2599 %pushd with no arguments does a %pushd to your home directory.
2599 2600 """
2600 2601 if parameter_s == '': parameter_s = '~'
2601 2602 dir_s = self.shell.dir_stack
2602 2603 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2603 2604 os.path.expanduser(self.shell.dir_stack[0]):
2604 2605 try:
2605 2606 self.magic_cd(parameter_s)
2606 2607 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2607 2608 self.magic_dirs()
2608 2609 except:
2609 2610 print 'Invalid directory'
2610 2611 else:
2611 2612 print 'You are already there!'
2612 2613
2613 2614 def magic_popd(self, parameter_s=''):
2614 2615 """Change to directory popped off the top of the stack.
2615 2616 """
2616 2617 if len (self.shell.dir_stack) > 1:
2617 2618 self.shell.dir_stack.pop(0)
2618 2619 self.magic_cd(self.shell.dir_stack[0])
2619 2620 print self.shell.dir_stack[0]
2620 2621 else:
2621 2622 print "You can't remove the starting directory from the stack:",\
2622 2623 self.shell.dir_stack
2623 2624
2624 2625 def magic_dirs(self, parameter_s=''):
2625 2626 """Return the current directory stack."""
2626 2627
2627 2628 return self.shell.dir_stack[:]
2628 2629
2629 2630 def magic_sc(self, parameter_s=''):
2630 2631 """Shell capture - execute a shell command and capture its output.
2631 2632
2632 2633 DEPRECATED. Suboptimal, retained for backwards compatibility.
2633 2634
2634 2635 You should use the form 'var = !command' instead. Example:
2635 2636
2636 2637 "%sc -l myfiles = ls ~" should now be written as
2637 2638
2638 2639 "myfiles = !ls ~"
2639 2640
2640 2641 myfiles.s, myfiles.l and myfiles.n still apply as documented
2641 2642 below.
2642 2643
2643 2644 --
2644 2645 %sc [options] varname=command
2645 2646
2646 2647 IPython will run the given command using commands.getoutput(), and
2647 2648 will then update the user's interactive namespace with a variable
2648 2649 called varname, containing the value of the call. Your command can
2649 2650 contain shell wildcards, pipes, etc.
2650 2651
2651 2652 The '=' sign in the syntax is mandatory, and the variable name you
2652 2653 supply must follow Python's standard conventions for valid names.
2653 2654
2654 2655 (A special format without variable name exists for internal use)
2655 2656
2656 2657 Options:
2657 2658
2658 2659 -l: list output. Split the output on newlines into a list before
2659 2660 assigning it to the given variable. By default the output is stored
2660 2661 as a single string.
2661 2662
2662 2663 -v: verbose. Print the contents of the variable.
2663 2664
2664 2665 In most cases you should not need to split as a list, because the
2665 2666 returned value is a special type of string which can automatically
2666 2667 provide its contents either as a list (split on newlines) or as a
2667 2668 space-separated string. These are convenient, respectively, either
2668 2669 for sequential processing or to be passed to a shell command.
2669 2670
2670 2671 For example:
2671 2672
2672 2673 # Capture into variable a
2673 2674 In [9]: sc a=ls *py
2674 2675
2675 2676 # a is a string with embedded newlines
2676 2677 In [10]: a
2677 2678 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2678 2679
2679 2680 # which can be seen as a list:
2680 2681 In [11]: a.l
2681 2682 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2682 2683
2683 2684 # or as a whitespace-separated string:
2684 2685 In [12]: a.s
2685 2686 Out[12]: 'setup.py win32_manual_post_install.py'
2686 2687
2687 2688 # a.s is useful to pass as a single command line:
2688 2689 In [13]: !wc -l $a.s
2689 2690 146 setup.py
2690 2691 130 win32_manual_post_install.py
2691 2692 276 total
2692 2693
2693 2694 # while the list form is useful to loop over:
2694 2695 In [14]: for f in a.l:
2695 2696 ....: !wc -l $f
2696 2697 ....:
2697 2698 146 setup.py
2698 2699 130 win32_manual_post_install.py
2699 2700
2700 2701 Similiarly, the lists returned by the -l option are also special, in
2701 2702 the sense that you can equally invoke the .s attribute on them to
2702 2703 automatically get a whitespace-separated string from their contents:
2703 2704
2704 2705 In [1]: sc -l b=ls *py
2705 2706
2706 2707 In [2]: b
2707 2708 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2708 2709
2709 2710 In [3]: b.s
2710 2711 Out[3]: 'setup.py win32_manual_post_install.py'
2711 2712
2712 2713 In summary, both the lists and strings used for ouptut capture have
2713 2714 the following special attributes:
2714 2715
2715 2716 .l (or .list) : value as list.
2716 2717 .n (or .nlstr): value as newline-separated string.
2717 2718 .s (or .spstr): value as space-separated string.
2718 2719 """
2719 2720
2720 2721 opts,args = self.parse_options(parameter_s,'lv')
2721 2722 # Try to get a variable name and command to run
2722 2723 try:
2723 2724 # the variable name must be obtained from the parse_options
2724 2725 # output, which uses shlex.split to strip options out.
2725 2726 var,_ = args.split('=',1)
2726 2727 var = var.strip()
2727 2728 # But the the command has to be extracted from the original input
2728 2729 # parameter_s, not on what parse_options returns, to avoid the
2729 2730 # quote stripping which shlex.split performs on it.
2730 2731 _,cmd = parameter_s.split('=',1)
2731 2732 except ValueError:
2732 2733 var,cmd = '',''
2733 2734 # If all looks ok, proceed
2734 2735 out,err = self.shell.getoutputerror(cmd)
2735 2736 if err:
2736 2737 print >> Term.cerr,err
2737 2738 if opts.has_key('l'):
2738 2739 out = SList(out.split('\n'))
2739 2740 else:
2740 2741 out = LSString(out)
2741 2742 if opts.has_key('v'):
2742 2743 print '%s ==\n%s' % (var,pformat(out))
2743 2744 if var:
2744 2745 self.shell.user_ns.update({var:out})
2745 2746 else:
2746 2747 return out
2747 2748
2748 2749 def magic_sx(self, parameter_s=''):
2749 2750 """Shell execute - run a shell command and capture its output.
2750 2751
2751 2752 %sx command
2752 2753
2753 2754 IPython will run the given command using commands.getoutput(), and
2754 2755 return the result formatted as a list (split on '\\n'). Since the
2755 2756 output is _returned_, it will be stored in ipython's regular output
2756 2757 cache Out[N] and in the '_N' automatic variables.
2757 2758
2758 2759 Notes:
2759 2760
2760 2761 1) If an input line begins with '!!', then %sx is automatically
2761 2762 invoked. That is, while:
2762 2763 !ls
2763 2764 causes ipython to simply issue system('ls'), typing
2764 2765 !!ls
2765 2766 is a shorthand equivalent to:
2766 2767 %sx ls
2767 2768
2768 2769 2) %sx differs from %sc in that %sx automatically splits into a list,
2769 2770 like '%sc -l'. The reason for this is to make it as easy as possible
2770 2771 to process line-oriented shell output via further python commands.
2771 2772 %sc is meant to provide much finer control, but requires more
2772 2773 typing.
2773 2774
2774 2775 3) Just like %sc -l, this is a list with special attributes:
2775 2776
2776 2777 .l (or .list) : value as list.
2777 2778 .n (or .nlstr): value as newline-separated string.
2778 2779 .s (or .spstr): value as whitespace-separated string.
2779 2780
2780 2781 This is very useful when trying to use such lists as arguments to
2781 2782 system commands."""
2782 2783
2783 2784 if parameter_s:
2784 2785 out,err = self.shell.getoutputerror(parameter_s)
2785 2786 if err:
2786 2787 print >> Term.cerr,err
2787 2788 return SList(out.split('\n'))
2788 2789
2789 2790 def magic_bg(self, parameter_s=''):
2790 2791 """Run a job in the background, in a separate thread.
2791 2792
2792 2793 For example,
2793 2794
2794 2795 %bg myfunc(x,y,z=1)
2795 2796
2796 2797 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2797 2798 execution starts, a message will be printed indicating the job
2798 2799 number. If your job number is 5, you can use
2799 2800
2800 2801 myvar = jobs.result(5) or myvar = jobs[5].result
2801 2802
2802 2803 to assign this result to variable 'myvar'.
2803 2804
2804 2805 IPython has a job manager, accessible via the 'jobs' object. You can
2805 2806 type jobs? to get more information about it, and use jobs.<TAB> to see
2806 2807 its attributes. All attributes not starting with an underscore are
2807 2808 meant for public use.
2808 2809
2809 2810 In particular, look at the jobs.new() method, which is used to create
2810 2811 new jobs. This magic %bg function is just a convenience wrapper
2811 2812 around jobs.new(), for expression-based jobs. If you want to create a
2812 2813 new job with an explicit function object and arguments, you must call
2813 2814 jobs.new() directly.
2814 2815
2815 2816 The jobs.new docstring also describes in detail several important
2816 2817 caveats associated with a thread-based model for background job
2817 2818 execution. Type jobs.new? for details.
2818 2819
2819 2820 You can check the status of all jobs with jobs.status().
2820 2821
2821 2822 The jobs variable is set by IPython into the Python builtin namespace.
2822 2823 If you ever declare a variable named 'jobs', you will shadow this
2823 2824 name. You can either delete your global jobs variable to regain
2824 2825 access to the job manager, or make a new name and assign it manually
2825 2826 to the manager (stored in IPython's namespace). For example, to
2826 2827 assign the job manager to the Jobs name, use:
2827 2828
2828 2829 Jobs = __builtins__.jobs"""
2829 2830
2830 2831 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2831 2832
2832 2833
2833 2834 def magic_bookmark(self, parameter_s=''):
2834 2835 """Manage IPython's bookmark system.
2835 2836
2836 2837 %bookmark <name> - set bookmark to current dir
2837 2838 %bookmark <name> <dir> - set bookmark to <dir>
2838 2839 %bookmark -l - list all bookmarks
2839 2840 %bookmark -d <name> - remove bookmark
2840 2841 %bookmark -r - remove all bookmarks
2841 2842
2842 2843 You can later on access a bookmarked folder with:
2843 2844 %cd -b <name>
2844 2845 or simply '%cd <name>' if there is no directory called <name> AND
2845 2846 there is such a bookmark defined.
2846 2847
2847 2848 Your bookmarks persist through IPython sessions, but they are
2848 2849 associated with each profile."""
2849 2850
2850 2851 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2851 2852 if len(args) > 2:
2852 2853 error('You can only give at most two arguments')
2853 2854 return
2854 2855
2855 2856 bkms = self.db.get('bookmarks',{})
2856 2857
2857 2858 if opts.has_key('d'):
2858 2859 try:
2859 2860 todel = args[0]
2860 2861 except IndexError:
2861 2862 error('You must provide a bookmark to delete')
2862 2863 else:
2863 2864 try:
2864 2865 del bkms[todel]
2865 2866 except:
2866 2867 error("Can't delete bookmark '%s'" % todel)
2867 2868 elif opts.has_key('r'):
2868 2869 bkms = {}
2869 2870 elif opts.has_key('l'):
2870 2871 bks = bkms.keys()
2871 2872 bks.sort()
2872 2873 if bks:
2873 2874 size = max(map(len,bks))
2874 2875 else:
2875 2876 size = 0
2876 2877 fmt = '%-'+str(size)+'s -> %s'
2877 2878 print 'Current bookmarks:'
2878 2879 for bk in bks:
2879 2880 print fmt % (bk,bkms[bk])
2880 2881 else:
2881 2882 if not args:
2882 2883 error("You must specify the bookmark name")
2883 2884 elif len(args)==1:
2884 2885 bkms[args[0]] = os.getcwd()
2885 2886 elif len(args)==2:
2886 2887 bkms[args[0]] = args[1]
2887 2888 self.db['bookmarks'] = bkms
2888 2889
2889 2890 def magic_pycat(self, parameter_s=''):
2890 2891 """Show a syntax-highlighted file through a pager.
2891 2892
2892 2893 This magic is similar to the cat utility, but it will assume the file
2893 2894 to be Python source and will show it with syntax highlighting. """
2894 2895
2895 2896 try:
2896 2897 filename = get_py_filename(parameter_s)
2897 2898 cont = file_read(filename)
2898 2899 except IOError:
2899 2900 try:
2900 2901 cont = eval(parameter_s,self.user_ns)
2901 2902 except NameError:
2902 2903 cont = None
2903 2904 if cont is None:
2904 2905 print "Error: no such file or variable"
2905 2906 return
2906 2907
2907 2908 page(self.shell.pycolorize(cont),
2908 2909 screen_lines=self.shell.rc.screen_length)
2909 2910
2910 2911 def magic_cpaste(self, parameter_s=''):
2911 2912 """Allows you to paste & execute a pre-formatted code block from clipboard
2912 2913
2913 2914 You must terminate the block with '--' (two minus-signs) alone on the
2914 2915 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2915 2916 is the new sentinel for this operation)
2916 2917
2917 2918 The block is dedented prior to execution to enable execution of
2918 2919 method definitions. '>' characters at the beginning of a line is
2919 2920 ignored, to allow pasting directly from e-mails. The executed block
2920 2921 is also assigned to variable named 'pasted_block' for later editing
2921 2922 with '%edit pasted_block'.
2922 2923
2923 2924 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2924 2925 This assigns the pasted block to variable 'foo' as string, without
2925 2926 dedenting or executing it.
2926 2927
2927 2928 Do not be alarmed by garbled output on Windows (it's a readline bug).
2928 2929 Just press enter and type -- (and press enter again) and the block
2929 2930 will be what was just pasted.
2930 2931
2931 2932 IPython statements (magics, shell escapes) are not supported (yet).
2932 2933 """
2933 2934 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2934 2935 par = args.strip()
2935 2936 sentinel = opts.get('s','--')
2936 2937
2937 2938 from IPython import iplib
2938 2939 lines = []
2939 2940 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2940 2941 while 1:
2941 2942 l = iplib.raw_input_original(':')
2942 2943 if l ==sentinel:
2943 2944 break
2944 2945 lines.append(l.lstrip('>'))
2945 2946 block = "\n".join(lines) + '\n'
2946 2947 #print "block:\n",block
2947 2948 if not par:
2948 2949 b = textwrap.dedent(block)
2949 2950 exec b in self.user_ns
2950 2951 self.user_ns['pasted_block'] = b
2951 2952 else:
2952 2953 self.user_ns[par] = block
2953 2954 print "Block assigned to '%s'" % par
2954 2955
2955 2956 def magic_quickref(self,arg):
2956 2957 """ Show a quick reference sheet """
2957 2958 import IPython.usage
2958 2959 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
2959 2960
2960 2961 page(qr)
2961 2962
2962 2963 def magic_upgrade(self,arg):
2963 2964 """ Upgrade your IPython installation
2964 2965
2965 2966 This will copy the config files that don't yet exist in your
2966 2967 ipython dir from the system config dir. Use this after upgrading
2967 2968 IPython if you don't wish to delete your .ipython dir.
2968 2969
2969 2970 Call with -nolegacy to get rid of ipythonrc* files (recommended for
2970 2971 new users)
2971 2972
2972 2973 """
2973 2974 ip = self.getapi()
2974 2975 ipinstallation = path(IPython.__file__).dirname()
2975 2976 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
2976 2977 src_config = ipinstallation / 'UserConfig'
2977 2978 userdir = path(ip.options.ipythondir)
2978 2979 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
2979 2980 print ">",cmd
2980 2981 shell(cmd)
2981 2982 if arg == '-nolegacy':
2982 2983 legacy = userdir.files('ipythonrc*')
2983 2984 print "Nuking legacy files:",legacy
2984 2985
2985 2986 [p.remove() for p in legacy]
2986 2987 suffix = (sys.platform == 'win32' and '.ini' or '')
2987 2988 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
2988 2989
2989 2990
2990 2991 # end Magic
@@ -1,2356 +1,2354 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.3 or newer.
6 6
7 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 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #
19 19 # Note: this code originally subclassed code.InteractiveConsole from the
20 20 # Python standard library. Over time, all of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. At this point, there are no dependencies at all on the code
23 23 # module anymore (it is not even imported). The Python License (sec. 2)
24 24 # allows for this, but it's always nice to acknowledge credit where credit is
25 25 # due.
26 26 #*****************************************************************************
27 27
28 28 #****************************************************************************
29 29 # Modules and globals
30 30
31 31 from IPython import Release
32 32 __author__ = '%s <%s>\n%s <%s>' % \
33 33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 34 __license__ = Release.license
35 35 __version__ = Release.version
36 36
37 37 # Python standard modules
38 38 import __main__
39 39 import __builtin__
40 40 import StringIO
41 41 import bdb
42 42 import cPickle as pickle
43 43 import codeop
44 44 import exceptions
45 45 import glob
46 46 import inspect
47 47 import keyword
48 48 import new
49 49 import os
50 50 import pdb
51 51 import pydoc
52 52 import re
53 53 import shutil
54 54 import string
55 55 import sys
56 56 import tempfile
57 57 import traceback
58 58 import types
59 59 import pickleshare
60 60
61 61 from pprint import pprint, pformat
62 62
63 63 # IPython's own modules
64 64 import IPython
65 65 from IPython import OInspect,PyColorize,ultraTB
66 66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 67 from IPython.FakeModule import FakeModule
68 68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 69 from IPython.Logger import Logger
70 70 from IPython.Magic import Magic
71 71 from IPython.Prompts import CachedOutput
72 72 from IPython.ipstruct import Struct
73 73 from IPython.background_jobs import BackgroundJobManager
74 74 from IPython.usage import cmd_line_usage,interactive_usage
75 75 from IPython.genutils import *
76 76 import IPython.ipapi
77 77
78 78 # Globals
79 79
80 80 # store the builtin raw_input globally, and use this always, in case user code
81 81 # overwrites it (like wx.py.PyShell does)
82 82 raw_input_original = raw_input
83 83
84 84 # compiled regexps for autoindent management
85 85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86 86
87 87
88 88 #****************************************************************************
89 89 # Some utility function definitions
90 90
91 91 ini_spaces_re = re.compile(r'^(\s+)')
92 92
93 93 def num_ini_spaces(strng):
94 94 """Return the number of initial spaces in a string"""
95 95
96 96 ini_spaces = ini_spaces_re.match(strng)
97 97 if ini_spaces:
98 98 return ini_spaces.end()
99 99 else:
100 100 return 0
101 101
102 102 def softspace(file, newvalue):
103 103 """Copied from code.py, to remove the dependency"""
104 104
105 105 oldvalue = 0
106 106 try:
107 107 oldvalue = file.softspace
108 108 except AttributeError:
109 109 pass
110 110 try:
111 111 file.softspace = newvalue
112 112 except (AttributeError, TypeError):
113 113 # "attribute-less object" or "read-only attributes"
114 114 pass
115 115 return oldvalue
116 116
117 117
118 118 #****************************************************************************
119 119 # Local use exceptions
120 120 class SpaceInInput(exceptions.Exception): pass
121 121
122 122
123 123 #****************************************************************************
124 124 # Local use classes
125 125 class Bunch: pass
126 126
127 127 class Undefined: pass
128 128
129 129 class InputList(list):
130 130 """Class to store user input.
131 131
132 132 It's basically a list, but slices return a string instead of a list, thus
133 133 allowing things like (assuming 'In' is an instance):
134 134
135 135 exec In[4:7]
136 136
137 137 or
138 138
139 139 exec In[5:9] + In[14] + In[21:25]"""
140 140
141 141 def __getslice__(self,i,j):
142 142 return ''.join(list.__getslice__(self,i,j))
143 143
144 144 class SyntaxTB(ultraTB.ListTB):
145 145 """Extension which holds some state: the last exception value"""
146 146
147 147 def __init__(self,color_scheme = 'NoColor'):
148 148 ultraTB.ListTB.__init__(self,color_scheme)
149 149 self.last_syntax_error = None
150 150
151 151 def __call__(self, etype, value, elist):
152 152 self.last_syntax_error = value
153 153 ultraTB.ListTB.__call__(self,etype,value,elist)
154 154
155 155 def clear_err_state(self):
156 156 """Return the current error state and clear it"""
157 157 e = self.last_syntax_error
158 158 self.last_syntax_error = None
159 159 return e
160 160
161 161 #****************************************************************************
162 162 # Main IPython class
163 163
164 164 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
165 165 # until a full rewrite is made. I've cleaned all cross-class uses of
166 166 # attributes and methods, but too much user code out there relies on the
167 167 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
168 168 #
169 169 # But at least now, all the pieces have been separated and we could, in
170 170 # principle, stop using the mixin. This will ease the transition to the
171 171 # chainsaw branch.
172 172
173 173 # For reference, the following is the list of 'self.foo' uses in the Magic
174 174 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
175 175 # class, to prevent clashes.
176 176
177 177 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
178 178 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
179 179 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
180 180 # 'self.value']
181 181
182 182 class InteractiveShell(object,Magic):
183 183 """An enhanced console for Python."""
184 184
185 185 # class attribute to indicate whether the class supports threads or not.
186 186 # Subclasses with thread support should override this as needed.
187 187 isthreaded = False
188 188
189 189 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
190 190 user_ns = None,user_global_ns=None,banner2='',
191 191 custom_exceptions=((),None),embedded=False):
192 192
193 193 # log system
194 194 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
195 195
196 196 # some minimal strict typechecks. For some core data structures, I
197 197 # want actual basic python types, not just anything that looks like
198 198 # one. This is especially true for namespaces.
199 199 for ns in (user_ns,user_global_ns):
200 200 if ns is not None and type(ns) != types.DictType:
201 201 raise TypeError,'namespace must be a dictionary'
202 202
203 203 # Job manager (for jobs run as background threads)
204 204 self.jobs = BackgroundJobManager()
205 205
206 206 # Store the actual shell's name
207 207 self.name = name
208 208
209 209 # We need to know whether the instance is meant for embedding, since
210 210 # global/local namespaces need to be handled differently in that case
211 211 self.embedded = embedded
212 212
213 213 # command compiler
214 214 self.compile = codeop.CommandCompiler()
215 215
216 216 # User input buffer
217 217 self.buffer = []
218 218
219 219 # Default name given in compilation of code
220 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 228 # Make an empty namespace, which extension writers can rely on both
223 229 # existing and NEVER being used by ipython itself. This gives them a
224 230 # convenient location for storing additional information and state
225 231 # their extensions may require, without fear of collisions with other
226 232 # ipython names that may develop later.
227 233 self.meta = Struct()
228 234
229 235 # Create the namespace where the user will operate. user_ns is
230 236 # normally the only one used, and it is passed to the exec calls as
231 237 # the locals argument. But we do carry a user_global_ns namespace
232 238 # given as the exec 'globals' argument, This is useful in embedding
233 239 # situations where the ipython shell opens in a context where the
234 240 # distinction between locals and globals is meaningful.
235 241
236 242 # FIXME. For some strange reason, __builtins__ is showing up at user
237 243 # level as a dict instead of a module. This is a manual fix, but I
238 244 # should really track down where the problem is coming from. Alex
239 245 # Schmolck reported this problem first.
240 246
241 247 # A useful post by Alex Martelli on this topic:
242 248 # Re: inconsistent value from __builtins__
243 249 # Von: Alex Martelli <aleaxit@yahoo.com>
244 250 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
245 251 # Gruppen: comp.lang.python
246 252
247 253 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
248 254 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
249 255 # > <type 'dict'>
250 256 # > >>> print type(__builtins__)
251 257 # > <type 'module'>
252 258 # > Is this difference in return value intentional?
253 259
254 260 # Well, it's documented that '__builtins__' can be either a dictionary
255 261 # or a module, and it's been that way for a long time. Whether it's
256 262 # intentional (or sensible), I don't know. In any case, the idea is
257 263 # that if you need to access the built-in namespace directly, you
258 264 # should start with "import __builtin__" (note, no 's') which will
259 265 # definitely give you a module. Yeah, it's somewhat confusing:-(.
260 266
261 267 # These routines return properly built dicts as needed by the rest of
262 268 # the code, and can also be used by extension writers to generate
263 269 # properly initialized namespaces.
264 270 user_ns = IPython.ipapi.make_user_ns(user_ns)
265 271 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
266 272
267 273 # Assign namespaces
268 274 # This is the namespace where all normal user variables live
269 275 self.user_ns = user_ns
270 276 # Embedded instances require a separate namespace for globals.
271 277 # Normally this one is unused by non-embedded instances.
272 278 self.user_global_ns = user_global_ns
273 279 # A namespace to keep track of internal data structures to prevent
274 280 # them from cluttering user-visible stuff. Will be updated later
275 281 self.internal_ns = {}
276 282
277 283 # Namespace of system aliases. Each entry in the alias
278 284 # table must be a 2-tuple of the form (N,name), where N is the number
279 285 # of positional arguments of the alias.
280 286 self.alias_table = {}
281 287
282 288 # A table holding all the namespaces IPython deals with, so that
283 289 # introspection facilities can search easily.
284 290 self.ns_table = {'user':user_ns,
285 291 'user_global':user_global_ns,
286 292 'alias':self.alias_table,
287 293 'internal':self.internal_ns,
288 294 'builtin':__builtin__.__dict__
289 295 }
290 296
291 297 # The user namespace MUST have a pointer to the shell itself.
292 298 self.user_ns[name] = self
293 299
294 300 # We need to insert into sys.modules something that looks like a
295 301 # module but which accesses the IPython namespace, for shelve and
296 302 # pickle to work interactively. Normally they rely on getting
297 303 # everything out of __main__, but for embedding purposes each IPython
298 304 # instance has its own private namespace, so we can't go shoving
299 305 # everything into __main__.
300 306
301 307 # note, however, that we should only do this for non-embedded
302 308 # ipythons, which really mimic the __main__.__dict__ with their own
303 309 # namespace. Embedded instances, on the other hand, should not do
304 310 # this because they need to manage the user local/global namespaces
305 311 # only, but they live within a 'normal' __main__ (meaning, they
306 312 # shouldn't overtake the execution environment of the script they're
307 313 # embedded in).
308 314
309 315 if not embedded:
310 316 try:
311 317 main_name = self.user_ns['__name__']
312 318 except KeyError:
313 319 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
314 320 else:
315 321 #print "pickle hack in place" # dbg
316 322 #print 'main_name:',main_name # dbg
317 323 sys.modules[main_name] = FakeModule(self.user_ns)
318 324
319 325 # List of input with multi-line handling.
320 326 # Fill its zero entry, user counter starts at 1
321 327 self.input_hist = InputList(['\n'])
322 328 # This one will hold the 'raw' input history, without any
323 329 # pre-processing. This will allow users to retrieve the input just as
324 330 # it was exactly typed in by the user, with %hist -r.
325 331 self.input_hist_raw = InputList(['\n'])
326 332
327 333 # list of visited directories
328 334 try:
329 335 self.dir_hist = [os.getcwd()]
330 336 except IOError, e:
331 337 self.dir_hist = []
332 338
333 339 # dict of output history
334 340 self.output_hist = {}
335 341
336 342 # dict of things NOT to alias (keywords, builtins and some magics)
337 343 no_alias = {}
338 344 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
339 345 for key in keyword.kwlist + no_alias_magics:
340 346 no_alias[key] = 1
341 347 no_alias.update(__builtin__.__dict__)
342 348 self.no_alias = no_alias
343 349
344 350 # make global variables for user access to these
345 351 self.user_ns['_ih'] = self.input_hist
346 352 self.user_ns['_oh'] = self.output_hist
347 353 self.user_ns['_dh'] = self.dir_hist
348 354
349 355 # user aliases to input and output histories
350 356 self.user_ns['In'] = self.input_hist
351 357 self.user_ns['Out'] = self.output_hist
352 358
353 359 # Object variable to store code object waiting execution. This is
354 360 # used mainly by the multithreaded shells, but it can come in handy in
355 361 # other situations. No need to use a Queue here, since it's a single
356 362 # item which gets cleared once run.
357 363 self.code_to_run = None
358 364
359 365 # escapes for automatic behavior on the command line
360 366 self.ESC_SHELL = '!'
361 367 self.ESC_HELP = '?'
362 368 self.ESC_MAGIC = '%'
363 369 self.ESC_QUOTE = ','
364 370 self.ESC_QUOTE2 = ';'
365 371 self.ESC_PAREN = '/'
366 372
367 373 # And their associated handlers
368 374 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
369 375 self.ESC_QUOTE : self.handle_auto,
370 376 self.ESC_QUOTE2 : self.handle_auto,
371 377 self.ESC_MAGIC : self.handle_magic,
372 378 self.ESC_HELP : self.handle_help,
373 379 self.ESC_SHELL : self.handle_shell_escape,
374 380 }
375 381
376 382 # class initializations
377 383 Magic.__init__(self,self)
378 384
379 385 # Python source parser/formatter for syntax highlighting
380 386 pyformat = PyColorize.Parser().format
381 387 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
382 388
383 389 # hooks holds pointers used for user-side customizations
384 390 self.hooks = Struct()
385 391
386 392 # Set all default hooks, defined in the IPython.hooks module.
387 393 hooks = IPython.hooks
388 394 for hook_name in hooks.__all__:
389 395 # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority
390 396 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
391 397 #print "bound hook",hook_name
392 398
393 399 # Flag to mark unconditional exit
394 400 self.exit_now = False
395 401
396 402 self.usage_min = """\
397 403 An enhanced console for Python.
398 404 Some of its features are:
399 405 - Readline support if the readline library is present.
400 406 - Tab completion in the local namespace.
401 407 - Logging of input, see command-line options.
402 408 - System shell escape via ! , eg !ls.
403 409 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
404 410 - Keeps track of locally defined variables via %who, %whos.
405 411 - Show object information with a ? eg ?x or x? (use ?? for more info).
406 412 """
407 413 if usage: self.usage = usage
408 414 else: self.usage = self.usage_min
409 415
410 416 # Storage
411 417 self.rc = rc # This will hold all configuration information
412 418 self.pager = 'less'
413 419 # temporary files used for various purposes. Deleted at exit.
414 420 self.tempfiles = []
415 421
416 422 # Keep track of readline usage (later set by init_readline)
417 423 self.has_readline = False
418 424
419 425 # template for logfile headers. It gets resolved at runtime by the
420 426 # logstart method.
421 427 self.loghead_tpl = \
422 428 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
423 429 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
424 430 #log# opts = %s
425 431 #log# args = %s
426 432 #log# It is safe to make manual edits below here.
427 433 #log#-----------------------------------------------------------------------
428 434 """
429 435 # for pushd/popd management
430 436 try:
431 437 self.home_dir = get_home_dir()
432 438 except HomeDirError,msg:
433 439 fatal(msg)
434 440
435 441 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
436 442
437 443 # Functions to call the underlying shell.
438 444
439 445 # utility to expand user variables via Itpl
440 446 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
441 447 self.user_ns))
442 448 # The first is similar to os.system, but it doesn't return a value,
443 449 # and it allows interpolation of variables in the user's namespace.
444 450 self.system = lambda cmd: shell(self.var_expand(cmd),
445 451 header='IPython system call: ',
446 452 verbose=self.rc.system_verbose)
447 453 # These are for getoutput and getoutputerror:
448 454 self.getoutput = lambda cmd: \
449 455 getoutput(self.var_expand(cmd),
450 456 header='IPython system call: ',
451 457 verbose=self.rc.system_verbose)
452 458 self.getoutputerror = lambda cmd: \
453 459 getoutputerror(self.var_expand(cmd),
454 460 header='IPython system call: ',
455 461 verbose=self.rc.system_verbose)
456 462
457 463 # RegExp for splitting line contents into pre-char//first
458 464 # word-method//rest. For clarity, each group in on one line.
459 465
460 466 # WARNING: update the regexp if the above escapes are changed, as they
461 467 # are hardwired in.
462 468
463 469 # Don't get carried away with trying to make the autocalling catch too
464 470 # much: it's better to be conservative rather than to trigger hidden
465 471 # evals() somewhere and end up causing side effects.
466 472
467 473 self.line_split = re.compile(r'^([\s*,;/])'
468 474 r'([\?\w\.]+\w*\s*)'
469 475 r'(\(?.*$)')
470 476
471 477 # Original re, keep around for a while in case changes break something
472 478 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
473 479 # r'(\s*[\?\w\.]+\w*\s*)'
474 480 # r'(\(?.*$)')
475 481
476 482 # RegExp to identify potential function names
477 483 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
478 484
479 485 # RegExp to exclude strings with this start from autocalling. In
480 486 # particular, all binary operators should be excluded, so that if foo
481 487 # is callable, foo OP bar doesn't become foo(OP bar), which is
482 488 # invalid. The characters '!=()' don't need to be checked for, as the
483 489 # _prefilter routine explicitely does so, to catch direct calls and
484 490 # rebindings of existing names.
485 491
486 492 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
487 493 # it affects the rest of the group in square brackets.
488 494 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
489 495 '|^is |^not |^in |^and |^or ')
490 496
491 497 # try to catch also methods for stuff in lists/tuples/dicts: off
492 498 # (experimental). For this to work, the line_split regexp would need
493 499 # to be modified so it wouldn't break things at '['. That line is
494 500 # nasty enough that I shouldn't change it until I can test it _well_.
495 501 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
496 502
497 503 # keep track of where we started running (mainly for crash post-mortem)
498 504 self.starting_dir = os.getcwd()
499 505
500 506 # Various switches which can be set
501 507 self.CACHELENGTH = 5000 # this is cheap, it's just text
502 508 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
503 509 self.banner2 = banner2
504 510
505 511 # TraceBack handlers:
506 512
507 513 # Syntax error handler.
508 514 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
509 515
510 516 # The interactive one is initialized with an offset, meaning we always
511 517 # want to remove the topmost item in the traceback, which is our own
512 518 # internal code. Valid modes: ['Plain','Context','Verbose']
513 519 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
514 520 color_scheme='NoColor',
515 521 tb_offset = 1)
516 522
517 523 # IPython itself shouldn't crash. This will produce a detailed
518 524 # post-mortem if it does. But we only install the crash handler for
519 525 # non-threaded shells, the threaded ones use a normal verbose reporter
520 526 # and lose the crash handler. This is because exceptions in the main
521 527 # thread (such as in GUI code) propagate directly to sys.excepthook,
522 528 # and there's no point in printing crash dumps for every user exception.
523 529 if self.isthreaded:
524 530 sys.excepthook = ultraTB.FormattedTB()
525 531 else:
526 532 from IPython import CrashHandler
527 533 sys.excepthook = CrashHandler.CrashHandler(self)
528 534
529 535 # The instance will store a pointer to this, so that runtime code
530 536 # (such as magics) can access it. This is because during the
531 537 # read-eval loop, it gets temporarily overwritten (to deal with GUI
532 538 # frameworks).
533 539 self.sys_excepthook = sys.excepthook
534 540
535 541 # and add any custom exception handlers the user may have specified
536 542 self.set_custom_exc(*custom_exceptions)
537 543
538 544 # indentation management
539 545 self.autoindent = False
540 546 self.indent_current_nsp = 0
541 547
542 548 # Make some aliases automatically
543 549 # Prepare list of shell aliases to auto-define
544 550 if os.name == 'posix':
545 551 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
546 552 'mv mv -i','rm rm -i','cp cp -i',
547 553 'cat cat','less less','clear clear',
548 554 # a better ls
549 555 'ls ls -F',
550 556 # long ls
551 557 'll ls -lF')
552 558 # Extra ls aliases with color, which need special treatment on BSD
553 559 # variants
554 560 ls_extra = ( # color ls
555 561 'lc ls -F -o --color',
556 562 # ls normal files only
557 563 'lf ls -F -o --color %l | grep ^-',
558 564 # ls symbolic links
559 565 'lk ls -F -o --color %l | grep ^l',
560 566 # directories or links to directories,
561 567 'ldir ls -F -o --color %l | grep /$',
562 568 # things which are executable
563 569 'lx ls -F -o --color %l | grep ^-..x',
564 570 )
565 571 # The BSDs don't ship GNU ls, so they don't understand the
566 572 # --color switch out of the box
567 573 if 'bsd' in sys.platform:
568 574 ls_extra = ( # ls normal files only
569 575 'lf ls -lF | grep ^-',
570 576 # ls symbolic links
571 577 'lk ls -lF | grep ^l',
572 578 # directories or links to directories,
573 579 'ldir ls -lF | grep /$',
574 580 # things which are executable
575 581 'lx ls -lF | grep ^-..x',
576 582 )
577 583 auto_alias = auto_alias + ls_extra
578 584 elif os.name in ['nt','dos']:
579 585 auto_alias = ('dir dir /on', 'ls dir /on',
580 586 'ddir dir /ad /on', 'ldir dir /ad /on',
581 587 'mkdir mkdir','rmdir rmdir','echo echo',
582 588 'ren ren','cls cls','copy copy')
583 589 else:
584 590 auto_alias = ()
585 591 self.auto_alias = [s.split(None,1) for s in auto_alias]
586 592 # Call the actual (public) initializer
587 593 self.init_auto_alias()
588 594
589 595 # Produce a public API instance
590 596 self.api = IPython.ipapi.IPApi(self)
591 597
592 598 # track which builtins we add, so we can clean up later
593 599 self.builtins_added = {}
594 600 # This method will add the necessary builtins for operation, but
595 601 # tracking what it did via the builtins_added dict.
596 602 self.add_builtins()
597 603
598 604 # end __init__
599 605
600 606 def pre_config_initialization(self):
601 607 """Pre-configuration init method
602 608
603 609 This is called before the configuration files are processed to
604 610 prepare the services the config files might need.
605 611
606 612 self.rc already has reasonable default values at this point.
607 613 """
608 614 rc = self.rc
609 615
610 616 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
611 617
612 618 def post_config_initialization(self):
613 619 """Post configuration init method
614 620
615 621 This is called after the configuration files have been processed to
616 622 'finalize' the initialization."""
617 623
618 624 rc = self.rc
619 625
620 626 # Object inspector
621 627 self.inspector = OInspect.Inspector(OInspect.InspectColors,
622 628 PyColorize.ANSICodeColors,
623 629 'NoColor',
624 630 rc.object_info_string_level)
625 631
626 632 # Load readline proper
627 633 if rc.readline:
628 634 self.init_readline()
629 635
630 636 # local shortcut, this is used a LOT
631 637 self.log = self.logger.log
632 638
633 639 # Initialize cache, set in/out prompts and printing system
634 640 self.outputcache = CachedOutput(self,
635 641 rc.cache_size,
636 642 rc.pprint,
637 643 input_sep = rc.separate_in,
638 644 output_sep = rc.separate_out,
639 645 output_sep2 = rc.separate_out2,
640 646 ps1 = rc.prompt_in1,
641 647 ps2 = rc.prompt_in2,
642 648 ps_out = rc.prompt_out,
643 649 pad_left = rc.prompts_pad_left)
644 650
645 651 # user may have over-ridden the default print hook:
646 652 try:
647 653 self.outputcache.__class__.display = self.hooks.display
648 654 except AttributeError:
649 655 pass
650 656
651 657 # I don't like assigning globally to sys, because it means when embedding
652 658 # instances, each embedded instance overrides the previous choice. But
653 659 # sys.displayhook seems to be called internally by exec, so I don't see a
654 660 # way around it.
655 661 sys.displayhook = self.outputcache
656 662
657 663 # Set user colors (don't do it in the constructor above so that it
658 664 # doesn't crash if colors option is invalid)
659 665 self.magic_colors(rc.colors)
660 666
661 667 # Set calling of pdb on exceptions
662 668 self.call_pdb = rc.pdb
663 669
664 670 # Load user aliases
665 671 for alias in rc.alias:
666 672 self.magic_alias(alias)
667 673 self.hooks.late_startup_hook()
668 674
669 675 batchrun = False
670 676 for batchfile in [path(arg) for arg in self.rc.args
671 677 if arg.lower().endswith('.ipy')]:
672 678 if not batchfile.isfile():
673 679 print "No such batch file:", batchfile
674 680 continue
675 681 self.api.runlines(batchfile.text())
676 682 batchrun = True
677 683 if batchrun:
678 684 self.exit_now = True
679 685
680 686 def add_builtins(self):
681 687 """Store ipython references into the builtin namespace.
682 688
683 689 Some parts of ipython operate via builtins injected here, which hold a
684 690 reference to IPython itself."""
685 691
686 692 # TODO: deprecate all except _ip; 'jobs' should be installed
687 693 # by an extension and the rest are under _ip, ipalias is redundant
688 694 builtins_new = dict(__IPYTHON__ = self,
689 695 ip_set_hook = self.set_hook,
690 696 jobs = self.jobs,
691 697 ipmagic = self.ipmagic,
692 698 ipalias = self.ipalias,
693 699 ipsystem = self.ipsystem,
694 700 _ip = self.api
695 701 )
696 702 for biname,bival in builtins_new.items():
697 703 try:
698 704 # store the orignal value so we can restore it
699 705 self.builtins_added[biname] = __builtin__.__dict__[biname]
700 706 except KeyError:
701 707 # or mark that it wasn't defined, and we'll just delete it at
702 708 # cleanup
703 709 self.builtins_added[biname] = Undefined
704 710 __builtin__.__dict__[biname] = bival
705 711
706 712 # Keep in the builtins a flag for when IPython is active. We set it
707 713 # with setdefault so that multiple nested IPythons don't clobber one
708 714 # another. Each will increase its value by one upon being activated,
709 715 # which also gives us a way to determine the nesting level.
710 716 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
711 717
712 718 def clean_builtins(self):
713 719 """Remove any builtins which might have been added by add_builtins, or
714 720 restore overwritten ones to their previous values."""
715 721 for biname,bival in self.builtins_added.items():
716 722 if bival is Undefined:
717 723 del __builtin__.__dict__[biname]
718 724 else:
719 725 __builtin__.__dict__[biname] = bival
720 726 self.builtins_added.clear()
721 727
722 728 def set_hook(self,name,hook, priority = 50):
723 729 """set_hook(name,hook) -> sets an internal IPython hook.
724 730
725 731 IPython exposes some of its internal API as user-modifiable hooks. By
726 732 adding your function to one of these hooks, you can modify IPython's
727 733 behavior to call at runtime your own routines."""
728 734
729 735 # At some point in the future, this should validate the hook before it
730 736 # accepts it. Probably at least check that the hook takes the number
731 737 # of args it's supposed to.
732 738 dp = getattr(self.hooks, name, None)
733 739 if name not in IPython.hooks.__all__:
734 740 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
735 741 if not dp:
736 742 dp = IPython.hooks.CommandChainDispatcher()
737 743
738 744 f = new.instancemethod(hook,self,self.__class__)
739 745 try:
740 746 dp.add(f,priority)
741 747 except AttributeError:
742 748 # it was not commandchain, plain old func - replace
743 749 dp = f
744 750
745 751 setattr(self.hooks,name, dp)
746 752
747 753
748 754 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
749 755
750 756 def set_custom_exc(self,exc_tuple,handler):
751 757 """set_custom_exc(exc_tuple,handler)
752 758
753 759 Set a custom exception handler, which will be called if any of the
754 760 exceptions in exc_tuple occur in the mainloop (specifically, in the
755 761 runcode() method.
756 762
757 763 Inputs:
758 764
759 765 - exc_tuple: a *tuple* of valid exceptions to call the defined
760 766 handler for. It is very important that you use a tuple, and NOT A
761 767 LIST here, because of the way Python's except statement works. If
762 768 you only want to trap a single exception, use a singleton tuple:
763 769
764 770 exc_tuple == (MyCustomException,)
765 771
766 772 - handler: this must be defined as a function with the following
767 773 basic interface: def my_handler(self,etype,value,tb).
768 774
769 775 This will be made into an instance method (via new.instancemethod)
770 776 of IPython itself, and it will be called if any of the exceptions
771 777 listed in the exc_tuple are caught. If the handler is None, an
772 778 internal basic one is used, which just prints basic info.
773 779
774 780 WARNING: by putting in your own exception handler into IPython's main
775 781 execution loop, you run a very good chance of nasty crashes. This
776 782 facility should only be used if you really know what you are doing."""
777 783
778 784 assert type(exc_tuple)==type(()) , \
779 785 "The custom exceptions must be given AS A TUPLE."
780 786
781 787 def dummy_handler(self,etype,value,tb):
782 788 print '*** Simple custom exception handler ***'
783 789 print 'Exception type :',etype
784 790 print 'Exception value:',value
785 791 print 'Traceback :',tb
786 792 print 'Source code :','\n'.join(self.buffer)
787 793
788 794 if handler is None: handler = dummy_handler
789 795
790 796 self.CustomTB = new.instancemethod(handler,self,self.__class__)
791 797 self.custom_exceptions = exc_tuple
792 798
793 799 def set_custom_completer(self,completer,pos=0):
794 800 """set_custom_completer(completer,pos=0)
795 801
796 802 Adds a new custom completer function.
797 803
798 804 The position argument (defaults to 0) is the index in the completers
799 805 list where you want the completer to be inserted."""
800 806
801 807 newcomp = new.instancemethod(completer,self.Completer,
802 808 self.Completer.__class__)
803 809 self.Completer.matchers.insert(pos,newcomp)
804 810
805 811 def _get_call_pdb(self):
806 812 return self._call_pdb
807 813
808 814 def _set_call_pdb(self,val):
809 815
810 816 if val not in (0,1,False,True):
811 817 raise ValueError,'new call_pdb value must be boolean'
812 818
813 819 # store value in instance
814 820 self._call_pdb = val
815 821
816 822 # notify the actual exception handlers
817 823 self.InteractiveTB.call_pdb = val
818 824 if self.isthreaded:
819 825 try:
820 826 self.sys_excepthook.call_pdb = val
821 827 except:
822 828 warn('Failed to activate pdb for threaded exception handler')
823 829
824 830 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
825 831 'Control auto-activation of pdb at exceptions')
826 832
827 833
828 834 # These special functions get installed in the builtin namespace, to
829 835 # provide programmatic (pure python) access to magics, aliases and system
830 836 # calls. This is important for logging, user scripting, and more.
831 837
832 838 # We are basically exposing, via normal python functions, the three
833 839 # mechanisms in which ipython offers special call modes (magics for
834 840 # internal control, aliases for direct system access via pre-selected
835 841 # names, and !cmd for calling arbitrary system commands).
836 842
837 843 def ipmagic(self,arg_s):
838 844 """Call a magic function by name.
839 845
840 846 Input: a string containing the name of the magic function to call and any
841 847 additional arguments to be passed to the magic.
842 848
843 849 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
844 850 prompt:
845 851
846 852 In[1]: %name -opt foo bar
847 853
848 854 To call a magic without arguments, simply use ipmagic('name').
849 855
850 856 This provides a proper Python function to call IPython's magics in any
851 857 valid Python code you can type at the interpreter, including loops and
852 858 compound statements. It is added by IPython to the Python builtin
853 859 namespace upon initialization."""
854 860
855 861 args = arg_s.split(' ',1)
856 862 magic_name = args[0]
857 863 magic_name = magic_name.lstrip(self.ESC_MAGIC)
858 864
859 865 try:
860 866 magic_args = args[1]
861 867 except IndexError:
862 868 magic_args = ''
863 869 fn = getattr(self,'magic_'+magic_name,None)
864 870 if fn is None:
865 871 error("Magic function `%s` not found." % magic_name)
866 872 else:
867 873 magic_args = self.var_expand(magic_args)
868 874 return fn(magic_args)
869 875
870 876 def ipalias(self,arg_s):
871 877 """Call an alias by name.
872 878
873 879 Input: a string containing the name of the alias to call and any
874 880 additional arguments to be passed to the magic.
875 881
876 882 ipalias('name -opt foo bar') is equivalent to typing at the ipython
877 883 prompt:
878 884
879 885 In[1]: name -opt foo bar
880 886
881 887 To call an alias without arguments, simply use ipalias('name').
882 888
883 889 This provides a proper Python function to call IPython's aliases in any
884 890 valid Python code you can type at the interpreter, including loops and
885 891 compound statements. It is added by IPython to the Python builtin
886 892 namespace upon initialization."""
887 893
888 894 args = arg_s.split(' ',1)
889 895 alias_name = args[0]
890 896 try:
891 897 alias_args = args[1]
892 898 except IndexError:
893 899 alias_args = ''
894 900 if alias_name in self.alias_table:
895 901 self.call_alias(alias_name,alias_args)
896 902 else:
897 903 error("Alias `%s` not found." % alias_name)
898 904
899 905 def ipsystem(self,arg_s):
900 906 """Make a system call, using IPython."""
901 907
902 908 self.system(arg_s)
903 909
904 910 def complete(self,text):
905 911 """Return a sorted list of all possible completions on text.
906 912
907 913 Inputs:
908 914
909 915 - text: a string of text to be completed on.
910 916
911 917 This is a wrapper around the completion mechanism, similar to what
912 918 readline does at the command line when the TAB key is hit. By
913 919 exposing it as a method, it can be used by other non-readline
914 920 environments (such as GUIs) for text completion.
915 921
916 922 Simple usage example:
917 923
918 924 In [1]: x = 'hello'
919 925
920 926 In [2]: __IP.complete('x.l')
921 927 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
922 928
923 929 complete = self.Completer.complete
924 930 state = 0
925 931 # use a dict so we get unique keys, since ipyhton's multiple
926 932 # completers can return duplicates.
927 933 comps = {}
928 934 while True:
929 935 newcomp = complete(text,state)
930 936 if newcomp is None:
931 937 break
932 938 comps[newcomp] = 1
933 939 state += 1
934 940 outcomps = comps.keys()
935 941 outcomps.sort()
936 942 return outcomps
937 943
938 944 def set_completer_frame(self, frame=None):
939 945 if frame:
940 946 self.Completer.namespace = frame.f_locals
941 947 self.Completer.global_namespace = frame.f_globals
942 948 else:
943 949 self.Completer.namespace = self.user_ns
944 950 self.Completer.global_namespace = self.user_global_ns
945 951
946 952 def init_auto_alias(self):
947 953 """Define some aliases automatically.
948 954
949 955 These are ALL parameter-less aliases"""
950 956
951 957 for alias,cmd in self.auto_alias:
952 958 self.alias_table[alias] = (0,cmd)
953 959
954 960 def alias_table_validate(self,verbose=0):
955 961 """Update information about the alias table.
956 962
957 963 In particular, make sure no Python keywords/builtins are in it."""
958 964
959 965 no_alias = self.no_alias
960 966 for k in self.alias_table.keys():
961 967 if k in no_alias:
962 968 del self.alias_table[k]
963 969 if verbose:
964 970 print ("Deleting alias <%s>, it's a Python "
965 971 "keyword or builtin." % k)
966 972
967 973 def set_autoindent(self,value=None):
968 974 """Set the autoindent flag, checking for readline support.
969 975
970 976 If called with no arguments, it acts as a toggle."""
971 977
972 978 if not self.has_readline:
973 979 if os.name == 'posix':
974 980 warn("The auto-indent feature requires the readline library")
975 981 self.autoindent = 0
976 982 return
977 983 if value is None:
978 984 self.autoindent = not self.autoindent
979 985 else:
980 986 self.autoindent = value
981 987
982 988 def rc_set_toggle(self,rc_field,value=None):
983 989 """Set or toggle a field in IPython's rc config. structure.
984 990
985 991 If called with no arguments, it acts as a toggle.
986 992
987 993 If called with a non-existent field, the resulting AttributeError
988 994 exception will propagate out."""
989 995
990 996 rc_val = getattr(self.rc,rc_field)
991 997 if value is None:
992 998 value = not rc_val
993 999 setattr(self.rc,rc_field,value)
994 1000
995 1001 def user_setup(self,ipythondir,rc_suffix,mode='install'):
996 1002 """Install the user configuration directory.
997 1003
998 1004 Can be called when running for the first time or to upgrade the user's
999 1005 .ipython/ directory with the mode parameter. Valid modes are 'install'
1000 1006 and 'upgrade'."""
1001 1007
1002 1008 def wait():
1003 1009 try:
1004 1010 raw_input("Please press <RETURN> to start IPython.")
1005 1011 except EOFError:
1006 1012 print >> Term.cout
1007 1013 print '*'*70
1008 1014
1009 1015 cwd = os.getcwd() # remember where we started
1010 1016 glb = glob.glob
1011 1017 print '*'*70
1012 1018 if mode == 'install':
1013 1019 print \
1014 1020 """Welcome to IPython. I will try to create a personal configuration directory
1015 1021 where you can customize many aspects of IPython's functionality in:\n"""
1016 1022 else:
1017 1023 print 'I am going to upgrade your configuration in:'
1018 1024
1019 1025 print ipythondir
1020 1026
1021 1027 rcdirend = os.path.join('IPython','UserConfig')
1022 1028 cfg = lambda d: os.path.join(d,rcdirend)
1023 1029 try:
1024 1030 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1025 1031 except IOError:
1026 1032 warning = """
1027 1033 Installation error. IPython's directory was not found.
1028 1034
1029 1035 Check the following:
1030 1036
1031 1037 The ipython/IPython directory should be in a directory belonging to your
1032 1038 PYTHONPATH environment variable (that is, it should be in a directory
1033 1039 belonging to sys.path). You can copy it explicitly there or just link to it.
1034 1040
1035 1041 IPython will proceed with builtin defaults.
1036 1042 """
1037 1043 warn(warning)
1038 1044 wait()
1039 1045 return
1040 1046
1041 1047 if mode == 'install':
1042 1048 try:
1043 1049 shutil.copytree(rcdir,ipythondir)
1044 1050 os.chdir(ipythondir)
1045 1051 rc_files = glb("ipythonrc*")
1046 1052 for rc_file in rc_files:
1047 1053 os.rename(rc_file,rc_file+rc_suffix)
1048 1054 except:
1049 1055 warning = """
1050 1056
1051 1057 There was a problem with the installation:
1052 1058 %s
1053 1059 Try to correct it or contact the developers if you think it's a bug.
1054 1060 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1055 1061 warn(warning)
1056 1062 wait()
1057 1063 return
1058 1064
1059 1065 elif mode == 'upgrade':
1060 1066 try:
1061 1067 os.chdir(ipythondir)
1062 1068 except:
1063 1069 print """
1064 1070 Can not upgrade: changing to directory %s failed. Details:
1065 1071 %s
1066 1072 """ % (ipythondir,sys.exc_info()[1])
1067 1073 wait()
1068 1074 return
1069 1075 else:
1070 1076 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1071 1077 for new_full_path in sources:
1072 1078 new_filename = os.path.basename(new_full_path)
1073 1079 if new_filename.startswith('ipythonrc'):
1074 1080 new_filename = new_filename + rc_suffix
1075 1081 # The config directory should only contain files, skip any
1076 1082 # directories which may be there (like CVS)
1077 1083 if os.path.isdir(new_full_path):
1078 1084 continue
1079 1085 if os.path.exists(new_filename):
1080 1086 old_file = new_filename+'.old'
1081 1087 if os.path.exists(old_file):
1082 1088 os.remove(old_file)
1083 1089 os.rename(new_filename,old_file)
1084 1090 shutil.copy(new_full_path,new_filename)
1085 1091 else:
1086 1092 raise ValueError,'unrecognized mode for install:',`mode`
1087 1093
1088 1094 # Fix line-endings to those native to each platform in the config
1089 1095 # directory.
1090 1096 try:
1091 1097 os.chdir(ipythondir)
1092 1098 except:
1093 1099 print """
1094 1100 Problem: changing to directory %s failed.
1095 1101 Details:
1096 1102 %s
1097 1103
1098 1104 Some configuration files may have incorrect line endings. This should not
1099 1105 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1100 1106 wait()
1101 1107 else:
1102 1108 for fname in glb('ipythonrc*'):
1103 1109 try:
1104 1110 native_line_ends(fname,backup=0)
1105 1111 except IOError:
1106 1112 pass
1107 1113
1108 1114 if mode == 'install':
1109 1115 print """
1110 1116 Successful installation!
1111 1117
1112 1118 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1113 1119 IPython manual (there are both HTML and PDF versions supplied with the
1114 1120 distribution) to make sure that your system environment is properly configured
1115 1121 to take advantage of IPython's features.
1116 1122
1117 1123 Important note: the configuration system has changed! The old system is
1118 1124 still in place, but its setting may be partly overridden by the settings in
1119 1125 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1120 1126 if some of the new settings bother you.
1121 1127
1122 1128 """
1123 1129 else:
1124 1130 print """
1125 1131 Successful upgrade!
1126 1132
1127 1133 All files in your directory:
1128 1134 %(ipythondir)s
1129 1135 which would have been overwritten by the upgrade were backed up with a .old
1130 1136 extension. If you had made particular customizations in those files you may
1131 1137 want to merge them back into the new files.""" % locals()
1132 1138 wait()
1133 1139 os.chdir(cwd)
1134 1140 # end user_setup()
1135 1141
1136 1142 def atexit_operations(self):
1137 1143 """This will be executed at the time of exit.
1138 1144
1139 1145 Saving of persistent data should be performed here. """
1140 1146
1141 1147 #print '*** IPython exit cleanup ***' # dbg
1142 1148 # input history
1143 1149 self.savehist()
1144 1150
1145 1151 # Cleanup all tempfiles left around
1146 1152 for tfile in self.tempfiles:
1147 1153 try:
1148 1154 os.unlink(tfile)
1149 1155 except OSError:
1150 1156 pass
1151 1157
1152 1158 # save the "persistent data" catch-all dictionary
1153 1159 self.hooks.shutdown_hook()
1154 1160
1155 1161 def savehist(self):
1156 1162 """Save input history to a file (via readline library)."""
1157 1163 try:
1158 1164 self.readline.write_history_file(self.histfile)
1159 1165 except:
1160 1166 print 'Unable to save IPython command history to file: ' + \
1161 1167 `self.histfile`
1162 1168
1163 1169 def pre_readline(self):
1164 1170 """readline hook to be used at the start of each line.
1165 1171
1166 1172 Currently it handles auto-indent only."""
1167 1173
1168 1174 #debugx('self.indent_current_nsp','pre_readline:')
1169 1175 self.readline.insert_text(self.indent_current_str())
1170 1176
1171 1177 def init_readline(self):
1172 1178 """Command history completion/saving/reloading."""
1173 1179
1174 1180 import IPython.rlineimpl as readline
1175 1181 if not readline.have_readline:
1176 1182 self.has_readline = 0
1177 1183 self.readline = None
1178 1184 # no point in bugging windows users with this every time:
1179 1185 warn('Readline services not available on this platform.')
1180 1186 else:
1181 1187 sys.modules['readline'] = readline
1182 1188 import atexit
1183 1189 from IPython.completer import IPCompleter
1184 1190 self.Completer = IPCompleter(self,
1185 1191 self.user_ns,
1186 1192 self.user_global_ns,
1187 1193 self.rc.readline_omit__names,
1188 1194 self.alias_table)
1189 1195
1190 1196 # Platform-specific configuration
1191 1197 if os.name == 'nt':
1192 1198 self.readline_startup_hook = readline.set_pre_input_hook
1193 1199 else:
1194 1200 self.readline_startup_hook = readline.set_startup_hook
1195 1201
1196 1202 # Load user's initrc file (readline config)
1197 1203 inputrc_name = os.environ.get('INPUTRC')
1198 1204 if inputrc_name is None:
1199 1205 home_dir = get_home_dir()
1200 1206 if home_dir is not None:
1201 1207 inputrc_name = os.path.join(home_dir,'.inputrc')
1202 1208 if os.path.isfile(inputrc_name):
1203 1209 try:
1204 1210 readline.read_init_file(inputrc_name)
1205 1211 except:
1206 1212 warn('Problems reading readline initialization file <%s>'
1207 1213 % inputrc_name)
1208 1214
1209 1215 self.has_readline = 1
1210 1216 self.readline = readline
1211 1217 # save this in sys so embedded copies can restore it properly
1212 1218 sys.ipcompleter = self.Completer.complete
1213 1219 readline.set_completer(self.Completer.complete)
1214 1220
1215 1221 # Configure readline according to user's prefs
1216 1222 for rlcommand in self.rc.readline_parse_and_bind:
1217 1223 readline.parse_and_bind(rlcommand)
1218 1224
1219 1225 # remove some chars from the delimiters list
1220 1226 delims = readline.get_completer_delims()
1221 1227 delims = delims.translate(string._idmap,
1222 1228 self.rc.readline_remove_delims)
1223 1229 readline.set_completer_delims(delims)
1224 1230 # otherwise we end up with a monster history after a while:
1225 1231 readline.set_history_length(1000)
1226 1232 try:
1227 1233 #print '*** Reading readline history' # dbg
1228 1234 readline.read_history_file(self.histfile)
1229 1235 except IOError:
1230 1236 pass # It doesn't exist yet.
1231 1237
1232 1238 atexit.register(self.atexit_operations)
1233 1239 del atexit
1234 1240
1235 1241 # Configure auto-indent for all platforms
1236 1242 self.set_autoindent(self.rc.autoindent)
1237 1243
1238 1244 def ask_yes_no(self,prompt,default=True):
1239 1245 if self.rc.quiet:
1240 1246 return True
1241 1247 return ask_yes_no(prompt,default)
1242 1248
1243 1249 def _should_recompile(self,e):
1244 1250 """Utility routine for edit_syntax_error"""
1245 1251
1246 1252 if e.filename in ('<ipython console>','<input>','<string>',
1247 1253 '<console>','<BackgroundJob compilation>',
1248 1254 None):
1249 1255
1250 1256 return False
1251 1257 try:
1252 1258 if (self.rc.autoedit_syntax and
1253 1259 not self.ask_yes_no('Return to editor to correct syntax error? '
1254 1260 '[Y/n] ','y')):
1255 1261 return False
1256 1262 except EOFError:
1257 1263 return False
1258 1264
1259 1265 def int0(x):
1260 1266 try:
1261 1267 return int(x)
1262 1268 except TypeError:
1263 1269 return 0
1264 1270 # always pass integer line and offset values to editor hook
1265 1271 self.hooks.fix_error_editor(e.filename,
1266 1272 int0(e.lineno),int0(e.offset),e.msg)
1267 1273 return True
1268 1274
1269 1275 def edit_syntax_error(self):
1270 1276 """The bottom half of the syntax error handler called in the main loop.
1271 1277
1272 1278 Loop until syntax error is fixed or user cancels.
1273 1279 """
1274 1280
1275 1281 while self.SyntaxTB.last_syntax_error:
1276 1282 # copy and clear last_syntax_error
1277 1283 err = self.SyntaxTB.clear_err_state()
1278 1284 if not self._should_recompile(err):
1279 1285 return
1280 1286 try:
1281 1287 # may set last_syntax_error again if a SyntaxError is raised
1282 1288 self.safe_execfile(err.filename,self.user_ns)
1283 1289 except:
1284 1290 self.showtraceback()
1285 1291 else:
1286 1292 try:
1287 1293 f = file(err.filename)
1288 1294 try:
1289 1295 sys.displayhook(f.read())
1290 1296 finally:
1291 1297 f.close()
1292 1298 except:
1293 1299 self.showtraceback()
1294 1300
1295 1301 def showsyntaxerror(self, filename=None):
1296 1302 """Display the syntax error that just occurred.
1297 1303
1298 1304 This doesn't display a stack trace because there isn't one.
1299 1305
1300 1306 If a filename is given, it is stuffed in the exception instead
1301 1307 of what was there before (because Python's parser always uses
1302 1308 "<string>" when reading from a string).
1303 1309 """
1304 1310 etype, value, last_traceback = sys.exc_info()
1305 1311
1306 1312 # See note about these variables in showtraceback() below
1307 1313 sys.last_type = etype
1308 1314 sys.last_value = value
1309 1315 sys.last_traceback = last_traceback
1310 1316
1311 1317 if filename and etype is SyntaxError:
1312 1318 # Work hard to stuff the correct filename in the exception
1313 1319 try:
1314 1320 msg, (dummy_filename, lineno, offset, line) = value
1315 1321 except:
1316 1322 # Not the format we expect; leave it alone
1317 1323 pass
1318 1324 else:
1319 1325 # Stuff in the right filename
1320 1326 try:
1321 1327 # Assume SyntaxError is a class exception
1322 1328 value = SyntaxError(msg, (filename, lineno, offset, line))
1323 1329 except:
1324 1330 # If that failed, assume SyntaxError is a string
1325 1331 value = msg, (filename, lineno, offset, line)
1326 1332 self.SyntaxTB(etype,value,[])
1327 1333
1328 1334 def debugger(self):
1329 1335 """Call the pdb debugger."""
1330 1336
1331 1337 if not self.rc.pdb:
1332 1338 return
1333 1339 pdb.pm()
1334 1340
1335 1341 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1336 1342 """Display the exception that just occurred.
1337 1343
1338 1344 If nothing is known about the exception, this is the method which
1339 1345 should be used throughout the code for presenting user tracebacks,
1340 1346 rather than directly invoking the InteractiveTB object.
1341 1347
1342 1348 A specific showsyntaxerror() also exists, but this method can take
1343 1349 care of calling it if needed, so unless you are explicitly catching a
1344 1350 SyntaxError exception, don't try to analyze the stack manually and
1345 1351 simply call this method."""
1346 1352
1347 1353 # Though this won't be called by syntax errors in the input line,
1348 1354 # there may be SyntaxError cases whith imported code.
1349 1355 if exc_tuple is None:
1350 1356 etype, value, tb = sys.exc_info()
1351 1357 else:
1352 1358 etype, value, tb = exc_tuple
1353 1359 if etype is SyntaxError:
1354 1360 self.showsyntaxerror(filename)
1355 1361 else:
1356 1362 # WARNING: these variables are somewhat deprecated and not
1357 1363 # necessarily safe to use in a threaded environment, but tools
1358 1364 # like pdb depend on their existence, so let's set them. If we
1359 1365 # find problems in the field, we'll need to revisit their use.
1360 1366 sys.last_type = etype
1361 1367 sys.last_value = value
1362 1368 sys.last_traceback = tb
1363 1369
1364 1370 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1365 1371 if self.InteractiveTB.call_pdb and self.has_readline:
1366 1372 # pdb mucks up readline, fix it back
1367 1373 self.readline.set_completer(self.Completer.complete)
1368 1374
1369 1375 def mainloop(self,banner=None):
1370 1376 """Creates the local namespace and starts the mainloop.
1371 1377
1372 1378 If an optional banner argument is given, it will override the
1373 1379 internally created default banner."""
1374 1380
1375 1381 if self.rc.c: # Emulate Python's -c option
1376 1382 self.exec_init_cmd()
1377 1383 if banner is None:
1378 1384 if not self.rc.banner:
1379 1385 banner = ''
1380 1386 # banner is string? Use it directly!
1381 1387 elif isinstance(self.rc.banner,basestring):
1382 1388 banner = self.rc.banner
1383 1389 else:
1384 1390 banner = self.BANNER+self.banner2
1385 1391
1386 1392 self.interact(banner)
1387 1393
1388 1394 def exec_init_cmd(self):
1389 1395 """Execute a command given at the command line.
1390 1396
1391 1397 This emulates Python's -c option."""
1392 1398
1393 1399 #sys.argv = ['-c']
1394 1400 self.push(self.rc.c)
1395 1401
1396 1402 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1397 1403 """Embeds IPython into a running python program.
1398 1404
1399 1405 Input:
1400 1406
1401 1407 - header: An optional header message can be specified.
1402 1408
1403 1409 - local_ns, global_ns: working namespaces. If given as None, the
1404 1410 IPython-initialized one is updated with __main__.__dict__, so that
1405 1411 program variables become visible but user-specific configuration
1406 1412 remains possible.
1407 1413
1408 1414 - stack_depth: specifies how many levels in the stack to go to
1409 1415 looking for namespaces (when local_ns and global_ns are None). This
1410 1416 allows an intermediate caller to make sure that this function gets
1411 1417 the namespace from the intended level in the stack. By default (0)
1412 1418 it will get its locals and globals from the immediate caller.
1413 1419
1414 1420 Warning: it's possible to use this in a program which is being run by
1415 1421 IPython itself (via %run), but some funny things will happen (a few
1416 1422 globals get overwritten). In the future this will be cleaned up, as
1417 1423 there is no fundamental reason why it can't work perfectly."""
1418 1424
1419 1425 # Get locals and globals from caller
1420 1426 if local_ns is None or global_ns is None:
1421 1427 call_frame = sys._getframe(stack_depth).f_back
1422 1428
1423 1429 if local_ns is None:
1424 1430 local_ns = call_frame.f_locals
1425 1431 if global_ns is None:
1426 1432 global_ns = call_frame.f_globals
1427 1433
1428 1434 # Update namespaces and fire up interpreter
1429 1435
1430 1436 # The global one is easy, we can just throw it in
1431 1437 self.user_global_ns = global_ns
1432 1438
1433 1439 # but the user/local one is tricky: ipython needs it to store internal
1434 1440 # data, but we also need the locals. We'll copy locals in the user
1435 1441 # one, but will track what got copied so we can delete them at exit.
1436 1442 # This is so that a later embedded call doesn't see locals from a
1437 1443 # previous call (which most likely existed in a separate scope).
1438 1444 local_varnames = local_ns.keys()
1439 1445 self.user_ns.update(local_ns)
1440 1446
1441 1447 # Patch for global embedding to make sure that things don't overwrite
1442 1448 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1443 1449 # FIXME. Test this a bit more carefully (the if.. is new)
1444 1450 if local_ns is None and global_ns is None:
1445 1451 self.user_global_ns.update(__main__.__dict__)
1446 1452
1447 1453 # make sure the tab-completer has the correct frame information, so it
1448 1454 # actually completes using the frame's locals/globals
1449 1455 self.set_completer_frame()
1450 1456
1451 1457 # before activating the interactive mode, we need to make sure that
1452 1458 # all names in the builtin namespace needed by ipython point to
1453 1459 # ourselves, and not to other instances.
1454 1460 self.add_builtins()
1455 1461
1456 1462 self.interact(header)
1457 1463
1458 1464 # now, purge out the user namespace from anything we might have added
1459 1465 # from the caller's local namespace
1460 1466 delvar = self.user_ns.pop
1461 1467 for var in local_varnames:
1462 1468 delvar(var,None)
1463 1469 # and clean builtins we may have overridden
1464 1470 self.clean_builtins()
1465 1471
1466 1472 def interact(self, banner=None):
1467 1473 """Closely emulate the interactive Python console.
1468 1474
1469 1475 The optional banner argument specify the banner to print
1470 1476 before the first interaction; by default it prints a banner
1471 1477 similar to the one printed by the real Python interpreter,
1472 1478 followed by the current class name in parentheses (so as not
1473 1479 to confuse this with the real interpreter -- since it's so
1474 1480 close!).
1475 1481
1476 1482 """
1477 1483
1478 1484 if self.exit_now:
1479 1485 # batch run -> do not interact
1480 1486 return
1481 1487 cprt = 'Type "copyright", "credits" or "license" for more information.'
1482 1488 if banner is None:
1483 1489 self.write("Python %s on %s\n%s\n(%s)\n" %
1484 1490 (sys.version, sys.platform, cprt,
1485 1491 self.__class__.__name__))
1486 1492 else:
1487 1493 self.write(banner)
1488 1494
1489 1495 more = 0
1490 1496
1491 1497 # Mark activity in the builtins
1492 1498 __builtin__.__dict__['__IPYTHON__active'] += 1
1493 1499
1494 1500 # exit_now is set by a call to %Exit or %Quit
1495 1501 while not self.exit_now:
1496 1502 if more:
1497 1503 prompt = self.hooks.generate_prompt(True)
1498 1504 if self.autoindent:
1499 1505 self.readline_startup_hook(self.pre_readline)
1500 1506 else:
1501 1507 prompt = self.hooks.generate_prompt(False)
1502 1508 try:
1503 1509 line = self.raw_input(prompt,more)
1504 1510 if self.autoindent:
1505 1511 self.readline_startup_hook(None)
1506 1512 except KeyboardInterrupt:
1507 1513 self.write('\nKeyboardInterrupt\n')
1508 1514 self.resetbuffer()
1509 1515 # keep cache in sync with the prompt counter:
1510 1516 self.outputcache.prompt_count -= 1
1511 1517
1512 1518 if self.autoindent:
1513 1519 self.indent_current_nsp = 0
1514 1520 more = 0
1515 1521 except EOFError:
1516 1522 if self.autoindent:
1517 1523 self.readline_startup_hook(None)
1518 1524 self.write('\n')
1519 1525 self.exit()
1520 1526 except bdb.BdbQuit:
1521 1527 warn('The Python debugger has exited with a BdbQuit exception.\n'
1522 1528 'Because of how pdb handles the stack, it is impossible\n'
1523 1529 'for IPython to properly format this particular exception.\n'
1524 1530 'IPython will resume normal operation.')
1525 1531 except:
1526 1532 # exceptions here are VERY RARE, but they can be triggered
1527 1533 # asynchronously by signal handlers, for example.
1528 1534 self.showtraceback()
1529 1535 else:
1530 1536 more = self.push(line)
1531 1537 if (self.SyntaxTB.last_syntax_error and
1532 1538 self.rc.autoedit_syntax):
1533 1539 self.edit_syntax_error()
1534 1540
1535 1541 # We are off again...
1536 1542 __builtin__.__dict__['__IPYTHON__active'] -= 1
1537 1543
1538 1544 def excepthook(self, etype, value, tb):
1539 1545 """One more defense for GUI apps that call sys.excepthook.
1540 1546
1541 1547 GUI frameworks like wxPython trap exceptions and call
1542 1548 sys.excepthook themselves. I guess this is a feature that
1543 1549 enables them to keep running after exceptions that would
1544 1550 otherwise kill their mainloop. This is a bother for IPython
1545 1551 which excepts to catch all of the program exceptions with a try:
1546 1552 except: statement.
1547 1553
1548 1554 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1549 1555 any app directly invokes sys.excepthook, it will look to the user like
1550 1556 IPython crashed. In order to work around this, we can disable the
1551 1557 CrashHandler and replace it with this excepthook instead, which prints a
1552 1558 regular traceback using our InteractiveTB. In this fashion, apps which
1553 1559 call sys.excepthook will generate a regular-looking exception from
1554 1560 IPython, and the CrashHandler will only be triggered by real IPython
1555 1561 crashes.
1556 1562
1557 1563 This hook should be used sparingly, only in places which are not likely
1558 1564 to be true IPython errors.
1559 1565 """
1560 1566 self.showtraceback((etype,value,tb),tb_offset=0)
1561 1567
1562 1568 def transform_alias(self, alias,rest=''):
1563 1569 """ Transform alias to system command string.
1564 1570 """
1565 1571 nargs,cmd = self.alias_table[alias]
1566 1572 if ' ' in cmd and os.path.isfile(cmd):
1567 1573 cmd = '"%s"' % cmd
1568 1574
1569 1575 # Expand the %l special to be the user's input line
1570 1576 if cmd.find('%l') >= 0:
1571 1577 cmd = cmd.replace('%l',rest)
1572 1578 rest = ''
1573 1579 if nargs==0:
1574 1580 # Simple, argument-less aliases
1575 1581 cmd = '%s %s' % (cmd,rest)
1576 1582 else:
1577 1583 # Handle aliases with positional arguments
1578 1584 args = rest.split(None,nargs)
1579 1585 if len(args)< nargs:
1580 1586 error('Alias <%s> requires %s arguments, %s given.' %
1581 1587 (alias,nargs,len(args)))
1582 1588 return None
1583 1589 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1584 1590 # Now call the macro, evaluating in the user's namespace
1585 1591 #print 'new command: <%r>' % cmd # dbg
1586 1592 return cmd
1587 1593
1588 1594 def call_alias(self,alias,rest=''):
1589 1595 """Call an alias given its name and the rest of the line.
1590 1596
1591 1597 This is only used to provide backwards compatibility for users of
1592 1598 ipalias(), use of which is not recommended for anymore."""
1593 1599
1594 1600 # Now call the macro, evaluating in the user's namespace
1595 1601 cmd = self.transform_alias(alias, rest)
1596 1602 try:
1597 1603 self.system(cmd)
1598 1604 except:
1599 1605 self.showtraceback()
1600 1606
1601 1607 def indent_current_str(self):
1602 1608 """return the current level of indentation as a string"""
1603 1609 return self.indent_current_nsp * ' '
1604 1610
1605 1611 def autoindent_update(self,line):
1606 1612 """Keep track of the indent level."""
1607 1613
1608 1614 #debugx('line')
1609 1615 #debugx('self.indent_current_nsp')
1610 1616 if self.autoindent:
1611 1617 if line:
1612 1618 inisp = num_ini_spaces(line)
1613 1619 if inisp < self.indent_current_nsp:
1614 1620 self.indent_current_nsp = inisp
1615 1621
1616 1622 if line[-1] == ':':
1617 1623 self.indent_current_nsp += 4
1618 1624 elif dedent_re.match(line):
1619 1625 self.indent_current_nsp -= 4
1620 1626 else:
1621 1627 self.indent_current_nsp = 0
1622 1628
1623 1629 def runlines(self,lines):
1624 1630 """Run a string of one or more lines of source.
1625 1631
1626 1632 This method is capable of running a string containing multiple source
1627 1633 lines, as if they had been entered at the IPython prompt. Since it
1628 1634 exposes IPython's processing machinery, the given strings can contain
1629 1635 magic calls (%magic), special shell access (!cmd), etc."""
1630 1636
1631 1637 # We must start with a clean buffer, in case this is run from an
1632 1638 # interactive IPython session (via a magic, for example).
1633 1639 self.resetbuffer()
1634 1640 lines = lines.split('\n')
1635 1641 more = 0
1636 1642 for line in lines:
1637 1643 # skip blank lines so we don't mess up the prompt counter, but do
1638 1644 # NOT skip even a blank line if we are in a code block (more is
1639 1645 # true)
1640 1646 if line or more:
1641 1647 more = self.push(self.prefilter(line,more))
1642 1648 # IPython's runsource returns None if there was an error
1643 1649 # compiling the code. This allows us to stop processing right
1644 1650 # away, so the user gets the error message at the right place.
1645 1651 if more is None:
1646 1652 break
1647 1653 # final newline in case the input didn't have it, so that the code
1648 1654 # actually does get executed
1649 1655 if more:
1650 1656 self.push('\n')
1651 1657
1652 1658 def runsource(self, source, filename='<input>', symbol='single'):
1653 1659 """Compile and run some source in the interpreter.
1654 1660
1655 1661 Arguments are as for compile_command().
1656 1662
1657 1663 One several things can happen:
1658 1664
1659 1665 1) The input is incorrect; compile_command() raised an
1660 1666 exception (SyntaxError or OverflowError). A syntax traceback
1661 1667 will be printed by calling the showsyntaxerror() method.
1662 1668
1663 1669 2) The input is incomplete, and more input is required;
1664 1670 compile_command() returned None. Nothing happens.
1665 1671
1666 1672 3) The input is complete; compile_command() returned a code
1667 1673 object. The code is executed by calling self.runcode() (which
1668 1674 also handles run-time exceptions, except for SystemExit).
1669 1675
1670 1676 The return value is:
1671 1677
1672 1678 - True in case 2
1673 1679
1674 1680 - False in the other cases, unless an exception is raised, where
1675 1681 None is returned instead. This can be used by external callers to
1676 1682 know whether to continue feeding input or not.
1677 1683
1678 1684 The return value can be used to decide whether to use sys.ps1 or
1679 1685 sys.ps2 to prompt the next line."""
1680 1686
1681 1687 try:
1682 1688 code = self.compile(source,filename,symbol)
1683 1689 except (OverflowError, SyntaxError, ValueError):
1684 1690 # Case 1
1685 1691 self.showsyntaxerror(filename)
1686 1692 return None
1687 1693
1688 1694 if code is None:
1689 1695 # Case 2
1690 1696 return True
1691 1697
1692 1698 # Case 3
1693 1699 # We store the code object so that threaded shells and
1694 1700 # custom exception handlers can access all this info if needed.
1695 1701 # The source corresponding to this can be obtained from the
1696 1702 # buffer attribute as '\n'.join(self.buffer).
1697 1703 self.code_to_run = code
1698 1704 # now actually execute the code object
1699 1705 if self.runcode(code) == 0:
1700 1706 return False
1701 1707 else:
1702 1708 return None
1703 1709
1704 1710 def runcode(self,code_obj):
1705 1711 """Execute a code object.
1706 1712
1707 1713 When an exception occurs, self.showtraceback() is called to display a
1708 1714 traceback.
1709 1715
1710 1716 Return value: a flag indicating whether the code to be run completed
1711 1717 successfully:
1712 1718
1713 1719 - 0: successful execution.
1714 1720 - 1: an error occurred.
1715 1721 """
1716 1722
1717 1723 # Set our own excepthook in case the user code tries to call it
1718 1724 # directly, so that the IPython crash handler doesn't get triggered
1719 1725 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1720 1726
1721 1727 # we save the original sys.excepthook in the instance, in case config
1722 1728 # code (such as magics) needs access to it.
1723 1729 self.sys_excepthook = old_excepthook
1724 1730 outflag = 1 # happens in more places, so it's easier as default
1725 1731 try:
1726 1732 try:
1727 1733 # Embedded instances require separate global/local namespaces
1728 1734 # so they can see both the surrounding (local) namespace and
1729 1735 # the module-level globals when called inside another function.
1730 1736 if self.embedded:
1731 1737 exec code_obj in self.user_global_ns, self.user_ns
1732 1738 # Normal (non-embedded) instances should only have a single
1733 1739 # namespace for user code execution, otherwise functions won't
1734 1740 # see interactive top-level globals.
1735 1741 else:
1736 1742 exec code_obj in self.user_ns
1737 1743 finally:
1738 1744 # Reset our crash handler in place
1739 1745 sys.excepthook = old_excepthook
1740 1746 except SystemExit:
1741 1747 self.resetbuffer()
1742 1748 self.showtraceback()
1743 1749 warn("Type %exit or %quit to exit IPython "
1744 1750 "(%Exit or %Quit do so unconditionally).",level=1)
1745 1751 except self.custom_exceptions:
1746 1752 etype,value,tb = sys.exc_info()
1747 1753 self.CustomTB(etype,value,tb)
1748 1754 except:
1749 1755 self.showtraceback()
1750 1756 else:
1751 1757 outflag = 0
1752 1758 if softspace(sys.stdout, 0):
1753 1759 print
1754 1760 # Flush out code object which has been run (and source)
1755 1761 self.code_to_run = None
1756 1762 return outflag
1757 1763
1758 1764 def push(self, line):
1759 1765 """Push a line to the interpreter.
1760 1766
1761 1767 The line should not have a trailing newline; it may have
1762 1768 internal newlines. The line is appended to a buffer and the
1763 1769 interpreter's runsource() method is called with the
1764 1770 concatenated contents of the buffer as source. If this
1765 1771 indicates that the command was executed or invalid, the buffer
1766 1772 is reset; otherwise, the command is incomplete, and the buffer
1767 1773 is left as it was after the line was appended. The return
1768 1774 value is 1 if more input is required, 0 if the line was dealt
1769 1775 with in some way (this is the same as runsource()).
1770 1776 """
1771 1777
1772 1778 # autoindent management should be done here, and not in the
1773 1779 # interactive loop, since that one is only seen by keyboard input. We
1774 1780 # need this done correctly even for code run via runlines (which uses
1775 1781 # push).
1776 1782
1777 1783 #print 'push line: <%s>' % line # dbg
1778 1784 for subline in line.splitlines():
1779 1785 self.autoindent_update(subline)
1780 1786 self.buffer.append(line)
1781 1787 more = self.runsource('\n'.join(self.buffer), self.filename)
1782 1788 if not more:
1783 1789 self.resetbuffer()
1784 1790 return more
1785 1791
1786 1792 def resetbuffer(self):
1787 1793 """Reset the input buffer."""
1788 1794 self.buffer[:] = []
1789 1795
1790 1796 def raw_input(self,prompt='',continue_prompt=False):
1791 1797 """Write a prompt and read a line.
1792 1798
1793 1799 The returned line does not include the trailing newline.
1794 1800 When the user enters the EOF key sequence, EOFError is raised.
1795 1801
1796 1802 Optional inputs:
1797 1803
1798 1804 - prompt(''): a string to be printed to prompt the user.
1799 1805
1800 1806 - continue_prompt(False): whether this line is the first one or a
1801 1807 continuation in a sequence of inputs.
1802 1808 """
1803 1809
1804 try:
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
1810 line = raw_input_original(prompt)
1812 1811
1813 1812 # Try to be reasonably smart about not re-indenting pasted input more
1814 1813 # than necessary. We do this by trimming out the auto-indent initial
1815 1814 # spaces, if the user's actual input started itself with whitespace.
1816 1815 #debugx('self.buffer[-1]')
1817 1816
1818 1817 if self.autoindent:
1819 1818 if num_ini_spaces(line) > self.indent_current_nsp:
1820 1819 line = line[self.indent_current_nsp:]
1821 1820 self.indent_current_nsp = 0
1822 1821
1823 1822 # store the unfiltered input before the user has any chance to modify
1824 1823 # it.
1825 1824 if line.strip():
1826 1825 if continue_prompt:
1827 1826 self.input_hist_raw[-1] += '%s\n' % line
1828 1827 if self.has_readline: # and some config option is set?
1829 1828 try:
1830 1829 histlen = self.readline.get_current_history_length()
1831 1830 newhist = self.input_hist_raw[-1].rstrip()
1832 1831 self.readline.remove_history_item(histlen-1)
1833 1832 self.readline.replace_history_item(histlen-2,newhist)
1834 1833 except AttributeError:
1835 1834 pass # re{move,place}_history_item are new in 2.4.
1836 1835 else:
1837 1836 self.input_hist_raw.append('%s\n' % line)
1838 1837
1839 1838 try:
1840 1839 lineout = self.prefilter(line,continue_prompt)
1841 1840 except:
1842 1841 # blanket except, in case a user-defined prefilter crashes, so it
1843 1842 # can't take all of ipython with it.
1844 1843 self.showtraceback()
1845 1844 return ''
1846 1845 else:
1847 1846 return lineout
1848 1847
1849 1848 def split_user_input(self,line):
1850 1849 """Split user input into pre-char, function part and rest."""
1851 1850
1852 1851 lsplit = self.line_split.match(line)
1853 1852 if lsplit is None: # no regexp match returns None
1854 1853 try:
1855 1854 iFun,theRest = line.split(None,1)
1856 1855 except ValueError:
1857 1856 iFun,theRest = line,''
1858 1857 pre = re.match('^(\s*)(.*)',line).groups()[0]
1859 1858 else:
1860 1859 pre,iFun,theRest = lsplit.groups()
1861 1860
1862 1861 #print 'line:<%s>' % line # dbg
1863 1862 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1864 1863 return pre,iFun.strip(),theRest
1865 1864
1866 1865 def _prefilter(self, line, continue_prompt):
1867 1866 """Calls different preprocessors, depending on the form of line."""
1868 1867
1869 1868 # All handlers *must* return a value, even if it's blank ('').
1870 1869
1871 1870 # Lines are NOT logged here. Handlers should process the line as
1872 1871 # needed, update the cache AND log it (so that the input cache array
1873 1872 # stays synced).
1874 1873
1875 1874 # This function is _very_ delicate, and since it's also the one which
1876 1875 # determines IPython's response to user input, it must be as efficient
1877 1876 # as possible. For this reason it has _many_ returns in it, trying
1878 1877 # always to exit as quickly as it can figure out what it needs to do.
1879 1878
1880 1879 # This function is the main responsible for maintaining IPython's
1881 1880 # behavior respectful of Python's semantics. So be _very_ careful if
1882 1881 # making changes to anything here.
1883 1882
1884 1883 #.....................................................................
1885 1884 # Code begins
1886 1885
1887 1886 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1888 1887
1889 1888 # save the line away in case we crash, so the post-mortem handler can
1890 1889 # record it
1891 1890 self._last_input_line = line
1892 1891
1893 1892 #print '***line: <%s>' % line # dbg
1894 1893
1895 1894 # the input history needs to track even empty lines
1896 1895 stripped = line.strip()
1897 1896
1898 1897 if not stripped:
1899 1898 if not continue_prompt:
1900 1899 self.outputcache.prompt_count -= 1
1901 1900 return self.handle_normal(line,continue_prompt)
1902 1901 #return self.handle_normal('',continue_prompt)
1903 1902
1904 1903 # print '***cont',continue_prompt # dbg
1905 1904 # special handlers are only allowed for single line statements
1906 1905 if continue_prompt and not self.rc.multi_line_specials:
1907 1906 return self.handle_normal(line,continue_prompt)
1908 1907
1909 1908
1910 1909 # For the rest, we need the structure of the input
1911 1910 pre,iFun,theRest = self.split_user_input(line)
1912 1911
1913 1912 # See whether any pre-existing handler can take care of it
1914 1913
1915 1914 rewritten = self.hooks.input_prefilter(stripped)
1916 1915 if rewritten != stripped: # ok, some prefilter did something
1917 1916 rewritten = pre + rewritten # add indentation
1918 1917 return self.handle_normal(rewritten)
1919 1918
1920 1919 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1921 1920
1922 1921 # First check for explicit escapes in the last/first character
1923 1922 handler = None
1924 1923 if line[-1] == self.ESC_HELP:
1925 1924 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1926 1925 if handler is None:
1927 1926 # look at the first character of iFun, NOT of line, so we skip
1928 1927 # leading whitespace in multiline input
1929 1928 handler = self.esc_handlers.get(iFun[0:1])
1930 1929 if handler is not None:
1931 1930 return handler(line,continue_prompt,pre,iFun,theRest)
1932 1931 # Emacs ipython-mode tags certain input lines
1933 1932 if line.endswith('# PYTHON-MODE'):
1934 1933 return self.handle_emacs(line,continue_prompt)
1935 1934
1936 1935 # Next, check if we can automatically execute this thing
1937 1936
1938 1937 # Allow ! in multi-line statements if multi_line_specials is on:
1939 1938 if continue_prompt and self.rc.multi_line_specials and \
1940 1939 iFun.startswith(self.ESC_SHELL):
1941 1940 return self.handle_shell_escape(line,continue_prompt,
1942 1941 pre=pre,iFun=iFun,
1943 1942 theRest=theRest)
1944 1943
1945 1944 # Let's try to find if the input line is a magic fn
1946 1945 oinfo = None
1947 1946 if hasattr(self,'magic_'+iFun):
1948 1947 # WARNING: _ofind uses getattr(), so it can consume generators and
1949 1948 # cause other side effects.
1950 1949 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1951 1950 if oinfo['ismagic']:
1952 1951 # Be careful not to call magics when a variable assignment is
1953 1952 # being made (ls='hi', for example)
1954 1953 if self.rc.automagic and \
1955 1954 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1956 1955 (self.rc.multi_line_specials or not continue_prompt):
1957 1956 return self.handle_magic(line,continue_prompt,
1958 1957 pre,iFun,theRest)
1959 1958 else:
1960 1959 return self.handle_normal(line,continue_prompt)
1961 1960
1962 1961 # If the rest of the line begins with an (in)equality, assginment or
1963 1962 # function call, we should not call _ofind but simply execute it.
1964 1963 # This avoids spurious geattr() accesses on objects upon assignment.
1965 1964 #
1966 1965 # It also allows users to assign to either alias or magic names true
1967 1966 # python variables (the magic/alias systems always take second seat to
1968 1967 # true python code).
1969 1968 if theRest and theRest[0] in '!=()':
1970 1969 return self.handle_normal(line,continue_prompt)
1971 1970
1972 1971 if oinfo is None:
1973 1972 # let's try to ensure that _oinfo is ONLY called when autocall is
1974 1973 # on. Since it has inevitable potential side effects, at least
1975 1974 # having autocall off should be a guarantee to the user that no
1976 1975 # weird things will happen.
1977 1976
1978 1977 if self.rc.autocall:
1979 1978 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1980 1979 else:
1981 1980 # in this case, all that's left is either an alias or
1982 1981 # processing the line normally.
1983 1982 if iFun in self.alias_table:
1984 1983 # if autocall is off, by not running _ofind we won't know
1985 1984 # whether the given name may also exist in one of the
1986 1985 # user's namespace. At this point, it's best to do a
1987 1986 # quick check just to be sure that we don't let aliases
1988 1987 # shadow variables.
1989 1988 head = iFun.split('.',1)[0]
1990 1989 if head in self.user_ns or head in self.internal_ns \
1991 1990 or head in __builtin__.__dict__:
1992 1991 return self.handle_normal(line,continue_prompt)
1993 1992 else:
1994 1993 return self.handle_alias(line,continue_prompt,
1995 1994 pre,iFun,theRest)
1996 1995
1997 1996 else:
1998 1997 return self.handle_normal(line,continue_prompt)
1999 1998
2000 1999 if not oinfo['found']:
2001 2000 return self.handle_normal(line,continue_prompt)
2002 2001 else:
2003 2002 #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2004 2003 if oinfo['isalias']:
2005 2004 return self.handle_alias(line,continue_prompt,
2006 2005 pre,iFun,theRest)
2007 2006
2008 2007 if (self.rc.autocall
2009 2008 and
2010 2009 (
2011 2010 #only consider exclusion re if not "," or ";" autoquoting
2012 2011 (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2
2013 2012 or pre == self.ESC_PAREN) or
2014 2013 (not self.re_exclude_auto.match(theRest)))
2015 2014 and
2016 2015 self.re_fun_name.match(iFun) and
2017 2016 callable(oinfo['obj'])) :
2018 2017 #print 'going auto' # dbg
2019 2018 return self.handle_auto(line,continue_prompt,
2020 2019 pre,iFun,theRest,oinfo['obj'])
2021 2020 else:
2022 2021 #print 'was callable?', callable(oinfo['obj']) # dbg
2023 2022 return self.handle_normal(line,continue_prompt)
2024 2023
2025 2024 # If we get here, we have a normal Python line. Log and return.
2026 2025 return self.handle_normal(line,continue_prompt)
2027 2026
2028 2027 def _prefilter_dumb(self, line, continue_prompt):
2029 2028 """simple prefilter function, for debugging"""
2030 2029 return self.handle_normal(line,continue_prompt)
2031 2030
2032 2031
2033 2032 def multiline_prefilter(self, line, continue_prompt):
2034 2033 """ Run _prefilter for each line of input
2035 2034
2036 2035 Covers cases where there are multiple lines in the user entry,
2037 2036 which is the case when the user goes back to a multiline history
2038 2037 entry and presses enter.
2039 2038
2040 2039 """
2041 2040 out = []
2042 2041 for l in line.rstrip('\n').split('\n'):
2043 2042 out.append(self._prefilter(l, continue_prompt))
2044 2043 return '\n'.join(out)
2045 2044
2046 2045 # Set the default prefilter() function (this can be user-overridden)
2047 2046 prefilter = multiline_prefilter
2048 2047
2049 2048 def handle_normal(self,line,continue_prompt=None,
2050 2049 pre=None,iFun=None,theRest=None):
2051 2050 """Handle normal input lines. Use as a template for handlers."""
2052 2051
2053 2052 # With autoindent on, we need some way to exit the input loop, and I
2054 2053 # don't want to force the user to have to backspace all the way to
2055 2054 # clear the line. The rule will be in this case, that either two
2056 2055 # lines of pure whitespace in a row, or a line of pure whitespace but
2057 2056 # of a size different to the indent level, will exit the input loop.
2058 2057
2059 2058 if (continue_prompt and self.autoindent and line.isspace() and
2060 2059 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2061 2060 (self.buffer[-1]).isspace() )):
2062 2061 line = ''
2063 2062
2064 2063 self.log(line,line,continue_prompt)
2065 2064 return line
2066 2065
2067 2066 def handle_alias(self,line,continue_prompt=None,
2068 2067 pre=None,iFun=None,theRest=None):
2069 2068 """Handle alias input lines. """
2070 2069
2071 2070 # pre is needed, because it carries the leading whitespace. Otherwise
2072 2071 # aliases won't work in indented sections.
2073 2072 transformed = self.transform_alias(iFun, theRest)
2074 2073 line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed ))
2075 2074 self.log(line,line_out,continue_prompt)
2076 2075 #print 'line out:',line_out # dbg
2077 2076 return line_out
2078 2077
2079 2078 def handle_shell_escape(self, line, continue_prompt=None,
2080 2079 pre=None,iFun=None,theRest=None):
2081 2080 """Execute the line in a shell, empty return value"""
2082 2081
2083 2082 #print 'line in :', `line` # dbg
2084 2083 # Example of a special handler. Others follow a similar pattern.
2085 2084 if line.lstrip().startswith('!!'):
2086 2085 # rewrite iFun/theRest to properly hold the call to %sx and
2087 2086 # the actual command to be executed, so handle_magic can work
2088 2087 # correctly
2089 2088 theRest = '%s %s' % (iFun[2:],theRest)
2090 2089 iFun = 'sx'
2091 2090 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,
2092 2091 line.lstrip()[2:]),
2093 2092 continue_prompt,pre,iFun,theRest)
2094 2093 else:
2095 2094 cmd=line.lstrip().lstrip('!')
2096 2095 line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd))
2097 2096 # update cache/log and return
2098 2097 self.log(line,line_out,continue_prompt)
2099 2098 return line_out
2100 2099
2101 2100 def handle_magic(self, line, continue_prompt=None,
2102 2101 pre=None,iFun=None,theRest=None):
2103 2102 """Execute magic functions."""
2104 2103
2105 2104
2106 2105 cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
2107 2106 self.log(line,cmd,continue_prompt)
2108 2107 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2109 2108 return cmd
2110 2109
2111 2110 def handle_auto(self, line, continue_prompt=None,
2112 2111 pre=None,iFun=None,theRest=None,obj=None):
2113 2112 """Hande lines which can be auto-executed, quoting if requested."""
2114 2113
2115 2114 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2116 2115
2117 2116 # This should only be active for single-line input!
2118 2117 if continue_prompt:
2119 2118 self.log(line,line,continue_prompt)
2120 2119 return line
2121 2120
2122 2121 auto_rewrite = True
2123 2122
2124 2123 if pre == self.ESC_QUOTE:
2125 2124 # Auto-quote splitting on whitespace
2126 2125 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2127 2126 elif pre == self.ESC_QUOTE2:
2128 2127 # Auto-quote whole string
2129 2128 newcmd = '%s("%s")' % (iFun,theRest)
2130 2129 elif pre == self.ESC_PAREN:
2131 2130 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2132 2131 else:
2133 2132 # Auto-paren.
2134 2133 # We only apply it to argument-less calls if the autocall
2135 2134 # parameter is set to 2. We only need to check that autocall is <
2136 2135 # 2, since this function isn't called unless it's at least 1.
2137 2136 if not theRest and (self.rc.autocall < 2):
2138 2137 newcmd = '%s %s' % (iFun,theRest)
2139 2138 auto_rewrite = False
2140 2139 else:
2141 2140 if theRest.startswith('['):
2142 2141 if hasattr(obj,'__getitem__'):
2143 2142 # Don't autocall in this case: item access for an object
2144 2143 # which is BOTH callable and implements __getitem__.
2145 2144 newcmd = '%s %s' % (iFun,theRest)
2146 2145 auto_rewrite = False
2147 2146 else:
2148 2147 # if the object doesn't support [] access, go ahead and
2149 2148 # autocall
2150 2149 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2151 2150 elif theRest.endswith(';'):
2152 2151 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2153 2152 else:
2154 2153 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2155 2154
2156 2155 if auto_rewrite:
2157 2156 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2158 2157 # log what is now valid Python, not the actual user input (without the
2159 2158 # final newline)
2160 2159 self.log(line,newcmd,continue_prompt)
2161 2160 return newcmd
2162 2161
2163 2162 def handle_help(self, line, continue_prompt=None,
2164 2163 pre=None,iFun=None,theRest=None):
2165 2164 """Try to get some help for the object.
2166 2165
2167 2166 obj? or ?obj -> basic information.
2168 2167 obj?? or ??obj -> more details.
2169 2168 """
2170 2169
2171 2170 # We need to make sure that we don't process lines which would be
2172 2171 # otherwise valid python, such as "x=1 # what?"
2173 2172 try:
2174 2173 codeop.compile_command(line)
2175 2174 except SyntaxError:
2176 2175 # We should only handle as help stuff which is NOT valid syntax
2177 2176 if line[0]==self.ESC_HELP:
2178 2177 line = line[1:]
2179 2178 elif line[-1]==self.ESC_HELP:
2180 2179 line = line[:-1]
2181 2180 self.log(line,'#?'+line,continue_prompt)
2182 2181 if line:
2183 2182 self.magic_pinfo(line)
2184 2183 else:
2185 2184 page(self.usage,screen_lines=self.rc.screen_length)
2186 2185 return '' # Empty string is needed here!
2187 2186 except:
2188 2187 # Pass any other exceptions through to the normal handler
2189 2188 return self.handle_normal(line,continue_prompt)
2190 2189 else:
2191 2190 # If the code compiles ok, we should handle it normally
2192 2191 return self.handle_normal(line,continue_prompt)
2193 2192
2194 2193 def getapi(self):
2195 2194 """ Get an IPApi object for this shell instance
2196 2195
2197 2196 Getting an IPApi object is always preferable to accessing the shell
2198 2197 directly, but this holds true especially for extensions.
2199 2198
2200 2199 It should always be possible to implement an extension with IPApi
2201 2200 alone. If not, contact maintainer to request an addition.
2202 2201
2203 2202 """
2204 2203 return self.api
2205 2204
2206 2205 def handle_emacs(self,line,continue_prompt=None,
2207 2206 pre=None,iFun=None,theRest=None):
2208 2207 """Handle input lines marked by python-mode."""
2209 2208
2210 2209 # Currently, nothing is done. Later more functionality can be added
2211 2210 # here if needed.
2212 2211
2213 2212 # The input cache shouldn't be updated
2214 2213
2215 2214 return line
2216 2215
2217 2216 def mktempfile(self,data=None):
2218 2217 """Make a new tempfile and return its filename.
2219 2218
2220 2219 This makes a call to tempfile.mktemp, but it registers the created
2221 2220 filename internally so ipython cleans it up at exit time.
2222 2221
2223 2222 Optional inputs:
2224 2223
2225 2224 - data(None): if data is given, it gets written out to the temp file
2226 2225 immediately, and the file is closed again."""
2227 2226
2228 2227 filename = tempfile.mktemp('.py','ipython_edit_')
2229 2228 self.tempfiles.append(filename)
2230 2229
2231 2230 if data:
2232 2231 tmp_file = open(filename,'w')
2233 2232 tmp_file.write(data)
2234 2233 tmp_file.close()
2235 2234 return filename
2236 2235
2237 2236 def write(self,data):
2238 2237 """Write a string to the default output"""
2239 2238 Term.cout.write(data)
2240 2239
2241 2240 def write_err(self,data):
2242 2241 """Write a string to the default error output"""
2243 2242 Term.cerr.write(data)
2244 2243
2245 2244 def exit(self):
2246 2245 """Handle interactive exit.
2247 2246
2248 2247 This method sets the exit_now attribute."""
2249 2248
2250 2249 if self.rc.confirm_exit:
2251 2250 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2252 2251 self.exit_now = True
2253 2252 else:
2254 2253 self.exit_now = True
2255 return self.exit_now
2256 2254
2257 2255 def safe_execfile(self,fname,*where,**kw):
2258 2256 fname = os.path.expanduser(fname)
2259 2257
2260 2258 # find things also in current directory
2261 2259 dname = os.path.dirname(fname)
2262 2260 if not sys.path.count(dname):
2263 2261 sys.path.append(dname)
2264 2262
2265 2263 try:
2266 2264 xfile = open(fname)
2267 2265 except:
2268 2266 print >> Term.cerr, \
2269 2267 'Could not open file <%s> for safe execution.' % fname
2270 2268 return None
2271 2269
2272 2270 kw.setdefault('islog',0)
2273 2271 kw.setdefault('quiet',1)
2274 2272 kw.setdefault('exit_ignore',0)
2275 2273 first = xfile.readline()
2276 2274 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2277 2275 xfile.close()
2278 2276 # line by line execution
2279 2277 if first.startswith(loghead) or kw['islog']:
2280 2278 print 'Loading log file <%s> one line at a time...' % fname
2281 2279 if kw['quiet']:
2282 2280 stdout_save = sys.stdout
2283 2281 sys.stdout = StringIO.StringIO()
2284 2282 try:
2285 2283 globs,locs = where[0:2]
2286 2284 except:
2287 2285 try:
2288 2286 globs = locs = where[0]
2289 2287 except:
2290 2288 globs = locs = globals()
2291 2289 badblocks = []
2292 2290
2293 2291 # we also need to identify indented blocks of code when replaying
2294 2292 # logs and put them together before passing them to an exec
2295 2293 # statement. This takes a bit of regexp and look-ahead work in the
2296 2294 # file. It's easiest if we swallow the whole thing in memory
2297 2295 # first, and manually walk through the lines list moving the
2298 2296 # counter ourselves.
2299 2297 indent_re = re.compile('\s+\S')
2300 2298 xfile = open(fname)
2301 2299 filelines = xfile.readlines()
2302 2300 xfile.close()
2303 2301 nlines = len(filelines)
2304 2302 lnum = 0
2305 2303 while lnum < nlines:
2306 2304 line = filelines[lnum]
2307 2305 lnum += 1
2308 2306 # don't re-insert logger status info into cache
2309 2307 if line.startswith('#log#'):
2310 2308 continue
2311 2309 else:
2312 2310 # build a block of code (maybe a single line) for execution
2313 2311 block = line
2314 2312 try:
2315 2313 next = filelines[lnum] # lnum has already incremented
2316 2314 except:
2317 2315 next = None
2318 2316 while next and indent_re.match(next):
2319 2317 block += next
2320 2318 lnum += 1
2321 2319 try:
2322 2320 next = filelines[lnum]
2323 2321 except:
2324 2322 next = None
2325 2323 # now execute the block of one or more lines
2326 2324 try:
2327 2325 exec block in globs,locs
2328 2326 except SystemExit:
2329 2327 pass
2330 2328 except:
2331 2329 badblocks.append(block.rstrip())
2332 2330 if kw['quiet']: # restore stdout
2333 2331 sys.stdout.close()
2334 2332 sys.stdout = stdout_save
2335 2333 print 'Finished replaying log file <%s>' % fname
2336 2334 if badblocks:
2337 2335 print >> sys.stderr, ('\nThe following lines/blocks in file '
2338 2336 '<%s> reported errors:' % fname)
2339 2337
2340 2338 for badline in badblocks:
2341 2339 print >> sys.stderr, badline
2342 2340 else: # regular file execution
2343 2341 try:
2344 2342 execfile(fname,*where)
2345 2343 except SyntaxError:
2346 2344 self.showsyntaxerror()
2347 2345 warn('Failure executing file: <%s>' % fname)
2348 2346 except SystemExit,status:
2349 2347 if not kw['exit_ignore']:
2350 2348 self.showtraceback()
2351 2349 warn('Failure executing file: <%s>' % fname)
2352 2350 except:
2353 2351 self.showtraceback()
2354 2352 warn('Failure executing file: <%s>' % fname)
2355 2353
2356 2354 #************************* end of file <iplib.py> *****************************
@@ -1,319 +1,297 b''
1 1 #!/usr/bin/env python
2 2 """Module for interactively running scripts.
3 3
4 4 This module implements classes for interactively running scripts written for
5 5 any system with a prompt which can be matched by a regexp suitable for
6 6 pexpect. It can be used to run as if they had been typed up interactively, an
7 7 arbitrary series of commands for the target system.
8 8
9 9 The module includes classes ready for IPython (with the default prompts),
10 10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
11 11 simply run the module as a script:
12 12
13 13 ./irunner.py --help
14 14
15 15
16 16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
17 17 contributed on the ipython-user list:
18 18
19 19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
20 20
21 21
22 22 NOTES:
23 23
24 24 - This module requires pexpect, available in most linux distros, or which can
25 25 be downloaded from
26 26
27 27 http://pexpect.sourceforge.net
28 28
29 29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
30 30 limitations. This means that it will NOT work under native windows Python.
31 31 """
32 32
33 33 # Stdlib imports
34 34 import optparse
35 35 import os
36 36 import sys
37 37
38 38 # Third-party modules.
39 39 import pexpect
40 40
41 41 # Global usage strings, to avoid indentation issues when typing it below.
42 42 USAGE = """
43 43 Interactive script runner, type: %s
44 44
45 45 runner [opts] script_name
46 46 """
47 47
48 48 # The generic runner class
49 49 class InteractiveRunner(object):
50 50 """Class to run a sequence of commands through an interactive program."""
51 51
52 52 def __init__(self,program,prompts,args=None):
53 53 """Construct a runner.
54 54
55 55 Inputs:
56 56
57 57 - program: command to execute the given program.
58 58
59 59 - prompts: a list of patterns to match as valid prompts, in the
60 60 format used by pexpect. This basically means that it can be either
61 61 a string (to be compiled as a regular expression) or a list of such
62 62 (it must be a true list, as pexpect does type checks).
63 63
64 64 If more than one prompt is given, the first is treated as the main
65 65 program prompt and the others as 'continuation' prompts, like
66 66 python's. This means that blank lines in the input source are
67 67 ommitted when the first prompt is matched, but are NOT ommitted when
68 68 the continuation one matches, since this is how python signals the
69 69 end of multiline input interactively.
70 70
71 71 Optional inputs:
72 72
73 73 - args(None): optional list of strings to pass as arguments to the
74 74 child program.
75 75
76 76 Public members not parameterized in the constructor:
77 77
78 78 - delaybeforesend(0): Newer versions of pexpect have a delay before
79 79 sending each new input. For our purposes here, it's typically best
80 80 to just set this to zero, but if you encounter reliability problems
81 81 or want an interactive run to pause briefly at each prompt, just
82 82 increase this value (it is measured in seconds). Note that this
83 83 variable is not honored at all by older versions of pexpect.
84 84 """
85 85
86 86 self.program = program
87 87 self.prompts = prompts
88 88 if args is None: args = []
89 89 self.args = args
90 90 # Other public members which we don't make as parameters, but which
91 91 # users may occasionally want to tweak
92 92 self.delaybeforesend = 0
93 93
94 94 def run_file(self,fname,interact=False):
95 95 """Run the given file interactively.
96 96
97 97 Inputs:
98 98
99 99 -fname: name of the file to execute.
100 100
101 101 See the run_source docstring for the meaning of the optional
102 102 arguments."""
103 103
104 104 fobj = open(fname,'r')
105 105 try:
106 106 self.run_source(fobj,interact)
107 107 finally:
108 108 fobj.close()
109 109
110 110 def run_source(self,source,interact=False):
111 111 """Run the given source code interactively.
112 112
113 113 Inputs:
114 114
115 115 - source: a string of code to be executed, or an open file object we
116 116 can iterate over.
117 117
118 118 Optional inputs:
119 119
120 120 - interact(False): if true, start to interact with the running
121 121 program at the end of the script. Otherwise, just exit.
122 122 """
123 123
124 124 # if the source is a string, chop it up in lines so we can iterate
125 125 # over it just as if it were an open file.
126 126 if not isinstance(source,file):
127 127 source = source.splitlines(True)
128 128
129 129 # grab the true write method of stdout, in case anything later
130 130 # reassigns sys.stdout, so that we really are writing to the true
131 131 # stdout and not to something else. We also normalize all strings we
132 132 # write to use the native OS line separators.
133 133 linesep = os.linesep
134 134 stdwrite = sys.stdout.write
135 135 write = lambda s: stdwrite(s.replace('\r\n',linesep))
136 136
137 137 c = pexpect.spawn(self.program,self.args,timeout=None)
138 138 c.delaybeforesend = self.delaybeforesend
139 139
140 140 prompts = c.compile_pattern_list(self.prompts)
141 141
142 142 prompt_idx = c.expect_list(prompts)
143 143 # Flag whether the script ends normally or not, to know whether we can
144 144 # do anything further with the underlying process.
145 145 end_normal = True
146 146 for cmd in source:
147 147 # skip blank lines for all matches to the 'main' prompt, while the
148 148 # secondary prompts do not
149 149 if prompt_idx==0 and \
150 150 (cmd.isspace() or cmd.lstrip().startswith('#')):
151 151 print cmd,
152 152 continue
153 153
154 154 write(c.after)
155 155 c.send(cmd)
156 156 try:
157 157 prompt_idx = c.expect_list(prompts)
158 158 except pexpect.EOF:
159 159 # this will happen if the child dies unexpectedly
160 160 write(c.before)
161 161 end_normal = False
162 162 break
163 163 write(c.before)
164 164
165 165 if end_normal:
166 166 if interact:
167 167 c.send('\n')
168 168 print '<< Starting interactive mode >>',
169 169 try:
170 170 c.interact()
171 171 except OSError:
172 172 # This is what fires when the child stops. Simply print a
173 173 # newline so the system prompt is aligned. The extra
174 174 # space is there to make sure it gets printed, otherwise
175 175 # OS buffering sometimes just suppresses it.
176 176 write(' \n')
177 177 sys.stdout.flush()
178 178 else:
179 179 c.close()
180 180 else:
181 181 if interact:
182 182 e="Further interaction is not possible: child process is dead."
183 183 print >> sys.stderr, e
184 184
185 185 def main(self,argv=None):
186 186 """Run as a command-line script."""
187 187
188 188 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
189 189 newopt = parser.add_option
190 190 newopt('-i','--interact',action='store_true',default=False,
191 191 help='Interact with the program after the script is run.')
192 192
193 193 opts,args = parser.parse_args(argv)
194 194
195 195 if len(args) != 1:
196 196 print >> sys.stderr,"You must supply exactly one file to run."
197 197 sys.exit(1)
198 198
199 199 self.run_file(args[0],opts.interact)
200 200
201 201
202 202 # Specific runners for particular programs
203 203 class IPythonRunner(InteractiveRunner):
204 204 """Interactive IPython runner.
205 205
206 206 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
207 207 avoid having to write a regexp that matches ANSI sequences, though pexpect
208 208 does support them. If anyone contributes patches for ANSI color support,
209 209 they will be welcome.
210 210
211 211 It also sets the prompts manually, since the prompt regexps for
212 212 pexpect need to be matched to the actual prompts, so user-customized
213 213 prompts would break this.
214 214 """
215 215
216 216 def __init__(self,program = 'ipython',args=None):
217 217 """New runner, optionally passing the ipython command to use."""
218 218
219 219 args0 = ['-colors','NoColor',
220 220 '-pi1','In [\\#]: ',
221 221 '-pi2',' .\\D.: ']
222 222 if args is None: args = args0
223 223 else: args = args0 + args
224 224 prompts = [r'In \[\d+\]: ',r' \.*: ']
225 225 InteractiveRunner.__init__(self,program,prompts,args)
226 226
227 227
228 228 class PythonRunner(InteractiveRunner):
229 229 """Interactive Python runner."""
230 230
231 231 def __init__(self,program='python',args=None):
232 232 """New runner, optionally passing the python command to use."""
233 233
234 234 prompts = [r'>>> ',r'\.\.\. ']
235 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 238 class SAGERunner(InteractiveRunner):
261 239 """Interactive SAGE runner.
262 240
263 241 WARNING: this runner only works if you manually configure your SAGE copy
264 242 to use 'colors NoColor' in the ipythonrc config file, since currently the
265 243 prompt matching regexp does not identify color sequences."""
266 244
267 245 def __init__(self,program='sage',args=None):
268 246 """New runner, optionally passing the sage command to use."""
269 247
270 248 prompts = ['sage: ',r'\s*\.\.\. ']
271 249 InteractiveRunner.__init__(self,program,prompts,args)
272 250
273 251 # Global usage string, to avoid indentation issues if typed in a function def.
274 252 MAIN_USAGE = """
275 253 %prog [options] file_to_run
276 254
277 255 This is an interface to the various interactive runners available in this
278 256 module. If you want to pass specific options to one of the runners, you need
279 257 to first terminate the main options with a '--', and then provide the runner's
280 258 options. For example:
281 259
282 260 irunner.py --python -- --help
283 261
284 262 will pass --help to the python runner. Similarly,
285 263
286 264 irunner.py --ipython -- --interact script.ipy
287 265
288 266 will run the script.ipy file under the IPython runner, and then will start to
289 267 interact with IPython at the end of the script (instead of exiting).
290 268
291 269 The already implemented runners are listed below; adding one for a new program
292 270 is a trivial task, see the source for examples.
293 271
294 272 WARNING: the SAGE runner only works if you manually configure your SAGE copy
295 273 to use 'colors NoColor' in the ipythonrc config file, since currently the
296 274 prompt matching regexp does not identify color sequences.
297 275 """
298 276
299 277 def main():
300 278 """Run as a command-line script."""
301 279
302 280 parser = optparse.OptionParser(usage=MAIN_USAGE)
303 281 newopt = parser.add_option
304 282 parser.set_defaults(mode='ipython')
305 283 newopt('--ipython',action='store_const',dest='mode',const='ipython',
306 284 help='IPython interactive runner (default).')
307 285 newopt('--python',action='store_const',dest='mode',const='python',
308 286 help='Python interactive runner.')
309 287 newopt('--sage',action='store_const',dest='mode',const='sage',
310 288 help='SAGE interactive runner.')
311 289
312 290 opts,args = parser.parse_args()
313 291 runners = dict(ipython=IPythonRunner,
314 292 python=PythonRunner,
315 293 sage=SAGERunner)
316 294 runners[opts.mode]().main(args)
317 295
318 296 if __name__ == '__main__':
319 297 main()
@@ -1,883 +1,887 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 ultraTB.py -- Spice up your tracebacks!
4 4
5 5 * ColorTB
6 6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 7 ColorTB class is a solution to that problem. It colors the different parts of a
8 8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 9 text editor.
10 10
11 11 Installation instructions for ColorTB:
12 12 import sys,ultraTB
13 13 sys.excepthook = ultraTB.ColorTB()
14 14
15 15 * VerboseTB
16 16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 18 and intended it for CGI programmers, but why should they have all the fun? I
19 19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 20 but kind of neat, and maybe useful for long-running programs that you believe
21 21 are bug-free. If a crash *does* occur in that type of program you want details.
22 22 Give it a shot--you'll love it or you'll hate it.
23 23
24 24 Note:
25 25
26 26 The Verbose mode prints the variables currently visible where the exception
27 27 happened (shortening their strings if too long). This can potentially be
28 28 very slow, if you happen to have a huge data structure whose string
29 29 representation is complex to compute. Your computer may appear to freeze for
30 30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 31 with Ctrl-C (maybe hitting it more than once).
32 32
33 33 If you encounter this kind of situation often, you may want to use the
34 34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 35 variables (but otherwise includes the information and context given by
36 36 Verbose).
37 37
38 38
39 39 Installation instructions for ColorTB:
40 40 import sys,ultraTB
41 41 sys.excepthook = ultraTB.VerboseTB()
42 42
43 43 Note: Much of the code in this module was lifted verbatim from the standard
44 44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45 45
46 46 * Color schemes
47 47 The colors are defined in the class TBTools through the use of the
48 48 ColorSchemeTable class. Currently the following exist:
49 49
50 50 - NoColor: allows all of this module to be used in any terminal (the color
51 51 escapes are just dummy blank strings).
52 52
53 53 - Linux: is meant to look good in a terminal like the Linux console (black
54 54 or very dark background).
55 55
56 56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 57 in light background terminals.
58 58
59 59 You can implement other color schemes easily, the syntax is fairly
60 60 self-explanatory. Please send back new schemes you develop to the author for
61 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 66 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
67 67 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
68 68 #
69 69 # Distributed under the terms of the BSD License. The full license is in
70 70 # the file COPYING, distributed as part of this software.
71 71 #*****************************************************************************
72 72
73 73 from IPython import Release
74 74 __author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
75 75 Release.authors['Fernando'])
76 76 __license__ = Release.license
77 77
78 78 # Required modules
79 79 import inspect
80 80 import keyword
81 81 import linecache
82 82 import os
83 83 import pydoc
84 84 import string
85 85 import sys
86 86 import time
87 87 import tokenize
88 88 import traceback
89 89 import types
90 90
91 91 # IPython's own modules
92 92 # Modified pdb which doesn't damage IPython's readline handling
93 93 from IPython import Debugger
94 94 from IPython.ipstruct import Struct
95 95 from IPython.excolors import ExceptionColors
96 96 from IPython.genutils import Term,uniq_stable,error,info
97 97
98 98 # Globals
99 99 # amount of space to put line numbers before verbose tracebacks
100 100 INDENT_SIZE = 8
101 101
102 102 #---------------------------------------------------------------------------
103 103 # Code begins
104 104
105 105 # Utility functions
106 106 def inspect_error():
107 107 """Print a message about internal inspect errors.
108 108
109 109 These are unfortunately quite common."""
110 110
111 111 error('Internal Python error in the inspect module.\n'
112 112 'Below is the traceback from this internal error.\n')
113 113
114 114 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
115 115 import linecache
116 116 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
117 117
118 118 records = inspect.getinnerframes(etb, context)
119 119
120 120 # If the error is at the console, don't build any context, since it would
121 121 # otherwise produce 5 blank lines printed out (there is no file at the
122 122 # console)
123 123 rec_check = records[tb_offset:]
124 124 try:
125 125 rname = rec_check[0][1]
126 126 if rname == '<ipython console>' or rname.endswith('<string>'):
127 127 return rec_check
128 128 except IndexError:
129 129 pass
130 130
131 131 aux = traceback.extract_tb(etb)
132 132 assert len(records) == len(aux)
133 133 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
134 134 maybeStart = lnum-1 - context//2
135 135 start = max(maybeStart, 0)
136 136 end = start + context
137 137 lines = linecache.getlines(file)[start:end]
138 138 # pad with empty lines if necessary
139 139 if maybeStart < 0:
140 140 lines = (['\n'] * -maybeStart) + lines
141 141 if len(lines) < context:
142 142 lines += ['\n'] * (context - len(lines))
143 143 buf = list(records[i])
144 144 buf[LNUM_POS] = lnum
145 145 buf[INDEX_POS] = lnum - 1 - start
146 146 buf[LINES_POS] = lines
147 147 records[i] = tuple(buf)
148 148 return records[tb_offset:]
149 149
150 150 # Helper function -- largely belongs to VerboseTB, but we need the same
151 151 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
152 152 # can be recognized properly by ipython.el's py-traceback-line-re
153 153 # (SyntaxErrors have to be treated specially because they have no traceback)
154 154 def _formatTracebackLines(lnum, index, lines, Colors, lvals=None):
155 155 numbers_width = INDENT_SIZE - 1
156 156 res = []
157 157 i = lnum - index
158 158 for line in lines:
159 159 if i == lnum:
160 160 # This is the line with the error
161 161 pad = numbers_width - len(str(i))
162 162 if pad >= 3:
163 163 marker = '-'*(pad-3) + '-> '
164 164 elif pad == 2:
165 165 marker = '> '
166 166 elif pad == 1:
167 167 marker = '>'
168 168 else:
169 169 marker = ''
170 170 num = marker + str(i)
171 171 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
172 172 Colors.line, line, Colors.Normal)
173 173 else:
174 174 num = '%*s' % (numbers_width,i)
175 175 line = '%s%s%s %s' %(Colors.lineno, num,
176 176 Colors.Normal, line)
177 177
178 178 res.append(line)
179 179 if lvals and i == lnum:
180 180 res.append(lvals + '\n')
181 181 i = i + 1
182 182 return res
183 183
184 184 #---------------------------------------------------------------------------
185 185 # Module classes
186 186 class TBTools:
187 187 """Basic tools used by all traceback printer classes."""
188 188
189 189 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
190 190 # Whether to call the interactive pdb debugger after printing
191 191 # tracebacks or not
192 192 self.call_pdb = call_pdb
193 193
194 194 # Create color table
195 195 self.color_scheme_table = ExceptionColors
196 196
197 197 self.set_colors(color_scheme)
198 198 self.old_scheme = color_scheme # save initial value for toggles
199 199
200 200 if call_pdb:
201 201 self.pdb = Debugger.Pdb(self.color_scheme_table.active_scheme_name)
202 202 else:
203 203 self.pdb = None
204 204
205 205 def set_colors(self,*args,**kw):
206 206 """Shorthand access to the color table scheme selector method."""
207
207
208 # Set own color table
208 209 self.color_scheme_table.set_active_scheme(*args,**kw)
209 210 # for convenience, set Colors to the active scheme
210 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 216 def color_toggle(self):
213 217 """Toggle between the currently active color scheme and NoColor."""
214 218
215 219 if self.color_scheme_table.active_scheme_name == 'NoColor':
216 220 self.color_scheme_table.set_active_scheme(self.old_scheme)
217 221 self.Colors = self.color_scheme_table.active_colors
218 222 else:
219 223 self.old_scheme = self.color_scheme_table.active_scheme_name
220 224 self.color_scheme_table.set_active_scheme('NoColor')
221 225 self.Colors = self.color_scheme_table.active_colors
222 226
223 227 #---------------------------------------------------------------------------
224 228 class ListTB(TBTools):
225 229 """Print traceback information from a traceback list, with optional color.
226 230
227 231 Calling: requires 3 arguments:
228 232 (etype, evalue, elist)
229 233 as would be obtained by:
230 234 etype, evalue, tb = sys.exc_info()
231 235 if tb:
232 236 elist = traceback.extract_tb(tb)
233 237 else:
234 238 elist = None
235 239
236 240 It can thus be used by programs which need to process the traceback before
237 241 printing (such as console replacements based on the code module from the
238 242 standard library).
239 243
240 244 Because they are meant to be called without a full traceback (only a
241 245 list), instances of this class can't call the interactive pdb debugger."""
242 246
243 247 def __init__(self,color_scheme = 'NoColor'):
244 248 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
245 249
246 250 def __call__(self, etype, value, elist):
247 251 print >> Term.cerr, self.text(etype,value,elist)
248 252
249 253 def text(self,etype, value, elist,context=5):
250 254 """Return a color formatted string with the traceback info."""
251 255
252 256 Colors = self.Colors
253 257 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
254 258 if elist:
255 259 out_string.append('Traceback %s(most recent call last)%s:' % \
256 260 (Colors.normalEm, Colors.Normal) + '\n')
257 261 out_string.extend(self._format_list(elist))
258 262 lines = self._format_exception_only(etype, value)
259 263 for line in lines[:-1]:
260 264 out_string.append(" "+line)
261 265 out_string.append(lines[-1])
262 266 return ''.join(out_string)
263 267
264 268 def _format_list(self, extracted_list):
265 269 """Format a list of traceback entry tuples for printing.
266 270
267 271 Given a list of tuples as returned by extract_tb() or
268 272 extract_stack(), return a list of strings ready for printing.
269 273 Each string in the resulting list corresponds to the item with the
270 274 same index in the argument list. Each string ends in a newline;
271 275 the strings may contain internal newlines as well, for those items
272 276 whose source text line is not None.
273 277
274 278 Lifted almost verbatim from traceback.py
275 279 """
276 280
277 281 Colors = self.Colors
278 282 list = []
279 283 for filename, lineno, name, line in extracted_list[:-1]:
280 284 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
281 285 (Colors.filename, filename, Colors.Normal,
282 286 Colors.lineno, lineno, Colors.Normal,
283 287 Colors.name, name, Colors.Normal)
284 288 if line:
285 289 item = item + ' %s\n' % line.strip()
286 290 list.append(item)
287 291 # Emphasize the last entry
288 292 filename, lineno, name, line = extracted_list[-1]
289 293 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
290 294 (Colors.normalEm,
291 295 Colors.filenameEm, filename, Colors.normalEm,
292 296 Colors.linenoEm, lineno, Colors.normalEm,
293 297 Colors.nameEm, name, Colors.normalEm,
294 298 Colors.Normal)
295 299 if line:
296 300 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
297 301 Colors.Normal)
298 302 list.append(item)
299 303 return list
300 304
301 305 def _format_exception_only(self, etype, value):
302 306 """Format the exception part of a traceback.
303 307
304 308 The arguments are the exception type and value such as given by
305 309 sys.exc_info()[:2]. The return value is a list of strings, each ending
306 310 in a newline. Normally, the list contains a single string; however,
307 311 for SyntaxError exceptions, it contains several lines that (when
308 312 printed) display detailed information about where the syntax error
309 313 occurred. The message indicating which exception occurred is the
310 314 always last string in the list.
311 315
312 316 Also lifted nearly verbatim from traceback.py
313 317 """
314 318
315 319 Colors = self.Colors
316 320 list = []
317 321 if type(etype) == types.ClassType:
318 322 stype = Colors.excName + etype.__name__ + Colors.Normal
319 323 else:
320 324 stype = etype # String exceptions don't get special coloring
321 325 if value is None:
322 326 list.append( str(stype) + '\n')
323 327 else:
324 328 if etype is SyntaxError:
325 329 try:
326 330 msg, (filename, lineno, offset, line) = value
327 331 except:
328 332 pass
329 333 else:
330 334 #print 'filename is',filename # dbg
331 335 if not filename: filename = "<string>"
332 336 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
333 337 (Colors.normalEm,
334 338 Colors.filenameEm, filename, Colors.normalEm,
335 339 Colors.linenoEm, lineno, Colors.Normal ))
336 340 if line is not None:
337 341 i = 0
338 342 while i < len(line) and line[i].isspace():
339 343 i = i+1
340 344 list.append('%s %s%s\n' % (Colors.line,
341 345 line.strip(),
342 346 Colors.Normal))
343 347 if offset is not None:
344 348 s = ' '
345 349 for c in line[i:offset-1]:
346 350 if c.isspace():
347 351 s = s + c
348 352 else:
349 353 s = s + ' '
350 354 list.append('%s%s^%s\n' % (Colors.caret, s,
351 355 Colors.Normal) )
352 356 value = msg
353 357 s = self._some_str(value)
354 358 if s:
355 359 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
356 360 Colors.Normal, s))
357 361 else:
358 362 list.append('%s\n' % str(stype))
359 363 return list
360 364
361 365 def _some_str(self, value):
362 366 # Lifted from traceback.py
363 367 try:
364 368 return str(value)
365 369 except:
366 370 return '<unprintable %s object>' % type(value).__name__
367 371
368 372 #----------------------------------------------------------------------------
369 373 class VerboseTB(TBTools):
370 374 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
371 375 of HTML. Requires inspect and pydoc. Crazy, man.
372 376
373 377 Modified version which optionally strips the topmost entries from the
374 378 traceback, to be used with alternate interpreters (because their own code
375 379 would appear in the traceback)."""
376 380
377 381 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
378 382 call_pdb = 0, include_vars=1):
379 383 """Specify traceback offset, headers and color scheme.
380 384
381 385 Define how many frames to drop from the tracebacks. Calling it with
382 386 tb_offset=1 allows use of this handler in interpreters which will have
383 387 their own code at the top of the traceback (VerboseTB will first
384 388 remove that frame before printing the traceback info)."""
385 389 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
386 390 self.tb_offset = tb_offset
387 391 self.long_header = long_header
388 392 self.include_vars = include_vars
389 393
390 394 def text(self, etype, evalue, etb, context=5):
391 395 """Return a nice text document describing the traceback."""
392 396
393 397 # some locals
394 398 Colors = self.Colors # just a shorthand + quicker name lookup
395 399 ColorsNormal = Colors.Normal # used a lot
396 400 indent = ' '*INDENT_SIZE
397 401 exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
398 402 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
399 403 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
400 404
401 405 # some internal-use functions
402 406 def text_repr(value):
403 407 """Hopefully pretty robust repr equivalent."""
404 408 # this is pretty horrible but should always return *something*
405 409 try:
406 410 return pydoc.text.repr(value)
407 411 except KeyboardInterrupt:
408 412 raise
409 413 except:
410 414 try:
411 415 return repr(value)
412 416 except KeyboardInterrupt:
413 417 raise
414 418 except:
415 419 try:
416 420 # all still in an except block so we catch
417 421 # getattr raising
418 422 name = getattr(value, '__name__', None)
419 423 if name:
420 424 # ick, recursion
421 425 return text_repr(name)
422 426 klass = getattr(value, '__class__', None)
423 427 if klass:
424 428 return '%s instance' % text_repr(klass)
425 429 except KeyboardInterrupt:
426 430 raise
427 431 except:
428 432 return 'UNRECOVERABLE REPR FAILURE'
429 433 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
430 434 def nullrepr(value, repr=text_repr): return ''
431 435
432 436 # meat of the code begins
433 437 if type(etype) is types.ClassType:
434 438 etype = etype.__name__
435 439
436 440 if self.long_header:
437 441 # Header with the exception type, python version, and date
438 442 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
439 443 date = time.ctime(time.time())
440 444
441 445 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
442 446 exc, ' '*(75-len(str(etype))-len(pyver)),
443 447 pyver, string.rjust(date, 75) )
444 448 head += "\nA problem occured executing Python code. Here is the sequence of function"\
445 449 "\ncalls leading up to the error, with the most recent (innermost) call last."
446 450 else:
447 451 # Simplified header
448 452 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
449 453 string.rjust('Traceback (most recent call last)',
450 454 75 - len(str(etype)) ) )
451 455 frames = []
452 456 # Flush cache before calling inspect. This helps alleviate some of the
453 457 # problems with python 2.3's inspect.py.
454 458 linecache.checkcache()
455 459 # Drop topmost frames if requested
456 460 try:
457 461 # Try the default getinnerframes and Alex's: Alex's fixes some
458 462 # problems, but it generates empty tracebacks for console errors
459 463 # (5 blanks lines) where none should be returned.
460 464 #records = inspect.getinnerframes(etb, context)[self.tb_offset:]
461 465 #print 'python records:', records # dbg
462 466 records = _fixed_getinnerframes(etb, context,self.tb_offset)
463 467 #print 'alex records:', records # dbg
464 468 except:
465 469
466 470 # FIXME: I've been getting many crash reports from python 2.3
467 471 # users, traceable to inspect.py. If I can find a small test-case
468 472 # to reproduce this, I should either write a better workaround or
469 473 # file a bug report against inspect (if that's the real problem).
470 474 # So far, I haven't been able to find an isolated example to
471 475 # reproduce the problem.
472 476 inspect_error()
473 477 traceback.print_exc(file=Term.cerr)
474 478 info('\nUnfortunately, your original traceback can not be constructed.\n')
475 479 return ''
476 480
477 481 # build some color string templates outside these nested loops
478 482 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
479 483 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
480 484 ColorsNormal)
481 485 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
482 486 (Colors.vName, Colors.valEm, ColorsNormal)
483 487 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
484 488 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
485 489 Colors.vName, ColorsNormal)
486 490 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
487 491 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
488 492 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
489 493 ColorsNormal)
490 494
491 495 # now, loop over all records printing context and info
492 496 abspath = os.path.abspath
493 497 for frame, file, lnum, func, lines, index in records:
494 498 #print '*** record:',file,lnum,func,lines,index # dbg
495 499 try:
496 500 file = file and abspath(file) or '?'
497 501 except OSError:
498 502 # if file is '<console>' or something not in the filesystem,
499 503 # the abspath call will throw an OSError. Just ignore it and
500 504 # keep the original file string.
501 505 pass
502 506 link = tpl_link % file
503 507 try:
504 508 args, varargs, varkw, locals = inspect.getargvalues(frame)
505 509 except:
506 510 # This can happen due to a bug in python2.3. We should be
507 511 # able to remove this try/except when 2.4 becomes a
508 512 # requirement. Bug details at http://python.org/sf/1005466
509 513 inspect_error()
510 514 traceback.print_exc(file=Term.cerr)
511 515 info("\nIPython's exception reporting continues...\n")
512 516
513 517 if func == '?':
514 518 call = ''
515 519 else:
516 520 # Decide whether to include variable details or not
517 521 var_repr = self.include_vars and eqrepr or nullrepr
518 522 try:
519 523 call = tpl_call % (func,inspect.formatargvalues(args,
520 524 varargs, varkw,
521 525 locals,formatvalue=var_repr))
522 526 except KeyError:
523 527 # Very odd crash from inspect.formatargvalues(). The
524 528 # scenario under which it appeared was a call to
525 529 # view(array,scale) in NumTut.view.view(), where scale had
526 530 # been defined as a scalar (it should be a tuple). Somehow
527 531 # inspect messes up resolving the argument list of view()
528 532 # and barfs out. At some point I should dig into this one
529 533 # and file a bug report about it.
530 534 inspect_error()
531 535 traceback.print_exc(file=Term.cerr)
532 536 info("\nIPython's exception reporting continues...\n")
533 537 call = tpl_call_fail % func
534 538
535 539 # Initialize a list of names on the current line, which the
536 540 # tokenizer below will populate.
537 541 names = []
538 542
539 543 def tokeneater(token_type, token, start, end, line):
540 544 """Stateful tokeneater which builds dotted names.
541 545
542 546 The list of names it appends to (from the enclosing scope) can
543 547 contain repeated composite names. This is unavoidable, since
544 548 there is no way to disambguate partial dotted structures until
545 549 the full list is known. The caller is responsible for pruning
546 550 the final list of duplicates before using it."""
547 551
548 552 # build composite names
549 553 if token == '.':
550 554 try:
551 555 names[-1] += '.'
552 556 # store state so the next token is added for x.y.z names
553 557 tokeneater.name_cont = True
554 558 return
555 559 except IndexError:
556 560 pass
557 561 if token_type == tokenize.NAME and token not in keyword.kwlist:
558 562 if tokeneater.name_cont:
559 563 # Dotted names
560 564 names[-1] += token
561 565 tokeneater.name_cont = False
562 566 else:
563 567 # Regular new names. We append everything, the caller
564 568 # will be responsible for pruning the list later. It's
565 569 # very tricky to try to prune as we go, b/c composite
566 570 # names can fool us. The pruning at the end is easy
567 571 # to do (or the caller can print a list with repeated
568 572 # names if so desired.
569 573 names.append(token)
570 574 elif token_type == tokenize.NEWLINE:
571 575 raise IndexError
572 576 # we need to store a bit of state in the tokenizer to build
573 577 # dotted names
574 578 tokeneater.name_cont = False
575 579
576 580 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
577 581 line = getline(file, lnum[0])
578 582 lnum[0] += 1
579 583 return line
580 584
581 585 # Build the list of names on this line of code where the exception
582 586 # occurred.
583 587 try:
584 588 # This builds the names list in-place by capturing it from the
585 589 # enclosing scope.
586 590 tokenize.tokenize(linereader, tokeneater)
587 591 except IndexError:
588 592 # signals exit of tokenizer
589 593 pass
590 594 except tokenize.TokenError,msg:
591 595 _m = ("An unexpected error occurred while tokenizing input\n"
592 596 "The following traceback may be corrupted or invalid\n"
593 597 "The error message is: %s\n" % msg)
594 598 error(_m)
595 599
596 600 # prune names list of duplicates, but keep the right order
597 601 unique_names = uniq_stable(names)
598 602
599 603 # Start loop over vars
600 604 lvals = []
601 605 if self.include_vars:
602 606 for name_full in unique_names:
603 607 name_base = name_full.split('.',1)[0]
604 608 if name_base in frame.f_code.co_varnames:
605 609 if locals.has_key(name_base):
606 610 try:
607 611 value = repr(eval(name_full,locals))
608 612 except:
609 613 value = undefined
610 614 else:
611 615 value = undefined
612 616 name = tpl_local_var % name_full
613 617 else:
614 618 if frame.f_globals.has_key(name_base):
615 619 try:
616 620 value = repr(eval(name_full,frame.f_globals))
617 621 except:
618 622 value = undefined
619 623 else:
620 624 value = undefined
621 625 name = tpl_global_var % name_full
622 626 lvals.append(tpl_name_val % (name,value))
623 627 if lvals:
624 628 lvals = '%s%s' % (indent,em_normal.join(lvals))
625 629 else:
626 630 lvals = ''
627 631
628 632 level = '%s %s\n' % (link,call)
629 633
630 634 if index is None:
631 635 frames.append(level)
632 636 else:
633 637 frames.append('%s%s' % (level,''.join(
634 638 _formatTracebackLines(lnum,index,lines,self.Colors,lvals))))
635 639
636 640 # Get (safely) a string form of the exception info
637 641 try:
638 642 etype_str,evalue_str = map(str,(etype,evalue))
639 643 except:
640 644 # User exception is improperly defined.
641 645 etype,evalue = str,sys.exc_info()[:2]
642 646 etype_str,evalue_str = map(str,(etype,evalue))
643 647 # ... and format it
644 648 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
645 649 ColorsNormal, evalue_str)]
646 650 if type(evalue) is types.InstanceType:
647 651 try:
648 652 names = [w for w in dir(evalue) if isinstance(w, basestring)]
649 653 except:
650 654 # Every now and then, an object with funny inernals blows up
651 655 # when dir() is called on it. We do the best we can to report
652 656 # the problem and continue
653 657 _m = '%sException reporting error (object with broken dir())%s:'
654 658 exception.append(_m % (Colors.excName,ColorsNormal))
655 659 etype_str,evalue_str = map(str,sys.exc_info()[:2])
656 660 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
657 661 ColorsNormal, evalue_str))
658 662 names = []
659 663 for name in names:
660 664 value = text_repr(getattr(evalue, name))
661 665 exception.append('\n%s%s = %s' % (indent, name, value))
662 666 # return all our info assembled as a single string
663 667 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
664 668
665 669 def debugger(self):
666 670 """Call up the pdb debugger if desired, always clean up the tb reference.
667 671
668 672 If the call_pdb flag is set, the pdb interactive debugger is
669 673 invoked. In all cases, the self.tb reference to the current traceback
670 674 is deleted to prevent lingering references which hamper memory
671 675 management.
672 676
673 677 Note that each call to pdb() does an 'import readline', so if your app
674 678 requires a special setup for the readline completers, you'll have to
675 679 fix that by hand after invoking the exception handler."""
676 680
677 681 if self.call_pdb:
678 682 if self.pdb is None:
679 683 self.pdb = Debugger.Pdb(
680 684 self.color_scheme_table.active_scheme_name)
681 685 # the system displayhook may have changed, restore the original
682 686 # for pdb
683 687 dhook = sys.displayhook
684 688 sys.displayhook = sys.__displayhook__
685 689 self.pdb.reset()
686 690 # Find the right frame so we don't pop up inside ipython itself
687 691 etb = self.tb
688 692 while self.tb.tb_next is not None:
689 693 self.tb = self.tb.tb_next
690 694 try:
691 695 if etb and etb.tb_next:
692 696 etb = etb.tb_next
693 697 self.pdb.botframe = etb.tb_frame
694 698 self.pdb.interaction(self.tb.tb_frame, self.tb)
695 except 'ha': # dbg
699 except:
696 700 print '*** ERROR ***'
697 701 print 'This version of pdb has a bug and crashed.'
698 702 print 'Returning to IPython...'
699 703 sys.displayhook = dhook
700 704 del self.tb
701 705
702 706 def handler(self, info=None):
703 707 (etype, evalue, etb) = info or sys.exc_info()
704 708 self.tb = etb
705 709 print >> Term.cerr, self.text(etype, evalue, etb)
706 710
707 711 # Changed so an instance can just be called as VerboseTB_inst() and print
708 712 # out the right info on its own.
709 713 def __call__(self, etype=None, evalue=None, etb=None):
710 714 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
711 715 if etb is None:
712 716 self.handler()
713 717 else:
714 718 self.handler((etype, evalue, etb))
715 719 self.debugger()
716 720
717 721 #----------------------------------------------------------------------------
718 722 class FormattedTB(VerboseTB,ListTB):
719 723 """Subclass ListTB but allow calling with a traceback.
720 724
721 725 It can thus be used as a sys.excepthook for Python > 2.1.
722 726
723 727 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
724 728
725 729 Allows a tb_offset to be specified. This is useful for situations where
726 730 one needs to remove a number of topmost frames from the traceback (such as
727 731 occurs with python programs that themselves execute other python code,
728 732 like Python shells). """
729 733
730 734 def __init__(self, mode = 'Plain', color_scheme='Linux',
731 735 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
732 736
733 737 # NEVER change the order of this list. Put new modes at the end:
734 738 self.valid_modes = ['Plain','Context','Verbose']
735 739 self.verbose_modes = self.valid_modes[1:3]
736 740
737 741 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
738 742 call_pdb=call_pdb,include_vars=include_vars)
739 743 self.set_mode(mode)
740 744
741 745 def _extract_tb(self,tb):
742 746 if tb:
743 747 return traceback.extract_tb(tb)
744 748 else:
745 749 return None
746 750
747 751 def text(self, etype, value, tb,context=5,mode=None):
748 752 """Return formatted traceback.
749 753
750 754 If the optional mode parameter is given, it overrides the current
751 755 mode."""
752 756
753 757 if mode is None:
754 758 mode = self.mode
755 759 if mode in self.verbose_modes:
756 760 # verbose modes need a full traceback
757 761 return VerboseTB.text(self,etype, value, tb,context=5)
758 762 else:
759 763 # We must check the source cache because otherwise we can print
760 764 # out-of-date source code.
761 765 linecache.checkcache()
762 766 # Now we can extract and format the exception
763 767 elist = self._extract_tb(tb)
764 768 if len(elist) > self.tb_offset:
765 769 del elist[:self.tb_offset]
766 770 return ListTB.text(self,etype,value,elist)
767 771
768 772 def set_mode(self,mode=None):
769 773 """Switch to the desired mode.
770 774
771 775 If mode is not specified, cycles through the available modes."""
772 776
773 777 if not mode:
774 778 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
775 779 len(self.valid_modes)
776 780 self.mode = self.valid_modes[new_idx]
777 781 elif mode not in self.valid_modes:
778 782 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
779 783 'Valid modes: '+str(self.valid_modes)
780 784 else:
781 785 self.mode = mode
782 786 # include variable details only in 'Verbose' mode
783 787 self.include_vars = (self.mode == self.valid_modes[2])
784 788
785 789 # some convenient shorcuts
786 790 def plain(self):
787 791 self.set_mode(self.valid_modes[0])
788 792
789 793 def context(self):
790 794 self.set_mode(self.valid_modes[1])
791 795
792 796 def verbose(self):
793 797 self.set_mode(self.valid_modes[2])
794 798
795 799 #----------------------------------------------------------------------------
796 800 class AutoFormattedTB(FormattedTB):
797 801 """A traceback printer which can be called on the fly.
798 802
799 803 It will find out about exceptions by itself.
800 804
801 805 A brief example:
802 806
803 807 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
804 808 try:
805 809 ...
806 810 except:
807 811 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
808 812 """
809 813 def __call__(self,etype=None,evalue=None,etb=None,
810 814 out=None,tb_offset=None):
811 815 """Print out a formatted exception traceback.
812 816
813 817 Optional arguments:
814 818 - out: an open file-like object to direct output to.
815 819
816 820 - tb_offset: the number of frames to skip over in the stack, on a
817 821 per-call basis (this overrides temporarily the instance's tb_offset
818 822 given at initialization time. """
819 823
820 824 if out is None:
821 825 out = Term.cerr
822 826 if tb_offset is not None:
823 827 tb_offset, self.tb_offset = self.tb_offset, tb_offset
824 828 print >> out, self.text(etype, evalue, etb)
825 829 self.tb_offset = tb_offset
826 830 else:
827 831 print >> out, self.text(etype, evalue, etb)
828 832 self.debugger()
829 833
830 834 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
831 835 if etype is None:
832 836 etype,value,tb = sys.exc_info()
833 837 self.tb = tb
834 838 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
835 839
836 840 #---------------------------------------------------------------------------
837 841 # A simple class to preserve Nathan's original functionality.
838 842 class ColorTB(FormattedTB):
839 843 """Shorthand to initialize a FormattedTB in Linux colors mode."""
840 844 def __init__(self,color_scheme='Linux',call_pdb=0):
841 845 FormattedTB.__init__(self,color_scheme=color_scheme,
842 846 call_pdb=call_pdb)
843 847
844 848 #----------------------------------------------------------------------------
845 849 # module testing (minimal)
846 850 if __name__ == "__main__":
847 851 def spam(c, (d, e)):
848 852 x = c + d
849 853 y = c * d
850 854 foo(x, y)
851 855
852 856 def foo(a, b, bar=1):
853 857 eggs(a, b + bar)
854 858
855 859 def eggs(f, g, z=globals()):
856 860 h = f + g
857 861 i = f - g
858 862 return h / i
859 863
860 864 print ''
861 865 print '*** Before ***'
862 866 try:
863 867 print spam(1, (2, 3))
864 868 except:
865 869 traceback.print_exc()
866 870 print ''
867 871
868 872 handler = ColorTB()
869 873 print '*** ColorTB ***'
870 874 try:
871 875 print spam(1, (2, 3))
872 876 except:
873 877 apply(handler, sys.exc_info() )
874 878 print ''
875 879
876 880 handler = VerboseTB()
877 881 print '*** VerboseTB ***'
878 882 try:
879 883 print spam(1, (2, 3))
880 884 except:
881 885 apply(handler, sys.exc_info() )
882 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 19 2006-09-27 Ville Vainio <vivainio@gmail.com>
2 20
3 21 * iplib.py (raw_input): python 2.5 closes stdin on quit -> avoid
4 22 infinite loop and just exit. It's a hack, but will do for a while.
5 23
6 24 2006-08-25 Walter Doerwald <walter@livinglogic.de>
7 25
8 26 * IPython/Extensions/ipipe.py (ils): Add arguments dirs and files to
9 27 the constructor, this makes it possible to get a list of only directories
10 28 or only files.
11 29
12 30 2006-08-12 Ville Vainio <vivainio@gmail.com>
13 31
14 32 * Fakemodule.py, OInspect.py: Reverted 2006-08-11 mods,
15 33 they broke unittest
16 34
17 35 2006-08-11 Ville Vainio <vivainio@gmail.com>
18 36
19 37 * Fakemodule.py, OInspect.py: remove 2006-08-09 monkepatch
20 38 by resolving issue properly, i.e. by inheriting FakeModule
21 39 from types.ModuleType. Pickling ipython interactive data
22 40 should still work as usual (testing appreciated).
23 41
24 42 2006-08-09 Fernando Perez <Fernando.Perez@colorado.edu>
25 43
26 44 * IPython/OInspect.py: monkeypatch inspect from the stdlib if
27 45 running under python 2.3 with code from 2.4 to fix a bug with
28 46 help(). Reported by the Debian maintainers, Norbert Tretkowski
29 47 <norbert-AT-tretkowski.de> and Alexandre Fayolle
30 48 <afayolle-AT-debian.org>.
31 49
32 50 2006-08-04 Walter Doerwald <walter@livinglogic.de>
33 51
34 52 * IPython/Extensions/ibrowse.py: Fixed the help message in the footer
35 53 (which was displaying "quit" twice).
36 54
37 55 2006-07-28 Walter Doerwald <walter@livinglogic.de>
38 56
39 57 * IPython/Extensions/ipipe.py: Fix isort.__iter__() (was still using
40 58 the mode argument).
41 59
42 60 2006-07-27 Walter Doerwald <walter@livinglogic.de>
43 61
44 62 * IPython/Extensions/ipipe.py: Fix getglobals() if we're
45 63 not running under IPython.
46 64
47 65 * IPython/Extensions/ipipe.py: Rename XAttr to AttributeDetail
48 66 and make it iterable (iterating over the attribute itself). Add two new
49 67 magic strings for __xattrs__(): If the string starts with "-", the attribute
50 68 will not be displayed in ibrowse's detail view (but it can still be
51 69 iterated over). This makes it possible to add attributes that are large
52 70 lists or generator methods to the detail view. Replace magic attribute names
53 71 and _attrname() and _getattr() with "descriptors": For each type of magic
54 72 attribute name there's a subclass of Descriptor: None -> SelfDescriptor();
55 73 "foo" -> AttributeDescriptor("foo"); "foo()" -> MethodDescriptor("foo");
56 74 "-foo" -> IterAttributeDescriptor("foo"); "-foo()" -> IterMethodDescriptor("foo");
57 75 foo() -> FunctionDescriptor(foo). Magic strings returned from __xattrs__()
58 76 are still supported.
59 77
60 78 * IPython/Extensions/ibrowse.py: If fetching the next row from the input
61 79 fails in ibrowse.fetch(), the exception object is added as the last item
62 80 and item fetching is canceled. This prevents ibrowse from aborting if e.g.
63 81 a generator throws an exception midway through execution.
64 82
65 83 * IPython/Extensions/ipipe.py: Turn ifile's properties mimetype and
66 84 encoding into methods.
67 85
68 86 2006-07-26 Ville Vainio <vivainio@gmail.com>
69 87
70 88 * iplib.py: history now stores multiline input as single
71 89 history entries. Patch by Jorgen Cederlof.
72 90
73 91 2006-07-18 Walter Doerwald <walter@livinglogic.de>
74 92
75 93 * IPython/Extensions/ibrowse.py: Make cursor visible over
76 94 non existing attributes.
77 95
78 96 2006-07-14 Walter Doerwald <walter@livinglogic.de>
79 97
80 98 * IPython/Extensions/ipipe.py (ix): Use os.popen4() so that the
81 99 error output of the running command doesn't mess up the screen.
82 100
83 101 2006-07-13 Walter Doerwald <walter@livinglogic.de>
84 102
85 103 * IPython/Extensions/ipipe.py (isort): Make isort usable without
86 104 argument. This sorts the items themselves.
87 105
88 106 2006-07-12 Walter Doerwald <walter@livinglogic.de>
89 107
90 108 * IPython/Extensions/ipipe.py (eval, ifilter, isort, ieval):
91 109 Compile expression strings into code objects. This should speed
92 110 up ifilter and friends somewhat.
93 111
94 112 2006-07-08 Ville Vainio <vivainio@gmail.com>
95 113
96 114 * Magic.py: %cpaste now strips > from the beginning of lines
97 115 to ease pasting quoted code from emails. Contributed by
98 116 Stefan van der Walt.
99 117
100 118 2006-06-29 Ville Vainio <vivainio@gmail.com>
101 119
102 120 * ipmaker.py, Shell.py: qt4agg matplotlib backend support for pylab
103 121 mode, patch contributed by Darren Dale. NEEDS TESTING!
104 122
105 123 2006-06-28 Walter Doerwald <walter@livinglogic.de>
106 124
107 125 * IPython/Extensions/ibrowse.py: Give the ibrowse cursor row
108 126 a blue background. Fix fetching new display rows when the browser
109 127 scrolls more than a screenful (e.g. by using the goto command).
110 128
111 129 2006-06-27 Ville Vainio <vivainio@gmail.com>
112 130
113 131 * Magic.py (_inspect, _ofind) Apply David Huard's
114 132 patch for displaying the correct docstring for 'property'
115 133 attributes.
116 134
117 135 2006-06-23 Walter Doerwald <walter@livinglogic.de>
118 136
119 137 * IPython/Extensions/ibrowse.py: Put the documentation of the keyboard
120 138 commands into the methods implementing them.
121 139
122 140 2006-06-22 Fernando Perez <Fernando.Perez@colorado.edu>
123 141
124 142 * ipython.el (ipython-indentation-hook): cleanup patch, submitted
125 143 by Kov Chai <tchaikov-AT-gmail.com>. He notes that the original
126 144 autoindent support was authored by Jin Liu.
127 145
128 146 2006-06-22 Walter Doerwald <walter@livinglogic.de>
129 147
130 148 * IPython/Extensions/ibrowse.py: Replace the plain dictionaries used
131 149 for keymaps with a custom class that simplifies handling.
132 150
133 151 2006-06-19 Walter Doerwald <walter@livinglogic.de>
134 152
135 153 * IPython/Extensions/ibrowse.py: ibrowse now properly handles terminal
136 154 resizing. This requires Python 2.5 to work.
137 155
138 156 2006-06-16 Walter Doerwald <walter@livinglogic.de>
139 157
140 158 * IPython/Extensions/ibrowse.py: Add two new commands to
141 159 ibrowse: "hideattr" (mapped to "h") hides the attribute under
142 160 the cursor. "unhiderattrs" (mapped to "H") reveals all hidden
143 161 attributes again. Remapped the help command to "?". Display
144 162 keycodes in the range 0x01-0x1F as CTRL-xx. Add CTRL-a and CTRL-e
145 163 as keys for the "home" and "end" commands. Add three new commands
146 164 to the input mode for "find" and friends: "delend" (CTRL-K)
147 165 deletes to the end of line. "incsearchup" searches upwards in the
148 166 command history for an input that starts with the text before the cursor.
149 167 "incsearchdown" does the same downwards. Removed a bogus mapping of
150 168 the x key to "delete".
151 169
152 170 2006-06-15 Ville Vainio <vivainio@gmail.com>
153 171
154 172 * iplib.py, hooks.py: Added new generate_prompt hook that can be
155 173 used to create prompts dynamically, instead of the "old" way of
156 174 assigning "magic" strings to prompt_in1 and prompt_in2. The old
157 175 way still works (it's invoked by the default hook), of course.
158 176
159 177 * Prompts.py: added generate_output_prompt hook for altering output
160 178 prompt
161 179
162 180 * Release.py: Changed version string to 0.7.3.svn.
163 181
164 182 2006-06-15 Walter Doerwald <walter@livinglogic.de>
165 183
166 184 * IPython/Extensions/ibrowse.py: Change _BrowserLevel.moveto() so that
167 185 the call to fetch() always tries to fetch enough data for at least one
168 186 full screen. This makes it possible to simply call moveto(0,0,True) in
169 187 the constructor. Fix typos and removed the obsolete goto attribute.
170 188
171 189 2006-06-12 Ville Vainio <vivainio@gmail.com>
172 190
173 191 * ipy_profile_sh.py: applied Krisha Mohan Gundu's patch for
174 192 allowing $variable interpolation within multiline statements,
175 193 though so far only with "sh" profile for a testing period.
176 194 The patch also enables splitting long commands with \ but it
177 195 doesn't work properly yet.
178 196
179 197 2006-06-12 Walter Doerwald <walter@livinglogic.de>
180 198
181 199 * IPython/Extensions/ibrowse.py (_dodisplay): Display the length of the
182 200 input history and the position of the cursor in the input history for
183 201 the find, findbackwards and goto command.
184 202
185 203 2006-06-10 Walter Doerwald <walter@livinglogic.de>
186 204
187 205 * IPython/Extensions/ibrowse.py: Add a class _CommandInput that
188 206 implements the basic functionality of browser commands that require
189 207 input. Reimplement the goto, find and findbackwards commands as
190 208 subclasses of _CommandInput. Add an input history and keymaps to those
191 209 commands. Add "\r" as a keyboard shortcut for the enterdefault and
192 210 execute commands.
193 211
194 212 2006-06-07 Ville Vainio <vivainio@gmail.com>
195 213
196 214 * iplib.py: ipython mybatch.ipy exits ipython immediately after
197 215 running the batch files instead of leaving the session open.
198 216
199 217 2006-06-07 Fernando Perez <Fernando.Perez@colorado.edu>
200 218
201 219 * IPython/iplib.py (InteractiveShell.__init__): update BSD fix, as
202 220 the original fix was incomplete. Patch submitted by W. Maier.
203 221
204 222 2006-06-07 Ville Vainio <vivainio@gmail.com>
205 223
206 224 * iplib.py,Magic.py, ipmaker.py (magic_rehashx):
207 225 Confirmation prompts can be supressed by 'quiet' option.
208 226 _ip.options.quiet = 1 means "assume yes for all yes/no queries".
209 227
210 228 2006-06-06 *** Released version 0.7.2
211 229
212 230 2006-06-06 Fernando Perez <Fernando.Perez@colorado.edu>
213 231
214 232 * IPython/Release.py (version): Made 0.7.2 final for release.
215 233 Repo tagged and release cut.
216 234
217 235 2006-06-05 Ville Vainio <vivainio@gmail.com>
218 236
219 237 * Magic.py (magic_rehashx): Honor no_alias list earlier in
220 238 %rehashx, to avoid clobbering builtins in ipy_profile_sh.py
221 239
222 240 * upgrade_dir.py: try import 'path' module a bit harder
223 241 (for %upgrade)
224 242
225 243 2006-06-03 Fernando Perez <Fernando.Perez@colorado.edu>
226 244
227 245 * IPython/genutils.py (ask_yes_no): treat EOF as a default answer
228 246 instead of looping 20 times.
229 247
230 248 * IPython/ipmaker.py (make_IPython): honor -ipythondir flag
231 249 correctly at initialization time. Bug reported by Krishna Mohan
232 250 Gundu <gkmohan-AT-gmail.com> on the user list.
233 251
234 252 * IPython/Release.py (version): Mark 0.7.2 version to start
235 253 testing for release on 06/06.
236 254
237 255 2006-05-31 Fernando Perez <Fernando.Perez@colorado.edu>
238 256
239 257 * scripts/irunner: thin script interface so users don't have to
240 258 find the module and call it as an executable, since modules rarely
241 259 live in people's PATH.
242 260
243 261 * IPython/irunner.py (InteractiveRunner.__init__): added
244 262 delaybeforesend attribute to control delays with newer versions of
245 263 pexpect. Thanks to detailed help from pexpect's author, Noah
246 264 Spurrier <noah-AT-noah.org>. Noted how to use the SAGE runner
247 265 correctly (it works in NoColor mode).
248 266
249 267 * IPython/iplib.py (handle_normal): fix nasty crash reported on
250 268 SAGE list, from improper log() calls.
251 269
252 270 2006-05-31 Ville Vainio <vivainio@gmail.com>
253 271
254 272 * upgrade_dir.py, Magic.py (magic_upgrade): call upgrade_dir
255 273 with args in parens to work correctly with dirs that have spaces.
256 274
257 275 2006-05-30 Fernando Perez <Fernando.Perez@colorado.edu>
258 276
259 277 * IPython/Logger.py (Logger.logstart): add option to log raw input
260 278 instead of the processed one. A -r flag was added to the
261 279 %logstart magic used for controlling logging.
262 280
263 281 2006-05-29 Fernando Perez <Fernando.Perez@colorado.edu>
264 282
265 283 * IPython/iplib.py (InteractiveShell.__init__): add check for the
266 284 *BSDs to omit --color from all 'ls' aliases, since *BSD ls doesn't
267 285 recognize the option. After a bug report by Will Maier. This
268 286 closes #64 (will do it after confirmation from W. Maier).
269 287
270 288 * IPython/irunner.py: New module to run scripts as if manually
271 289 typed into an interactive environment, based on pexpect. After a
272 290 submission by Ken Schutte <kschutte-AT-csail.mit.edu> on the
273 291 ipython-user list. Simple unittests in the tests/ directory.
274 292
275 293 * tools/release: add Will Maier, OpenBSD port maintainer, to
276 294 recepients list. We are now officially part of the OpenBSD ports:
277 295 http://www.openbsd.org/ports.html ! Many thanks to Will for the
278 296 work.
279 297
280 298 2006-05-26 Fernando Perez <Fernando.Perez@colorado.edu>
281 299
282 300 * IPython/ipmaker.py (make_IPython): modify sys.argv fix (below)
283 301 so that it doesn't break tkinter apps.
284 302
285 303 * IPython/iplib.py (_prefilter): fix bug where aliases would
286 304 shadow variables when autocall was fully off. Reported by SAGE
287 305 author William Stein.
288 306
289 307 * IPython/OInspect.py (Inspector.__init__): add a flag to control
290 308 at what detail level strings are computed when foo? is requested.
291 309 This allows users to ask for example that the string form of an
292 310 object is only computed when foo?? is called, or even never, by
293 311 setting the object_info_string_level >= 2 in the configuration
294 312 file. This new option has been added and documented. After a
295 313 request by SAGE to be able to control the printing of very large
296 314 objects more easily.
297 315
298 316 2006-05-25 Fernando Perez <Fernando.Perez@colorado.edu>
299 317
300 318 * IPython/ipmaker.py (make_IPython): remove the ipython call path
301 319 from sys.argv, to be 100% consistent with how Python itself works
302 320 (as seen for example with python -i file.py). After a bug report
303 321 by Jeffrey Collins.
304 322
305 323 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix
306 324 nasty bug which was preventing custom namespaces with -pylab,
307 325 reported by M. Foord. Minor cleanup, remove old matplotlib.matlab
308 326 compatibility (long gone from mpl).
309 327
310 328 * IPython/ipapi.py (make_session): name change: create->make. We
311 329 use make in other places (ipmaker,...), it's shorter and easier to
312 330 type and say, etc. I'm trying to clean things before 0.7.2 so
313 331 that I can keep things stable wrt to ipapi in the chainsaw branch.
314 332
315 333 * ipython.el: fix the py-pdbtrack-input-prompt variable so that
316 334 python-mode recognizes our debugger mode. Add support for
317 335 autoindent inside (X)emacs. After a patch sent in by Jin Liu
318 336 <m.liu.jin-AT-gmail.com> originally written by
319 337 doxgen-AT-newsmth.net (with minor modifications for xemacs
320 338 compatibility)
321 339
322 340 * IPython/Debugger.py (Pdb.format_stack_entry): fix formatting of
323 341 tracebacks when walking the stack so that the stack tracking system
324 342 in emacs' python-mode can identify the frames correctly.
325 343
326 344 * IPython/ipmaker.py (make_IPython): make the internal (and
327 345 default config) autoedit_syntax value false by default. Too many
328 346 users have complained to me (both on and off-list) about problems
329 347 with this option being on by default, so I'm making it default to
330 348 off. It can still be enabled by anyone via the usual mechanisms.
331 349
332 350 * IPython/completer.py (Completer.attr_matches): add support for
333 351 PyCrust-style _getAttributeNames magic method. Patch contributed
334 352 by <mscott-AT-goldenspud.com>. Closes #50.
335 353
336 354 * IPython/iplib.py (InteractiveShell.__init__): remove the
337 355 deletion of exit/quit from __builtin__, which can break
338 356 third-party tools like the Zope debugging console. The
339 357 %exit/%quit magics remain. In general, it's probably a good idea
340 358 not to delete anything from __builtin__, since we never know what
341 359 that will break. In any case, python now (for 2.5) will support
342 360 'real' exit/quit, so this issue is moot. Closes #55.
343 361
344 362 * IPython/genutils.py (with_obj): rename the 'with' function to
345 363 'withobj' to avoid incompatibilities with Python 2.5, where 'with'
346 364 becomes a language keyword. Closes #53.
347 365
348 366 * IPython/FakeModule.py (FakeModule.__init__): add a proper
349 367 __file__ attribute to this so it fools more things into thinking
350 368 it is a real module. Closes #59.
351 369
352 370 * IPython/Magic.py (magic_edit): add -n option to open the editor
353 371 at a specific line number. After a patch by Stefan van der Walt.
354 372
355 373 2006-05-23 Fernando Perez <Fernando.Perez@colorado.edu>
356 374
357 375 * IPython/iplib.py (edit_syntax_error): fix crash when for some
358 376 reason the file could not be opened. After automatic crash
359 377 reports sent by James Graham <jgraham-AT-ast.cam.ac.uk> and
360 378 Charles Dolan <charlespatrickdolan-AT-yahoo.com>.
361 379 (_should_recompile): Don't fire editor if using %bg, since there
362 380 is no file in the first place. From the same report as above.
363 381 (raw_input): protect against faulty third-party prefilters. After
364 382 an automatic crash report sent by Dirk Laurie <dirk-AT-sun.ac.za>
365 383 while running under SAGE.
366 384
367 385 2006-05-23 Ville Vainio <vivainio@gmail.com>
368 386
369 387 * ipapi.py: Stripped down ip.to_user_ns() to work only as
370 388 ip.to_user_ns("x1 y1"), which exposes vars x1 and y1. ipapi.get()
371 389 now returns None (again), unless dummy is specifically allowed by
372 390 ipapi.get(allow_dummy=True).
373 391
374 392 2006-05-18 Fernando Perez <Fernando.Perez@colorado.edu>
375 393
376 394 * IPython: remove all 2.2-compatibility objects and hacks from
377 395 everywhere, since we only support 2.3 at this point. Docs
378 396 updated.
379 397
380 398 * IPython/ipapi.py (IPApi.__init__): Cleanup of all getters.
381 399 Anything requiring extra validation can be turned into a Python
382 400 property in the future. I used a property for the db one b/c
383 401 there was a nasty circularity problem with the initialization
384 402 order, which right now I don't have time to clean up.
385 403
386 404 * IPython/Shell.py (MTInteractiveShell.runcode): Fix, I think,
387 405 another locking bug reported by Jorgen. I'm not 100% sure though,
388 406 so more testing is needed...
389 407
390 408 2006-05-17 Fernando Perez <Fernando.Perez@colorado.edu>
391 409
392 410 * IPython/ipapi.py (IPApi.to_user_ns): New function to inject
393 411 local variables from any routine in user code (typically executed
394 412 with %run) directly into the interactive namespace. Very useful
395 413 when doing complex debugging.
396 414 (IPythonNotRunning): Changed the default None object to a dummy
397 415 whose attributes can be queried as well as called without
398 416 exploding, to ease writing code which works transparently both in
399 417 and out of ipython and uses some of this API.
400 418
401 419 2006-05-16 Fernando Perez <Fernando.Perez@colorado.edu>
402 420
403 421 * IPython/hooks.py (result_display): Fix the fact that our display
404 422 hook was using str() instead of repr(), as the default python
405 423 console does. This had gone unnoticed b/c it only happened if
406 424 %Pprint was off, but the inconsistency was there.
407 425
408 426 2006-05-15 Ville Vainio <vivainio@gmail.com>
409 427
410 428 * Oinspect.py: Only show docstring for nonexisting/binary files
411 429 when doing object??, closing ticket #62
412 430
413 431 2006-05-13 Fernando Perez <Fernando.Perez@colorado.edu>
414 432
415 433 * IPython/Shell.py (MTInteractiveShell.runsource): Fix threading
416 434 bug, closes http://www.scipy.net/roundup/ipython/issue55. A lock
417 435 was being released in a routine which hadn't checked if it had
418 436 been the one to acquire it.
419 437
420 438 2006-05-07 Fernando Perez <Fernando.Perez@colorado.edu>
421 439
422 440 * IPython/Release.py (version): put out 0.7.2.rc1 for testing.
423 441
424 442 2006-04-11 Ville Vainio <vivainio@gmail.com>
425 443
426 444 * iplib.py, ipmaker.py: .ipy extension now means "ipython batch file"
427 445 in command line. E.g. "ipython test.ipy" runs test.ipy with ipython
428 446 prefilters, allowing stuff like magics and aliases in the file.
429 447
430 448 * Prompts.py, Extensions/clearcmd.py, ipy_system_conf.py: %clear magic
431 449 added. Supported now are "%clear in" and "%clear out" (clear input and
432 450 output history, respectively). Also fixed CachedOutput.flush to
433 451 properly flush the output cache.
434 452
435 453 * Extensions/pspersistence.py: Fix %store to avoid "%store obj.attr"
436 454 half-success (and fail explicitly).
437 455
438 456 2006-03-28 Ville Vainio <vivainio@gmail.com>
439 457
440 458 * iplib.py: Fix quoting of aliases so that only argless ones
441 459 are quoted
442 460
443 461 2006-03-28 Ville Vainio <vivainio@gmail.com>
444 462
445 463 * iplib.py: Quote aliases with spaces in the name.
446 464 "c:\program files\blah\bin" is now legal alias target.
447 465
448 466 * ext_rehashdir.py: Space no longer allowed as arg
449 467 separator, since space is legal in path names.
450 468
451 469 2006-03-16 Ville Vainio <vivainio@gmail.com>
452 470
453 471 * upgrade_dir.py: Take path.py from Extensions, correcting
454 472 %upgrade magic
455 473
456 474 * ipmaker.py: Suggest using %upgrade if ipy_user_conf.py isn't found.
457 475
458 476 * hooks.py: Only enclose editor binary in quotes if legal and
459 477 necessary (space in the name, and is an existing file). Fixes a bug
460 478 reported by Zachary Pincus.
461 479
462 480 2006-03-13 Fernando Perez <Fernando.Perez@colorado.edu>
463 481
464 482 * Manual: thanks to a tip on proper color handling for Emacs, by
465 483 Eric J Haywiser <ejh1-AT-MIT.EDU>.
466 484
467 485 * ipython.el: close http://www.scipy.net/roundup/ipython/issue57
468 486 by applying the provided patch. Thanks to Liu Jin
469 487 <m.liu.jin-AT-gmail.com> for the contribution. No problems under
470 488 XEmacs/Linux, I'm trusting the submitter that it actually helps
471 489 under win32/GNU Emacs. Will revisit if any problems are reported.
472 490
473 491 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
474 492
475 493 * IPython/Gnuplot2.py (_FileClass): update for current Gnuplot.py
476 494 from SVN, thanks to a patch by Ryan Woodard <rywo@bas.ac.uk>.
477 495
478 496 2006-03-12 Ville Vainio <vivainio@gmail.com>
479 497
480 498 * Magic.py (magic_timeit): Added %timeit magic, contributed by
481 499 Torsten Marek.
482 500
483 501 2006-03-12 Fernando Perez <Fernando.Perez@colorado.edu>
484 502
485 503 * IPython/Magic.py (magic_macro): fix so that the n1-n2 syntax for
486 504 line ranges works again.
487 505
488 506 2006-03-11 Fernando Perez <Fernando.Perez@colorado.edu>
489 507
490 508 * IPython/iplib.py (showtraceback): add back sys.last_traceback
491 509 and friends, after a discussion with Zach Pincus on ipython-user.
492 510 I'm not 100% sure, but after thinking about it quite a bit, it may
493 511 be OK. Testing with the multithreaded shells didn't reveal any
494 512 problems, but let's keep an eye out.
495 513
496 514 In the process, I fixed a few things which were calling
497 515 self.InteractiveTB() directly (like safe_execfile), which is a
498 516 mistake: ALL exception reporting should be done by calling
499 517 self.showtraceback(), which handles state and tab-completion and
500 518 more.
501 519
502 520 2006-03-01 Ville Vainio <vivainio@gmail.com>
503 521
504 522 * Extensions/ipipe.py: Added Walter Doerwald's "ipipe" module.
505 523 To use, do "from ipipe import *".
506 524
507 525 2006-02-24 Ville Vainio <vivainio@gmail.com>
508 526
509 527 * Magic.py, upgrade_dir.py: %upgrade magic added. Does things more
510 528 "cleanly" and safely than the older upgrade mechanism.
511 529
512 530 2006-02-21 Ville Vainio <vivainio@gmail.com>
513 531
514 532 * Magic.py: %save works again.
515 533
516 534 2006-02-15 Ville Vainio <vivainio@gmail.com>
517 535
518 536 * Magic.py: %Pprint works again
519 537
520 538 * Extensions/ipy_sane_defaults.py: Provide everything provided
521 539 in default ipythonrc, to make it possible to have a completely empty
522 540 ipythonrc (and thus completely rc-file free configuration)
523 541
524 542 2006-02-11 Fernando Perez <Fernando.Perez@colorado.edu>
525 543
526 544 * IPython/hooks.py (editor): quote the call to the editor command,
527 545 to allow commands with spaces in them. Problem noted by watching
528 546 Ian Oswald's video about textpad under win32 at
529 547 http://showmedo.com/videoListPage?listKey=PythonIPythonSeries
530 548
531 549 * IPython/UserConfig/ipythonrc: Replace @ signs with % when
532 550 describing magics (we haven't used @ for a loong time).
533 551
534 552 * IPython/ultraTB.py (VerboseTB.text.text_repr): Added patch
535 553 contributed by marienz to close
536 554 http://www.scipy.net/roundup/ipython/issue53.
537 555
538 556 2006-02-10 Ville Vainio <vivainio@gmail.com>
539 557
540 558 * genutils.py: getoutput now works in win32 too
541 559
542 560 * completer.py: alias and magic completion only invoked
543 561 at the first "item" in the line, to avoid "cd %store"
544 562 nonsense.
545 563
546 564 2006-02-09 Ville Vainio <vivainio@gmail.com>
547 565
548 566 * test/*: Added a unit testing framework (finally).
549 567 '%run runtests.py' to run test_*.
550 568
551 569 * ipapi.py: Exposed runlines and set_custom_exc
552 570
553 571 2006-02-07 Ville Vainio <vivainio@gmail.com>
554 572
555 573 * iplib.py: don't split "f 1 2" to "f(1,2)" in autocall,
556 574 instead use "f(1 2)" as before.
557 575
558 576 2006-02-05 Fernando Perez <Fernando.Perez@colorado.edu>
559 577
560 578 * IPython/demo.py (IPythonDemo): Add new classes to the demo
561 579 facilities, for demos processed by the IPython input filter
562 580 (IPythonDemo), and for running a script one-line-at-a-time as a
563 581 demo, both for pure Python (LineDemo) and for IPython-processed
564 582 input (IPythonLineDemo). After a request by Dave Kohel, from the
565 583 SAGE team.
566 584 (Demo.edit): added an edit() method to the demo objects, to edit
567 585 the in-memory copy of the last executed block.
568 586
569 587 * IPython/Magic.py (magic_edit): add '-r' option for 'raw'
570 588 processing to %edit, %macro and %save. These commands can now be
571 589 invoked on the unprocessed input as it was typed by the user
572 590 (without any prefilters applied). After requests by the SAGE team
573 591 at SAGE days 2006: http://modular.ucsd.edu/sage/days1/schedule.html.
574 592
575 593 2006-02-01 Ville Vainio <vivainio@gmail.com>
576 594
577 595 * setup.py, eggsetup.py: easy_install ipython==dev works
578 596 correctly now (on Linux)
579 597
580 598 * ipy_user_conf,ipmaker: user config changes, removed spurious
581 599 warnings
582 600
583 601 * iplib: if rc.banner is string, use it as is.
584 602
585 603 * Magic: %pycat accepts a string argument and pages it's contents.
586 604
587 605
588 606 2006-01-30 Ville Vainio <vivainio@gmail.com>
589 607
590 608 * pickleshare,pspersistence,ipapi,Magic: persistence overhaul.
591 609 Now %store and bookmarks work through PickleShare, meaning that
592 610 concurrent access is possible and all ipython sessions see the
593 611 same database situation all the time, instead of snapshot of
594 612 the situation when the session was started. Hence, %bookmark
595 613 results are immediately accessible from othes sessions. The database
596 614 is also available for use by user extensions. See:
597 615 http://www.python.org/pypi/pickleshare
598 616
599 617 * hooks.py: Two new hooks, 'shutdown_hook' and 'late_startup_hook'.
600 618
601 619 * aliases can now be %store'd
602 620
603 621 * path.py moved to Extensions so that pickleshare does not need
604 622 IPython-specific import. Extensions added to pythonpath right
605 623 at __init__.
606 624
607 625 * iplib.py: ipalias deprecated/redundant; aliases are converted and
608 626 called with _ip.system and the pre-transformed command string.
609 627
610 628 2006-01-29 Fernando Perez <Fernando.Perez@colorado.edu>
611 629
612 630 * IPython/iplib.py (interact): Fix that we were not catching
613 631 KeyboardInterrupt exceptions properly. I'm not quite sure why the
614 632 logic here had to change, but it's fixed now.
615 633
616 634 2006-01-29 Ville Vainio <vivainio@gmail.com>
617 635
618 636 * iplib.py: Try to import pyreadline on Windows.
619 637
620 638 2006-01-27 Ville Vainio <vivainio@gmail.com>
621 639
622 640 * iplib.py: Expose ipapi as _ip in builtin namespace.
623 641 Makes ipmagic (-> _ip.magic), ipsystem (-> _ip.system)
624 642 and ip_set_hook (-> _ip.set_hook) redundant. % and !
625 643 syntax now produce _ip.* variant of the commands.
626 644
627 645 * "_ip.options().autoedit_syntax = 2" automatically throws
628 646 user to editor for syntax error correction without prompting.
629 647
630 648 2006-01-27 Ville Vainio <vivainio@gmail.com>
631 649
632 650 * ipmaker.py: Give "realistic" sys.argv for scripts (without
633 651 'ipython' at argv[0]) executed through command line.
634 652 NOTE: this DEPRECATES calling ipython with multiple scripts
635 653 ("ipython a.py b.py c.py")
636 654
637 655 * iplib.py, hooks.py: Added configurable input prefilter,
638 656 named 'input_prefilter'. See ext_rescapture.py for example
639 657 usage.
640 658
641 659 * ext_rescapture.py, Magic.py: Better system command output capture
642 660 through 'var = !ls' (deprecates user-visible %sc). Same notation
643 661 applies for magics, 'var = %alias' assigns alias list to var.
644 662
645 663 * ipapi.py: added meta() for accessing extension-usable data store.
646 664
647 665 * iplib.py: added InteractiveShell.getapi(). New magics should be
648 666 written doing self.getapi() instead of using the shell directly.
649 667
650 668 * Magic.py: %store now allows doing %store foo > ~/myfoo.txt and
651 669 %store foo >> ~/myfoo.txt to store variables to files (in clean
652 670 textual form, not a restorable pickle).
653 671
654 672 * ipmaker.py: now import ipy_profile_PROFILENAME automatically
655 673
656 674 * usage.py, Magic.py: added %quickref
657 675
658 676 * iplib.py: ESC_PAREN fixes: /f 1 2 -> f(1,2), not f(1 2).
659 677
660 678 * GetoptErrors when invoking magics etc. with wrong args
661 679 are now more helpful:
662 680 GetoptError: option -l not recognized (allowed: "qb" )
663 681
664 682 2006-01-25 Fernando Perez <Fernando.Perez@colorado.edu>
665 683
666 684 * IPython/demo.py (Demo.show): Flush stdout after each block, so
667 685 computationally intensive blocks don't appear to stall the demo.
668 686
669 687 2006-01-24 Ville Vainio <vivainio@gmail.com>
670 688
671 689 * iplib.py, hooks.py: 'result_display' hook can return a non-None
672 690 value to manipulate resulting history entry.
673 691
674 692 * ipapi.py: Moved TryNext here from hooks.py. Moved functions
675 693 to instance methods of IPApi class, to make extending an embedded
676 694 IPython feasible. See ext_rehashdir.py for example usage.
677 695
678 696 * Merged 1071-1076 from branches/0.7.1
679 697
680 698
681 699 2006-01-23 Fernando Perez <Fernando.Perez@colorado.edu>
682 700
683 701 * tools/release (daystamp): Fix build tools to use the new
684 702 eggsetup.py script to build lightweight eggs.
685 703
686 704 * Applied changesets 1062 and 1064 before 0.7.1 release.
687 705
688 706 * IPython/Magic.py (magic_history): Add '-r' option to %hist, to
689 707 see the raw input history (without conversions like %ls ->
690 708 ipmagic("ls")). After a request from W. Stein, SAGE
691 709 (http://modular.ucsd.edu/sage) developer. This information is
692 710 stored in the input_hist_raw attribute of the IPython instance, so
693 711 developers can access it if needed (it's an InputList instance).
694 712
695 713 * Versionstring = 0.7.2.svn
696 714
697 715 * eggsetup.py: A separate script for constructing eggs, creates
698 716 proper launch scripts even on Windows (an .exe file in
699 717 \python24\scripts).
700 718
701 719 * ipapi.py: launch_new_instance, launch entry point needed for the
702 720 egg.
703 721
704 722 2006-01-23 Ville Vainio <vivainio@gmail.com>
705 723
706 724 * Added %cpaste magic for pasting python code
707 725
708 726 2006-01-22 Ville Vainio <vivainio@gmail.com>
709 727
710 728 * Merge from branches/0.7.1 into trunk, revs 1052-1057
711 729
712 730 * Versionstring = 0.7.2.svn
713 731
714 732 * eggsetup.py: A separate script for constructing eggs, creates
715 733 proper launch scripts even on Windows (an .exe file in
716 734 \python24\scripts).
717 735
718 736 * ipapi.py: launch_new_instance, launch entry point needed for the
719 737 egg.
720 738
721 739 2006-01-22 Fernando Perez <Fernando.Perez@colorado.edu>
722 740
723 741 * IPython/OInspect.py (Inspector.pinfo): fix bug where foo?? or
724 742 %pfile foo would print the file for foo even if it was a binary.
725 743 Now, extensions '.so' and '.dll' are skipped.
726 744
727 745 * IPython/Shell.py (MTInteractiveShell.__init__): Fix threading
728 746 bug, where macros would fail in all threaded modes. I'm not 100%
729 747 sure, so I'm going to put out an rc instead of making a release
730 748 today, and wait for feedback for at least a few days.
731 749
732 750 * IPython/iplib.py (handle_normal): fix (finally? somehow I doubt
733 751 it...) the handling of pasting external code with autoindent on.
734 752 To get out of a multiline input, the rule will appear for most
735 753 users unchanged: two blank lines or change the indent level
736 754 proposed by IPython. But there is a twist now: you can
737 755 add/subtract only *one or two spaces*. If you add/subtract three
738 756 or more (unless you completely delete the line), IPython will
739 757 accept that line, and you'll need to enter a second one of pure
740 758 whitespace. I know it sounds complicated, but I can't find a
741 759 different solution that covers all the cases, with the right
742 760 heuristics. Hopefully in actual use, nobody will really notice
743 761 all these strange rules and things will 'just work'.
744 762
745 763 2006-01-21 Fernando Perez <Fernando.Perez@colorado.edu>
746 764
747 765 * IPython/iplib.py (interact): catch exceptions which can be
748 766 triggered asynchronously by signal handlers. Thanks to an
749 767 automatic crash report, submitted by Colin Kingsley
750 768 <tercel-AT-gentoo.org>.
751 769
752 770 2006-01-20 Ville Vainio <vivainio@gmail.com>
753 771
754 772 * Ipython/Extensions/ext_rehashdir.py: Created a usable example
755 773 (%rehashdir, very useful, try it out) of how to extend ipython
756 774 with new magics. Also added Extensions dir to pythonpath to make
757 775 importing extensions easy.
758 776
759 777 * %store now complains when trying to store interactively declared
760 778 classes / instances of those classes.
761 779
762 780 * Extensions/ipy_system_conf.py, UserConfig/ipy_user_conf.py,
763 781 ipmaker.py: Config rehaul. Now ipy_..._conf.py are always imported
764 782 if they exist, and ipy_user_conf.py with some defaults is created for
765 783 the user.
766 784
767 785 * Startup rehashing done by the config file, not InterpreterExec.
768 786 This means system commands are available even without selecting the
769 787 pysh profile. It's the sensible default after all.
770 788
771 789 2006-01-20 Fernando Perez <Fernando.Perez@colorado.edu>
772 790
773 791 * IPython/iplib.py (raw_input): I _think_ I got the pasting of
774 792 multiline code with autoindent on working. But I am really not
775 793 sure, so this needs more testing. Will commit a debug-enabled
776 794 version for now, while I test it some more, so that Ville and
777 795 others may also catch any problems. Also made
778 796 self.indent_current_str() a method, to ensure that there's no
779 797 chance of the indent space count and the corresponding string
780 798 falling out of sync. All code needing the string should just call
781 799 the method.
782 800
783 801 2006-01-18 Fernando Perez <Fernando.Perez@colorado.edu>
784 802
785 803 * IPython/Magic.py (magic_edit): fix check for when users don't
786 804 save their output files, the try/except was in the wrong section.
787 805
788 806 2006-01-17 Fernando Perez <Fernando.Perez@colorado.edu>
789 807
790 808 * IPython/Magic.py (magic_run): fix __file__ global missing from
791 809 script's namespace when executed via %run. After a report by
792 810 Vivian.
793 811
794 812 * IPython/Debugger.py (Pdb.__init__): Fix breakage with '%run -d'
795 813 when using python 2.4. The parent constructor changed in 2.4, and
796 814 we need to track it directly (we can't call it, as it messes up
797 815 readline and tab-completion inside our pdb would stop working).
798 816 After a bug report by R. Bernstein <rocky-AT-panix.com>.
799 817
800 818 2006-01-16 Ville Vainio <vivainio@gmail.com>
801 819
802 820 * Ipython/magic.py: Reverted back to old %edit functionality
803 821 that returns file contents on exit.
804 822
805 823 * IPython/path.py: Added Jason Orendorff's "path" module to
806 824 IPython tree, http://www.jorendorff.com/articles/python/path/.
807 825 You can get path objects conveniently through %sc, and !!, e.g.:
808 826 sc files=ls
809 827 for p in files.paths: # or files.p
810 828 print p,p.mtime
811 829
812 830 * Ipython/iplib.py:"," and ";" autoquoting-upon-autocall
813 831 now work again without considering the exclusion regexp -
814 832 hence, things like ',foo my/path' turn to 'foo("my/path")'
815 833 instead of syntax error.
816 834
817 835
818 836 2006-01-14 Ville Vainio <vivainio@gmail.com>
819 837
820 838 * IPython/ipapi.py (ashook, asmagic, options): Added convenience
821 839 ipapi decorators for python 2.4 users, options() provides access to rc
822 840 data.
823 841
824 842 * IPython/Magic.py (magic_cd): %cd now accepts backslashes
825 843 as path separators (even on Linux ;-). Space character after
826 844 backslash (as yielded by tab completer) is still space;
827 845 "%cd long\ name" works as expected.
828 846
829 847 * IPython/ipapi.py,hooks.py,iplib.py: Hooks now implemented
830 848 as "chain of command", with priority. API stays the same,
831 849 TryNext exception raised by a hook function signals that
832 850 current hook failed and next hook should try handling it, as
833 851 suggested by Walter DΓΆrwald <walter@livinglogic.de>. Walter also
834 852 requested configurable display hook, which is now implemented.
835 853
836 854 2006-01-13 Ville Vainio <vivainio@gmail.com>
837 855
838 856 * IPython/platutils*.py: platform specific utility functions,
839 857 so far only set_term_title is implemented (change terminal
840 858 label in windowing systems). %cd now changes the title to
841 859 current dir.
842 860
843 861 * IPython/Release.py: Added myself to "authors" list,
844 862 had to create new files.
845 863
846 864 * IPython/iplib.py (handle_shell_escape): fixed logical flaw in
847 865 shell escape; not a known bug but had potential to be one in the
848 866 future.
849 867
850 868 * IPython/ipapi.py (added),OInspect.py,iplib.py: "Public"
851 869 extension API for IPython! See the module for usage example. Fix
852 870 OInspect for docstring-less magic functions.
853 871
854 872
855 873 2006-01-13 Fernando Perez <Fernando.Perez@colorado.edu>
856 874
857 875 * IPython/iplib.py (raw_input): temporarily deactivate all
858 876 attempts at allowing pasting of code with autoindent on. It
859 877 introduced bugs (reported by Prabhu) and I can't seem to find a
860 878 robust combination which works in all cases. Will have to revisit
861 879 later.
862 880
863 881 * IPython/genutils.py: remove isspace() function. We've dropped
864 882 2.2 compatibility, so it's OK to use the string method.
865 883
866 884 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
867 885
868 886 * IPython/iplib.py (InteractiveShell.__init__): fix regexp
869 887 matching what NOT to autocall on, to include all python binary
870 888 operators (including things like 'and', 'or', 'is' and 'in').
871 889 Prompted by a bug report on 'foo & bar', but I realized we had
872 890 many more potential bug cases with other operators. The regexp is
873 891 self.re_exclude_auto, it's fairly commented.
874 892
875 893 2006-01-12 Ville Vainio <vivainio@gmail.com>
876 894
877 895 * IPython/iplib.py (make_quoted_expr,handle_shell_escape):
878 896 Prettified and hardened string/backslash quoting with ipsystem(),
879 897 ipalias() and ipmagic(). Now even \ characters are passed to
880 898 %magics, !shell escapes and aliases exactly as they are in the
881 899 ipython command line. Should improve backslash experience,
882 900 particularly in Windows (path delimiter for some commands that
883 901 won't understand '/'), but Unix benefits as well (regexps). %cd
884 902 magic still doesn't support backslash path delimiters, though. Also
885 903 deleted all pretense of supporting multiline command strings in
886 904 !system or %magic commands. Thanks to Jerry McRae for suggestions.
887 905
888 906 * doc/build_doc_instructions.txt added. Documentation on how to
889 907 use doc/update_manual.py, added yesterday. Both files contributed
890 908 by JΓΆrgen Stenarson <jorgen.stenarson-AT-bostream.nu>. This slates
891 909 doc/*.sh for deprecation at a later date.
892 910
893 911 * /ipython.py Added ipython.py to root directory for
894 912 zero-installation (tar xzvf ipython.tgz; cd ipython; python
895 913 ipython.py) and development convenience (no need to keep doing
896 914 "setup.py install" between changes).
897 915
898 916 * Made ! and !! shell escapes work (again) in multiline expressions:
899 917 if 1:
900 918 !ls
901 919 !!ls
902 920
903 921 2006-01-12 Fernando Perez <Fernando.Perez@colorado.edu>
904 922
905 923 * IPython/ipstruct.py (Struct): Rename IPython.Struct to
906 924 IPython.ipstruct, to avoid local shadowing of the stdlib 'struct'
907 925 module in case-insensitive installation. Was causing crashes
908 926 under win32. Closes http://www.scipy.net/roundup/ipython/issue49.
909 927
910 928 * IPython/Magic.py (magic_pycat): Fix pycat, patch by Marien Zwart
911 929 <marienz-AT-gentoo.org>, closes
912 930 http://www.scipy.net/roundup/ipython/issue51.
913 931
914 932 2006-01-11 Fernando Perez <Fernando.Perez@colorado.edu>
915 933
916 934 * IPython/Shell.py (IPShellGTK.on_timer): Finally fix the
917 935 problem of excessive CPU usage under *nix and keyboard lag under
918 936 win32.
919 937
920 938 2006-01-10 *** Released version 0.7.0
921 939
922 940 2006-01-10 Fernando Perez <Fernando.Perez@colorado.edu>
923 941
924 942 * IPython/Release.py (revision): tag version number to 0.7.0,
925 943 ready for release.
926 944
927 945 * IPython/Magic.py (magic_edit): Add print statement to %edit so
928 946 it informs the user of the name of the temp. file used. This can
929 947 help if you decide later to reuse that same file, so you know
930 948 where to copy the info from.
931 949
932 950 2006-01-09 Fernando Perez <Fernando.Perez@colorado.edu>
933 951
934 952 * setup_bdist_egg.py: little script to build an egg. Added
935 953 support in the release tools as well.
936 954
937 955 2006-01-08 Fernando Perez <Fernando.Perez@colorado.edu>
938 956
939 957 * IPython/Shell.py (IPShellWX.__init__): add support for WXPython
940 958 version selection (new -wxversion command line and ipythonrc
941 959 parameter). Patch contributed by Arnd Baecker
942 960 <arnd.baecker-AT-web.de>.
943 961
944 962 * IPython/iplib.py (embed_mainloop): fix tab-completion in
945 963 embedded instances, for variables defined at the interactive
946 964 prompt of the embedded ipython. Reported by Arnd.
947 965
948 966 * IPython/Magic.py (magic_autocall): Fix %autocall magic. Now
949 967 it can be used as a (stateful) toggle, or with a direct parameter.
950 968
951 969 * IPython/ultraTB.py (_fixed_getinnerframes): remove debug assert which
952 970 could be triggered in certain cases and cause the traceback
953 971 printer not to work.
954 972
955 973 2006-01-07 Fernando Perez <Fernando.Perez@colorado.edu>
956 974
957 975 * IPython/iplib.py (_should_recompile): Small fix, closes
958 976 http://www.scipy.net/roundup/ipython/issue48. Patch by Scott.
959 977
960 978 2006-01-04 Fernando Perez <Fernando.Perez@colorado.edu>
961 979
962 980 * IPython/Shell.py (IPShellGTK.mainloop): fix bug in the GTK
963 981 backend for matplotlib (100% cpu utiliziation). Thanks to Charlie
964 982 Moad for help with tracking it down.
965 983
966 984 * IPython/iplib.py (handle_auto): fix autocall handling for
967 985 objects which support BOTH __getitem__ and __call__ (so that f [x]
968 986 is left alone, instead of becoming f([x]) automatically).
969 987
970 988 * IPython/Magic.py (magic_cd): fix crash when cd -b was used.
971 989 Ville's patch.
972 990
973 991 2006-01-03 Fernando Perez <Fernando.Perez@colorado.edu>
974 992
975 993 * IPython/iplib.py (handle_auto): changed autocall semantics to
976 994 include 'smart' mode, where the autocall transformation is NOT
977 995 applied if there are no arguments on the line. This allows you to
978 996 just type 'foo' if foo is a callable to see its internal form,
979 997 instead of having it called with no arguments (typically a
980 998 mistake). The old 'full' autocall still exists: for that, you
981 999 need to set the 'autocall' parameter to 2 in your ipythonrc file.
982 1000
983 1001 * IPython/completer.py (Completer.attr_matches): add
984 1002 tab-completion support for Enthoughts' traits. After a report by
985 1003 Arnd and a patch by Prabhu.
986 1004
987 1005 2006-01-02 Fernando Perez <Fernando.Perez@colorado.edu>
988 1006
989 1007 * IPython/ultraTB.py (_fixed_getinnerframes): added Alex
990 1008 Schmolck's patch to fix inspect.getinnerframes().
991 1009
992 1010 * IPython/iplib.py (InteractiveShell.__init__): significant fixes
993 1011 for embedded instances, regarding handling of namespaces and items
994 1012 added to the __builtin__ one. Multiple embedded instances and
995 1013 recursive embeddings should work better now (though I'm not sure
996 1014 I've got all the corner cases fixed, that code is a bit of a brain
997 1015 twister).
998 1016
999 1017 * IPython/Magic.py (magic_edit): added support to edit in-memory
1000 1018 macros (automatically creates the necessary temp files). %edit
1001 1019 also doesn't return the file contents anymore, it's just noise.
1002 1020
1003 1021 * IPython/completer.py (Completer.attr_matches): revert change to
1004 1022 complete only on attributes listed in __all__. I realized it
1005 1023 cripples the tab-completion system as a tool for exploring the
1006 1024 internals of unknown libraries (it renders any non-__all__
1007 1025 attribute off-limits). I got bit by this when trying to see
1008 1026 something inside the dis module.
1009 1027
1010 1028 2005-12-31 Fernando Perez <Fernando.Perez@colorado.edu>
1011 1029
1012 1030 * IPython/iplib.py (InteractiveShell.__init__): add .meta
1013 1031 namespace for users and extension writers to hold data in. This
1014 1032 follows the discussion in
1015 1033 http://projects.scipy.org/ipython/ipython/wiki/RefactoringIPython.
1016 1034
1017 1035 * IPython/completer.py (IPCompleter.complete): small patch to help
1018 1036 tab-completion under Emacs, after a suggestion by John Barnard
1019 1037 <barnarj-AT-ccf.org>.
1020 1038
1021 1039 * IPython/Magic.py (Magic.extract_input_slices): added support for
1022 1040 the slice notation in magics to use N-M to represent numbers N...M
1023 1041 (closed endpoints). This is used by %macro and %save.
1024 1042
1025 1043 * IPython/completer.py (Completer.attr_matches): for modules which
1026 1044 define __all__, complete only on those. After a patch by Jeffrey
1027 1045 Collins <jcollins_boulder-AT-earthlink.net>. Also, clean up and
1028 1046 speed up this routine.
1029 1047
1030 1048 * IPython/Logger.py (Logger.log): fix a history handling bug. I
1031 1049 don't know if this is the end of it, but the behavior now is
1032 1050 certainly much more correct. Note that coupled with macros,
1033 1051 slightly surprising (at first) behavior may occur: a macro will in
1034 1052 general expand to multiple lines of input, so upon exiting, the
1035 1053 in/out counters will both be bumped by the corresponding amount
1036 1054 (as if the macro's contents had been typed interactively). Typing
1037 1055 %hist will reveal the intermediate (silently processed) lines.
1038 1056
1039 1057 * IPython/Magic.py (magic_run): fix a subtle bug which could cause
1040 1058 pickle to fail (%run was overwriting __main__ and not restoring
1041 1059 it, but pickle relies on __main__ to operate).
1042 1060
1043 1061 * IPython/iplib.py (InteractiveShell): fix pdb calling: I'm now
1044 1062 using properties, but forgot to make the main InteractiveShell
1045 1063 class a new-style class. Properties fail silently, and
1046 1064 mysteriously, with old-style class (getters work, but
1047 1065 setters don't do anything).
1048 1066
1049 1067 2005-12-30 Fernando Perez <Fernando.Perez@colorado.edu>
1050 1068
1051 1069 * IPython/Magic.py (magic_history): fix history reporting bug (I
1052 1070 know some nasties are still there, I just can't seem to find a
1053 1071 reproducible test case to track them down; the input history is
1054 1072 falling out of sync...)
1055 1073
1056 1074 * IPython/iplib.py (handle_shell_escape): fix bug where both
1057 1075 aliases and system accesses where broken for indented code (such
1058 1076 as loops).
1059 1077
1060 1078 * IPython/genutils.py (shell): fix small but critical bug for
1061 1079 win32 system access.
1062 1080
1063 1081 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
1064 1082
1065 1083 * IPython/iplib.py (showtraceback): remove use of the
1066 1084 sys.last_{type/value/traceback} structures, which are non
1067 1085 thread-safe.
1068 1086 (_prefilter): change control flow to ensure that we NEVER
1069 1087 introspect objects when autocall is off. This will guarantee that
1070 1088 having an input line of the form 'x.y', where access to attribute
1071 1089 'y' has side effects, doesn't trigger the side effect TWICE. It
1072 1090 is important to note that, with autocall on, these side effects
1073 1091 can still happen.
1074 1092 (ipsystem): new builtin, to complete the ip{magic/alias/system}
1075 1093 trio. IPython offers these three kinds of special calls which are
1076 1094 not python code, and it's a good thing to have their call method
1077 1095 be accessible as pure python functions (not just special syntax at
1078 1096 the command line). It gives us a better internal implementation
1079 1097 structure, as well as exposing these for user scripting more
1080 1098 cleanly.
1081 1099
1082 1100 * IPython/macro.py (Macro.__init__): moved macros to a standalone
1083 1101 file. Now that they'll be more likely to be used with the
1084 1102 persistance system (%store), I want to make sure their module path
1085 1103 doesn't change in the future, so that we don't break things for
1086 1104 users' persisted data.
1087 1105
1088 1106 * IPython/iplib.py (autoindent_update): move indentation
1089 1107 management into the _text_ processing loop, not the keyboard
1090 1108 interactive one. This is necessary to correctly process non-typed
1091 1109 multiline input (such as macros).
1092 1110
1093 1111 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
1094 1112 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
1095 1113 which was producing problems in the resulting manual.
1096 1114 (magic_whos): improve reporting of instances (show their class,
1097 1115 instead of simply printing 'instance' which isn't terribly
1098 1116 informative).
1099 1117
1100 1118 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
1101 1119 (minor mods) to support network shares under win32.
1102 1120
1103 1121 * IPython/winconsole.py (get_console_size): add new winconsole
1104 1122 module and fixes to page_dumb() to improve its behavior under
1105 1123 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
1106 1124
1107 1125 * IPython/Magic.py (Macro): simplified Macro class to just
1108 1126 subclass list. We've had only 2.2 compatibility for a very long
1109 1127 time, yet I was still avoiding subclassing the builtin types. No
1110 1128 more (I'm also starting to use properties, though I won't shift to
1111 1129 2.3-specific features quite yet).
1112 1130 (magic_store): added Ville's patch for lightweight variable
1113 1131 persistence, after a request on the user list by Matt Wilkie
1114 1132 <maphew-AT-gmail.com>. The new %store magic's docstring has full
1115 1133 details.
1116 1134
1117 1135 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1118 1136 changed the default logfile name from 'ipython.log' to
1119 1137 'ipython_log.py'. These logs are real python files, and now that
1120 1138 we have much better multiline support, people are more likely to
1121 1139 want to use them as such. Might as well name them correctly.
1122 1140
1123 1141 * IPython/Magic.py: substantial cleanup. While we can't stop
1124 1142 using magics as mixins, due to the existing customizations 'out
1125 1143 there' which rely on the mixin naming conventions, at least I
1126 1144 cleaned out all cross-class name usage. So once we are OK with
1127 1145 breaking compatibility, the two systems can be separated.
1128 1146
1129 1147 * IPython/Logger.py: major cleanup. This one is NOT a mixin
1130 1148 anymore, and the class is a fair bit less hideous as well. New
1131 1149 features were also introduced: timestamping of input, and logging
1132 1150 of output results. These are user-visible with the -t and -o
1133 1151 options to %logstart. Closes
1134 1152 http://www.scipy.net/roundup/ipython/issue11 and a request by
1135 1153 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
1136 1154
1137 1155 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
1138 1156
1139 1157 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
1140 1158 better handle backslashes in paths. See the thread 'More Windows
1141 1159 questions part 2 - \/ characters revisited' on the iypthon user
1142 1160 list:
1143 1161 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
1144 1162
1145 1163 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
1146 1164
1147 1165 (InteractiveShell.__init__): change threaded shells to not use the
1148 1166 ipython crash handler. This was causing more problems than not,
1149 1167 as exceptions in the main thread (GUI code, typically) would
1150 1168 always show up as a 'crash', when they really weren't.
1151 1169
1152 1170 The colors and exception mode commands (%colors/%xmode) have been
1153 1171 synchronized to also take this into account, so users can get
1154 1172 verbose exceptions for their threaded code as well. I also added
1155 1173 support for activating pdb inside this exception handler as well,
1156 1174 so now GUI authors can use IPython's enhanced pdb at runtime.
1157 1175
1158 1176 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
1159 1177 true by default, and add it to the shipped ipythonrc file. Since
1160 1178 this asks the user before proceeding, I think it's OK to make it
1161 1179 true by default.
1162 1180
1163 1181 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
1164 1182 of the previous special-casing of input in the eval loop. I think
1165 1183 this is cleaner, as they really are commands and shouldn't have
1166 1184 a special role in the middle of the core code.
1167 1185
1168 1186 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
1169 1187
1170 1188 * IPython/iplib.py (edit_syntax_error): added support for
1171 1189 automatically reopening the editor if the file had a syntax error
1172 1190 in it. Thanks to scottt who provided the patch at:
1173 1191 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
1174 1192 version committed).
1175 1193
1176 1194 * IPython/iplib.py (handle_normal): add suport for multi-line
1177 1195 input with emtpy lines. This fixes
1178 1196 http://www.scipy.net/roundup/ipython/issue43 and a similar
1179 1197 discussion on the user list.
1180 1198
1181 1199 WARNING: a behavior change is necessarily introduced to support
1182 1200 blank lines: now a single blank line with whitespace does NOT
1183 1201 break the input loop, which means that when autoindent is on, by
1184 1202 default hitting return on the next (indented) line does NOT exit.
1185 1203
1186 1204 Instead, to exit a multiline input you can either have:
1187 1205
1188 1206 - TWO whitespace lines (just hit return again), or
1189 1207 - a single whitespace line of a different length than provided
1190 1208 by the autoindent (add or remove a space).
1191 1209
1192 1210 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
1193 1211 module to better organize all readline-related functionality.
1194 1212 I've deleted FlexCompleter and put all completion clases here.
1195 1213
1196 1214 * IPython/iplib.py (raw_input): improve indentation management.
1197 1215 It is now possible to paste indented code with autoindent on, and
1198 1216 the code is interpreted correctly (though it still looks bad on
1199 1217 screen, due to the line-oriented nature of ipython).
1200 1218 (MagicCompleter.complete): change behavior so that a TAB key on an
1201 1219 otherwise empty line actually inserts a tab, instead of completing
1202 1220 on the entire global namespace. This makes it easier to use the
1203 1221 TAB key for indentation. After a request by Hans Meine
1204 1222 <hans_meine-AT-gmx.net>
1205 1223 (_prefilter): add support so that typing plain 'exit' or 'quit'
1206 1224 does a sensible thing. Originally I tried to deviate as little as
1207 1225 possible from the default python behavior, but even that one may
1208 1226 change in this direction (thread on python-dev to that effect).
1209 1227 Regardless, ipython should do the right thing even if CPython's
1210 1228 '>>>' prompt doesn't.
1211 1229 (InteractiveShell): removed subclassing code.InteractiveConsole
1212 1230 class. By now we'd overridden just about all of its methods: I've
1213 1231 copied the remaining two over, and now ipython is a standalone
1214 1232 class. This will provide a clearer picture for the chainsaw
1215 1233 branch refactoring.
1216 1234
1217 1235 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
1218 1236
1219 1237 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
1220 1238 failures for objects which break when dir() is called on them.
1221 1239
1222 1240 * IPython/FlexCompleter.py (Completer.__init__): Added support for
1223 1241 distinct local and global namespaces in the completer API. This
1224 1242 change allows us to properly handle completion with distinct
1225 1243 scopes, including in embedded instances (this had never really
1226 1244 worked correctly).
1227 1245
1228 1246 Note: this introduces a change in the constructor for
1229 1247 MagicCompleter, as a new global_namespace parameter is now the
1230 1248 second argument (the others were bumped one position).
1231 1249
1232 1250 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
1233 1251
1234 1252 * IPython/iplib.py (embed_mainloop): fix tab-completion in
1235 1253 embedded instances (which can be done now thanks to Vivian's
1236 1254 frame-handling fixes for pdb).
1237 1255 (InteractiveShell.__init__): Fix namespace handling problem in
1238 1256 embedded instances. We were overwriting __main__ unconditionally,
1239 1257 and this should only be done for 'full' (non-embedded) IPython;
1240 1258 embedded instances must respect the caller's __main__. Thanks to
1241 1259 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
1242 1260
1243 1261 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
1244 1262
1245 1263 * setup.py: added download_url to setup(). This registers the
1246 1264 download address at PyPI, which is not only useful to humans
1247 1265 browsing the site, but is also picked up by setuptools (the Eggs
1248 1266 machinery). Thanks to Ville and R. Kern for the info/discussion
1249 1267 on this.
1250 1268
1251 1269 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
1252 1270
1253 1271 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
1254 1272 This brings a lot of nice functionality to the pdb mode, which now
1255 1273 has tab-completion, syntax highlighting, and better stack handling
1256 1274 than before. Many thanks to Vivian De Smedt
1257 1275 <vivian-AT-vdesmedt.com> for the original patches.
1258 1276
1259 1277 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
1260 1278
1261 1279 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
1262 1280 sequence to consistently accept the banner argument. The
1263 1281 inconsistency was tripping SAGE, thanks to Gary Zablackis
1264 1282 <gzabl-AT-yahoo.com> for the report.
1265 1283
1266 1284 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
1267 1285
1268 1286 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1269 1287 Fix bug where a naked 'alias' call in the ipythonrc file would
1270 1288 cause a crash. Bug reported by Jorgen Stenarson.
1271 1289
1272 1290 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
1273 1291
1274 1292 * IPython/ipmaker.py (make_IPython): cleanups which should improve
1275 1293 startup time.
1276 1294
1277 1295 * IPython/iplib.py (runcode): my globals 'fix' for embedded
1278 1296 instances had introduced a bug with globals in normal code. Now
1279 1297 it's working in all cases.
1280 1298
1281 1299 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
1282 1300 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
1283 1301 has been introduced to set the default case sensitivity of the
1284 1302 searches. Users can still select either mode at runtime on a
1285 1303 per-search basis.
1286 1304
1287 1305 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
1288 1306
1289 1307 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
1290 1308 attributes in wildcard searches for subclasses. Modified version
1291 1309 of a patch by Jorgen.
1292 1310
1293 1311 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
1294 1312
1295 1313 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
1296 1314 embedded instances. I added a user_global_ns attribute to the
1297 1315 InteractiveShell class to handle this.
1298 1316
1299 1317 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
1300 1318
1301 1319 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
1302 1320 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
1303 1321 (reported under win32, but may happen also in other platforms).
1304 1322 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
1305 1323
1306 1324 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
1307 1325
1308 1326 * IPython/Magic.py (magic_psearch): new support for wildcard
1309 1327 patterns. Now, typing ?a*b will list all names which begin with a
1310 1328 and end in b, for example. The %psearch magic has full
1311 1329 docstrings. Many thanks to JΓΆrgen Stenarson
1312 1330 <jorgen.stenarson-AT-bostream.nu>, author of the patches
1313 1331 implementing this functionality.
1314 1332
1315 1333 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
1316 1334
1317 1335 * Manual: fixed long-standing annoyance of double-dashes (as in
1318 1336 --prefix=~, for example) being stripped in the HTML version. This
1319 1337 is a latex2html bug, but a workaround was provided. Many thanks
1320 1338 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
1321 1339 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
1322 1340 rolling. This seemingly small issue had tripped a number of users
1323 1341 when first installing, so I'm glad to see it gone.
1324 1342
1325 1343 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
1326 1344
1327 1345 * IPython/Extensions/numeric_formats.py: fix missing import,
1328 1346 reported by Stephen Walton.
1329 1347
1330 1348 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
1331 1349
1332 1350 * IPython/demo.py: finish demo module, fully documented now.
1333 1351
1334 1352 * IPython/genutils.py (file_read): simple little utility to read a
1335 1353 file and ensure it's closed afterwards.
1336 1354
1337 1355 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
1338 1356
1339 1357 * IPython/demo.py (Demo.__init__): added support for individually
1340 1358 tagging blocks for automatic execution.
1341 1359
1342 1360 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
1343 1361 syntax-highlighted python sources, requested by John.
1344 1362
1345 1363 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
1346 1364
1347 1365 * IPython/demo.py (Demo.again): fix bug where again() blocks after
1348 1366 finishing.
1349 1367
1350 1368 * IPython/genutils.py (shlex_split): moved from Magic to here,
1351 1369 where all 2.2 compatibility stuff lives. I needed it for demo.py.
1352 1370
1353 1371 * IPython/demo.py (Demo.__init__): added support for silent
1354 1372 blocks, improved marks as regexps, docstrings written.
1355 1373 (Demo.__init__): better docstring, added support for sys.argv.
1356 1374
1357 1375 * IPython/genutils.py (marquee): little utility used by the demo
1358 1376 code, handy in general.
1359 1377
1360 1378 * IPython/demo.py (Demo.__init__): new class for interactive
1361 1379 demos. Not documented yet, I just wrote it in a hurry for
1362 1380 scipy'05. Will docstring later.
1363 1381
1364 1382 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
1365 1383
1366 1384 * IPython/Shell.py (sigint_handler): Drastic simplification which
1367 1385 also seems to make Ctrl-C work correctly across threads! This is
1368 1386 so simple, that I can't beleive I'd missed it before. Needs more
1369 1387 testing, though.
1370 1388 (KBINT): Never mind, revert changes. I'm sure I'd tried something
1371 1389 like this before...
1372 1390
1373 1391 * IPython/genutils.py (get_home_dir): add protection against
1374 1392 non-dirs in win32 registry.
1375 1393
1376 1394 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
1377 1395 bug where dict was mutated while iterating (pysh crash).
1378 1396
1379 1397 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
1380 1398
1381 1399 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
1382 1400 spurious newlines added by this routine. After a report by
1383 1401 F. Mantegazza.
1384 1402
1385 1403 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
1386 1404
1387 1405 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
1388 1406 calls. These were a leftover from the GTK 1.x days, and can cause
1389 1407 problems in certain cases (after a report by John Hunter).
1390 1408
1391 1409 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
1392 1410 os.getcwd() fails at init time. Thanks to patch from David Remahl
1393 1411 <chmod007-AT-mac.com>.
1394 1412 (InteractiveShell.__init__): prevent certain special magics from
1395 1413 being shadowed by aliases. Closes
1396 1414 http://www.scipy.net/roundup/ipython/issue41.
1397 1415
1398 1416 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
1399 1417
1400 1418 * IPython/iplib.py (InteractiveShell.complete): Added new
1401 1419 top-level completion method to expose the completion mechanism
1402 1420 beyond readline-based environments.
1403 1421
1404 1422 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
1405 1423
1406 1424 * tools/ipsvnc (svnversion): fix svnversion capture.
1407 1425
1408 1426 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
1409 1427 attribute to self, which was missing. Before, it was set by a
1410 1428 routine which in certain cases wasn't being called, so the
1411 1429 instance could end up missing the attribute. This caused a crash.
1412 1430 Closes http://www.scipy.net/roundup/ipython/issue40.
1413 1431
1414 1432 2005-08-16 Fernando Perez <fperez@colorado.edu>
1415 1433
1416 1434 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
1417 1435 contains non-string attribute. Closes
1418 1436 http://www.scipy.net/roundup/ipython/issue38.
1419 1437
1420 1438 2005-08-14 Fernando Perez <fperez@colorado.edu>
1421 1439
1422 1440 * tools/ipsvnc: Minor improvements, to add changeset info.
1423 1441
1424 1442 2005-08-12 Fernando Perez <fperez@colorado.edu>
1425 1443
1426 1444 * IPython/iplib.py (runsource): remove self.code_to_run_src
1427 1445 attribute. I realized this is nothing more than
1428 1446 '\n'.join(self.buffer), and having the same data in two different
1429 1447 places is just asking for synchronization bugs. This may impact
1430 1448 people who have custom exception handlers, so I need to warn
1431 1449 ipython-dev about it (F. Mantegazza may use them).
1432 1450
1433 1451 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
1434 1452
1435 1453 * IPython/genutils.py: fix 2.2 compatibility (generators)
1436 1454
1437 1455 2005-07-18 Fernando Perez <fperez@colorado.edu>
1438 1456
1439 1457 * IPython/genutils.py (get_home_dir): fix to help users with
1440 1458 invalid $HOME under win32.
1441 1459
1442 1460 2005-07-17 Fernando Perez <fperez@colorado.edu>
1443 1461
1444 1462 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
1445 1463 some old hacks and clean up a bit other routines; code should be
1446 1464 simpler and a bit faster.
1447 1465
1448 1466 * IPython/iplib.py (interact): removed some last-resort attempts
1449 1467 to survive broken stdout/stderr. That code was only making it
1450 1468 harder to abstract out the i/o (necessary for gui integration),
1451 1469 and the crashes it could prevent were extremely rare in practice
1452 1470 (besides being fully user-induced in a pretty violent manner).
1453 1471
1454 1472 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
1455 1473 Nothing major yet, but the code is simpler to read; this should
1456 1474 make it easier to do more serious modifications in the future.
1457 1475
1458 1476 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
1459 1477 which broke in .15 (thanks to a report by Ville).
1460 1478
1461 1479 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
1462 1480 be quite correct, I know next to nothing about unicode). This
1463 1481 will allow unicode strings to be used in prompts, amongst other
1464 1482 cases. It also will prevent ipython from crashing when unicode
1465 1483 shows up unexpectedly in many places. If ascii encoding fails, we
1466 1484 assume utf_8. Currently the encoding is not a user-visible
1467 1485 setting, though it could be made so if there is demand for it.
1468 1486
1469 1487 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
1470 1488
1471 1489 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
1472 1490
1473 1491 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
1474 1492
1475 1493 * IPython/genutils.py: Add 2.2 compatibility here, so all other
1476 1494 code can work transparently for 2.2/2.3.
1477 1495
1478 1496 2005-07-16 Fernando Perez <fperez@colorado.edu>
1479 1497
1480 1498 * IPython/ultraTB.py (ExceptionColors): Make a global variable
1481 1499 out of the color scheme table used for coloring exception
1482 1500 tracebacks. This allows user code to add new schemes at runtime.
1483 1501 This is a minimally modified version of the patch at
1484 1502 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
1485 1503 for the contribution.
1486 1504
1487 1505 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
1488 1506 slightly modified version of the patch in
1489 1507 http://www.scipy.net/roundup/ipython/issue34, which also allows me
1490 1508 to remove the previous try/except solution (which was costlier).
1491 1509 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
1492 1510
1493 1511 2005-06-08 Fernando Perez <fperez@colorado.edu>
1494 1512
1495 1513 * IPython/iplib.py (write/write_err): Add methods to abstract all
1496 1514 I/O a bit more.
1497 1515
1498 1516 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
1499 1517 warning, reported by Aric Hagberg, fix by JD Hunter.
1500 1518
1501 1519 2005-06-02 *** Released version 0.6.15
1502 1520
1503 1521 2005-06-01 Fernando Perez <fperez@colorado.edu>
1504 1522
1505 1523 * IPython/iplib.py (MagicCompleter.file_matches): Fix
1506 1524 tab-completion of filenames within open-quoted strings. Note that
1507 1525 this requires that in ~/.ipython/ipythonrc, users change the
1508 1526 readline delimiters configuration to read:
1509 1527
1510 1528 readline_remove_delims -/~
1511 1529
1512 1530
1513 1531 2005-05-31 *** Released version 0.6.14
1514 1532
1515 1533 2005-05-29 Fernando Perez <fperez@colorado.edu>
1516 1534
1517 1535 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
1518 1536 with files not on the filesystem. Reported by Eliyahu Sandler
1519 1537 <eli@gondolin.net>
1520 1538
1521 1539 2005-05-22 Fernando Perez <fperez@colorado.edu>
1522 1540
1523 1541 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
1524 1542 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
1525 1543
1526 1544 2005-05-19 Fernando Perez <fperez@colorado.edu>
1527 1545
1528 1546 * IPython/iplib.py (safe_execfile): close a file which could be
1529 1547 left open (causing problems in win32, which locks open files).
1530 1548 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
1531 1549
1532 1550 2005-05-18 Fernando Perez <fperez@colorado.edu>
1533 1551
1534 1552 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
1535 1553 keyword arguments correctly to safe_execfile().
1536 1554
1537 1555 2005-05-13 Fernando Perez <fperez@colorado.edu>
1538 1556
1539 1557 * ipython.1: Added info about Qt to manpage, and threads warning
1540 1558 to usage page (invoked with --help).
1541 1559
1542 1560 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
1543 1561 new matcher (it goes at the end of the priority list) to do
1544 1562 tab-completion on named function arguments. Submitted by George
1545 1563 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
1546 1564 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
1547 1565 for more details.
1548 1566
1549 1567 * IPython/Magic.py (magic_run): Added new -e flag to ignore
1550 1568 SystemExit exceptions in the script being run. Thanks to a report
1551 1569 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
1552 1570 producing very annoying behavior when running unit tests.
1553 1571
1554 1572 2005-05-12 Fernando Perez <fperez@colorado.edu>
1555 1573
1556 1574 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
1557 1575 which I'd broken (again) due to a changed regexp. In the process,
1558 1576 added ';' as an escape to auto-quote the whole line without
1559 1577 splitting its arguments. Thanks to a report by Jerry McRae
1560 1578 <qrs0xyc02-AT-sneakemail.com>.
1561 1579
1562 1580 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
1563 1581 possible crashes caused by a TokenError. Reported by Ed Schofield
1564 1582 <schofield-AT-ftw.at>.
1565 1583
1566 1584 2005-05-06 Fernando Perez <fperez@colorado.edu>
1567 1585
1568 1586 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
1569 1587
1570 1588 2005-04-29 Fernando Perez <fperez@colorado.edu>
1571 1589
1572 1590 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
1573 1591 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
1574 1592 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
1575 1593 which provides support for Qt interactive usage (similar to the
1576 1594 existing one for WX and GTK). This had been often requested.
1577 1595
1578 1596 2005-04-14 *** Released version 0.6.13
1579 1597
1580 1598 2005-04-08 Fernando Perez <fperez@colorado.edu>
1581 1599
1582 1600 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
1583 1601 from _ofind, which gets called on almost every input line. Now,
1584 1602 we only try to get docstrings if they are actually going to be
1585 1603 used (the overhead of fetching unnecessary docstrings can be
1586 1604 noticeable for certain objects, such as Pyro proxies).
1587 1605
1588 1606 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
1589 1607 for completers. For some reason I had been passing them the state
1590 1608 variable, which completers never actually need, and was in
1591 1609 conflict with the rlcompleter API. Custom completers ONLY need to
1592 1610 take the text parameter.
1593 1611
1594 1612 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
1595 1613 work correctly in pysh. I've also moved all the logic which used
1596 1614 to be in pysh.py here, which will prevent problems with future
1597 1615 upgrades. However, this time I must warn users to update their
1598 1616 pysh profile to include the line
1599 1617
1600 1618 import_all IPython.Extensions.InterpreterExec
1601 1619
1602 1620 because otherwise things won't work for them. They MUST also
1603 1621 delete pysh.py and the line
1604 1622
1605 1623 execfile pysh.py
1606 1624
1607 1625 from their ipythonrc-pysh.
1608 1626
1609 1627 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
1610 1628 robust in the face of objects whose dir() returns non-strings
1611 1629 (which it shouldn't, but some broken libs like ITK do). Thanks to
1612 1630 a patch by John Hunter (implemented differently, though). Also
1613 1631 minor improvements by using .extend instead of + on lists.
1614 1632
1615 1633 * pysh.py:
1616 1634
1617 1635 2005-04-06 Fernando Perez <fperez@colorado.edu>
1618 1636
1619 1637 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
1620 1638 by default, so that all users benefit from it. Those who don't
1621 1639 want it can still turn it off.
1622 1640
1623 1641 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
1624 1642 config file, I'd forgotten about this, so users were getting it
1625 1643 off by default.
1626 1644
1627 1645 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
1628 1646 consistency. Now magics can be called in multiline statements,
1629 1647 and python variables can be expanded in magic calls via $var.
1630 1648 This makes the magic system behave just like aliases or !system
1631 1649 calls.
1632 1650
1633 1651 2005-03-28 Fernando Perez <fperez@colorado.edu>
1634 1652
1635 1653 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
1636 1654 expensive string additions for building command. Add support for
1637 1655 trailing ';' when autocall is used.
1638 1656
1639 1657 2005-03-26 Fernando Perez <fperez@colorado.edu>
1640 1658
1641 1659 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
1642 1660 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
1643 1661 ipython.el robust against prompts with any number of spaces
1644 1662 (including 0) after the ':' character.
1645 1663
1646 1664 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
1647 1665 continuation prompt, which misled users to think the line was
1648 1666 already indented. Closes debian Bug#300847, reported to me by
1649 1667 Norbert Tretkowski <tretkowski-AT-inittab.de>.
1650 1668
1651 1669 2005-03-23 Fernando Perez <fperez@colorado.edu>
1652 1670
1653 1671 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
1654 1672 properly aligned if they have embedded newlines.
1655 1673
1656 1674 * IPython/iplib.py (runlines): Add a public method to expose
1657 1675 IPython's code execution machinery, so that users can run strings
1658 1676 as if they had been typed at the prompt interactively.
1659 1677 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
1660 1678 methods which can call the system shell, but with python variable
1661 1679 expansion. The three such methods are: __IPYTHON__.system,
1662 1680 .getoutput and .getoutputerror. These need to be documented in a
1663 1681 'public API' section (to be written) of the manual.
1664 1682
1665 1683 2005-03-20 Fernando Perez <fperez@colorado.edu>
1666 1684
1667 1685 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
1668 1686 for custom exception handling. This is quite powerful, and it
1669 1687 allows for user-installable exception handlers which can trap
1670 1688 custom exceptions at runtime and treat them separately from
1671 1689 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
1672 1690 Mantegazza <mantegazza-AT-ill.fr>.
1673 1691 (InteractiveShell.set_custom_completer): public API function to
1674 1692 add new completers at runtime.
1675 1693
1676 1694 2005-03-19 Fernando Perez <fperez@colorado.edu>
1677 1695
1678 1696 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
1679 1697 allow objects which provide their docstrings via non-standard
1680 1698 mechanisms (like Pyro proxies) to still be inspected by ipython's
1681 1699 ? system.
1682 1700
1683 1701 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
1684 1702 automatic capture system. I tried quite hard to make it work
1685 1703 reliably, and simply failed. I tried many combinations with the
1686 1704 subprocess module, but eventually nothing worked in all needed
1687 1705 cases (not blocking stdin for the child, duplicating stdout
1688 1706 without blocking, etc). The new %sc/%sx still do capture to these
1689 1707 magical list/string objects which make shell use much more
1690 1708 conveninent, so not all is lost.
1691 1709
1692 1710 XXX - FIX MANUAL for the change above!
1693 1711
1694 1712 (runsource): I copied code.py's runsource() into ipython to modify
1695 1713 it a bit. Now the code object and source to be executed are
1696 1714 stored in ipython. This makes this info accessible to third-party
1697 1715 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
1698 1716 Mantegazza <mantegazza-AT-ill.fr>.
1699 1717
1700 1718 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
1701 1719 history-search via readline (like C-p/C-n). I'd wanted this for a
1702 1720 long time, but only recently found out how to do it. For users
1703 1721 who already have their ipythonrc files made and want this, just
1704 1722 add:
1705 1723
1706 1724 readline_parse_and_bind "\e[A": history-search-backward
1707 1725 readline_parse_and_bind "\e[B": history-search-forward
1708 1726
1709 1727 2005-03-18 Fernando Perez <fperez@colorado.edu>
1710 1728
1711 1729 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
1712 1730 LSString and SList classes which allow transparent conversions
1713 1731 between list mode and whitespace-separated string.
1714 1732 (magic_r): Fix recursion problem in %r.
1715 1733
1716 1734 * IPython/genutils.py (LSString): New class to be used for
1717 1735 automatic storage of the results of all alias/system calls in _o
1718 1736 and _e (stdout/err). These provide a .l/.list attribute which
1719 1737 does automatic splitting on newlines. This means that for most
1720 1738 uses, you'll never need to do capturing of output with %sc/%sx
1721 1739 anymore, since ipython keeps this always done for you. Note that
1722 1740 only the LAST results are stored, the _o/e variables are
1723 1741 overwritten on each call. If you need to save their contents
1724 1742 further, simply bind them to any other name.
1725 1743
1726 1744 2005-03-17 Fernando Perez <fperez@colorado.edu>
1727 1745
1728 1746 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
1729 1747 prompt namespace handling.
1730 1748
1731 1749 2005-03-16 Fernando Perez <fperez@colorado.edu>
1732 1750
1733 1751 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
1734 1752 classic prompts to be '>>> ' (final space was missing, and it
1735 1753 trips the emacs python mode).
1736 1754 (BasePrompt.__str__): Added safe support for dynamic prompt
1737 1755 strings. Now you can set your prompt string to be '$x', and the
1738 1756 value of x will be printed from your interactive namespace. The
1739 1757 interpolation syntax includes the full Itpl support, so
1740 1758 ${foo()+x+bar()} is a valid prompt string now, and the function
1741 1759 calls will be made at runtime.
1742 1760
1743 1761 2005-03-15 Fernando Perez <fperez@colorado.edu>
1744 1762
1745 1763 * IPython/Magic.py (magic_history): renamed %hist to %history, to
1746 1764 avoid name clashes in pylab. %hist still works, it just forwards
1747 1765 the call to %history.
1748 1766
1749 1767 2005-03-02 *** Released version 0.6.12
1750 1768
1751 1769 2005-03-02 Fernando Perez <fperez@colorado.edu>
1752 1770
1753 1771 * IPython/iplib.py (handle_magic): log magic calls properly as
1754 1772 ipmagic() function calls.
1755 1773
1756 1774 * IPython/Magic.py (magic_time): Improved %time to support
1757 1775 statements and provide wall-clock as well as CPU time.
1758 1776
1759 1777 2005-02-27 Fernando Perez <fperez@colorado.edu>
1760 1778
1761 1779 * IPython/hooks.py: New hooks module, to expose user-modifiable
1762 1780 IPython functionality in a clean manner. For now only the editor
1763 1781 hook is actually written, and other thigns which I intend to turn
1764 1782 into proper hooks aren't yet there. The display and prefilter
1765 1783 stuff, for example, should be hooks. But at least now the
1766 1784 framework is in place, and the rest can be moved here with more
1767 1785 time later. IPython had had a .hooks variable for a long time for
1768 1786 this purpose, but I'd never actually used it for anything.
1769 1787
1770 1788 2005-02-26 Fernando Perez <fperez@colorado.edu>
1771 1789
1772 1790 * IPython/ipmaker.py (make_IPython): make the default ipython
1773 1791 directory be called _ipython under win32, to follow more the
1774 1792 naming peculiarities of that platform (where buggy software like
1775 1793 Visual Sourcesafe breaks with .named directories). Reported by
1776 1794 Ville Vainio.
1777 1795
1778 1796 2005-02-23 Fernando Perez <fperez@colorado.edu>
1779 1797
1780 1798 * IPython/iplib.py (InteractiveShell.__init__): removed a few
1781 1799 auto_aliases for win32 which were causing problems. Users can
1782 1800 define the ones they personally like.
1783 1801
1784 1802 2005-02-21 Fernando Perez <fperez@colorado.edu>
1785 1803
1786 1804 * IPython/Magic.py (magic_time): new magic to time execution of
1787 1805 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
1788 1806
1789 1807 2005-02-19 Fernando Perez <fperez@colorado.edu>
1790 1808
1791 1809 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
1792 1810 into keys (for prompts, for example).
1793 1811
1794 1812 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
1795 1813 prompts in case users want them. This introduces a small behavior
1796 1814 change: ipython does not automatically add a space to all prompts
1797 1815 anymore. To get the old prompts with a space, users should add it
1798 1816 manually to their ipythonrc file, so for example prompt_in1 should
1799 1817 now read 'In [\#]: ' instead of 'In [\#]:'.
1800 1818 (BasePrompt.__init__): New option prompts_pad_left (only in rc
1801 1819 file) to control left-padding of secondary prompts.
1802 1820
1803 1821 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
1804 1822 the profiler can't be imported. Fix for Debian, which removed
1805 1823 profile.py because of License issues. I applied a slightly
1806 1824 modified version of the original Debian patch at
1807 1825 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
1808 1826
1809 1827 2005-02-17 Fernando Perez <fperez@colorado.edu>
1810 1828
1811 1829 * IPython/genutils.py (native_line_ends): Fix bug which would
1812 1830 cause improper line-ends under win32 b/c I was not opening files
1813 1831 in binary mode. Bug report and fix thanks to Ville.
1814 1832
1815 1833 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
1816 1834 trying to catch spurious foo[1] autocalls. My fix actually broke
1817 1835 ',/' autoquote/call with explicit escape (bad regexp).
1818 1836
1819 1837 2005-02-15 *** Released version 0.6.11
1820 1838
1821 1839 2005-02-14 Fernando Perez <fperez@colorado.edu>
1822 1840
1823 1841 * IPython/background_jobs.py: New background job management
1824 1842 subsystem. This is implemented via a new set of classes, and
1825 1843 IPython now provides a builtin 'jobs' object for background job
1826 1844 execution. A convenience %bg magic serves as a lightweight
1827 1845 frontend for starting the more common type of calls. This was
1828 1846 inspired by discussions with B. Granger and the BackgroundCommand
1829 1847 class described in the book Python Scripting for Computational
1830 1848 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
1831 1849 (although ultimately no code from this text was used, as IPython's
1832 1850 system is a separate implementation).
1833 1851
1834 1852 * IPython/iplib.py (MagicCompleter.python_matches): add new option
1835 1853 to control the completion of single/double underscore names
1836 1854 separately. As documented in the example ipytonrc file, the
1837 1855 readline_omit__names variable can now be set to 2, to omit even
1838 1856 single underscore names. Thanks to a patch by Brian Wong
1839 1857 <BrianWong-AT-AirgoNetworks.Com>.
1840 1858 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
1841 1859 be autocalled as foo([1]) if foo were callable. A problem for
1842 1860 things which are both callable and implement __getitem__.
1843 1861 (init_readline): Fix autoindentation for win32. Thanks to a patch
1844 1862 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
1845 1863
1846 1864 2005-02-12 Fernando Perez <fperez@colorado.edu>
1847 1865
1848 1866 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
1849 1867 which I had written long ago to sort out user error messages which
1850 1868 may occur during startup. This seemed like a good idea initially,
1851 1869 but it has proven a disaster in retrospect. I don't want to
1852 1870 change much code for now, so my fix is to set the internal 'debug'
1853 1871 flag to true everywhere, whose only job was precisely to control
1854 1872 this subsystem. This closes issue 28 (as well as avoiding all
1855 1873 sorts of strange hangups which occur from time to time).
1856 1874
1857 1875 2005-02-07 Fernando Perez <fperez@colorado.edu>
1858 1876
1859 1877 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
1860 1878 previous call produced a syntax error.
1861 1879
1862 1880 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1863 1881 classes without constructor.
1864 1882
1865 1883 2005-02-06 Fernando Perez <fperez@colorado.edu>
1866 1884
1867 1885 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
1868 1886 completions with the results of each matcher, so we return results
1869 1887 to the user from all namespaces. This breaks with ipython
1870 1888 tradition, but I think it's a nicer behavior. Now you get all
1871 1889 possible completions listed, from all possible namespaces (python,
1872 1890 filesystem, magics...) After a request by John Hunter
1873 1891 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1874 1892
1875 1893 2005-02-05 Fernando Perez <fperez@colorado.edu>
1876 1894
1877 1895 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
1878 1896 the call had quote characters in it (the quotes were stripped).
1879 1897
1880 1898 2005-01-31 Fernando Perez <fperez@colorado.edu>
1881 1899
1882 1900 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
1883 1901 Itpl.itpl() to make the code more robust against psyco
1884 1902 optimizations.
1885 1903
1886 1904 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
1887 1905 of causing an exception. Quicker, cleaner.
1888 1906
1889 1907 2005-01-28 Fernando Perez <fperez@colorado.edu>
1890 1908
1891 1909 * scripts/ipython_win_post_install.py (install): hardcode
1892 1910 sys.prefix+'python.exe' as the executable path. It turns out that
1893 1911 during the post-installation run, sys.executable resolves to the
1894 1912 name of the binary installer! I should report this as a distutils
1895 1913 bug, I think. I updated the .10 release with this tiny fix, to
1896 1914 avoid annoying the lists further.
1897 1915
1898 1916 2005-01-27 *** Released version 0.6.10
1899 1917
1900 1918 2005-01-27 Fernando Perez <fperez@colorado.edu>
1901 1919
1902 1920 * IPython/numutils.py (norm): Added 'inf' as optional name for
1903 1921 L-infinity norm, included references to mathworld.com for vector
1904 1922 norm definitions.
1905 1923 (amin/amax): added amin/amax for array min/max. Similar to what
1906 1924 pylab ships with after the recent reorganization of names.
1907 1925 (spike/spike_odd): removed deprecated spike/spike_odd functions.
1908 1926
1909 1927 * ipython.el: committed Alex's recent fixes and improvements.
1910 1928 Tested with python-mode from CVS, and it looks excellent. Since
1911 1929 python-mode hasn't released anything in a while, I'm temporarily
1912 1930 putting a copy of today's CVS (v 4.70) of python-mode in:
1913 1931 http://ipython.scipy.org/tmp/python-mode.el
1914 1932
1915 1933 * scripts/ipython_win_post_install.py (install): Win32 fix to use
1916 1934 sys.executable for the executable name, instead of assuming it's
1917 1935 called 'python.exe' (the post-installer would have produced broken
1918 1936 setups on systems with a differently named python binary).
1919 1937
1920 1938 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
1921 1939 references to os.linesep, to make the code more
1922 1940 platform-independent. This is also part of the win32 coloring
1923 1941 fixes.
1924 1942
1925 1943 * IPython/genutils.py (page_dumb): Remove attempts to chop long
1926 1944 lines, which actually cause coloring bugs because the length of
1927 1945 the line is very difficult to correctly compute with embedded
1928 1946 escapes. This was the source of all the coloring problems under
1929 1947 Win32. I think that _finally_, Win32 users have a properly
1930 1948 working ipython in all respects. This would never have happened
1931 1949 if not for Gary Bishop and Viktor Ransmayr's great help and work.
1932 1950
1933 1951 2005-01-26 *** Released version 0.6.9
1934 1952
1935 1953 2005-01-25 Fernando Perez <fperez@colorado.edu>
1936 1954
1937 1955 * setup.py: finally, we have a true Windows installer, thanks to
1938 1956 the excellent work of Viktor Ransmayr
1939 1957 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
1940 1958 Windows users. The setup routine is quite a bit cleaner thanks to
1941 1959 this, and the post-install script uses the proper functions to
1942 1960 allow a clean de-installation using the standard Windows Control
1943 1961 Panel.
1944 1962
1945 1963 * IPython/genutils.py (get_home_dir): changed to use the $HOME
1946 1964 environment variable under all OSes (including win32) if
1947 1965 available. This will give consistency to win32 users who have set
1948 1966 this variable for any reason. If os.environ['HOME'] fails, the
1949 1967 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
1950 1968
1951 1969 2005-01-24 Fernando Perez <fperez@colorado.edu>
1952 1970
1953 1971 * IPython/numutils.py (empty_like): add empty_like(), similar to
1954 1972 zeros_like() but taking advantage of the new empty() Numeric routine.
1955 1973
1956 1974 2005-01-23 *** Released version 0.6.8
1957 1975
1958 1976 2005-01-22 Fernando Perez <fperez@colorado.edu>
1959 1977
1960 1978 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
1961 1979 automatic show() calls. After discussing things with JDH, it
1962 1980 turns out there are too many corner cases where this can go wrong.
1963 1981 It's best not to try to be 'too smart', and simply have ipython
1964 1982 reproduce as much as possible the default behavior of a normal
1965 1983 python shell.
1966 1984
1967 1985 * IPython/iplib.py (InteractiveShell.__init__): Modified the
1968 1986 line-splitting regexp and _prefilter() to avoid calling getattr()
1969 1987 on assignments. This closes
1970 1988 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
1971 1989 readline uses getattr(), so a simple <TAB> keypress is still
1972 1990 enough to trigger getattr() calls on an object.
1973 1991
1974 1992 2005-01-21 Fernando Perez <fperez@colorado.edu>
1975 1993
1976 1994 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
1977 1995 docstring under pylab so it doesn't mask the original.
1978 1996
1979 1997 2005-01-21 *** Released version 0.6.7
1980 1998
1981 1999 2005-01-21 Fernando Perez <fperez@colorado.edu>
1982 2000
1983 2001 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
1984 2002 signal handling for win32 users in multithreaded mode.
1985 2003
1986 2004 2005-01-17 Fernando Perez <fperez@colorado.edu>
1987 2005
1988 2006 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
1989 2007 instances with no __init__. After a crash report by Norbert Nemec
1990 2008 <Norbert-AT-nemec-online.de>.
1991 2009
1992 2010 2005-01-14 Fernando Perez <fperez@colorado.edu>
1993 2011
1994 2012 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
1995 2013 names for verbose exceptions, when multiple dotted names and the
1996 2014 'parent' object were present on the same line.
1997 2015
1998 2016 2005-01-11 Fernando Perez <fperez@colorado.edu>
1999 2017
2000 2018 * IPython/genutils.py (flag_calls): new utility to trap and flag
2001 2019 calls in functions. I need it to clean up matplotlib support.
2002 2020 Also removed some deprecated code in genutils.
2003 2021
2004 2022 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
2005 2023 that matplotlib scripts called with %run, which don't call show()
2006 2024 themselves, still have their plotting windows open.
2007 2025
2008 2026 2005-01-05 Fernando Perez <fperez@colorado.edu>
2009 2027
2010 2028 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
2011 2029 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
2012 2030
2013 2031 2004-12-19 Fernando Perez <fperez@colorado.edu>
2014 2032
2015 2033 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
2016 2034 parent_runcode, which was an eyesore. The same result can be
2017 2035 obtained with Python's regular superclass mechanisms.
2018 2036
2019 2037 2004-12-17 Fernando Perez <fperez@colorado.edu>
2020 2038
2021 2039 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
2022 2040 reported by Prabhu.
2023 2041 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
2024 2042 sys.stderr) instead of explicitly calling sys.stderr. This helps
2025 2043 maintain our I/O abstractions clean, for future GUI embeddings.
2026 2044
2027 2045 * IPython/genutils.py (info): added new utility for sys.stderr
2028 2046 unified info message handling (thin wrapper around warn()).
2029 2047
2030 2048 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
2031 2049 composite (dotted) names on verbose exceptions.
2032 2050 (VerboseTB.nullrepr): harden against another kind of errors which
2033 2051 Python's inspect module can trigger, and which were crashing
2034 2052 IPython. Thanks to a report by Marco Lombardi
2035 2053 <mlombard-AT-ma010192.hq.eso.org>.
2036 2054
2037 2055 2004-12-13 *** Released version 0.6.6
2038 2056
2039 2057 2004-12-12 Fernando Perez <fperez@colorado.edu>
2040 2058
2041 2059 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
2042 2060 generated by pygtk upon initialization if it was built without
2043 2061 threads (for matplotlib users). After a crash reported by
2044 2062 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
2045 2063
2046 2064 * IPython/ipmaker.py (make_IPython): fix small bug in the
2047 2065 import_some parameter for multiple imports.
2048 2066
2049 2067 * IPython/iplib.py (ipmagic): simplified the interface of
2050 2068 ipmagic() to take a single string argument, just as it would be
2051 2069 typed at the IPython cmd line.
2052 2070 (ipalias): Added new ipalias() with an interface identical to
2053 2071 ipmagic(). This completes exposing a pure python interface to the
2054 2072 alias and magic system, which can be used in loops or more complex
2055 2073 code where IPython's automatic line mangling is not active.
2056 2074
2057 2075 * IPython/genutils.py (timing): changed interface of timing to
2058 2076 simply run code once, which is the most common case. timings()
2059 2077 remains unchanged, for the cases where you want multiple runs.
2060 2078
2061 2079 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
2062 2080 bug where Python2.2 crashes with exec'ing code which does not end
2063 2081 in a single newline. Python 2.3 is OK, so I hadn't noticed this
2064 2082 before.
2065 2083
2066 2084 2004-12-10 Fernando Perez <fperez@colorado.edu>
2067 2085
2068 2086 * IPython/Magic.py (Magic.magic_prun): changed name of option from
2069 2087 -t to -T, to accomodate the new -t flag in %run (the %run and
2070 2088 %prun options are kind of intermixed, and it's not easy to change
2071 2089 this with the limitations of python's getopt).
2072 2090
2073 2091 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
2074 2092 the execution of scripts. It's not as fine-tuned as timeit.py,
2075 2093 but it works from inside ipython (and under 2.2, which lacks
2076 2094 timeit.py). Optionally a number of runs > 1 can be given for
2077 2095 timing very short-running code.
2078 2096
2079 2097 * IPython/genutils.py (uniq_stable): new routine which returns a
2080 2098 list of unique elements in any iterable, but in stable order of
2081 2099 appearance. I needed this for the ultraTB fixes, and it's a handy
2082 2100 utility.
2083 2101
2084 2102 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
2085 2103 dotted names in Verbose exceptions. This had been broken since
2086 2104 the very start, now x.y will properly be printed in a Verbose
2087 2105 traceback, instead of x being shown and y appearing always as an
2088 2106 'undefined global'. Getting this to work was a bit tricky,
2089 2107 because by default python tokenizers are stateless. Saved by
2090 2108 python's ability to easily add a bit of state to an arbitrary
2091 2109 function (without needing to build a full-blown callable object).
2092 2110
2093 2111 Also big cleanup of this code, which had horrendous runtime
2094 2112 lookups of zillions of attributes for colorization. Moved all
2095 2113 this code into a few templates, which make it cleaner and quicker.
2096 2114
2097 2115 Printout quality was also improved for Verbose exceptions: one
2098 2116 variable per line, and memory addresses are printed (this can be
2099 2117 quite handy in nasty debugging situations, which is what Verbose
2100 2118 is for).
2101 2119
2102 2120 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
2103 2121 the command line as scripts to be loaded by embedded instances.
2104 2122 Doing so has the potential for an infinite recursion if there are
2105 2123 exceptions thrown in the process. This fixes a strange crash
2106 2124 reported by Philippe MULLER <muller-AT-irit.fr>.
2107 2125
2108 2126 2004-12-09 Fernando Perez <fperez@colorado.edu>
2109 2127
2110 2128 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
2111 2129 to reflect new names in matplotlib, which now expose the
2112 2130 matlab-compatible interface via a pylab module instead of the
2113 2131 'matlab' name. The new code is backwards compatible, so users of
2114 2132 all matplotlib versions are OK. Patch by J. Hunter.
2115 2133
2116 2134 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
2117 2135 of __init__ docstrings for instances (class docstrings are already
2118 2136 automatically printed). Instances with customized docstrings
2119 2137 (indep. of the class) are also recognized and all 3 separate
2120 2138 docstrings are printed (instance, class, constructor). After some
2121 2139 comments/suggestions by J. Hunter.
2122 2140
2123 2141 2004-12-05 Fernando Perez <fperez@colorado.edu>
2124 2142
2125 2143 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
2126 2144 warnings when tab-completion fails and triggers an exception.
2127 2145
2128 2146 2004-12-03 Fernando Perez <fperez@colorado.edu>
2129 2147
2130 2148 * IPython/Magic.py (magic_prun): Fix bug where an exception would
2131 2149 be triggered when using 'run -p'. An incorrect option flag was
2132 2150 being set ('d' instead of 'D').
2133 2151 (manpage): fix missing escaped \- sign.
2134 2152
2135 2153 2004-11-30 *** Released version 0.6.5
2136 2154
2137 2155 2004-11-30 Fernando Perez <fperez@colorado.edu>
2138 2156
2139 2157 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
2140 2158 setting with -d option.
2141 2159
2142 2160 * setup.py (docfiles): Fix problem where the doc glob I was using
2143 2161 was COMPLETELY BROKEN. It was giving the right files by pure
2144 2162 accident, but failed once I tried to include ipython.el. Note:
2145 2163 glob() does NOT allow you to do exclusion on multiple endings!
2146 2164
2147 2165 2004-11-29 Fernando Perez <fperez@colorado.edu>
2148 2166
2149 2167 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
2150 2168 the manpage as the source. Better formatting & consistency.
2151 2169
2152 2170 * IPython/Magic.py (magic_run): Added new -d option, to run
2153 2171 scripts under the control of the python pdb debugger. Note that
2154 2172 this required changing the %prun option -d to -D, to avoid a clash
2155 2173 (since %run must pass options to %prun, and getopt is too dumb to
2156 2174 handle options with string values with embedded spaces). Thanks
2157 2175 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
2158 2176 (magic_who_ls): added type matching to %who and %whos, so that one
2159 2177 can filter their output to only include variables of certain
2160 2178 types. Another suggestion by Matthew.
2161 2179 (magic_whos): Added memory summaries in kb and Mb for arrays.
2162 2180 (magic_who): Improve formatting (break lines every 9 vars).
2163 2181
2164 2182 2004-11-28 Fernando Perez <fperez@colorado.edu>
2165 2183
2166 2184 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
2167 2185 cache when empty lines were present.
2168 2186
2169 2187 2004-11-24 Fernando Perez <fperez@colorado.edu>
2170 2188
2171 2189 * IPython/usage.py (__doc__): document the re-activated threading
2172 2190 options for WX and GTK.
2173 2191
2174 2192 2004-11-23 Fernando Perez <fperez@colorado.edu>
2175 2193
2176 2194 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
2177 2195 the -wthread and -gthread options, along with a new -tk one to try
2178 2196 and coordinate Tk threading with wx/gtk. The tk support is very
2179 2197 platform dependent, since it seems to require Tcl and Tk to be
2180 2198 built with threads (Fedora1/2 appears NOT to have it, but in
2181 2199 Prabhu's Debian boxes it works OK). But even with some Tk
2182 2200 limitations, this is a great improvement.
2183 2201
2184 2202 * IPython/Prompts.py (prompt_specials_color): Added \t for time
2185 2203 info in user prompts. Patch by Prabhu.
2186 2204
2187 2205 2004-11-18 Fernando Perez <fperez@colorado.edu>
2188 2206
2189 2207 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
2190 2208 EOFErrors and bail, to avoid infinite loops if a non-terminating
2191 2209 file is fed into ipython. Patch submitted in issue 19 by user,
2192 2210 many thanks.
2193 2211
2194 2212 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
2195 2213 autoquote/parens in continuation prompts, which can cause lots of
2196 2214 problems. Closes roundup issue 20.
2197 2215
2198 2216 2004-11-17 Fernando Perez <fperez@colorado.edu>
2199 2217
2200 2218 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
2201 2219 reported as debian bug #280505. I'm not sure my local changelog
2202 2220 entry has the proper debian format (Jack?).
2203 2221
2204 2222 2004-11-08 *** Released version 0.6.4
2205 2223
2206 2224 2004-11-08 Fernando Perez <fperez@colorado.edu>
2207 2225
2208 2226 * IPython/iplib.py (init_readline): Fix exit message for Windows
2209 2227 when readline is active. Thanks to a report by Eric Jones
2210 2228 <eric-AT-enthought.com>.
2211 2229
2212 2230 2004-11-07 Fernando Perez <fperez@colorado.edu>
2213 2231
2214 2232 * IPython/genutils.py (page): Add a trap for OSError exceptions,
2215 2233 sometimes seen by win2k/cygwin users.
2216 2234
2217 2235 2004-11-06 Fernando Perez <fperez@colorado.edu>
2218 2236
2219 2237 * IPython/iplib.py (interact): Change the handling of %Exit from
2220 2238 trying to propagate a SystemExit to an internal ipython flag.
2221 2239 This is less elegant than using Python's exception mechanism, but
2222 2240 I can't get that to work reliably with threads, so under -pylab
2223 2241 %Exit was hanging IPython. Cross-thread exception handling is
2224 2242 really a bitch. Thaks to a bug report by Stephen Walton
2225 2243 <stephen.walton-AT-csun.edu>.
2226 2244
2227 2245 2004-11-04 Fernando Perez <fperez@colorado.edu>
2228 2246
2229 2247 * IPython/iplib.py (raw_input_original): store a pointer to the
2230 2248 true raw_input to harden against code which can modify it
2231 2249 (wx.py.PyShell does this and would otherwise crash ipython).
2232 2250 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
2233 2251
2234 2252 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
2235 2253 Ctrl-C problem, which does not mess up the input line.
2236 2254
2237 2255 2004-11-03 Fernando Perez <fperez@colorado.edu>
2238 2256
2239 2257 * IPython/Release.py: Changed licensing to BSD, in all files.
2240 2258 (name): lowercase name for tarball/RPM release.
2241 2259
2242 2260 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
2243 2261 use throughout ipython.
2244 2262
2245 2263 * IPython/Magic.py (Magic._ofind): Switch to using the new
2246 2264 OInspect.getdoc() function.
2247 2265
2248 2266 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
2249 2267 of the line currently being canceled via Ctrl-C. It's extremely
2250 2268 ugly, but I don't know how to do it better (the problem is one of
2251 2269 handling cross-thread exceptions).
2252 2270
2253 2271 2004-10-28 Fernando Perez <fperez@colorado.edu>
2254 2272
2255 2273 * IPython/Shell.py (signal_handler): add signal handlers to trap
2256 2274 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
2257 2275 report by Francesc Alted.
2258 2276
2259 2277 2004-10-21 Fernando Perez <fperez@colorado.edu>
2260 2278
2261 2279 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
2262 2280 to % for pysh syntax extensions.
2263 2281
2264 2282 2004-10-09 Fernando Perez <fperez@colorado.edu>
2265 2283
2266 2284 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
2267 2285 arrays to print a more useful summary, without calling str(arr).
2268 2286 This avoids the problem of extremely lengthy computations which
2269 2287 occur if arr is large, and appear to the user as a system lockup
2270 2288 with 100% cpu activity. After a suggestion by Kristian Sandberg
2271 2289 <Kristian.Sandberg@colorado.edu>.
2272 2290 (Magic.__init__): fix bug in global magic escapes not being
2273 2291 correctly set.
2274 2292
2275 2293 2004-10-08 Fernando Perez <fperez@colorado.edu>
2276 2294
2277 2295 * IPython/Magic.py (__license__): change to absolute imports of
2278 2296 ipython's own internal packages, to start adapting to the absolute
2279 2297 import requirement of PEP-328.
2280 2298
2281 2299 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
2282 2300 files, and standardize author/license marks through the Release
2283 2301 module instead of having per/file stuff (except for files with
2284 2302 particular licenses, like the MIT/PSF-licensed codes).
2285 2303
2286 2304 * IPython/Debugger.py: remove dead code for python 2.1
2287 2305
2288 2306 2004-10-04 Fernando Perez <fperez@colorado.edu>
2289 2307
2290 2308 * IPython/iplib.py (ipmagic): New function for accessing magics
2291 2309 via a normal python function call.
2292 2310
2293 2311 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
2294 2312 from '@' to '%', to accomodate the new @decorator syntax of python
2295 2313 2.4.
2296 2314
2297 2315 2004-09-29 Fernando Perez <fperez@colorado.edu>
2298 2316
2299 2317 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
2300 2318 matplotlib.use to prevent running scripts which try to switch
2301 2319 interactive backends from within ipython. This will just crash
2302 2320 the python interpreter, so we can't allow it (but a detailed error
2303 2321 is given to the user).
2304 2322
2305 2323 2004-09-28 Fernando Perez <fperez@colorado.edu>
2306 2324
2307 2325 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
2308 2326 matplotlib-related fixes so that using @run with non-matplotlib
2309 2327 scripts doesn't pop up spurious plot windows. This requires
2310 2328 matplotlib >= 0.63, where I had to make some changes as well.
2311 2329
2312 2330 * IPython/ipmaker.py (make_IPython): update version requirement to
2313 2331 python 2.2.
2314 2332
2315 2333 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
2316 2334 banner arg for embedded customization.
2317 2335
2318 2336 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
2319 2337 explicit uses of __IP as the IPython's instance name. Now things
2320 2338 are properly handled via the shell.name value. The actual code
2321 2339 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
2322 2340 is much better than before. I'll clean things completely when the
2323 2341 magic stuff gets a real overhaul.
2324 2342
2325 2343 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
2326 2344 minor changes to debian dir.
2327 2345
2328 2346 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
2329 2347 pointer to the shell itself in the interactive namespace even when
2330 2348 a user-supplied dict is provided. This is needed for embedding
2331 2349 purposes (found by tests with Michel Sanner).
2332 2350
2333 2351 2004-09-27 Fernando Perez <fperez@colorado.edu>
2334 2352
2335 2353 * IPython/UserConfig/ipythonrc: remove []{} from
2336 2354 readline_remove_delims, so that things like [modname.<TAB> do
2337 2355 proper completion. This disables [].TAB, but that's a less common
2338 2356 case than module names in list comprehensions, for example.
2339 2357 Thanks to a report by Andrea Riciputi.
2340 2358
2341 2359 2004-09-09 Fernando Perez <fperez@colorado.edu>
2342 2360
2343 2361 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
2344 2362 blocking problems in win32 and osx. Fix by John.
2345 2363
2346 2364 2004-09-08 Fernando Perez <fperez@colorado.edu>
2347 2365
2348 2366 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
2349 2367 for Win32 and OSX. Fix by John Hunter.
2350 2368
2351 2369 2004-08-30 *** Released version 0.6.3
2352 2370
2353 2371 2004-08-30 Fernando Perez <fperez@colorado.edu>
2354 2372
2355 2373 * setup.py (isfile): Add manpages to list of dependent files to be
2356 2374 updated.
2357 2375
2358 2376 2004-08-27 Fernando Perez <fperez@colorado.edu>
2359 2377
2360 2378 * IPython/Shell.py (start): I've disabled -wthread and -gthread
2361 2379 for now. They don't really work with standalone WX/GTK code
2362 2380 (though matplotlib IS working fine with both of those backends).
2363 2381 This will neeed much more testing. I disabled most things with
2364 2382 comments, so turning it back on later should be pretty easy.
2365 2383
2366 2384 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
2367 2385 autocalling of expressions like r'foo', by modifying the line
2368 2386 split regexp. Closes
2369 2387 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
2370 2388 Riley <ipythonbugs-AT-sabi.net>.
2371 2389 (InteractiveShell.mainloop): honor --nobanner with banner
2372 2390 extensions.
2373 2391
2374 2392 * IPython/Shell.py: Significant refactoring of all classes, so
2375 2393 that we can really support ALL matplotlib backends and threading
2376 2394 models (John spotted a bug with Tk which required this). Now we
2377 2395 should support single-threaded, WX-threads and GTK-threads, both
2378 2396 for generic code and for matplotlib.
2379 2397
2380 2398 * IPython/ipmaker.py (__call__): Changed -mpthread option to
2381 2399 -pylab, to simplify things for users. Will also remove the pylab
2382 2400 profile, since now all of matplotlib configuration is directly
2383 2401 handled here. This also reduces startup time.
2384 2402
2385 2403 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
2386 2404 shell wasn't being correctly called. Also in IPShellWX.
2387 2405
2388 2406 * IPython/iplib.py (InteractiveShell.__init__): Added option to
2389 2407 fine-tune banner.
2390 2408
2391 2409 * IPython/numutils.py (spike): Deprecate these spike functions,
2392 2410 delete (long deprecated) gnuplot_exec handler.
2393 2411
2394 2412 2004-08-26 Fernando Perez <fperez@colorado.edu>
2395 2413
2396 2414 * ipython.1: Update for threading options, plus some others which
2397 2415 were missing.
2398 2416
2399 2417 * IPython/ipmaker.py (__call__): Added -wthread option for
2400 2418 wxpython thread handling. Make sure threading options are only
2401 2419 valid at the command line.
2402 2420
2403 2421 * scripts/ipython: moved shell selection into a factory function
2404 2422 in Shell.py, to keep the starter script to a minimum.
2405 2423
2406 2424 2004-08-25 Fernando Perez <fperez@colorado.edu>
2407 2425
2408 2426 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
2409 2427 John. Along with some recent changes he made to matplotlib, the
2410 2428 next versions of both systems should work very well together.
2411 2429
2412 2430 2004-08-24 Fernando Perez <fperez@colorado.edu>
2413 2431
2414 2432 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
2415 2433 tried to switch the profiling to using hotshot, but I'm getting
2416 2434 strange errors from prof.runctx() there. I may be misreading the
2417 2435 docs, but it looks weird. For now the profiling code will
2418 2436 continue to use the standard profiler.
2419 2437
2420 2438 2004-08-23 Fernando Perez <fperez@colorado.edu>
2421 2439
2422 2440 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
2423 2441 threaded shell, by John Hunter. It's not quite ready yet, but
2424 2442 close.
2425 2443
2426 2444 2004-08-22 Fernando Perez <fperez@colorado.edu>
2427 2445
2428 2446 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
2429 2447 in Magic and ultraTB.
2430 2448
2431 2449 * ipython.1: document threading options in manpage.
2432 2450
2433 2451 * scripts/ipython: Changed name of -thread option to -gthread,
2434 2452 since this is GTK specific. I want to leave the door open for a
2435 2453 -wthread option for WX, which will most likely be necessary. This
2436 2454 change affects usage and ipmaker as well.
2437 2455
2438 2456 * IPython/Shell.py (matplotlib_shell): Add a factory function to
2439 2457 handle the matplotlib shell issues. Code by John Hunter
2440 2458 <jdhunter-AT-nitace.bsd.uchicago.edu>.
2441 2459 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
2442 2460 broken (and disabled for end users) for now, but it puts the
2443 2461 infrastructure in place.
2444 2462
2445 2463 2004-08-21 Fernando Perez <fperez@colorado.edu>
2446 2464
2447 2465 * ipythonrc-pylab: Add matplotlib support.
2448 2466
2449 2467 * matplotlib_config.py: new files for matplotlib support, part of
2450 2468 the pylab profile.
2451 2469
2452 2470 * IPython/usage.py (__doc__): documented the threading options.
2453 2471
2454 2472 2004-08-20 Fernando Perez <fperez@colorado.edu>
2455 2473
2456 2474 * ipython: Modified the main calling routine to handle the -thread
2457 2475 and -mpthread options. This needs to be done as a top-level hack,
2458 2476 because it determines which class to instantiate for IPython
2459 2477 itself.
2460 2478
2461 2479 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
2462 2480 classes to support multithreaded GTK operation without blocking,
2463 2481 and matplotlib with all backends. This is a lot of still very
2464 2482 experimental code, and threads are tricky. So it may still have a
2465 2483 few rough edges... This code owes a lot to
2466 2484 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
2467 2485 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
2468 2486 to John Hunter for all the matplotlib work.
2469 2487
2470 2488 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
2471 2489 options for gtk thread and matplotlib support.
2472 2490
2473 2491 2004-08-16 Fernando Perez <fperez@colorado.edu>
2474 2492
2475 2493 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
2476 2494 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
2477 2495 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
2478 2496
2479 2497 2004-08-11 Fernando Perez <fperez@colorado.edu>
2480 2498
2481 2499 * setup.py (isfile): Fix build so documentation gets updated for
2482 2500 rpms (it was only done for .tgz builds).
2483 2501
2484 2502 2004-08-10 Fernando Perez <fperez@colorado.edu>
2485 2503
2486 2504 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
2487 2505
2488 2506 * iplib.py : Silence syntax error exceptions in tab-completion.
2489 2507
2490 2508 2004-08-05 Fernando Perez <fperez@colorado.edu>
2491 2509
2492 2510 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
2493 2511 'color off' mark for continuation prompts. This was causing long
2494 2512 continuation lines to mis-wrap.
2495 2513
2496 2514 2004-08-01 Fernando Perez <fperez@colorado.edu>
2497 2515
2498 2516 * IPython/ipmaker.py (make_IPython): Allow the shell class used
2499 2517 for building ipython to be a parameter. All this is necessary
2500 2518 right now to have a multithreaded version, but this insane
2501 2519 non-design will be cleaned up soon. For now, it's a hack that
2502 2520 works.
2503 2521
2504 2522 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
2505 2523 args in various places. No bugs so far, but it's a dangerous
2506 2524 practice.
2507 2525
2508 2526 2004-07-31 Fernando Perez <fperez@colorado.edu>
2509 2527
2510 2528 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
2511 2529 fix completion of files with dots in their names under most
2512 2530 profiles (pysh was OK because the completion order is different).
2513 2531
2514 2532 2004-07-27 Fernando Perez <fperez@colorado.edu>
2515 2533
2516 2534 * IPython/iplib.py (InteractiveShell.__init__): build dict of
2517 2535 keywords manually, b/c the one in keyword.py was removed in python
2518 2536 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
2519 2537 This is NOT a bug under python 2.3 and earlier.
2520 2538
2521 2539 2004-07-26 Fernando Perez <fperez@colorado.edu>
2522 2540
2523 2541 * IPython/ultraTB.py (VerboseTB.text): Add another
2524 2542 linecache.checkcache() call to try to prevent inspect.py from
2525 2543 crashing under python 2.3. I think this fixes
2526 2544 http://www.scipy.net/roundup/ipython/issue17.
2527 2545
2528 2546 2004-07-26 *** Released version 0.6.2
2529 2547
2530 2548 2004-07-26 Fernando Perez <fperez@colorado.edu>
2531 2549
2532 2550 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
2533 2551 fail for any number.
2534 2552 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
2535 2553 empty bookmarks.
2536 2554
2537 2555 2004-07-26 *** Released version 0.6.1
2538 2556
2539 2557 2004-07-26 Fernando Perez <fperez@colorado.edu>
2540 2558
2541 2559 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
2542 2560
2543 2561 * IPython/iplib.py (protect_filename): Applied Ville's patch for
2544 2562 escaping '()[]{}' in filenames.
2545 2563
2546 2564 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
2547 2565 Python 2.2 users who lack a proper shlex.split.
2548 2566
2549 2567 2004-07-19 Fernando Perez <fperez@colorado.edu>
2550 2568
2551 2569 * IPython/iplib.py (InteractiveShell.init_readline): Add support
2552 2570 for reading readline's init file. I follow the normal chain:
2553 2571 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
2554 2572 report by Mike Heeter. This closes
2555 2573 http://www.scipy.net/roundup/ipython/issue16.
2556 2574
2557 2575 2004-07-18 Fernando Perez <fperez@colorado.edu>
2558 2576
2559 2577 * IPython/iplib.py (__init__): Add better handling of '\' under
2560 2578 Win32 for filenames. After a patch by Ville.
2561 2579
2562 2580 2004-07-17 Fernando Perez <fperez@colorado.edu>
2563 2581
2564 2582 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2565 2583 autocalling would be triggered for 'foo is bar' if foo is
2566 2584 callable. I also cleaned up the autocall detection code to use a
2567 2585 regexp, which is faster. Bug reported by Alexander Schmolck.
2568 2586
2569 2587 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
2570 2588 '?' in them would confuse the help system. Reported by Alex
2571 2589 Schmolck.
2572 2590
2573 2591 2004-07-16 Fernando Perez <fperez@colorado.edu>
2574 2592
2575 2593 * IPython/GnuplotInteractive.py (__all__): added plot2.
2576 2594
2577 2595 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
2578 2596 plotting dictionaries, lists or tuples of 1d arrays.
2579 2597
2580 2598 * IPython/Magic.py (Magic.magic_hist): small clenaups and
2581 2599 optimizations.
2582 2600
2583 2601 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
2584 2602 the information which was there from Janko's original IPP code:
2585 2603
2586 2604 03.05.99 20:53 porto.ifm.uni-kiel.de
2587 2605 --Started changelog.
2588 2606 --make clear do what it say it does
2589 2607 --added pretty output of lines from inputcache
2590 2608 --Made Logger a mixin class, simplifies handling of switches
2591 2609 --Added own completer class. .string<TAB> expands to last history
2592 2610 line which starts with string. The new expansion is also present
2593 2611 with Ctrl-r from the readline library. But this shows, who this
2594 2612 can be done for other cases.
2595 2613 --Added convention that all shell functions should accept a
2596 2614 parameter_string This opens the door for different behaviour for
2597 2615 each function. @cd is a good example of this.
2598 2616
2599 2617 04.05.99 12:12 porto.ifm.uni-kiel.de
2600 2618 --added logfile rotation
2601 2619 --added new mainloop method which freezes first the namespace
2602 2620
2603 2621 07.05.99 21:24 porto.ifm.uni-kiel.de
2604 2622 --added the docreader classes. Now there is a help system.
2605 2623 -This is only a first try. Currently it's not easy to put new
2606 2624 stuff in the indices. But this is the way to go. Info would be
2607 2625 better, but HTML is every where and not everybody has an info
2608 2626 system installed and it's not so easy to change html-docs to info.
2609 2627 --added global logfile option
2610 2628 --there is now a hook for object inspection method pinfo needs to
2611 2629 be provided for this. Can be reached by two '??'.
2612 2630
2613 2631 08.05.99 20:51 porto.ifm.uni-kiel.de
2614 2632 --added a README
2615 2633 --bug in rc file. Something has changed so functions in the rc
2616 2634 file need to reference the shell and not self. Not clear if it's a
2617 2635 bug or feature.
2618 2636 --changed rc file for new behavior
2619 2637
2620 2638 2004-07-15 Fernando Perez <fperez@colorado.edu>
2621 2639
2622 2640 * IPython/Logger.py (Logger.log): fixed recent bug where the input
2623 2641 cache was falling out of sync in bizarre manners when multi-line
2624 2642 input was present. Minor optimizations and cleanup.
2625 2643
2626 2644 (Logger): Remove old Changelog info for cleanup. This is the
2627 2645 information which was there from Janko's original code:
2628 2646
2629 2647 Changes to Logger: - made the default log filename a parameter
2630 2648
2631 2649 - put a check for lines beginning with !@? in log(). Needed
2632 2650 (even if the handlers properly log their lines) for mid-session
2633 2651 logging activation to work properly. Without this, lines logged
2634 2652 in mid session, which get read from the cache, would end up
2635 2653 'bare' (with !@? in the open) in the log. Now they are caught
2636 2654 and prepended with a #.
2637 2655
2638 2656 * IPython/iplib.py (InteractiveShell.init_readline): added check
2639 2657 in case MagicCompleter fails to be defined, so we don't crash.
2640 2658
2641 2659 2004-07-13 Fernando Perez <fperez@colorado.edu>
2642 2660
2643 2661 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
2644 2662 of EPS if the requested filename ends in '.eps'.
2645 2663
2646 2664 2004-07-04 Fernando Perez <fperez@colorado.edu>
2647 2665
2648 2666 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
2649 2667 escaping of quotes when calling the shell.
2650 2668
2651 2669 2004-07-02 Fernando Perez <fperez@colorado.edu>
2652 2670
2653 2671 * IPython/Prompts.py (CachedOutput.update): Fix problem with
2654 2672 gettext not working because we were clobbering '_'. Fixes
2655 2673 http://www.scipy.net/roundup/ipython/issue6.
2656 2674
2657 2675 2004-07-01 Fernando Perez <fperez@colorado.edu>
2658 2676
2659 2677 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
2660 2678 into @cd. Patch by Ville.
2661 2679
2662 2680 * IPython/iplib.py (InteractiveShell.post_config_initialization):
2663 2681 new function to store things after ipmaker runs. Patch by Ville.
2664 2682 Eventually this will go away once ipmaker is removed and the class
2665 2683 gets cleaned up, but for now it's ok. Key functionality here is
2666 2684 the addition of the persistent storage mechanism, a dict for
2667 2685 keeping data across sessions (for now just bookmarks, but more can
2668 2686 be implemented later).
2669 2687
2670 2688 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
2671 2689 persistent across sections. Patch by Ville, I modified it
2672 2690 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
2673 2691 added a '-l' option to list all bookmarks.
2674 2692
2675 2693 * IPython/iplib.py (InteractiveShell.atexit_operations): new
2676 2694 center for cleanup. Registered with atexit.register(). I moved
2677 2695 here the old exit_cleanup(). After a patch by Ville.
2678 2696
2679 2697 * IPython/Magic.py (get_py_filename): added '~' to the accepted
2680 2698 characters in the hacked shlex_split for python 2.2.
2681 2699
2682 2700 * IPython/iplib.py (file_matches): more fixes to filenames with
2683 2701 whitespace in them. It's not perfect, but limitations in python's
2684 2702 readline make it impossible to go further.
2685 2703
2686 2704 2004-06-29 Fernando Perez <fperez@colorado.edu>
2687 2705
2688 2706 * IPython/iplib.py (file_matches): escape whitespace correctly in
2689 2707 filename completions. Bug reported by Ville.
2690 2708
2691 2709 2004-06-28 Fernando Perez <fperez@colorado.edu>
2692 2710
2693 2711 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
2694 2712 the history file will be called 'history-PROFNAME' (or just
2695 2713 'history' if no profile is loaded). I was getting annoyed at
2696 2714 getting my Numerical work history clobbered by pysh sessions.
2697 2715
2698 2716 * IPython/iplib.py (InteractiveShell.__init__): Internal
2699 2717 getoutputerror() function so that we can honor the system_verbose
2700 2718 flag for _all_ system calls. I also added escaping of #
2701 2719 characters here to avoid confusing Itpl.
2702 2720
2703 2721 * IPython/Magic.py (shlex_split): removed call to shell in
2704 2722 parse_options and replaced it with shlex.split(). The annoying
2705 2723 part was that in Python 2.2, shlex.split() doesn't exist, so I had
2706 2724 to backport it from 2.3, with several frail hacks (the shlex
2707 2725 module is rather limited in 2.2). Thanks to a suggestion by Ville
2708 2726 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
2709 2727 problem.
2710 2728
2711 2729 (Magic.magic_system_verbose): new toggle to print the actual
2712 2730 system calls made by ipython. Mainly for debugging purposes.
2713 2731
2714 2732 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
2715 2733 doesn't support persistence. Reported (and fix suggested) by
2716 2734 Travis Caldwell <travis_caldwell2000@yahoo.com>.
2717 2735
2718 2736 2004-06-26 Fernando Perez <fperez@colorado.edu>
2719 2737
2720 2738 * IPython/Logger.py (Logger.log): fix to handle correctly empty
2721 2739 continue prompts.
2722 2740
2723 2741 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
2724 2742 function (basically a big docstring) and a few more things here to
2725 2743 speedup startup. pysh.py is now very lightweight. We want because
2726 2744 it gets execfile'd, while InterpreterExec gets imported, so
2727 2745 byte-compilation saves time.
2728 2746
2729 2747 2004-06-25 Fernando Perez <fperez@colorado.edu>
2730 2748
2731 2749 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
2732 2750 -NUM', which was recently broken.
2733 2751
2734 2752 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
2735 2753 in multi-line input (but not !!, which doesn't make sense there).
2736 2754
2737 2755 * IPython/UserConfig/ipythonrc: made autoindent on by default.
2738 2756 It's just too useful, and people can turn it off in the less
2739 2757 common cases where it's a problem.
2740 2758
2741 2759 2004-06-24 Fernando Perez <fperez@colorado.edu>
2742 2760
2743 2761 * IPython/iplib.py (InteractiveShell._prefilter): big change -
2744 2762 special syntaxes (like alias calling) is now allied in multi-line
2745 2763 input. This is still _very_ experimental, but it's necessary for
2746 2764 efficient shell usage combining python looping syntax with system
2747 2765 calls. For now it's restricted to aliases, I don't think it
2748 2766 really even makes sense to have this for magics.
2749 2767
2750 2768 2004-06-23 Fernando Perez <fperez@colorado.edu>
2751 2769
2752 2770 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
2753 2771 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
2754 2772
2755 2773 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
2756 2774 extensions under Windows (after code sent by Gary Bishop). The
2757 2775 extensions considered 'executable' are stored in IPython's rc
2758 2776 structure as win_exec_ext.
2759 2777
2760 2778 * IPython/genutils.py (shell): new function, like system() but
2761 2779 without return value. Very useful for interactive shell work.
2762 2780
2763 2781 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
2764 2782 delete aliases.
2765 2783
2766 2784 * IPython/iplib.py (InteractiveShell.alias_table_update): make
2767 2785 sure that the alias table doesn't contain python keywords.
2768 2786
2769 2787 2004-06-21 Fernando Perez <fperez@colorado.edu>
2770 2788
2771 2789 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
2772 2790 non-existent items are found in $PATH. Reported by Thorsten.
2773 2791
2774 2792 2004-06-20 Fernando Perez <fperez@colorado.edu>
2775 2793
2776 2794 * IPython/iplib.py (complete): modified the completer so that the
2777 2795 order of priorities can be easily changed at runtime.
2778 2796
2779 2797 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
2780 2798 Modified to auto-execute all lines beginning with '~', '/' or '.'.
2781 2799
2782 2800 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
2783 2801 expand Python variables prepended with $ in all system calls. The
2784 2802 same was done to InteractiveShell.handle_shell_escape. Now all
2785 2803 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
2786 2804 expansion of python variables and expressions according to the
2787 2805 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
2788 2806
2789 2807 Though PEP-215 has been rejected, a similar (but simpler) one
2790 2808 seems like it will go into Python 2.4, PEP-292 -
2791 2809 http://www.python.org/peps/pep-0292.html.
2792 2810
2793 2811 I'll keep the full syntax of PEP-215, since IPython has since the
2794 2812 start used Ka-Ping Yee's reference implementation discussed there
2795 2813 (Itpl), and I actually like the powerful semantics it offers.
2796 2814
2797 2815 In order to access normal shell variables, the $ has to be escaped
2798 2816 via an extra $. For example:
2799 2817
2800 2818 In [7]: PATH='a python variable'
2801 2819
2802 2820 In [8]: !echo $PATH
2803 2821 a python variable
2804 2822
2805 2823 In [9]: !echo $$PATH
2806 2824 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2807 2825
2808 2826 (Magic.parse_options): escape $ so the shell doesn't evaluate
2809 2827 things prematurely.
2810 2828
2811 2829 * IPython/iplib.py (InteractiveShell.call_alias): added the
2812 2830 ability for aliases to expand python variables via $.
2813 2831
2814 2832 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
2815 2833 system, now there's a @rehash/@rehashx pair of magics. These work
2816 2834 like the csh rehash command, and can be invoked at any time. They
2817 2835 build a table of aliases to everything in the user's $PATH
2818 2836 (@rehash uses everything, @rehashx is slower but only adds
2819 2837 executable files). With this, the pysh.py-based shell profile can
2820 2838 now simply call rehash upon startup, and full access to all
2821 2839 programs in the user's path is obtained.
2822 2840
2823 2841 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
2824 2842 functionality is now fully in place. I removed the old dynamic
2825 2843 code generation based approach, in favor of a much lighter one
2826 2844 based on a simple dict. The advantage is that this allows me to
2827 2845 now have thousands of aliases with negligible cost (unthinkable
2828 2846 with the old system).
2829 2847
2830 2848 2004-06-19 Fernando Perez <fperez@colorado.edu>
2831 2849
2832 2850 * IPython/iplib.py (__init__): extended MagicCompleter class to
2833 2851 also complete (last in priority) on user aliases.
2834 2852
2835 2853 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
2836 2854 call to eval.
2837 2855 (ItplNS.__init__): Added a new class which functions like Itpl,
2838 2856 but allows configuring the namespace for the evaluation to occur
2839 2857 in.
2840 2858
2841 2859 2004-06-18 Fernando Perez <fperez@colorado.edu>
2842 2860
2843 2861 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
2844 2862 better message when 'exit' or 'quit' are typed (a common newbie
2845 2863 confusion).
2846 2864
2847 2865 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
2848 2866 check for Windows users.
2849 2867
2850 2868 * IPython/iplib.py (InteractiveShell.user_setup): removed
2851 2869 disabling of colors for Windows. I'll test at runtime and issue a
2852 2870 warning if Gary's readline isn't found, as to nudge users to
2853 2871 download it.
2854 2872
2855 2873 2004-06-16 Fernando Perez <fperez@colorado.edu>
2856 2874
2857 2875 * IPython/genutils.py (Stream.__init__): changed to print errors
2858 2876 to sys.stderr. I had a circular dependency here. Now it's
2859 2877 possible to run ipython as IDLE's shell (consider this pre-alpha,
2860 2878 since true stdout things end up in the starting terminal instead
2861 2879 of IDLE's out).
2862 2880
2863 2881 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
2864 2882 users who haven't # updated their prompt_in2 definitions. Remove
2865 2883 eventually.
2866 2884 (multiple_replace): added credit to original ASPN recipe.
2867 2885
2868 2886 2004-06-15 Fernando Perez <fperez@colorado.edu>
2869 2887
2870 2888 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
2871 2889 list of auto-defined aliases.
2872 2890
2873 2891 2004-06-13 Fernando Perez <fperez@colorado.edu>
2874 2892
2875 2893 * setup.py (scriptfiles): Don't trigger win_post_install unless an
2876 2894 install was really requested (so setup.py can be used for other
2877 2895 things under Windows).
2878 2896
2879 2897 2004-06-10 Fernando Perez <fperez@colorado.edu>
2880 2898
2881 2899 * IPython/Logger.py (Logger.create_log): Manually remove any old
2882 2900 backup, since os.remove may fail under Windows. Fixes bug
2883 2901 reported by Thorsten.
2884 2902
2885 2903 2004-06-09 Fernando Perez <fperez@colorado.edu>
2886 2904
2887 2905 * examples/example-embed.py: fixed all references to %n (replaced
2888 2906 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
2889 2907 for all examples and the manual as well.
2890 2908
2891 2909 2004-06-08 Fernando Perez <fperez@colorado.edu>
2892 2910
2893 2911 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
2894 2912 alignment and color management. All 3 prompt subsystems now
2895 2913 inherit from BasePrompt.
2896 2914
2897 2915 * tools/release: updates for windows installer build and tag rpms
2898 2916 with python version (since paths are fixed).
2899 2917
2900 2918 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
2901 2919 which will become eventually obsolete. Also fixed the default
2902 2920 prompt_in2 to use \D, so at least new users start with the correct
2903 2921 defaults.
2904 2922 WARNING: Users with existing ipythonrc files will need to apply
2905 2923 this fix manually!
2906 2924
2907 2925 * setup.py: make windows installer (.exe). This is finally the
2908 2926 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
2909 2927 which I hadn't included because it required Python 2.3 (or recent
2910 2928 distutils).
2911 2929
2912 2930 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
2913 2931 usage of new '\D' escape.
2914 2932
2915 2933 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
2916 2934 lacks os.getuid())
2917 2935 (CachedOutput.set_colors): Added the ability to turn coloring
2918 2936 on/off with @colors even for manually defined prompt colors. It
2919 2937 uses a nasty global, but it works safely and via the generic color
2920 2938 handling mechanism.
2921 2939 (Prompt2.__init__): Introduced new escape '\D' for continuation
2922 2940 prompts. It represents the counter ('\#') as dots.
2923 2941 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
2924 2942 need to update their ipythonrc files and replace '%n' with '\D' in
2925 2943 their prompt_in2 settings everywhere. Sorry, but there's
2926 2944 otherwise no clean way to get all prompts to properly align. The
2927 2945 ipythonrc shipped with IPython has been updated.
2928 2946
2929 2947 2004-06-07 Fernando Perez <fperez@colorado.edu>
2930 2948
2931 2949 * setup.py (isfile): Pass local_icons option to latex2html, so the
2932 2950 resulting HTML file is self-contained. Thanks to
2933 2951 dryice-AT-liu.com.cn for the tip.
2934 2952
2935 2953 * pysh.py: I created a new profile 'shell', which implements a
2936 2954 _rudimentary_ IPython-based shell. This is in NO WAY a realy
2937 2955 system shell, nor will it become one anytime soon. It's mainly
2938 2956 meant to illustrate the use of the new flexible bash-like prompts.
2939 2957 I guess it could be used by hardy souls for true shell management,
2940 2958 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
2941 2959 profile. This uses the InterpreterExec extension provided by
2942 2960 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
2943 2961
2944 2962 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
2945 2963 auto-align itself with the length of the previous input prompt
2946 2964 (taking into account the invisible color escapes).
2947 2965 (CachedOutput.__init__): Large restructuring of this class. Now
2948 2966 all three prompts (primary1, primary2, output) are proper objects,
2949 2967 managed by the 'parent' CachedOutput class. The code is still a
2950 2968 bit hackish (all prompts share state via a pointer to the cache),
2951 2969 but it's overall far cleaner than before.
2952 2970
2953 2971 * IPython/genutils.py (getoutputerror): modified to add verbose,
2954 2972 debug and header options. This makes the interface of all getout*
2955 2973 functions uniform.
2956 2974 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
2957 2975
2958 2976 * IPython/Magic.py (Magic.default_option): added a function to
2959 2977 allow registering default options for any magic command. This
2960 2978 makes it easy to have profiles which customize the magics globally
2961 2979 for a certain use. The values set through this function are
2962 2980 picked up by the parse_options() method, which all magics should
2963 2981 use to parse their options.
2964 2982
2965 2983 * IPython/genutils.py (warn): modified the warnings framework to
2966 2984 use the Term I/O class. I'm trying to slowly unify all of
2967 2985 IPython's I/O operations to pass through Term.
2968 2986
2969 2987 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
2970 2988 the secondary prompt to correctly match the length of the primary
2971 2989 one for any prompt. Now multi-line code will properly line up
2972 2990 even for path dependent prompts, such as the new ones available
2973 2991 via the prompt_specials.
2974 2992
2975 2993 2004-06-06 Fernando Perez <fperez@colorado.edu>
2976 2994
2977 2995 * IPython/Prompts.py (prompt_specials): Added the ability to have
2978 2996 bash-like special sequences in the prompts, which get
2979 2997 automatically expanded. Things like hostname, current working
2980 2998 directory and username are implemented already, but it's easy to
2981 2999 add more in the future. Thanks to a patch by W.J. van der Laan
2982 3000 <gnufnork-AT-hetdigitalegat.nl>
2983 3001 (prompt_specials): Added color support for prompt strings, so
2984 3002 users can define arbitrary color setups for their prompts.
2985 3003
2986 3004 2004-06-05 Fernando Perez <fperez@colorado.edu>
2987 3005
2988 3006 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
2989 3007 code to load Gary Bishop's readline and configure it
2990 3008 automatically. Thanks to Gary for help on this.
2991 3009
2992 3010 2004-06-01 Fernando Perez <fperez@colorado.edu>
2993 3011
2994 3012 * IPython/Logger.py (Logger.create_log): fix bug for logging
2995 3013 with no filename (previous fix was incomplete).
2996 3014
2997 3015 2004-05-25 Fernando Perez <fperez@colorado.edu>
2998 3016
2999 3017 * IPython/Magic.py (Magic.parse_options): fix bug where naked
3000 3018 parens would get passed to the shell.
3001 3019
3002 3020 2004-05-20 Fernando Perez <fperez@colorado.edu>
3003 3021
3004 3022 * IPython/Magic.py (Magic.magic_prun): changed default profile
3005 3023 sort order to 'time' (the more common profiling need).
3006 3024
3007 3025 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
3008 3026 so that source code shown is guaranteed in sync with the file on
3009 3027 disk (also changed in psource). Similar fix to the one for
3010 3028 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
3011 3029 <yann.ledu-AT-noos.fr>.
3012 3030
3013 3031 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
3014 3032 with a single option would not be correctly parsed. Closes
3015 3033 http://www.scipy.net/roundup/ipython/issue14. This bug had been
3016 3034 introduced in 0.6.0 (on 2004-05-06).
3017 3035
3018 3036 2004-05-13 *** Released version 0.6.0
3019 3037
3020 3038 2004-05-13 Fernando Perez <fperez@colorado.edu>
3021 3039
3022 3040 * debian/: Added debian/ directory to CVS, so that debian support
3023 3041 is publicly accessible. The debian package is maintained by Jack
3024 3042 Moffit <jack-AT-xiph.org>.
3025 3043
3026 3044 * Documentation: included the notes about an ipython-based system
3027 3045 shell (the hypothetical 'pysh') into the new_design.pdf document,
3028 3046 so that these ideas get distributed to users along with the
3029 3047 official documentation.
3030 3048
3031 3049 2004-05-10 Fernando Perez <fperez@colorado.edu>
3032 3050
3033 3051 * IPython/Logger.py (Logger.create_log): fix recently introduced
3034 3052 bug (misindented line) where logstart would fail when not given an
3035 3053 explicit filename.
3036 3054
3037 3055 2004-05-09 Fernando Perez <fperez@colorado.edu>
3038 3056
3039 3057 * IPython/Magic.py (Magic.parse_options): skip system call when
3040 3058 there are no options to look for. Faster, cleaner for the common
3041 3059 case.
3042 3060
3043 3061 * Documentation: many updates to the manual: describing Windows
3044 3062 support better, Gnuplot updates, credits, misc small stuff. Also
3045 3063 updated the new_design doc a bit.
3046 3064
3047 3065 2004-05-06 *** Released version 0.6.0.rc1
3048 3066
3049 3067 2004-05-06 Fernando Perez <fperez@colorado.edu>
3050 3068
3051 3069 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
3052 3070 operations to use the vastly more efficient list/''.join() method.
3053 3071 (FormattedTB.text): Fix
3054 3072 http://www.scipy.net/roundup/ipython/issue12 - exception source
3055 3073 extract not updated after reload. Thanks to Mike Salib
3056 3074 <msalib-AT-mit.edu> for pinning the source of the problem.
3057 3075 Fortunately, the solution works inside ipython and doesn't require
3058 3076 any changes to python proper.
3059 3077
3060 3078 * IPython/Magic.py (Magic.parse_options): Improved to process the
3061 3079 argument list as a true shell would (by actually using the
3062 3080 underlying system shell). This way, all @magics automatically get
3063 3081 shell expansion for variables. Thanks to a comment by Alex
3064 3082 Schmolck.
3065 3083
3066 3084 2004-04-04 Fernando Perez <fperez@colorado.edu>
3067 3085
3068 3086 * IPython/iplib.py (InteractiveShell.interact): Added a special
3069 3087 trap for a debugger quit exception, which is basically impossible
3070 3088 to handle by normal mechanisms, given what pdb does to the stack.
3071 3089 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
3072 3090
3073 3091 2004-04-03 Fernando Perez <fperez@colorado.edu>
3074 3092
3075 3093 * IPython/genutils.py (Term): Standardized the names of the Term
3076 3094 class streams to cin/cout/cerr, following C++ naming conventions
3077 3095 (I can't use in/out/err because 'in' is not a valid attribute
3078 3096 name).
3079 3097
3080 3098 * IPython/iplib.py (InteractiveShell.interact): don't increment
3081 3099 the prompt if there's no user input. By Daniel 'Dang' Griffith
3082 3100 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
3083 3101 Francois Pinard.
3084 3102
3085 3103 2004-04-02 Fernando Perez <fperez@colorado.edu>
3086 3104
3087 3105 * IPython/genutils.py (Stream.__init__): Modified to survive at
3088 3106 least importing in contexts where stdin/out/err aren't true file
3089 3107 objects, such as PyCrust (they lack fileno() and mode). However,
3090 3108 the recovery facilities which rely on these things existing will
3091 3109 not work.
3092 3110
3093 3111 2004-04-01 Fernando Perez <fperez@colorado.edu>
3094 3112
3095 3113 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
3096 3114 use the new getoutputerror() function, so it properly
3097 3115 distinguishes stdout/err.
3098 3116
3099 3117 * IPython/genutils.py (getoutputerror): added a function to
3100 3118 capture separately the standard output and error of a command.
3101 3119 After a comment from dang on the mailing lists. This code is
3102 3120 basically a modified version of commands.getstatusoutput(), from
3103 3121 the standard library.
3104 3122
3105 3123 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
3106 3124 '!!' as a special syntax (shorthand) to access @sx.
3107 3125
3108 3126 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
3109 3127 command and return its output as a list split on '\n'.
3110 3128
3111 3129 2004-03-31 Fernando Perez <fperez@colorado.edu>
3112 3130
3113 3131 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
3114 3132 method to dictionaries used as FakeModule instances if they lack
3115 3133 it. At least pydoc in python2.3 breaks for runtime-defined
3116 3134 functions without this hack. At some point I need to _really_
3117 3135 understand what FakeModule is doing, because it's a gross hack.
3118 3136 But it solves Arnd's problem for now...
3119 3137
3120 3138 2004-02-27 Fernando Perez <fperez@colorado.edu>
3121 3139
3122 3140 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
3123 3141 mode would behave erratically. Also increased the number of
3124 3142 possible logs in rotate mod to 999. Thanks to Rod Holland
3125 3143 <rhh@StructureLABS.com> for the report and fixes.
3126 3144
3127 3145 2004-02-26 Fernando Perez <fperez@colorado.edu>
3128 3146
3129 3147 * IPython/genutils.py (page): Check that the curses module really
3130 3148 has the initscr attribute before trying to use it. For some
3131 3149 reason, the Solaris curses module is missing this. I think this
3132 3150 should be considered a Solaris python bug, but I'm not sure.
3133 3151
3134 3152 2004-01-17 Fernando Perez <fperez@colorado.edu>
3135 3153
3136 3154 * IPython/genutils.py (Stream.__init__): Changes to try to make
3137 3155 ipython robust against stdin/out/err being closed by the user.
3138 3156 This is 'user error' (and blocks a normal python session, at least
3139 3157 the stdout case). However, Ipython should be able to survive such
3140 3158 instances of abuse as gracefully as possible. To simplify the
3141 3159 coding and maintain compatibility with Gary Bishop's Term
3142 3160 contributions, I've made use of classmethods for this. I think
3143 3161 this introduces a dependency on python 2.2.
3144 3162
3145 3163 2004-01-13 Fernando Perez <fperez@colorado.edu>
3146 3164
3147 3165 * IPython/numutils.py (exp_safe): simplified the code a bit and
3148 3166 removed the need for importing the kinds module altogether.
3149 3167
3150 3168 2004-01-06 Fernando Perez <fperez@colorado.edu>
3151 3169
3152 3170 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
3153 3171 a magic function instead, after some community feedback. No
3154 3172 special syntax will exist for it, but its name is deliberately
3155 3173 very short.
3156 3174
3157 3175 2003-12-20 Fernando Perez <fperez@colorado.edu>
3158 3176
3159 3177 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
3160 3178 new functionality, to automagically assign the result of a shell
3161 3179 command to a variable. I'll solicit some community feedback on
3162 3180 this before making it permanent.
3163 3181
3164 3182 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
3165 3183 requested about callables for which inspect couldn't obtain a
3166 3184 proper argspec. Thanks to a crash report sent by Etienne
3167 3185 Posthumus <etienne-AT-apple01.cs.vu.nl>.
3168 3186
3169 3187 2003-12-09 Fernando Perez <fperez@colorado.edu>
3170 3188
3171 3189 * IPython/genutils.py (page): patch for the pager to work across
3172 3190 various versions of Windows. By Gary Bishop.
3173 3191
3174 3192 2003-12-04 Fernando Perez <fperez@colorado.edu>
3175 3193
3176 3194 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
3177 3195 Gnuplot.py version 1.7, whose internal names changed quite a bit.
3178 3196 While I tested this and it looks ok, there may still be corner
3179 3197 cases I've missed.
3180 3198
3181 3199 2003-12-01 Fernando Perez <fperez@colorado.edu>
3182 3200
3183 3201 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
3184 3202 where a line like 'p,q=1,2' would fail because the automagic
3185 3203 system would be triggered for @p.
3186 3204
3187 3205 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
3188 3206 cleanups, code unmodified.
3189 3207
3190 3208 * IPython/genutils.py (Term): added a class for IPython to handle
3191 3209 output. In most cases it will just be a proxy for stdout/err, but
3192 3210 having this allows modifications to be made for some platforms,
3193 3211 such as handling color escapes under Windows. All of this code
3194 3212 was contributed by Gary Bishop, with minor modifications by me.
3195 3213 The actual changes affect many files.
3196 3214
3197 3215 2003-11-30 Fernando Perez <fperez@colorado.edu>
3198 3216
3199 3217 * IPython/iplib.py (file_matches): new completion code, courtesy
3200 3218 of Jeff Collins. This enables filename completion again under
3201 3219 python 2.3, which disabled it at the C level.
3202 3220
3203 3221 2003-11-11 Fernando Perez <fperez@colorado.edu>
3204 3222
3205 3223 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
3206 3224 for Numeric.array(map(...)), but often convenient.
3207 3225
3208 3226 2003-11-05 Fernando Perez <fperez@colorado.edu>
3209 3227
3210 3228 * IPython/numutils.py (frange): Changed a call from int() to
3211 3229 int(round()) to prevent a problem reported with arange() in the
3212 3230 numpy list.
3213 3231
3214 3232 2003-10-06 Fernando Perez <fperez@colorado.edu>
3215 3233
3216 3234 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
3217 3235 prevent crashes if sys lacks an argv attribute (it happens with
3218 3236 embedded interpreters which build a bare-bones sys module).
3219 3237 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
3220 3238
3221 3239 2003-09-24 Fernando Perez <fperez@colorado.edu>
3222 3240
3223 3241 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
3224 3242 to protect against poorly written user objects where __getattr__
3225 3243 raises exceptions other than AttributeError. Thanks to a bug
3226 3244 report by Oliver Sander <osander-AT-gmx.de>.
3227 3245
3228 3246 * IPython/FakeModule.py (FakeModule.__repr__): this method was
3229 3247 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
3230 3248
3231 3249 2003-09-09 Fernando Perez <fperez@colorado.edu>
3232 3250
3233 3251 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
3234 3252 unpacking a list whith a callable as first element would
3235 3253 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
3236 3254 Collins.
3237 3255
3238 3256 2003-08-25 *** Released version 0.5.0
3239 3257
3240 3258 2003-08-22 Fernando Perez <fperez@colorado.edu>
3241 3259
3242 3260 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
3243 3261 improperly defined user exceptions. Thanks to feedback from Mark
3244 3262 Russell <mrussell-AT-verio.net>.
3245 3263
3246 3264 2003-08-20 Fernando Perez <fperez@colorado.edu>
3247 3265
3248 3266 * IPython/OInspect.py (Inspector.pinfo): changed String Form
3249 3267 printing so that it would print multi-line string forms starting
3250 3268 with a new line. This way the formatting is better respected for
3251 3269 objects which work hard to make nice string forms.
3252 3270
3253 3271 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
3254 3272 autocall would overtake data access for objects with both
3255 3273 __getitem__ and __call__.
3256 3274
3257 3275 2003-08-19 *** Released version 0.5.0-rc1
3258 3276
3259 3277 2003-08-19 Fernando Perez <fperez@colorado.edu>
3260 3278
3261 3279 * IPython/deep_reload.py (load_tail): single tiny change here
3262 3280 seems to fix the long-standing bug of dreload() failing to work
3263 3281 for dotted names. But this module is pretty tricky, so I may have
3264 3282 missed some subtlety. Needs more testing!.
3265 3283
3266 3284 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
3267 3285 exceptions which have badly implemented __str__ methods.
3268 3286 (VerboseTB.text): harden against inspect.getinnerframes crashing,
3269 3287 which I've been getting reports about from Python 2.3 users. I
3270 3288 wish I had a simple test case to reproduce the problem, so I could
3271 3289 either write a cleaner workaround or file a bug report if
3272 3290 necessary.
3273 3291
3274 3292 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
3275 3293 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
3276 3294 a bug report by Tjabo Kloppenburg.
3277 3295
3278 3296 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
3279 3297 crashes. Wrapped the pdb call in a blanket try/except, since pdb
3280 3298 seems rather unstable. Thanks to a bug report by Tjabo
3281 3299 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
3282 3300
3283 3301 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
3284 3302 this out soon because of the critical fixes in the inner loop for
3285 3303 generators.
3286 3304
3287 3305 * IPython/Magic.py (Magic.getargspec): removed. This (and
3288 3306 _get_def) have been obsoleted by OInspect for a long time, I
3289 3307 hadn't noticed that they were dead code.
3290 3308 (Magic._ofind): restored _ofind functionality for a few literals
3291 3309 (those in ["''",'""','[]','{}','()']). But it won't work anymore
3292 3310 for things like "hello".capitalize?, since that would require a
3293 3311 potentially dangerous eval() again.
3294 3312
3295 3313 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
3296 3314 logic a bit more to clean up the escapes handling and minimize the
3297 3315 use of _ofind to only necessary cases. The interactive 'feel' of
3298 3316 IPython should have improved quite a bit with the changes in
3299 3317 _prefilter and _ofind (besides being far safer than before).
3300 3318
3301 3319 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
3302 3320 obscure, never reported). Edit would fail to find the object to
3303 3321 edit under some circumstances.
3304 3322 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
3305 3323 which were causing double-calling of generators. Those eval calls
3306 3324 were _very_ dangerous, since code with side effects could be
3307 3325 triggered. As they say, 'eval is evil'... These were the
3308 3326 nastiest evals in IPython. Besides, _ofind is now far simpler,
3309 3327 and it should also be quite a bit faster. Its use of inspect is
3310 3328 also safer, so perhaps some of the inspect-related crashes I've
3311 3329 seen lately with Python 2.3 might be taken care of. That will
3312 3330 need more testing.
3313 3331
3314 3332 2003-08-17 Fernando Perez <fperez@colorado.edu>
3315 3333
3316 3334 * IPython/iplib.py (InteractiveShell._prefilter): significant
3317 3335 simplifications to the logic for handling user escapes. Faster
3318 3336 and simpler code.
3319 3337
3320 3338 2003-08-14 Fernando Perez <fperez@colorado.edu>
3321 3339
3322 3340 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
3323 3341 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
3324 3342 but it should be quite a bit faster. And the recursive version
3325 3343 generated O(log N) intermediate storage for all rank>1 arrays,
3326 3344 even if they were contiguous.
3327 3345 (l1norm): Added this function.
3328 3346 (norm): Added this function for arbitrary norms (including
3329 3347 l-infinity). l1 and l2 are still special cases for convenience
3330 3348 and speed.
3331 3349
3332 3350 2003-08-03 Fernando Perez <fperez@colorado.edu>
3333 3351
3334 3352 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
3335 3353 exceptions, which now raise PendingDeprecationWarnings in Python
3336 3354 2.3. There were some in Magic and some in Gnuplot2.
3337 3355
3338 3356 2003-06-30 Fernando Perez <fperez@colorado.edu>
3339 3357
3340 3358 * IPython/genutils.py (page): modified to call curses only for
3341 3359 terminals where TERM=='xterm'. After problems under many other
3342 3360 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
3343 3361
3344 3362 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
3345 3363 would be triggered when readline was absent. This was just an old
3346 3364 debugging statement I'd forgotten to take out.
3347 3365
3348 3366 2003-06-20 Fernando Perez <fperez@colorado.edu>
3349 3367
3350 3368 * IPython/genutils.py (clock): modified to return only user time
3351 3369 (not counting system time), after a discussion on scipy. While
3352 3370 system time may be a useful quantity occasionally, it may much
3353 3371 more easily be skewed by occasional swapping or other similar
3354 3372 activity.
3355 3373
3356 3374 2003-06-05 Fernando Perez <fperez@colorado.edu>
3357 3375
3358 3376 * IPython/numutils.py (identity): new function, for building
3359 3377 arbitrary rank Kronecker deltas (mostly backwards compatible with
3360 3378 Numeric.identity)
3361 3379
3362 3380 2003-06-03 Fernando Perez <fperez@colorado.edu>
3363 3381
3364 3382 * IPython/iplib.py (InteractiveShell.handle_magic): protect
3365 3383 arguments passed to magics with spaces, to allow trailing '\' to
3366 3384 work normally (mainly for Windows users).
3367 3385
3368 3386 2003-05-29 Fernando Perez <fperez@colorado.edu>
3369 3387
3370 3388 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
3371 3389 instead of pydoc.help. This fixes a bizarre behavior where
3372 3390 printing '%s' % locals() would trigger the help system. Now
3373 3391 ipython behaves like normal python does.
3374 3392
3375 3393 Note that if one does 'from pydoc import help', the bizarre
3376 3394 behavior returns, but this will also happen in normal python, so
3377 3395 it's not an ipython bug anymore (it has to do with how pydoc.help
3378 3396 is implemented).
3379 3397
3380 3398 2003-05-22 Fernando Perez <fperez@colorado.edu>
3381 3399
3382 3400 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
3383 3401 return [] instead of None when nothing matches, also match to end
3384 3402 of line. Patch by Gary Bishop.
3385 3403
3386 3404 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
3387 3405 protection as before, for files passed on the command line. This
3388 3406 prevents the CrashHandler from kicking in if user files call into
3389 3407 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
3390 3408 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
3391 3409
3392 3410 2003-05-20 *** Released version 0.4.0
3393 3411
3394 3412 2003-05-20 Fernando Perez <fperez@colorado.edu>
3395 3413
3396 3414 * setup.py: added support for manpages. It's a bit hackish b/c of
3397 3415 a bug in the way the bdist_rpm distutils target handles gzipped
3398 3416 manpages, but it works. After a patch by Jack.
3399 3417
3400 3418 2003-05-19 Fernando Perez <fperez@colorado.edu>
3401 3419
3402 3420 * IPython/numutils.py: added a mockup of the kinds module, since
3403 3421 it was recently removed from Numeric. This way, numutils will
3404 3422 work for all users even if they are missing kinds.
3405 3423
3406 3424 * IPython/Magic.py (Magic._ofind): Harden against an inspect
3407 3425 failure, which can occur with SWIG-wrapped extensions. After a
3408 3426 crash report from Prabhu.
3409 3427
3410 3428 2003-05-16 Fernando Perez <fperez@colorado.edu>
3411 3429
3412 3430 * IPython/iplib.py (InteractiveShell.excepthook): New method to
3413 3431 protect ipython from user code which may call directly
3414 3432 sys.excepthook (this looks like an ipython crash to the user, even
3415 3433 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3416 3434 This is especially important to help users of WxWindows, but may
3417 3435 also be useful in other cases.
3418 3436
3419 3437 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
3420 3438 an optional tb_offset to be specified, and to preserve exception
3421 3439 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
3422 3440
3423 3441 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
3424 3442
3425 3443 2003-05-15 Fernando Perez <fperez@colorado.edu>
3426 3444
3427 3445 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
3428 3446 installing for a new user under Windows.
3429 3447
3430 3448 2003-05-12 Fernando Perez <fperez@colorado.edu>
3431 3449
3432 3450 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
3433 3451 handler for Emacs comint-based lines. Currently it doesn't do
3434 3452 much (but importantly, it doesn't update the history cache). In
3435 3453 the future it may be expanded if Alex needs more functionality
3436 3454 there.
3437 3455
3438 3456 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
3439 3457 info to crash reports.
3440 3458
3441 3459 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
3442 3460 just like Python's -c. Also fixed crash with invalid -color
3443 3461 option value at startup. Thanks to Will French
3444 3462 <wfrench-AT-bestweb.net> for the bug report.
3445 3463
3446 3464 2003-05-09 Fernando Perez <fperez@colorado.edu>
3447 3465
3448 3466 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
3449 3467 to EvalDict (it's a mapping, after all) and simplified its code
3450 3468 quite a bit, after a nice discussion on c.l.py where Gustavo
3451 3469 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
3452 3470
3453 3471 2003-04-30 Fernando Perez <fperez@colorado.edu>
3454 3472
3455 3473 * IPython/genutils.py (timings_out): modified it to reduce its
3456 3474 overhead in the common reps==1 case.
3457 3475
3458 3476 2003-04-29 Fernando Perez <fperez@colorado.edu>
3459 3477
3460 3478 * IPython/genutils.py (timings_out): Modified to use the resource
3461 3479 module, which avoids the wraparound problems of time.clock().
3462 3480
3463 3481 2003-04-17 *** Released version 0.2.15pre4
3464 3482
3465 3483 2003-04-17 Fernando Perez <fperez@colorado.edu>
3466 3484
3467 3485 * setup.py (scriptfiles): Split windows-specific stuff over to a
3468 3486 separate file, in an attempt to have a Windows GUI installer.
3469 3487 That didn't work, but part of the groundwork is done.
3470 3488
3471 3489 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
3472 3490 indent/unindent with 4 spaces. Particularly useful in combination
3473 3491 with the new auto-indent option.
3474 3492
3475 3493 2003-04-16 Fernando Perez <fperez@colorado.edu>
3476 3494
3477 3495 * IPython/Magic.py: various replacements of self.rc for
3478 3496 self.shell.rc. A lot more remains to be done to fully disentangle
3479 3497 this class from the main Shell class.
3480 3498
3481 3499 * IPython/GnuplotRuntime.py: added checks for mouse support so
3482 3500 that we don't try to enable it if the current gnuplot doesn't
3483 3501 really support it. Also added checks so that we don't try to
3484 3502 enable persist under Windows (where Gnuplot doesn't recognize the
3485 3503 option).
3486 3504
3487 3505 * IPython/iplib.py (InteractiveShell.interact): Added optional
3488 3506 auto-indenting code, after a patch by King C. Shu
3489 3507 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
3490 3508 get along well with pasting indented code. If I ever figure out
3491 3509 how to make that part go well, it will become on by default.
3492 3510
3493 3511 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
3494 3512 crash ipython if there was an unmatched '%' in the user's prompt
3495 3513 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3496 3514
3497 3515 * IPython/iplib.py (InteractiveShell.interact): removed the
3498 3516 ability to ask the user whether he wants to crash or not at the
3499 3517 'last line' exception handler. Calling functions at that point
3500 3518 changes the stack, and the error reports would have incorrect
3501 3519 tracebacks.
3502 3520
3503 3521 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
3504 3522 pass through a peger a pretty-printed form of any object. After a
3505 3523 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
3506 3524
3507 3525 2003-04-14 Fernando Perez <fperez@colorado.edu>
3508 3526
3509 3527 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
3510 3528 all files in ~ would be modified at first install (instead of
3511 3529 ~/.ipython). This could be potentially disastrous, as the
3512 3530 modification (make line-endings native) could damage binary files.
3513 3531
3514 3532 2003-04-10 Fernando Perez <fperez@colorado.edu>
3515 3533
3516 3534 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
3517 3535 handle only lines which are invalid python. This now means that
3518 3536 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
3519 3537 for the bug report.
3520 3538
3521 3539 2003-04-01 Fernando Perez <fperez@colorado.edu>
3522 3540
3523 3541 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
3524 3542 where failing to set sys.last_traceback would crash pdb.pm().
3525 3543 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
3526 3544 report.
3527 3545
3528 3546 2003-03-25 Fernando Perez <fperez@colorado.edu>
3529 3547
3530 3548 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
3531 3549 before printing it (it had a lot of spurious blank lines at the
3532 3550 end).
3533 3551
3534 3552 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
3535 3553 output would be sent 21 times! Obviously people don't use this
3536 3554 too often, or I would have heard about it.
3537 3555
3538 3556 2003-03-24 Fernando Perez <fperez@colorado.edu>
3539 3557
3540 3558 * setup.py (scriptfiles): renamed the data_files parameter from
3541 3559 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
3542 3560 for the patch.
3543 3561
3544 3562 2003-03-20 Fernando Perez <fperez@colorado.edu>
3545 3563
3546 3564 * IPython/genutils.py (error): added error() and fatal()
3547 3565 functions.
3548 3566
3549 3567 2003-03-18 *** Released version 0.2.15pre3
3550 3568
3551 3569 2003-03-18 Fernando Perez <fperez@colorado.edu>
3552 3570
3553 3571 * setupext/install_data_ext.py
3554 3572 (install_data_ext.initialize_options): Class contributed by Jack
3555 3573 Moffit for fixing the old distutils hack. He is sending this to
3556 3574 the distutils folks so in the future we may not need it as a
3557 3575 private fix.
3558 3576
3559 3577 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
3560 3578 changes for Debian packaging. See his patch for full details.
3561 3579 The old distutils hack of making the ipythonrc* files carry a
3562 3580 bogus .py extension is gone, at last. Examples were moved to a
3563 3581 separate subdir under doc/, and the separate executable scripts
3564 3582 now live in their own directory. Overall a great cleanup. The
3565 3583 manual was updated to use the new files, and setup.py has been
3566 3584 fixed for this setup.
3567 3585
3568 3586 * IPython/PyColorize.py (Parser.usage): made non-executable and
3569 3587 created a pycolor wrapper around it to be included as a script.
3570 3588
3571 3589 2003-03-12 *** Released version 0.2.15pre2
3572 3590
3573 3591 2003-03-12 Fernando Perez <fperez@colorado.edu>
3574 3592
3575 3593 * IPython/ColorANSI.py (make_color_table): Finally fixed the
3576 3594 long-standing problem with garbage characters in some terminals.
3577 3595 The issue was really that the \001 and \002 escapes must _only_ be
3578 3596 passed to input prompts (which call readline), but _never_ to
3579 3597 normal text to be printed on screen. I changed ColorANSI to have
3580 3598 two classes: TermColors and InputTermColors, each with the
3581 3599 appropriate escapes for input prompts or normal text. The code in
3582 3600 Prompts.py got slightly more complicated, but this very old and
3583 3601 annoying bug is finally fixed.
3584 3602
3585 3603 All the credit for nailing down the real origin of this problem
3586 3604 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
3587 3605 *Many* thanks to him for spending quite a bit of effort on this.
3588 3606
3589 3607 2003-03-05 *** Released version 0.2.15pre1
3590 3608
3591 3609 2003-03-03 Fernando Perez <fperez@colorado.edu>
3592 3610
3593 3611 * IPython/FakeModule.py: Moved the former _FakeModule to a
3594 3612 separate file, because it's also needed by Magic (to fix a similar
3595 3613 pickle-related issue in @run).
3596 3614
3597 3615 2003-03-02 Fernando Perez <fperez@colorado.edu>
3598 3616
3599 3617 * IPython/Magic.py (Magic.magic_autocall): new magic to control
3600 3618 the autocall option at runtime.
3601 3619 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
3602 3620 across Magic.py to start separating Magic from InteractiveShell.
3603 3621 (Magic._ofind): Fixed to return proper namespace for dotted
3604 3622 names. Before, a dotted name would always return 'not currently
3605 3623 defined', because it would find the 'parent'. s.x would be found,
3606 3624 but since 'x' isn't defined by itself, it would get confused.
3607 3625 (Magic.magic_run): Fixed pickling problems reported by Ralf
3608 3626 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
3609 3627 that I'd used when Mike Heeter reported similar issues at the
3610 3628 top-level, but now for @run. It boils down to injecting the
3611 3629 namespace where code is being executed with something that looks
3612 3630 enough like a module to fool pickle.dump(). Since a pickle stores
3613 3631 a named reference to the importing module, we need this for
3614 3632 pickles to save something sensible.
3615 3633
3616 3634 * IPython/ipmaker.py (make_IPython): added an autocall option.
3617 3635
3618 3636 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
3619 3637 the auto-eval code. Now autocalling is an option, and the code is
3620 3638 also vastly safer. There is no more eval() involved at all.
3621 3639
3622 3640 2003-03-01 Fernando Perez <fperez@colorado.edu>
3623 3641
3624 3642 * IPython/Magic.py (Magic._ofind): Changed interface to return a
3625 3643 dict with named keys instead of a tuple.
3626 3644
3627 3645 * IPython: Started using CVS for IPython as of 0.2.15pre1.
3628 3646
3629 3647 * setup.py (make_shortcut): Fixed message about directories
3630 3648 created during Windows installation (the directories were ok, just
3631 3649 the printed message was misleading). Thanks to Chris Liechti
3632 3650 <cliechti-AT-gmx.net> for the heads up.
3633 3651
3634 3652 2003-02-21 Fernando Perez <fperez@colorado.edu>
3635 3653
3636 3654 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
3637 3655 of ValueError exception when checking for auto-execution. This
3638 3656 one is raised by things like Numeric arrays arr.flat when the
3639 3657 array is non-contiguous.
3640 3658
3641 3659 2003-01-31 Fernando Perez <fperez@colorado.edu>
3642 3660
3643 3661 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
3644 3662 not return any value at all (even though the command would get
3645 3663 executed).
3646 3664 (xsys): Flush stdout right after printing the command to ensure
3647 3665 proper ordering of commands and command output in the total
3648 3666 output.
3649 3667 (SystemExec/xsys/bq): Switched the names of xsys/bq and
3650 3668 system/getoutput as defaults. The old ones are kept for
3651 3669 compatibility reasons, so no code which uses this library needs
3652 3670 changing.
3653 3671
3654 3672 2003-01-27 *** Released version 0.2.14
3655 3673
3656 3674 2003-01-25 Fernando Perez <fperez@colorado.edu>
3657 3675
3658 3676 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
3659 3677 functions defined in previous edit sessions could not be re-edited
3660 3678 (because the temp files were immediately removed). Now temp files
3661 3679 are removed only at IPython's exit.
3662 3680 (Magic.magic_run): Improved @run to perform shell-like expansions
3663 3681 on its arguments (~users and $VARS). With this, @run becomes more
3664 3682 like a normal command-line.
3665 3683
3666 3684 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
3667 3685 bugs related to embedding and cleaned up that code. A fairly
3668 3686 important one was the impossibility to access the global namespace
3669 3687 through the embedded IPython (only local variables were visible).
3670 3688
3671 3689 2003-01-14 Fernando Perez <fperez@colorado.edu>
3672 3690
3673 3691 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
3674 3692 auto-calling to be a bit more conservative. Now it doesn't get
3675 3693 triggered if any of '!=()<>' are in the rest of the input line, to
3676 3694 allow comparing callables. Thanks to Alex for the heads up.
3677 3695
3678 3696 2003-01-07 Fernando Perez <fperez@colorado.edu>
3679 3697
3680 3698 * IPython/genutils.py (page): fixed estimation of the number of
3681 3699 lines in a string to be paged to simply count newlines. This
3682 3700 prevents over-guessing due to embedded escape sequences. A better
3683 3701 long-term solution would involve stripping out the control chars
3684 3702 for the count, but it's potentially so expensive I just don't
3685 3703 think it's worth doing.
3686 3704
3687 3705 2002-12-19 *** Released version 0.2.14pre50
3688 3706
3689 3707 2002-12-19 Fernando Perez <fperez@colorado.edu>
3690 3708
3691 3709 * tools/release (version): Changed release scripts to inform
3692 3710 Andrea and build a NEWS file with a list of recent changes.
3693 3711
3694 3712 * IPython/ColorANSI.py (__all__): changed terminal detection
3695 3713 code. Seems to work better for xterms without breaking
3696 3714 konsole. Will need more testing to determine if WinXP and Mac OSX
3697 3715 also work ok.
3698 3716
3699 3717 2002-12-18 *** Released version 0.2.14pre49
3700 3718
3701 3719 2002-12-18 Fernando Perez <fperez@colorado.edu>
3702 3720
3703 3721 * Docs: added new info about Mac OSX, from Andrea.
3704 3722
3705 3723 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
3706 3724 allow direct plotting of python strings whose format is the same
3707 3725 of gnuplot data files.
3708 3726
3709 3727 2002-12-16 Fernando Perez <fperez@colorado.edu>
3710 3728
3711 3729 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
3712 3730 value of exit question to be acknowledged.
3713 3731
3714 3732 2002-12-03 Fernando Perez <fperez@colorado.edu>
3715 3733
3716 3734 * IPython/ipmaker.py: removed generators, which had been added
3717 3735 by mistake in an earlier debugging run. This was causing trouble
3718 3736 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
3719 3737 for pointing this out.
3720 3738
3721 3739 2002-11-17 Fernando Perez <fperez@colorado.edu>
3722 3740
3723 3741 * Manual: updated the Gnuplot section.
3724 3742
3725 3743 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
3726 3744 a much better split of what goes in Runtime and what goes in
3727 3745 Interactive.
3728 3746
3729 3747 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
3730 3748 being imported from iplib.
3731 3749
3732 3750 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
3733 3751 for command-passing. Now the global Gnuplot instance is called
3734 3752 'gp' instead of 'g', which was really a far too fragile and
3735 3753 common name.
3736 3754
3737 3755 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
3738 3756 bounding boxes generated by Gnuplot for square plots.
3739 3757
3740 3758 * IPython/genutils.py (popkey): new function added. I should
3741 3759 suggest this on c.l.py as a dict method, it seems useful.
3742 3760
3743 3761 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
3744 3762 to transparently handle PostScript generation. MUCH better than
3745 3763 the previous plot_eps/replot_eps (which I removed now). The code
3746 3764 is also fairly clean and well documented now (including
3747 3765 docstrings).
3748 3766
3749 3767 2002-11-13 Fernando Perez <fperez@colorado.edu>
3750 3768
3751 3769 * IPython/Magic.py (Magic.magic_edit): fixed docstring
3752 3770 (inconsistent with options).
3753 3771
3754 3772 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
3755 3773 manually disabled, I don't know why. Fixed it.
3756 3774 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
3757 3775 eps output.
3758 3776
3759 3777 2002-11-12 Fernando Perez <fperez@colorado.edu>
3760 3778
3761 3779 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
3762 3780 don't propagate up to caller. Fixes crash reported by François
3763 3781 Pinard.
3764 3782
3765 3783 2002-11-09 Fernando Perez <fperez@colorado.edu>
3766 3784
3767 3785 * IPython/ipmaker.py (make_IPython): fixed problem with writing
3768 3786 history file for new users.
3769 3787 (make_IPython): fixed bug where initial install would leave the
3770 3788 user running in the .ipython dir.
3771 3789 (make_IPython): fixed bug where config dir .ipython would be
3772 3790 created regardless of the given -ipythondir option. Thanks to Cory
3773 3791 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
3774 3792
3775 3793 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
3776 3794 type confirmations. Will need to use it in all of IPython's code
3777 3795 consistently.
3778 3796
3779 3797 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
3780 3798 context to print 31 lines instead of the default 5. This will make
3781 3799 the crash reports extremely detailed in case the problem is in
3782 3800 libraries I don't have access to.
3783 3801
3784 3802 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
3785 3803 line of defense' code to still crash, but giving users fair
3786 3804 warning. I don't want internal errors to go unreported: if there's
3787 3805 an internal problem, IPython should crash and generate a full
3788 3806 report.
3789 3807
3790 3808 2002-11-08 Fernando Perez <fperez@colorado.edu>
3791 3809
3792 3810 * IPython/iplib.py (InteractiveShell.interact): added code to trap
3793 3811 otherwise uncaught exceptions which can appear if people set
3794 3812 sys.stdout to something badly broken. Thanks to a crash report
3795 3813 from henni-AT-mail.brainbot.com.
3796 3814
3797 3815 2002-11-04 Fernando Perez <fperez@colorado.edu>
3798 3816
3799 3817 * IPython/iplib.py (InteractiveShell.interact): added
3800 3818 __IPYTHON__active to the builtins. It's a flag which goes on when
3801 3819 the interaction starts and goes off again when it stops. This
3802 3820 allows embedding code to detect being inside IPython. Before this
3803 3821 was done via __IPYTHON__, but that only shows that an IPython
3804 3822 instance has been created.
3805 3823
3806 3824 * IPython/Magic.py (Magic.magic_env): I realized that in a
3807 3825 UserDict, instance.data holds the data as a normal dict. So I
3808 3826 modified @env to return os.environ.data instead of rebuilding a
3809 3827 dict by hand.
3810 3828
3811 3829 2002-11-02 Fernando Perez <fperez@colorado.edu>
3812 3830
3813 3831 * IPython/genutils.py (warn): changed so that level 1 prints no
3814 3832 header. Level 2 is now the default (with 'WARNING' header, as
3815 3833 before). I think I tracked all places where changes were needed in
3816 3834 IPython, but outside code using the old level numbering may have
3817 3835 broken.
3818 3836
3819 3837 * IPython/iplib.py (InteractiveShell.runcode): added this to
3820 3838 handle the tracebacks in SystemExit traps correctly. The previous
3821 3839 code (through interact) was printing more of the stack than
3822 3840 necessary, showing IPython internal code to the user.
3823 3841
3824 3842 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
3825 3843 default. Now that the default at the confirmation prompt is yes,
3826 3844 it's not so intrusive. François' argument that ipython sessions
3827 3845 tend to be complex enough not to lose them from an accidental C-d,
3828 3846 is a valid one.
3829 3847
3830 3848 * IPython/iplib.py (InteractiveShell.interact): added a
3831 3849 showtraceback() call to the SystemExit trap, and modified the exit
3832 3850 confirmation to have yes as the default.
3833 3851
3834 3852 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
3835 3853 this file. It's been gone from the code for a long time, this was
3836 3854 simply leftover junk.
3837 3855
3838 3856 2002-11-01 Fernando Perez <fperez@colorado.edu>
3839 3857
3840 3858 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
3841 3859 added. If set, IPython now traps EOF and asks for
3842 3860 confirmation. After a request by François Pinard.
3843 3861
3844 3862 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
3845 3863 of @abort, and with a new (better) mechanism for handling the
3846 3864 exceptions.
3847 3865
3848 3866 2002-10-27 Fernando Perez <fperez@colorado.edu>
3849 3867
3850 3868 * IPython/usage.py (__doc__): updated the --help information and
3851 3869 the ipythonrc file to indicate that -log generates
3852 3870 ./ipython.log. Also fixed the corresponding info in @logstart.
3853 3871 This and several other fixes in the manuals thanks to reports by
3854 3872 François Pinard <pinard-AT-iro.umontreal.ca>.
3855 3873
3856 3874 * IPython/Logger.py (Logger.switch_log): Fixed error message to
3857 3875 refer to @logstart (instead of @log, which doesn't exist).
3858 3876
3859 3877 * IPython/iplib.py (InteractiveShell._prefilter): fixed
3860 3878 AttributeError crash. Thanks to Christopher Armstrong
3861 3879 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
3862 3880 introduced recently (in 0.2.14pre37) with the fix to the eval
3863 3881 problem mentioned below.
3864 3882
3865 3883 2002-10-17 Fernando Perez <fperez@colorado.edu>
3866 3884
3867 3885 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
3868 3886 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
3869 3887
3870 3888 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
3871 3889 this function to fix a problem reported by Alex Schmolck. He saw
3872 3890 it with list comprehensions and generators, which were getting
3873 3891 called twice. The real problem was an 'eval' call in testing for
3874 3892 automagic which was evaluating the input line silently.
3875 3893
3876 3894 This is a potentially very nasty bug, if the input has side
3877 3895 effects which must not be repeated. The code is much cleaner now,
3878 3896 without any blanket 'except' left and with a regexp test for
3879 3897 actual function names.
3880 3898
3881 3899 But an eval remains, which I'm not fully comfortable with. I just
3882 3900 don't know how to find out if an expression could be a callable in
3883 3901 the user's namespace without doing an eval on the string. However
3884 3902 that string is now much more strictly checked so that no code
3885 3903 slips by, so the eval should only happen for things that can
3886 3904 really be only function/method names.
3887 3905
3888 3906 2002-10-15 Fernando Perez <fperez@colorado.edu>
3889 3907
3890 3908 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
3891 3909 OSX information to main manual, removed README_Mac_OSX file from
3892 3910 distribution. Also updated credits for recent additions.
3893 3911
3894 3912 2002-10-10 Fernando Perez <fperez@colorado.edu>
3895 3913
3896 3914 * README_Mac_OSX: Added a README for Mac OSX users for fixing
3897 3915 terminal-related issues. Many thanks to Andrea Riciputi
3898 3916 <andrea.riciputi-AT-libero.it> for writing it.
3899 3917
3900 3918 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
3901 3919 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
3902 3920
3903 3921 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
3904 3922 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
3905 3923 <syver-en-AT-online.no> who both submitted patches for this problem.
3906 3924
3907 3925 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
3908 3926 global embedding to make sure that things don't overwrite user
3909 3927 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
3910 3928
3911 3929 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
3912 3930 compatibility. Thanks to Hayden Callow
3913 3931 <h.callow-AT-elec.canterbury.ac.nz>
3914 3932
3915 3933 2002-10-04 Fernando Perez <fperez@colorado.edu>
3916 3934
3917 3935 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
3918 3936 Gnuplot.File objects.
3919 3937
3920 3938 2002-07-23 Fernando Perez <fperez@colorado.edu>
3921 3939
3922 3940 * IPython/genutils.py (timing): Added timings() and timing() for
3923 3941 quick access to the most commonly needed data, the execution
3924 3942 times. Old timing() renamed to timings_out().
3925 3943
3926 3944 2002-07-18 Fernando Perez <fperez@colorado.edu>
3927 3945
3928 3946 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
3929 3947 bug with nested instances disrupting the parent's tab completion.
3930 3948
3931 3949 * IPython/iplib.py (all_completions): Added Alex Schmolck's
3932 3950 all_completions code to begin the emacs integration.
3933 3951
3934 3952 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
3935 3953 argument to allow titling individual arrays when plotting.
3936 3954
3937 3955 2002-07-15 Fernando Perez <fperez@colorado.edu>
3938 3956
3939 3957 * setup.py (make_shortcut): changed to retrieve the value of
3940 3958 'Program Files' directory from the registry (this value changes in
3941 3959 non-english versions of Windows). Thanks to Thomas Fanslau
3942 3960 <tfanslau-AT-gmx.de> for the report.
3943 3961
3944 3962 2002-07-10 Fernando Perez <fperez@colorado.edu>
3945 3963
3946 3964 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
3947 3965 a bug in pdb, which crashes if a line with only whitespace is
3948 3966 entered. Bug report submitted to sourceforge.
3949 3967
3950 3968 2002-07-09 Fernando Perez <fperez@colorado.edu>
3951 3969
3952 3970 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
3953 3971 reporting exceptions (it's a bug in inspect.py, I just set a
3954 3972 workaround).
3955 3973
3956 3974 2002-07-08 Fernando Perez <fperez@colorado.edu>
3957 3975
3958 3976 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
3959 3977 __IPYTHON__ in __builtins__ to show up in user_ns.
3960 3978
3961 3979 2002-07-03 Fernando Perez <fperez@colorado.edu>
3962 3980
3963 3981 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
3964 3982 name from @gp_set_instance to @gp_set_default.
3965 3983
3966 3984 * IPython/ipmaker.py (make_IPython): default editor value set to
3967 3985 '0' (a string), to match the rc file. Otherwise will crash when
3968 3986 .strip() is called on it.
3969 3987
3970 3988
3971 3989 2002-06-28 Fernando Perez <fperez@colorado.edu>
3972 3990
3973 3991 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
3974 3992 of files in current directory when a file is executed via
3975 3993 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
3976 3994
3977 3995 * setup.py (manfiles): fix for rpm builds, submitted by RA
3978 3996 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
3979 3997
3980 3998 * IPython/ipmaker.py (make_IPython): fixed lookup of default
3981 3999 editor when set to '0'. Problem was, '0' evaluates to True (it's a
3982 4000 string!). A. Schmolck caught this one.
3983 4001
3984 4002 2002-06-27 Fernando Perez <fperez@colorado.edu>
3985 4003
3986 4004 * IPython/ipmaker.py (make_IPython): fixed bug when running user
3987 4005 defined files at the cmd line. __name__ wasn't being set to
3988 4006 __main__.
3989 4007
3990 4008 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
3991 4009 regular lists and tuples besides Numeric arrays.
3992 4010
3993 4011 * IPython/Prompts.py (CachedOutput.__call__): Added output
3994 4012 supression for input ending with ';'. Similar to Mathematica and
3995 4013 Matlab. The _* vars and Out[] list are still updated, just like
3996 4014 Mathematica behaves.
3997 4015
3998 4016 2002-06-25 Fernando Perez <fperez@colorado.edu>
3999 4017
4000 4018 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
4001 4019 .ini extensions for profiels under Windows.
4002 4020
4003 4021 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
4004 4022 string form. Fix contributed by Alexander Schmolck
4005 4023 <a.schmolck-AT-gmx.net>
4006 4024
4007 4025 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
4008 4026 pre-configured Gnuplot instance.
4009 4027
4010 4028 2002-06-21 Fernando Perez <fperez@colorado.edu>
4011 4029
4012 4030 * IPython/numutils.py (exp_safe): new function, works around the
4013 4031 underflow problems in Numeric.
4014 4032 (log2): New fn. Safe log in base 2: returns exact integer answer
4015 4033 for exact integer powers of 2.
4016 4034
4017 4035 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
4018 4036 properly.
4019 4037
4020 4038 2002-06-20 Fernando Perez <fperez@colorado.edu>
4021 4039
4022 4040 * IPython/genutils.py (timing): new function like
4023 4041 Mathematica's. Similar to time_test, but returns more info.
4024 4042
4025 4043 2002-06-18 Fernando Perez <fperez@colorado.edu>
4026 4044
4027 4045 * IPython/Magic.py (Magic.magic_save): modified @save and @r
4028 4046 according to Mike Heeter's suggestions.
4029 4047
4030 4048 2002-06-16 Fernando Perez <fperez@colorado.edu>
4031 4049
4032 4050 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
4033 4051 system. GnuplotMagic is gone as a user-directory option. New files
4034 4052 make it easier to use all the gnuplot stuff both from external
4035 4053 programs as well as from IPython. Had to rewrite part of
4036 4054 hardcopy() b/c of a strange bug: often the ps files simply don't
4037 4055 get created, and require a repeat of the command (often several
4038 4056 times).
4039 4057
4040 4058 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
4041 4059 resolve output channel at call time, so that if sys.stderr has
4042 4060 been redirected by user this gets honored.
4043 4061
4044 4062 2002-06-13 Fernando Perez <fperez@colorado.edu>
4045 4063
4046 4064 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
4047 4065 IPShell. Kept a copy with the old names to avoid breaking people's
4048 4066 embedded code.
4049 4067
4050 4068 * IPython/ipython: simplified it to the bare minimum after
4051 4069 Holger's suggestions. Added info about how to use it in
4052 4070 PYTHONSTARTUP.
4053 4071
4054 4072 * IPython/Shell.py (IPythonShell): changed the options passing
4055 4073 from a string with funky %s replacements to a straight list. Maybe
4056 4074 a bit more typing, but it follows sys.argv conventions, so there's
4057 4075 less special-casing to remember.
4058 4076
4059 4077 2002-06-12 Fernando Perez <fperez@colorado.edu>
4060 4078
4061 4079 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
4062 4080 command. Thanks to a suggestion by Mike Heeter.
4063 4081 (Magic.magic_pfile): added behavior to look at filenames if given
4064 4082 arg is not a defined object.
4065 4083 (Magic.magic_save): New @save function to save code snippets. Also
4066 4084 a Mike Heeter idea.
4067 4085
4068 4086 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
4069 4087 plot() and replot(). Much more convenient now, especially for
4070 4088 interactive use.
4071 4089
4072 4090 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
4073 4091 filenames.
4074 4092
4075 4093 2002-06-02 Fernando Perez <fperez@colorado.edu>
4076 4094
4077 4095 * IPython/Struct.py (Struct.__init__): modified to admit
4078 4096 initialization via another struct.
4079 4097
4080 4098 * IPython/genutils.py (SystemExec.__init__): New stateful
4081 4099 interface to xsys and bq. Useful for writing system scripts.
4082 4100
4083 4101 2002-05-30 Fernando Perez <fperez@colorado.edu>
4084 4102
4085 4103 * MANIFEST.in: Changed docfile selection to exclude all the lyx
4086 4104 documents. This will make the user download smaller (it's getting
4087 4105 too big).
4088 4106
4089 4107 2002-05-29 Fernando Perez <fperez@colorado.edu>
4090 4108
4091 4109 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
4092 4110 fix problems with shelve and pickle. Seems to work, but I don't
4093 4111 know if corner cases break it. Thanks to Mike Heeter
4094 4112 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
4095 4113
4096 4114 2002-05-24 Fernando Perez <fperez@colorado.edu>
4097 4115
4098 4116 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
4099 4117 macros having broken.
4100 4118
4101 4119 2002-05-21 Fernando Perez <fperez@colorado.edu>
4102 4120
4103 4121 * IPython/Magic.py (Magic.magic_logstart): fixed recently
4104 4122 introduced logging bug: all history before logging started was
4105 4123 being written one character per line! This came from the redesign
4106 4124 of the input history as a special list which slices to strings,
4107 4125 not to lists.
4108 4126
4109 4127 2002-05-20 Fernando Perez <fperez@colorado.edu>
4110 4128
4111 4129 * IPython/Prompts.py (CachedOutput.__init__): made the color table
4112 4130 be an attribute of all classes in this module. The design of these
4113 4131 classes needs some serious overhauling.
4114 4132
4115 4133 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
4116 4134 which was ignoring '_' in option names.
4117 4135
4118 4136 * IPython/ultraTB.py (FormattedTB.__init__): Changed
4119 4137 'Verbose_novars' to 'Context' and made it the new default. It's a
4120 4138 bit more readable and also safer than verbose.
4121 4139
4122 4140 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
4123 4141 triple-quoted strings.
4124 4142
4125 4143 * IPython/OInspect.py (__all__): new module exposing the object
4126 4144 introspection facilities. Now the corresponding magics are dummy
4127 4145 wrappers around this. Having this module will make it much easier
4128 4146 to put these functions into our modified pdb.
4129 4147 This new object inspector system uses the new colorizing module,
4130 4148 so source code and other things are nicely syntax highlighted.
4131 4149
4132 4150 2002-05-18 Fernando Perez <fperez@colorado.edu>
4133 4151
4134 4152 * IPython/ColorANSI.py: Split the coloring tools into a separate
4135 4153 module so I can use them in other code easier (they were part of
4136 4154 ultraTB).
4137 4155
4138 4156 2002-05-17 Fernando Perez <fperez@colorado.edu>
4139 4157
4140 4158 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
4141 4159 fixed it to set the global 'g' also to the called instance, as
4142 4160 long as 'g' was still a gnuplot instance (so it doesn't overwrite
4143 4161 user's 'g' variables).
4144 4162
4145 4163 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
4146 4164 global variables (aliases to _ih,_oh) so that users which expect
4147 4165 In[5] or Out[7] to work aren't unpleasantly surprised.
4148 4166 (InputList.__getslice__): new class to allow executing slices of
4149 4167 input history directly. Very simple class, complements the use of
4150 4168 macros.
4151 4169
4152 4170 2002-05-16 Fernando Perez <fperez@colorado.edu>
4153 4171
4154 4172 * setup.py (docdirbase): make doc directory be just doc/IPython
4155 4173 without version numbers, it will reduce clutter for users.
4156 4174
4157 4175 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
4158 4176 execfile call to prevent possible memory leak. See for details:
4159 4177 http://mail.python.org/pipermail/python-list/2002-February/088476.html
4160 4178
4161 4179 2002-05-15 Fernando Perez <fperez@colorado.edu>
4162 4180
4163 4181 * IPython/Magic.py (Magic.magic_psource): made the object
4164 4182 introspection names be more standard: pdoc, pdef, pfile and
4165 4183 psource. They all print/page their output, and it makes
4166 4184 remembering them easier. Kept old names for compatibility as
4167 4185 aliases.
4168 4186
4169 4187 2002-05-14 Fernando Perez <fperez@colorado.edu>
4170 4188
4171 4189 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
4172 4190 what the mouse problem was. The trick is to use gnuplot with temp
4173 4191 files and NOT with pipes (for data communication), because having
4174 4192 both pipes and the mouse on is bad news.
4175 4193
4176 4194 2002-05-13 Fernando Perez <fperez@colorado.edu>
4177 4195
4178 4196 * IPython/Magic.py (Magic._ofind): fixed namespace order search
4179 4197 bug. Information would be reported about builtins even when
4180 4198 user-defined functions overrode them.
4181 4199
4182 4200 2002-05-11 Fernando Perez <fperez@colorado.edu>
4183 4201
4184 4202 * IPython/__init__.py (__all__): removed FlexCompleter from
4185 4203 __all__ so that things don't fail in platforms without readline.
4186 4204
4187 4205 2002-05-10 Fernando Perez <fperez@colorado.edu>
4188 4206
4189 4207 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
4190 4208 it requires Numeric, effectively making Numeric a dependency for
4191 4209 IPython.
4192 4210
4193 4211 * Released 0.2.13
4194 4212
4195 4213 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
4196 4214 profiler interface. Now all the major options from the profiler
4197 4215 module are directly supported in IPython, both for single
4198 4216 expressions (@prun) and for full programs (@run -p).
4199 4217
4200 4218 2002-05-09 Fernando Perez <fperez@colorado.edu>
4201 4219
4202 4220 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
4203 4221 magic properly formatted for screen.
4204 4222
4205 4223 * setup.py (make_shortcut): Changed things to put pdf version in
4206 4224 doc/ instead of doc/manual (had to change lyxport a bit).
4207 4225
4208 4226 * IPython/Magic.py (Profile.string_stats): made profile runs go
4209 4227 through pager (they are long and a pager allows searching, saving,
4210 4228 etc.)
4211 4229
4212 4230 2002-05-08 Fernando Perez <fperez@colorado.edu>
4213 4231
4214 4232 * Released 0.2.12
4215 4233
4216 4234 2002-05-06 Fernando Perez <fperez@colorado.edu>
4217 4235
4218 4236 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
4219 4237 introduced); 'hist n1 n2' was broken.
4220 4238 (Magic.magic_pdb): added optional on/off arguments to @pdb
4221 4239 (Magic.magic_run): added option -i to @run, which executes code in
4222 4240 the IPython namespace instead of a clean one. Also added @irun as
4223 4241 an alias to @run -i.
4224 4242
4225 4243 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
4226 4244 fixed (it didn't really do anything, the namespaces were wrong).
4227 4245
4228 4246 * IPython/Debugger.py (__init__): Added workaround for python 2.1
4229 4247
4230 4248 * IPython/__init__.py (__all__): Fixed package namespace, now
4231 4249 'import IPython' does give access to IPython.<all> as
4232 4250 expected. Also renamed __release__ to Release.
4233 4251
4234 4252 * IPython/Debugger.py (__license__): created new Pdb class which
4235 4253 functions like a drop-in for the normal pdb.Pdb but does NOT
4236 4254 import readline by default. This way it doesn't muck up IPython's
4237 4255 readline handling, and now tab-completion finally works in the
4238 4256 debugger -- sort of. It completes things globally visible, but the
4239 4257 completer doesn't track the stack as pdb walks it. That's a bit
4240 4258 tricky, and I'll have to implement it later.
4241 4259
4242 4260 2002-05-05 Fernando Perez <fperez@colorado.edu>
4243 4261
4244 4262 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
4245 4263 magic docstrings when printed via ? (explicit \'s were being
4246 4264 printed).
4247 4265
4248 4266 * IPython/ipmaker.py (make_IPython): fixed namespace
4249 4267 identification bug. Now variables loaded via logs or command-line
4250 4268 files are recognized in the interactive namespace by @who.
4251 4269
4252 4270 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
4253 4271 log replay system stemming from the string form of Structs.
4254 4272
4255 4273 * IPython/Magic.py (Macro.__init__): improved macros to properly
4256 4274 handle magic commands in them.
4257 4275 (Magic.magic_logstart): usernames are now expanded so 'logstart
4258 4276 ~/mylog' now works.
4259 4277
4260 4278 * IPython/iplib.py (complete): fixed bug where paths starting with
4261 4279 '/' would be completed as magic names.
4262 4280
4263 4281 2002-05-04 Fernando Perez <fperez@colorado.edu>
4264 4282
4265 4283 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
4266 4284 allow running full programs under the profiler's control.
4267 4285
4268 4286 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
4269 4287 mode to report exceptions verbosely but without formatting
4270 4288 variables. This addresses the issue of ipython 'freezing' (it's
4271 4289 not frozen, but caught in an expensive formatting loop) when huge
4272 4290 variables are in the context of an exception.
4273 4291 (VerboseTB.text): Added '--->' markers at line where exception was
4274 4292 triggered. Much clearer to read, especially in NoColor modes.
4275 4293
4276 4294 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
4277 4295 implemented in reverse when changing to the new parse_options().
4278 4296
4279 4297 2002-05-03 Fernando Perez <fperez@colorado.edu>
4280 4298
4281 4299 * IPython/Magic.py (Magic.parse_options): new function so that
4282 4300 magics can parse options easier.
4283 4301 (Magic.magic_prun): new function similar to profile.run(),
4284 4302 suggested by Chris Hart.
4285 4303 (Magic.magic_cd): fixed behavior so that it only changes if
4286 4304 directory actually is in history.
4287 4305
4288 4306 * IPython/usage.py (__doc__): added information about potential
4289 4307 slowness of Verbose exception mode when there are huge data
4290 4308 structures to be formatted (thanks to Archie Paulson).
4291 4309
4292 4310 * IPython/ipmaker.py (make_IPython): Changed default logging
4293 4311 (when simply called with -log) to use curr_dir/ipython.log in
4294 4312 rotate mode. Fixed crash which was occuring with -log before
4295 4313 (thanks to Jim Boyle).
4296 4314
4297 4315 2002-05-01 Fernando Perez <fperez@colorado.edu>
4298 4316
4299 4317 * Released 0.2.11 for these fixes (mainly the ultraTB one which
4300 4318 was nasty -- though somewhat of a corner case).
4301 4319
4302 4320 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
4303 4321 text (was a bug).
4304 4322
4305 4323 2002-04-30 Fernando Perez <fperez@colorado.edu>
4306 4324
4307 4325 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
4308 4326 a print after ^D or ^C from the user so that the In[] prompt
4309 4327 doesn't over-run the gnuplot one.
4310 4328
4311 4329 2002-04-29 Fernando Perez <fperez@colorado.edu>
4312 4330
4313 4331 * Released 0.2.10
4314 4332
4315 4333 * IPython/__release__.py (version): get date dynamically.
4316 4334
4317 4335 * Misc. documentation updates thanks to Arnd's comments. Also ran
4318 4336 a full spellcheck on the manual (hadn't been done in a while).
4319 4337
4320 4338 2002-04-27 Fernando Perez <fperez@colorado.edu>
4321 4339
4322 4340 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
4323 4341 starting a log in mid-session would reset the input history list.
4324 4342
4325 4343 2002-04-26 Fernando Perez <fperez@colorado.edu>
4326 4344
4327 4345 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
4328 4346 all files were being included in an update. Now anything in
4329 4347 UserConfig that matches [A-Za-z]*.py will go (this excludes
4330 4348 __init__.py)
4331 4349
4332 4350 2002-04-25 Fernando Perez <fperez@colorado.edu>
4333 4351
4334 4352 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
4335 4353 to __builtins__ so that any form of embedded or imported code can
4336 4354 test for being inside IPython.
4337 4355
4338 4356 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
4339 4357 changed to GnuplotMagic because it's now an importable module,
4340 4358 this makes the name follow that of the standard Gnuplot module.
4341 4359 GnuplotMagic can now be loaded at any time in mid-session.
4342 4360
4343 4361 2002-04-24 Fernando Perez <fperez@colorado.edu>
4344 4362
4345 4363 * IPython/numutils.py: removed SIUnits. It doesn't properly set
4346 4364 the globals (IPython has its own namespace) and the
4347 4365 PhysicalQuantity stuff is much better anyway.
4348 4366
4349 4367 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
4350 4368 embedding example to standard user directory for
4351 4369 distribution. Also put it in the manual.
4352 4370
4353 4371 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
4354 4372 instance as first argument (so it doesn't rely on some obscure
4355 4373 hidden global).
4356 4374
4357 4375 * IPython/UserConfig/ipythonrc.py: put () back in accepted
4358 4376 delimiters. While it prevents ().TAB from working, it allows
4359 4377 completions in open (... expressions. This is by far a more common
4360 4378 case.
4361 4379
4362 4380 2002-04-23 Fernando Perez <fperez@colorado.edu>
4363 4381
4364 4382 * IPython/Extensions/InterpreterPasteInput.py: new
4365 4383 syntax-processing module for pasting lines with >>> or ... at the
4366 4384 start.
4367 4385
4368 4386 * IPython/Extensions/PhysicalQ_Interactive.py
4369 4387 (PhysicalQuantityInteractive.__int__): fixed to work with either
4370 4388 Numeric or math.
4371 4389
4372 4390 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
4373 4391 provided profiles. Now we have:
4374 4392 -math -> math module as * and cmath with its own namespace.
4375 4393 -numeric -> Numeric as *, plus gnuplot & grace
4376 4394 -physics -> same as before
4377 4395
4378 4396 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
4379 4397 user-defined magics wouldn't be found by @magic if they were
4380 4398 defined as class methods. Also cleaned up the namespace search
4381 4399 logic and the string building (to use %s instead of many repeated
4382 4400 string adds).
4383 4401
4384 4402 * IPython/UserConfig/example-magic.py (magic_foo): updated example
4385 4403 of user-defined magics to operate with class methods (cleaner, in
4386 4404 line with the gnuplot code).
4387 4405
4388 4406 2002-04-22 Fernando Perez <fperez@colorado.edu>
4389 4407
4390 4408 * setup.py: updated dependency list so that manual is updated when
4391 4409 all included files change.
4392 4410
4393 4411 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
4394 4412 the delimiter removal option (the fix is ugly right now).
4395 4413
4396 4414 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
4397 4415 all of the math profile (quicker loading, no conflict between
4398 4416 g-9.8 and g-gnuplot).
4399 4417
4400 4418 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
4401 4419 name of post-mortem files to IPython_crash_report.txt.
4402 4420
4403 4421 * Cleanup/update of the docs. Added all the new readline info and
4404 4422 formatted all lists as 'real lists'.
4405 4423
4406 4424 * IPython/ipmaker.py (make_IPython): removed now-obsolete
4407 4425 tab-completion options, since the full readline parse_and_bind is
4408 4426 now accessible.
4409 4427
4410 4428 * IPython/iplib.py (InteractiveShell.init_readline): Changed
4411 4429 handling of readline options. Now users can specify any string to
4412 4430 be passed to parse_and_bind(), as well as the delimiters to be
4413 4431 removed.
4414 4432 (InteractiveShell.__init__): Added __name__ to the global
4415 4433 namespace so that things like Itpl which rely on its existence
4416 4434 don't crash.
4417 4435 (InteractiveShell._prefilter): Defined the default with a _ so
4418 4436 that prefilter() is easier to override, while the default one
4419 4437 remains available.
4420 4438
4421 4439 2002-04-18 Fernando Perez <fperez@colorado.edu>
4422 4440
4423 4441 * Added information about pdb in the docs.
4424 4442
4425 4443 2002-04-17 Fernando Perez <fperez@colorado.edu>
4426 4444
4427 4445 * IPython/ipmaker.py (make_IPython): added rc_override option to
4428 4446 allow passing config options at creation time which may override
4429 4447 anything set in the config files or command line. This is
4430 4448 particularly useful for configuring embedded instances.
4431 4449
4432 4450 2002-04-15 Fernando Perez <fperez@colorado.edu>
4433 4451
4434 4452 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
4435 4453 crash embedded instances because of the input cache falling out of
4436 4454 sync with the output counter.
4437 4455
4438 4456 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
4439 4457 mode which calls pdb after an uncaught exception in IPython itself.
4440 4458
4441 4459 2002-04-14 Fernando Perez <fperez@colorado.edu>
4442 4460
4443 4461 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
4444 4462 readline, fix it back after each call.
4445 4463
4446 4464 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
4447 4465 method to force all access via __call__(), which guarantees that
4448 4466 traceback references are properly deleted.
4449 4467
4450 4468 * IPython/Prompts.py (CachedOutput._display): minor fixes to
4451 4469 improve printing when pprint is in use.
4452 4470
4453 4471 2002-04-13 Fernando Perez <fperez@colorado.edu>
4454 4472
4455 4473 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
4456 4474 exceptions aren't caught anymore. If the user triggers one, he
4457 4475 should know why he's doing it and it should go all the way up,
4458 4476 just like any other exception. So now @abort will fully kill the
4459 4477 embedded interpreter and the embedding code (unless that happens
4460 4478 to catch SystemExit).
4461 4479
4462 4480 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
4463 4481 and a debugger() method to invoke the interactive pdb debugger
4464 4482 after printing exception information. Also added the corresponding
4465 4483 -pdb option and @pdb magic to control this feature, and updated
4466 4484 the docs. After a suggestion from Christopher Hart
4467 4485 (hart-AT-caltech.edu).
4468 4486
4469 4487 2002-04-12 Fernando Perez <fperez@colorado.edu>
4470 4488
4471 4489 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
4472 4490 the exception handlers defined by the user (not the CrashHandler)
4473 4491 so that user exceptions don't trigger an ipython bug report.
4474 4492
4475 4493 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
4476 4494 configurable (it should have always been so).
4477 4495
4478 4496 2002-03-26 Fernando Perez <fperez@colorado.edu>
4479 4497
4480 4498 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
4481 4499 and there to fix embedding namespace issues. This should all be
4482 4500 done in a more elegant way.
4483 4501
4484 4502 2002-03-25 Fernando Perez <fperez@colorado.edu>
4485 4503
4486 4504 * IPython/genutils.py (get_home_dir): Try to make it work under
4487 4505 win9x also.
4488 4506
4489 4507 2002-03-20 Fernando Perez <fperez@colorado.edu>
4490 4508
4491 4509 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
4492 4510 sys.displayhook untouched upon __init__.
4493 4511
4494 4512 2002-03-19 Fernando Perez <fperez@colorado.edu>
4495 4513
4496 4514 * Released 0.2.9 (for embedding bug, basically).
4497 4515
4498 4516 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
4499 4517 exceptions so that enclosing shell's state can be restored.
4500 4518
4501 4519 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
4502 4520 naming conventions in the .ipython/ dir.
4503 4521
4504 4522 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
4505 4523 from delimiters list so filenames with - in them get expanded.
4506 4524
4507 4525 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
4508 4526 sys.displayhook not being properly restored after an embedded call.
4509 4527
4510 4528 2002-03-18 Fernando Perez <fperez@colorado.edu>
4511 4529
4512 4530 * Released 0.2.8
4513 4531
4514 4532 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
4515 4533 some files weren't being included in a -upgrade.
4516 4534 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
4517 4535 on' so that the first tab completes.
4518 4536 (InteractiveShell.handle_magic): fixed bug with spaces around
4519 4537 quotes breaking many magic commands.
4520 4538
4521 4539 * setup.py: added note about ignoring the syntax error messages at
4522 4540 installation.
4523 4541
4524 4542 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
4525 4543 streamlining the gnuplot interface, now there's only one magic @gp.
4526 4544
4527 4545 2002-03-17 Fernando Perez <fperez@colorado.edu>
4528 4546
4529 4547 * IPython/UserConfig/magic_gnuplot.py: new name for the
4530 4548 example-magic_pm.py file. Much enhanced system, now with a shell
4531 4549 for communicating directly with gnuplot, one command at a time.
4532 4550
4533 4551 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
4534 4552 setting __name__=='__main__'.
4535 4553
4536 4554 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
4537 4555 mini-shell for accessing gnuplot from inside ipython. Should
4538 4556 extend it later for grace access too. Inspired by Arnd's
4539 4557 suggestion.
4540 4558
4541 4559 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
4542 4560 calling magic functions with () in their arguments. Thanks to Arnd
4543 4561 Baecker for pointing this to me.
4544 4562
4545 4563 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
4546 4564 infinitely for integer or complex arrays (only worked with floats).
4547 4565
4548 4566 2002-03-16 Fernando Perez <fperez@colorado.edu>
4549 4567
4550 4568 * setup.py: Merged setup and setup_windows into a single script
4551 4569 which properly handles things for windows users.
4552 4570
4553 4571 2002-03-15 Fernando Perez <fperez@colorado.edu>
4554 4572
4555 4573 * Big change to the manual: now the magics are all automatically
4556 4574 documented. This information is generated from their docstrings
4557 4575 and put in a latex file included by the manual lyx file. This way
4558 4576 we get always up to date information for the magics. The manual
4559 4577 now also has proper version information, also auto-synced.
4560 4578
4561 4579 For this to work, an undocumented --magic_docstrings option was added.
4562 4580
4563 4581 2002-03-13 Fernando Perez <fperez@colorado.edu>
4564 4582
4565 4583 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
4566 4584 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
4567 4585
4568 4586 2002-03-12 Fernando Perez <fperez@colorado.edu>
4569 4587
4570 4588 * IPython/ultraTB.py (TermColors): changed color escapes again to
4571 4589 fix the (old, reintroduced) line-wrapping bug. Basically, if
4572 4590 \001..\002 aren't given in the color escapes, lines get wrapped
4573 4591 weirdly. But giving those screws up old xterms and emacs terms. So
4574 4592 I added some logic for emacs terms to be ok, but I can't identify old
4575 4593 xterms separately ($TERM=='xterm' for many terminals, like konsole).
4576 4594
4577 4595 2002-03-10 Fernando Perez <fperez@colorado.edu>
4578 4596
4579 4597 * IPython/usage.py (__doc__): Various documentation cleanups and
4580 4598 updates, both in usage docstrings and in the manual.
4581 4599
4582 4600 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
4583 4601 handling of caching. Set minimum acceptabe value for having a
4584 4602 cache at 20 values.
4585 4603
4586 4604 * IPython/iplib.py (InteractiveShell.user_setup): moved the
4587 4605 install_first_time function to a method, renamed it and added an
4588 4606 'upgrade' mode. Now people can update their config directory with
4589 4607 a simple command line switch (-upgrade, also new).
4590 4608
4591 4609 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
4592 4610 @file (convenient for automagic users under Python >= 2.2).
4593 4611 Removed @files (it seemed more like a plural than an abbrev. of
4594 4612 'file show').
4595 4613
4596 4614 * IPython/iplib.py (install_first_time): Fixed crash if there were
4597 4615 backup files ('~') in .ipython/ install directory.
4598 4616
4599 4617 * IPython/ipmaker.py (make_IPython): fixes for new prompt
4600 4618 system. Things look fine, but these changes are fairly
4601 4619 intrusive. Test them for a few days.
4602 4620
4603 4621 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
4604 4622 the prompts system. Now all in/out prompt strings are user
4605 4623 controllable. This is particularly useful for embedding, as one
4606 4624 can tag embedded instances with particular prompts.
4607 4625
4608 4626 Also removed global use of sys.ps1/2, which now allows nested
4609 4627 embeddings without any problems. Added command-line options for
4610 4628 the prompt strings.
4611 4629
4612 4630 2002-03-08 Fernando Perez <fperez@colorado.edu>
4613 4631
4614 4632 * IPython/UserConfig/example-embed-short.py (ipshell): added
4615 4633 example file with the bare minimum code for embedding.
4616 4634
4617 4635 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
4618 4636 functionality for the embeddable shell to be activated/deactivated
4619 4637 either globally or at each call.
4620 4638
4621 4639 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
4622 4640 rewriting the prompt with '--->' for auto-inputs with proper
4623 4641 coloring. Now the previous UGLY hack in handle_auto() is gone, and
4624 4642 this is handled by the prompts class itself, as it should.
4625 4643
4626 4644 2002-03-05 Fernando Perez <fperez@colorado.edu>
4627 4645
4628 4646 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
4629 4647 @logstart to avoid name clashes with the math log function.
4630 4648
4631 4649 * Big updates to X/Emacs section of the manual.
4632 4650
4633 4651 * Removed ipython_emacs. Milan explained to me how to pass
4634 4652 arguments to ipython through Emacs. Some day I'm going to end up
4635 4653 learning some lisp...
4636 4654
4637 4655 2002-03-04 Fernando Perez <fperez@colorado.edu>
4638 4656
4639 4657 * IPython/ipython_emacs: Created script to be used as the
4640 4658 py-python-command Emacs variable so we can pass IPython
4641 4659 parameters. I can't figure out how to tell Emacs directly to pass
4642 4660 parameters to IPython, so a dummy shell script will do it.
4643 4661
4644 4662 Other enhancements made for things to work better under Emacs'
4645 4663 various types of terminals. Many thanks to Milan Zamazal
4646 4664 <pdm-AT-zamazal.org> for all the suggestions and pointers.
4647 4665
4648 4666 2002-03-01 Fernando Perez <fperez@colorado.edu>
4649 4667
4650 4668 * IPython/ipmaker.py (make_IPython): added a --readline! option so
4651 4669 that loading of readline is now optional. This gives better
4652 4670 control to emacs users.
4653 4671
4654 4672 * IPython/ultraTB.py (__date__): Modified color escape sequences
4655 4673 and now things work fine under xterm and in Emacs' term buffers
4656 4674 (though not shell ones). Well, in emacs you get colors, but all
4657 4675 seem to be 'light' colors (no difference between dark and light
4658 4676 ones). But the garbage chars are gone, and also in xterms. It
4659 4677 seems that now I'm using 'cleaner' ansi sequences.
4660 4678
4661 4679 2002-02-21 Fernando Perez <fperez@colorado.edu>
4662 4680
4663 4681 * Released 0.2.7 (mainly to publish the scoping fix).
4664 4682
4665 4683 * IPython/Logger.py (Logger.logstate): added. A corresponding
4666 4684 @logstate magic was created.
4667 4685
4668 4686 * IPython/Magic.py: fixed nested scoping problem under Python
4669 4687 2.1.x (automagic wasn't working).
4670 4688
4671 4689 2002-02-20 Fernando Perez <fperez@colorado.edu>
4672 4690
4673 4691 * Released 0.2.6.
4674 4692
4675 4693 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
4676 4694 option so that logs can come out without any headers at all.
4677 4695
4678 4696 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
4679 4697 SciPy.
4680 4698
4681 4699 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
4682 4700 that embedded IPython calls don't require vars() to be explicitly
4683 4701 passed. Now they are extracted from the caller's frame (code
4684 4702 snatched from Eric Jones' weave). Added better documentation to
4685 4703 the section on embedding and the example file.
4686 4704
4687 4705 * IPython/genutils.py (page): Changed so that under emacs, it just
4688 4706 prints the string. You can then page up and down in the emacs
4689 4707 buffer itself. This is how the builtin help() works.
4690 4708
4691 4709 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
4692 4710 macro scoping: macros need to be executed in the user's namespace
4693 4711 to work as if they had been typed by the user.
4694 4712
4695 4713 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
4696 4714 execute automatically (no need to type 'exec...'). They then
4697 4715 behave like 'true macros'. The printing system was also modified
4698 4716 for this to work.
4699 4717
4700 4718 2002-02-19 Fernando Perez <fperez@colorado.edu>
4701 4719
4702 4720 * IPython/genutils.py (page_file): new function for paging files
4703 4721 in an OS-independent way. Also necessary for file viewing to work
4704 4722 well inside Emacs buffers.
4705 4723 (page): Added checks for being in an emacs buffer.
4706 4724 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
4707 4725 same bug in iplib.
4708 4726
4709 4727 2002-02-18 Fernando Perez <fperez@colorado.edu>
4710 4728
4711 4729 * IPython/iplib.py (InteractiveShell.init_readline): modified use
4712 4730 of readline so that IPython can work inside an Emacs buffer.
4713 4731
4714 4732 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
4715 4733 method signatures (they weren't really bugs, but it looks cleaner
4716 4734 and keeps PyChecker happy).
4717 4735
4718 4736 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
4719 4737 for implementing various user-defined hooks. Currently only
4720 4738 display is done.
4721 4739
4722 4740 * IPython/Prompts.py (CachedOutput._display): changed display
4723 4741 functions so that they can be dynamically changed by users easily.
4724 4742
4725 4743 * IPython/Extensions/numeric_formats.py (num_display): added an
4726 4744 extension for printing NumPy arrays in flexible manners. It
4727 4745 doesn't do anything yet, but all the structure is in
4728 4746 place. Ultimately the plan is to implement output format control
4729 4747 like in Octave.
4730 4748
4731 4749 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
4732 4750 methods are found at run-time by all the automatic machinery.
4733 4751
4734 4752 2002-02-17 Fernando Perez <fperez@colorado.edu>
4735 4753
4736 4754 * setup_Windows.py (make_shortcut): documented. Cleaned up the
4737 4755 whole file a little.
4738 4756
4739 4757 * ToDo: closed this document. Now there's a new_design.lyx
4740 4758 document for all new ideas. Added making a pdf of it for the
4741 4759 end-user distro.
4742 4760
4743 4761 * IPython/Logger.py (Logger.switch_log): Created this to replace
4744 4762 logon() and logoff(). It also fixes a nasty crash reported by
4745 4763 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
4746 4764
4747 4765 * IPython/iplib.py (complete): got auto-completion to work with
4748 4766 automagic (I had wanted this for a long time).
4749 4767
4750 4768 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
4751 4769 to @file, since file() is now a builtin and clashes with automagic
4752 4770 for @file.
4753 4771
4754 4772 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
4755 4773 of this was previously in iplib, which had grown to more than 2000
4756 4774 lines, way too long. No new functionality, but it makes managing
4757 4775 the code a bit easier.
4758 4776
4759 4777 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
4760 4778 information to crash reports.
4761 4779
4762 4780 2002-02-12 Fernando Perez <fperez@colorado.edu>
4763 4781
4764 4782 * Released 0.2.5.
4765 4783
4766 4784 2002-02-11 Fernando Perez <fperez@colorado.edu>
4767 4785
4768 4786 * Wrote a relatively complete Windows installer. It puts
4769 4787 everything in place, creates Start Menu entries and fixes the
4770 4788 color issues. Nothing fancy, but it works.
4771 4789
4772 4790 2002-02-10 Fernando Perez <fperez@colorado.edu>
4773 4791
4774 4792 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
4775 4793 os.path.expanduser() call so that we can type @run ~/myfile.py and
4776 4794 have thigs work as expected.
4777 4795
4778 4796 * IPython/genutils.py (page): fixed exception handling so things
4779 4797 work both in Unix and Windows correctly. Quitting a pager triggers
4780 4798 an IOError/broken pipe in Unix, and in windows not finding a pager
4781 4799 is also an IOError, so I had to actually look at the return value
4782 4800 of the exception, not just the exception itself. Should be ok now.
4783 4801
4784 4802 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
4785 4803 modified to allow case-insensitive color scheme changes.
4786 4804
4787 4805 2002-02-09 Fernando Perez <fperez@colorado.edu>
4788 4806
4789 4807 * IPython/genutils.py (native_line_ends): new function to leave
4790 4808 user config files with os-native line-endings.
4791 4809
4792 4810 * README and manual updates.
4793 4811
4794 4812 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
4795 4813 instead of StringType to catch Unicode strings.
4796 4814
4797 4815 * IPython/genutils.py (filefind): fixed bug for paths with
4798 4816 embedded spaces (very common in Windows).
4799 4817
4800 4818 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
4801 4819 files under Windows, so that they get automatically associated
4802 4820 with a text editor. Windows makes it a pain to handle
4803 4821 extension-less files.
4804 4822
4805 4823 * IPython/iplib.py (InteractiveShell.init_readline): Made the
4806 4824 warning about readline only occur for Posix. In Windows there's no
4807 4825 way to get readline, so why bother with the warning.
4808 4826
4809 4827 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
4810 4828 for __str__ instead of dir(self), since dir() changed in 2.2.
4811 4829
4812 4830 * Ported to Windows! Tested on XP, I suspect it should work fine
4813 4831 on NT/2000, but I don't think it will work on 98 et al. That
4814 4832 series of Windows is such a piece of junk anyway that I won't try
4815 4833 porting it there. The XP port was straightforward, showed a few
4816 4834 bugs here and there (fixed all), in particular some string
4817 4835 handling stuff which required considering Unicode strings (which
4818 4836 Windows uses). This is good, but hasn't been too tested :) No
4819 4837 fancy installer yet, I'll put a note in the manual so people at
4820 4838 least make manually a shortcut.
4821 4839
4822 4840 * IPython/iplib.py (Magic.magic_colors): Unified the color options
4823 4841 into a single one, "colors". This now controls both prompt and
4824 4842 exception color schemes, and can be changed both at startup
4825 4843 (either via command-line switches or via ipythonrc files) and at
4826 4844 runtime, with @colors.
4827 4845 (Magic.magic_run): renamed @prun to @run and removed the old
4828 4846 @run. The two were too similar to warrant keeping both.
4829 4847
4830 4848 2002-02-03 Fernando Perez <fperez@colorado.edu>
4831 4849
4832 4850 * IPython/iplib.py (install_first_time): Added comment on how to
4833 4851 configure the color options for first-time users. Put a <return>
4834 4852 request at the end so that small-terminal users get a chance to
4835 4853 read the startup info.
4836 4854
4837 4855 2002-01-23 Fernando Perez <fperez@colorado.edu>
4838 4856
4839 4857 * IPython/iplib.py (CachedOutput.update): Changed output memory
4840 4858 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
4841 4859 input history we still use _i. Did this b/c these variable are
4842 4860 very commonly used in interactive work, so the less we need to
4843 4861 type the better off we are.
4844 4862 (Magic.magic_prun): updated @prun to better handle the namespaces
4845 4863 the file will run in, including a fix for __name__ not being set
4846 4864 before.
4847 4865
4848 4866 2002-01-20 Fernando Perez <fperez@colorado.edu>
4849 4867
4850 4868 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
4851 4869 extra garbage for Python 2.2. Need to look more carefully into
4852 4870 this later.
4853 4871
4854 4872 2002-01-19 Fernando Perez <fperez@colorado.edu>
4855 4873
4856 4874 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
4857 4875 display SyntaxError exceptions properly formatted when they occur
4858 4876 (they can be triggered by imported code).
4859 4877
4860 4878 2002-01-18 Fernando Perez <fperez@colorado.edu>
4861 4879
4862 4880 * IPython/iplib.py (InteractiveShell.safe_execfile): now
4863 4881 SyntaxError exceptions are reported nicely formatted, instead of
4864 4882 spitting out only offset information as before.
4865 4883 (Magic.magic_prun): Added the @prun function for executing
4866 4884 programs with command line args inside IPython.
4867 4885
4868 4886 2002-01-16 Fernando Perez <fperez@colorado.edu>
4869 4887
4870 4888 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
4871 4889 to *not* include the last item given in a range. This brings their
4872 4890 behavior in line with Python's slicing:
4873 4891 a[n1:n2] -> a[n1]...a[n2-1]
4874 4892 It may be a bit less convenient, but I prefer to stick to Python's
4875 4893 conventions *everywhere*, so users never have to wonder.
4876 4894 (Magic.magic_macro): Added @macro function to ease the creation of
4877 4895 macros.
4878 4896
4879 4897 2002-01-05 Fernando Perez <fperez@colorado.edu>
4880 4898
4881 4899 * Released 0.2.4.
4882 4900
4883 4901 * IPython/iplib.py (Magic.magic_pdef):
4884 4902 (InteractiveShell.safe_execfile): report magic lines and error
4885 4903 lines without line numbers so one can easily copy/paste them for
4886 4904 re-execution.
4887 4905
4888 4906 * Updated manual with recent changes.
4889 4907
4890 4908 * IPython/iplib.py (Magic.magic_oinfo): added constructor
4891 4909 docstring printing when class? is called. Very handy for knowing
4892 4910 how to create class instances (as long as __init__ is well
4893 4911 documented, of course :)
4894 4912 (Magic.magic_doc): print both class and constructor docstrings.
4895 4913 (Magic.magic_pdef): give constructor info if passed a class and
4896 4914 __call__ info for callable object instances.
4897 4915
4898 4916 2002-01-04 Fernando Perez <fperez@colorado.edu>
4899 4917
4900 4918 * Made deep_reload() off by default. It doesn't always work
4901 4919 exactly as intended, so it's probably safer to have it off. It's
4902 4920 still available as dreload() anyway, so nothing is lost.
4903 4921
4904 4922 2002-01-02 Fernando Perez <fperez@colorado.edu>
4905 4923
4906 4924 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
4907 4925 so I wanted an updated release).
4908 4926
4909 4927 2001-12-27 Fernando Perez <fperez@colorado.edu>
4910 4928
4911 4929 * IPython/iplib.py (InteractiveShell.interact): Added the original
4912 4930 code from 'code.py' for this module in order to change the
4913 4931 handling of a KeyboardInterrupt. This was necessary b/c otherwise
4914 4932 the history cache would break when the user hit Ctrl-C, and
4915 4933 interact() offers no way to add any hooks to it.
4916 4934
4917 4935 2001-12-23 Fernando Perez <fperez@colorado.edu>
4918 4936
4919 4937 * setup.py: added check for 'MANIFEST' before trying to remove
4920 4938 it. Thanks to Sean Reifschneider.
4921 4939
4922 4940 2001-12-22 Fernando Perez <fperez@colorado.edu>
4923 4941
4924 4942 * Released 0.2.2.
4925 4943
4926 4944 * Finished (reasonably) writing the manual. Later will add the
4927 4945 python-standard navigation stylesheets, but for the time being
4928 4946 it's fairly complete. Distribution will include html and pdf
4929 4947 versions.
4930 4948
4931 4949 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
4932 4950 (MayaVi author).
4933 4951
4934 4952 2001-12-21 Fernando Perez <fperez@colorado.edu>
4935 4953
4936 4954 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
4937 4955 good public release, I think (with the manual and the distutils
4938 4956 installer). The manual can use some work, but that can go
4939 4957 slowly. Otherwise I think it's quite nice for end users. Next
4940 4958 summer, rewrite the guts of it...
4941 4959
4942 4960 * Changed format of ipythonrc files to use whitespace as the
4943 4961 separator instead of an explicit '='. Cleaner.
4944 4962
4945 4963 2001-12-20 Fernando Perez <fperez@colorado.edu>
4946 4964
4947 4965 * Started a manual in LyX. For now it's just a quick merge of the
4948 4966 various internal docstrings and READMEs. Later it may grow into a
4949 4967 nice, full-blown manual.
4950 4968
4951 4969 * Set up a distutils based installer. Installation should now be
4952 4970 trivially simple for end-users.
4953 4971
4954 4972 2001-12-11 Fernando Perez <fperez@colorado.edu>
4955 4973
4956 4974 * Released 0.2.0. First public release, announced it at
4957 4975 comp.lang.python. From now on, just bugfixes...
4958 4976
4959 4977 * Went through all the files, set copyright/license notices and
4960 4978 cleaned up things. Ready for release.
4961 4979
4962 4980 2001-12-10 Fernando Perez <fperez@colorado.edu>
4963 4981
4964 4982 * Changed the first-time installer not to use tarfiles. It's more
4965 4983 robust now and less unix-dependent. Also makes it easier for
4966 4984 people to later upgrade versions.
4967 4985
4968 4986 * Changed @exit to @abort to reflect the fact that it's pretty
4969 4987 brutal (a sys.exit()). The difference between @abort and Ctrl-D
4970 4988 becomes significant only when IPyhton is embedded: in that case,
4971 4989 C-D closes IPython only, but @abort kills the enclosing program
4972 4990 too (unless it had called IPython inside a try catching
4973 4991 SystemExit).
4974 4992
4975 4993 * Created Shell module which exposes the actuall IPython Shell
4976 4994 classes, currently the normal and the embeddable one. This at
4977 4995 least offers a stable interface we won't need to change when
4978 4996 (later) the internals are rewritten. That rewrite will be confined
4979 4997 to iplib and ipmaker, but the Shell interface should remain as is.
4980 4998
4981 4999 * Added embed module which offers an embeddable IPShell object,
4982 5000 useful to fire up IPython *inside* a running program. Great for
4983 5001 debugging or dynamical data analysis.
4984 5002
4985 5003 2001-12-08 Fernando Perez <fperez@colorado.edu>
4986 5004
4987 5005 * Fixed small bug preventing seeing info from methods of defined
4988 5006 objects (incorrect namespace in _ofind()).
4989 5007
4990 5008 * Documentation cleanup. Moved the main usage docstrings to a
4991 5009 separate file, usage.py (cleaner to maintain, and hopefully in the
4992 5010 future some perlpod-like way of producing interactive, man and
4993 5011 html docs out of it will be found).
4994 5012
4995 5013 * Added @profile to see your profile at any time.
4996 5014
4997 5015 * Added @p as an alias for 'print'. It's especially convenient if
4998 5016 using automagic ('p x' prints x).
4999 5017
5000 5018 * Small cleanups and fixes after a pychecker run.
5001 5019
5002 5020 * Changed the @cd command to handle @cd - and @cd -<n> for
5003 5021 visiting any directory in _dh.
5004 5022
5005 5023 * Introduced _dh, a history of visited directories. @dhist prints
5006 5024 it out with numbers.
5007 5025
5008 5026 2001-12-07 Fernando Perez <fperez@colorado.edu>
5009 5027
5010 5028 * Released 0.1.22
5011 5029
5012 5030 * Made initialization a bit more robust against invalid color
5013 5031 options in user input (exit, not traceback-crash).
5014 5032
5015 5033 * Changed the bug crash reporter to write the report only in the
5016 5034 user's .ipython directory. That way IPython won't litter people's
5017 5035 hard disks with crash files all over the place. Also print on
5018 5036 screen the necessary mail command.
5019 5037
5020 5038 * With the new ultraTB, implemented LightBG color scheme for light
5021 5039 background terminals. A lot of people like white backgrounds, so I
5022 5040 guess we should at least give them something readable.
5023 5041
5024 5042 2001-12-06 Fernando Perez <fperez@colorado.edu>
5025 5043
5026 5044 * Modified the structure of ultraTB. Now there's a proper class
5027 5045 for tables of color schemes which allow adding schemes easily and
5028 5046 switching the active scheme without creating a new instance every
5029 5047 time (which was ridiculous). The syntax for creating new schemes
5030 5048 is also cleaner. I think ultraTB is finally done, with a clean
5031 5049 class structure. Names are also much cleaner (now there's proper
5032 5050 color tables, no need for every variable to also have 'color' in
5033 5051 its name).
5034 5052
5035 5053 * Broke down genutils into separate files. Now genutils only
5036 5054 contains utility functions, and classes have been moved to their
5037 5055 own files (they had enough independent functionality to warrant
5038 5056 it): ConfigLoader, OutputTrap, Struct.
5039 5057
5040 5058 2001-12-05 Fernando Perez <fperez@colorado.edu>
5041 5059
5042 5060 * IPython turns 21! Released version 0.1.21, as a candidate for
5043 5061 public consumption. If all goes well, release in a few days.
5044 5062
5045 5063 * Fixed path bug (files in Extensions/ directory wouldn't be found
5046 5064 unless IPython/ was explicitly in sys.path).
5047 5065
5048 5066 * Extended the FlexCompleter class as MagicCompleter to allow
5049 5067 completion of @-starting lines.
5050 5068
5051 5069 * Created __release__.py file as a central repository for release
5052 5070 info that other files can read from.
5053 5071
5054 5072 * Fixed small bug in logging: when logging was turned on in
5055 5073 mid-session, old lines with special meanings (!@?) were being
5056 5074 logged without the prepended comment, which is necessary since
5057 5075 they are not truly valid python syntax. This should make session
5058 5076 restores produce less errors.
5059 5077
5060 5078 * The namespace cleanup forced me to make a FlexCompleter class
5061 5079 which is nothing but a ripoff of rlcompleter, but with selectable
5062 5080 namespace (rlcompleter only works in __main__.__dict__). I'll try
5063 5081 to submit a note to the authors to see if this change can be
5064 5082 incorporated in future rlcompleter releases (Dec.6: done)
5065 5083
5066 5084 * More fixes to namespace handling. It was a mess! Now all
5067 5085 explicit references to __main__.__dict__ are gone (except when
5068 5086 really needed) and everything is handled through the namespace
5069 5087 dicts in the IPython instance. We seem to be getting somewhere
5070 5088 with this, finally...
5071 5089
5072 5090 * Small documentation updates.
5073 5091
5074 5092 * Created the Extensions directory under IPython (with an
5075 5093 __init__.py). Put the PhysicalQ stuff there. This directory should
5076 5094 be used for all special-purpose extensions.
5077 5095
5078 5096 * File renaming:
5079 5097 ipythonlib --> ipmaker
5080 5098 ipplib --> iplib
5081 5099 This makes a bit more sense in terms of what these files actually do.
5082 5100
5083 5101 * Moved all the classes and functions in ipythonlib to ipplib, so
5084 5102 now ipythonlib only has make_IPython(). This will ease up its
5085 5103 splitting in smaller functional chunks later.
5086 5104
5087 5105 * Cleaned up (done, I think) output of @whos. Better column
5088 5106 formatting, and now shows str(var) for as much as it can, which is
5089 5107 typically what one gets with a 'print var'.
5090 5108
5091 5109 2001-12-04 Fernando Perez <fperez@colorado.edu>
5092 5110
5093 5111 * Fixed namespace problems. Now builtin/IPyhton/user names get
5094 5112 properly reported in their namespace. Internal namespace handling
5095 5113 is finally getting decent (not perfect yet, but much better than
5096 5114 the ad-hoc mess we had).
5097 5115
5098 5116 * Removed -exit option. If people just want to run a python
5099 5117 script, that's what the normal interpreter is for. Less
5100 5118 unnecessary options, less chances for bugs.
5101 5119
5102 5120 * Added a crash handler which generates a complete post-mortem if
5103 5121 IPython crashes. This will help a lot in tracking bugs down the
5104 5122 road.
5105 5123
5106 5124 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
5107 5125 which were boud to functions being reassigned would bypass the
5108 5126 logger, breaking the sync of _il with the prompt counter. This
5109 5127 would then crash IPython later when a new line was logged.
5110 5128
5111 5129 2001-12-02 Fernando Perez <fperez@colorado.edu>
5112 5130
5113 5131 * Made IPython a package. This means people don't have to clutter
5114 5132 their sys.path with yet another directory. Changed the INSTALL
5115 5133 file accordingly.
5116 5134
5117 5135 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
5118 5136 sorts its output (so @who shows it sorted) and @whos formats the
5119 5137 table according to the width of the first column. Nicer, easier to
5120 5138 read. Todo: write a generic table_format() which takes a list of
5121 5139 lists and prints it nicely formatted, with optional row/column
5122 5140 separators and proper padding and justification.
5123 5141
5124 5142 * Released 0.1.20
5125 5143
5126 5144 * Fixed bug in @log which would reverse the inputcache list (a
5127 5145 copy operation was missing).
5128 5146
5129 5147 * Code cleanup. @config was changed to use page(). Better, since
5130 5148 its output is always quite long.
5131 5149
5132 5150 * Itpl is back as a dependency. I was having too many problems
5133 5151 getting the parametric aliases to work reliably, and it's just
5134 5152 easier to code weird string operations with it than playing %()s
5135 5153 games. It's only ~6k, so I don't think it's too big a deal.
5136 5154
5137 5155 * Found (and fixed) a very nasty bug with history. !lines weren't
5138 5156 getting cached, and the out of sync caches would crash
5139 5157 IPython. Fixed it by reorganizing the prefilter/handlers/logger
5140 5158 division of labor a bit better. Bug fixed, cleaner structure.
5141 5159
5142 5160 2001-12-01 Fernando Perez <fperez@colorado.edu>
5143 5161
5144 5162 * Released 0.1.19
5145 5163
5146 5164 * Added option -n to @hist to prevent line number printing. Much
5147 5165 easier to copy/paste code this way.
5148 5166
5149 5167 * Created global _il to hold the input list. Allows easy
5150 5168 re-execution of blocks of code by slicing it (inspired by Janko's
5151 5169 comment on 'macros').
5152 5170
5153 5171 * Small fixes and doc updates.
5154 5172
5155 5173 * Rewrote @history function (was @h). Renamed it to @hist, @h is
5156 5174 much too fragile with automagic. Handles properly multi-line
5157 5175 statements and takes parameters.
5158 5176
5159 5177 2001-11-30 Fernando Perez <fperez@colorado.edu>
5160 5178
5161 5179 * Version 0.1.18 released.
5162 5180
5163 5181 * Fixed nasty namespace bug in initial module imports.
5164 5182
5165 5183 * Added copyright/license notes to all code files (except
5166 5184 DPyGetOpt). For the time being, LGPL. That could change.
5167 5185
5168 5186 * Rewrote a much nicer README, updated INSTALL, cleaned up
5169 5187 ipythonrc-* samples.
5170 5188
5171 5189 * Overall code/documentation cleanup. Basically ready for
5172 5190 release. Only remaining thing: licence decision (LGPL?).
5173 5191
5174 5192 * Converted load_config to a class, ConfigLoader. Now recursion
5175 5193 control is better organized. Doesn't include the same file twice.
5176 5194
5177 5195 2001-11-29 Fernando Perez <fperez@colorado.edu>
5178 5196
5179 5197 * Got input history working. Changed output history variables from
5180 5198 _p to _o so that _i is for input and _o for output. Just cleaner
5181 5199 convention.
5182 5200
5183 5201 * Implemented parametric aliases. This pretty much allows the
5184 5202 alias system to offer full-blown shell convenience, I think.
5185 5203
5186 5204 * Version 0.1.17 released, 0.1.18 opened.
5187 5205
5188 5206 * dot_ipython/ipythonrc (alias): added documentation.
5189 5207 (xcolor): Fixed small bug (xcolors -> xcolor)
5190 5208
5191 5209 * Changed the alias system. Now alias is a magic command to define
5192 5210 aliases just like the shell. Rationale: the builtin magics should
5193 5211 be there for things deeply connected to IPython's
5194 5212 architecture. And this is a much lighter system for what I think
5195 5213 is the really important feature: allowing users to define quickly
5196 5214 magics that will do shell things for them, so they can customize
5197 5215 IPython easily to match their work habits. If someone is really
5198 5216 desperate to have another name for a builtin alias, they can
5199 5217 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
5200 5218 works.
5201 5219
5202 5220 2001-11-28 Fernando Perez <fperez@colorado.edu>
5203 5221
5204 5222 * Changed @file so that it opens the source file at the proper
5205 5223 line. Since it uses less, if your EDITOR environment is
5206 5224 configured, typing v will immediately open your editor of choice
5207 5225 right at the line where the object is defined. Not as quick as
5208 5226 having a direct @edit command, but for all intents and purposes it
5209 5227 works. And I don't have to worry about writing @edit to deal with
5210 5228 all the editors, less does that.
5211 5229
5212 5230 * Version 0.1.16 released, 0.1.17 opened.
5213 5231
5214 5232 * Fixed some nasty bugs in the page/page_dumb combo that could
5215 5233 crash IPython.
5216 5234
5217 5235 2001-11-27 Fernando Perez <fperez@colorado.edu>
5218 5236
5219 5237 * Version 0.1.15 released, 0.1.16 opened.
5220 5238
5221 5239 * Finally got ? and ?? to work for undefined things: now it's
5222 5240 possible to type {}.get? and get information about the get method
5223 5241 of dicts, or os.path? even if only os is defined (so technically
5224 5242 os.path isn't). Works at any level. For example, after import os,
5225 5243 os?, os.path?, os.path.abspath? all work. This is great, took some
5226 5244 work in _ofind.
5227 5245
5228 5246 * Fixed more bugs with logging. The sanest way to do it was to add
5229 5247 to @log a 'mode' parameter. Killed two in one shot (this mode
5230 5248 option was a request of Janko's). I think it's finally clean
5231 5249 (famous last words).
5232 5250
5233 5251 * Added a page_dumb() pager which does a decent job of paging on
5234 5252 screen, if better things (like less) aren't available. One less
5235 5253 unix dependency (someday maybe somebody will port this to
5236 5254 windows).
5237 5255
5238 5256 * Fixed problem in magic_log: would lock of logging out if log
5239 5257 creation failed (because it would still think it had succeeded).
5240 5258
5241 5259 * Improved the page() function using curses to auto-detect screen
5242 5260 size. Now it can make a much better decision on whether to print
5243 5261 or page a string. Option screen_length was modified: a value 0
5244 5262 means auto-detect, and that's the default now.
5245 5263
5246 5264 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
5247 5265 go out. I'll test it for a few days, then talk to Janko about
5248 5266 licences and announce it.
5249 5267
5250 5268 * Fixed the length of the auto-generated ---> prompt which appears
5251 5269 for auto-parens and auto-quotes. Getting this right isn't trivial,
5252 5270 with all the color escapes, different prompt types and optional
5253 5271 separators. But it seems to be working in all the combinations.
5254 5272
5255 5273 2001-11-26 Fernando Perez <fperez@colorado.edu>
5256 5274
5257 5275 * Wrote a regexp filter to get option types from the option names
5258 5276 string. This eliminates the need to manually keep two duplicate
5259 5277 lists.
5260 5278
5261 5279 * Removed the unneeded check_option_names. Now options are handled
5262 5280 in a much saner manner and it's easy to visually check that things
5263 5281 are ok.
5264 5282
5265 5283 * Updated version numbers on all files I modified to carry a
5266 5284 notice so Janko and Nathan have clear version markers.
5267 5285
5268 5286 * Updated docstring for ultraTB with my changes. I should send
5269 5287 this to Nathan.
5270 5288
5271 5289 * Lots of small fixes. Ran everything through pychecker again.
5272 5290
5273 5291 * Made loading of deep_reload an cmd line option. If it's not too
5274 5292 kosher, now people can just disable it. With -nodeep_reload it's
5275 5293 still available as dreload(), it just won't overwrite reload().
5276 5294
5277 5295 * Moved many options to the no| form (-opt and -noopt
5278 5296 accepted). Cleaner.
5279 5297
5280 5298 * Changed magic_log so that if called with no parameters, it uses
5281 5299 'rotate' mode. That way auto-generated logs aren't automatically
5282 5300 over-written. For normal logs, now a backup is made if it exists
5283 5301 (only 1 level of backups). A new 'backup' mode was added to the
5284 5302 Logger class to support this. This was a request by Janko.
5285 5303
5286 5304 * Added @logoff/@logon to stop/restart an active log.
5287 5305
5288 5306 * Fixed a lot of bugs in log saving/replay. It was pretty
5289 5307 broken. Now special lines (!@,/) appear properly in the command
5290 5308 history after a log replay.
5291 5309
5292 5310 * Tried and failed to implement full session saving via pickle. My
5293 5311 idea was to pickle __main__.__dict__, but modules can't be
5294 5312 pickled. This would be a better alternative to replaying logs, but
5295 5313 seems quite tricky to get to work. Changed -session to be called
5296 5314 -logplay, which more accurately reflects what it does. And if we
5297 5315 ever get real session saving working, -session is now available.
5298 5316
5299 5317 * Implemented color schemes for prompts also. As for tracebacks,
5300 5318 currently only NoColor and Linux are supported. But now the
5301 5319 infrastructure is in place, based on a generic ColorScheme
5302 5320 class. So writing and activating new schemes both for the prompts
5303 5321 and the tracebacks should be straightforward.
5304 5322
5305 5323 * Version 0.1.13 released, 0.1.14 opened.
5306 5324
5307 5325 * Changed handling of options for output cache. Now counter is
5308 5326 hardwired starting at 1 and one specifies the maximum number of
5309 5327 entries *in the outcache* (not the max prompt counter). This is
5310 5328 much better, since many statements won't increase the cache
5311 5329 count. It also eliminated some confusing options, now there's only
5312 5330 one: cache_size.
5313 5331
5314 5332 * Added 'alias' magic function and magic_alias option in the
5315 5333 ipythonrc file. Now the user can easily define whatever names he
5316 5334 wants for the magic functions without having to play weird
5317 5335 namespace games. This gives IPython a real shell-like feel.
5318 5336
5319 5337 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
5320 5338 @ or not).
5321 5339
5322 5340 This was one of the last remaining 'visible' bugs (that I know
5323 5341 of). I think if I can clean up the session loading so it works
5324 5342 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
5325 5343 about licensing).
5326 5344
5327 5345 2001-11-25 Fernando Perez <fperez@colorado.edu>
5328 5346
5329 5347 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
5330 5348 there's a cleaner distinction between what ? and ?? show.
5331 5349
5332 5350 * Added screen_length option. Now the user can define his own
5333 5351 screen size for page() operations.
5334 5352
5335 5353 * Implemented magic shell-like functions with automatic code
5336 5354 generation. Now adding another function is just a matter of adding
5337 5355 an entry to a dict, and the function is dynamically generated at
5338 5356 run-time. Python has some really cool features!
5339 5357
5340 5358 * Renamed many options to cleanup conventions a little. Now all
5341 5359 are lowercase, and only underscores where needed. Also in the code
5342 5360 option name tables are clearer.
5343 5361
5344 5362 * Changed prompts a little. Now input is 'In [n]:' instead of
5345 5363 'In[n]:='. This allows it the numbers to be aligned with the
5346 5364 Out[n] numbers, and removes usage of ':=' which doesn't exist in
5347 5365 Python (it was a Mathematica thing). The '...' continuation prompt
5348 5366 was also changed a little to align better.
5349 5367
5350 5368 * Fixed bug when flushing output cache. Not all _p<n> variables
5351 5369 exist, so their deletion needs to be wrapped in a try:
5352 5370
5353 5371 * Figured out how to properly use inspect.formatargspec() (it
5354 5372 requires the args preceded by *). So I removed all the code from
5355 5373 _get_pdef in Magic, which was just replicating that.
5356 5374
5357 5375 * Added test to prefilter to allow redefining magic function names
5358 5376 as variables. This is ok, since the @ form is always available,
5359 5377 but whe should allow the user to define a variable called 'ls' if
5360 5378 he needs it.
5361 5379
5362 5380 * Moved the ToDo information from README into a separate ToDo.
5363 5381
5364 5382 * General code cleanup and small bugfixes. I think it's close to a
5365 5383 state where it can be released, obviously with a big 'beta'
5366 5384 warning on it.
5367 5385
5368 5386 * Got the magic function split to work. Now all magics are defined
5369 5387 in a separate class. It just organizes things a bit, and now
5370 5388 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
5371 5389 was too long).
5372 5390
5373 5391 * Changed @clear to @reset to avoid potential confusions with
5374 5392 the shell command clear. Also renamed @cl to @clear, which does
5375 5393 exactly what people expect it to from their shell experience.
5376 5394
5377 5395 Added a check to the @reset command (since it's so
5378 5396 destructive, it's probably a good idea to ask for confirmation).
5379 5397 But now reset only works for full namespace resetting. Since the
5380 5398 del keyword is already there for deleting a few specific
5381 5399 variables, I don't see the point of having a redundant magic
5382 5400 function for the same task.
5383 5401
5384 5402 2001-11-24 Fernando Perez <fperez@colorado.edu>
5385 5403
5386 5404 * Updated the builtin docs (esp. the ? ones).
5387 5405
5388 5406 * Ran all the code through pychecker. Not terribly impressed with
5389 5407 it: lots of spurious warnings and didn't really find anything of
5390 5408 substance (just a few modules being imported and not used).
5391 5409
5392 5410 * Implemented the new ultraTB functionality into IPython. New
5393 5411 option: xcolors. This chooses color scheme. xmode now only selects
5394 5412 between Plain and Verbose. Better orthogonality.
5395 5413
5396 5414 * Large rewrite of ultraTB. Much cleaner now, with a separation of
5397 5415 mode and color scheme for the exception handlers. Now it's
5398 5416 possible to have the verbose traceback with no coloring.
5399 5417
5400 5418 2001-11-23 Fernando Perez <fperez@colorado.edu>
5401 5419
5402 5420 * Version 0.1.12 released, 0.1.13 opened.
5403 5421
5404 5422 * Removed option to set auto-quote and auto-paren escapes by
5405 5423 user. The chances of breaking valid syntax are just too high. If
5406 5424 someone *really* wants, they can always dig into the code.
5407 5425
5408 5426 * Made prompt separators configurable.
5409 5427
5410 5428 2001-11-22 Fernando Perez <fperez@colorado.edu>
5411 5429
5412 5430 * Small bugfixes in many places.
5413 5431
5414 5432 * Removed the MyCompleter class from ipplib. It seemed redundant
5415 5433 with the C-p,C-n history search functionality. Less code to
5416 5434 maintain.
5417 5435
5418 5436 * Moved all the original ipython.py code into ipythonlib.py. Right
5419 5437 now it's just one big dump into a function called make_IPython, so
5420 5438 no real modularity has been gained. But at least it makes the
5421 5439 wrapper script tiny, and since ipythonlib is a module, it gets
5422 5440 compiled and startup is much faster.
5423 5441
5424 5442 This is a reasobably 'deep' change, so we should test it for a
5425 5443 while without messing too much more with the code.
5426 5444
5427 5445 2001-11-21 Fernando Perez <fperez@colorado.edu>
5428 5446
5429 5447 * Version 0.1.11 released, 0.1.12 opened for further work.
5430 5448
5431 5449 * Removed dependency on Itpl. It was only needed in one place. It
5432 5450 would be nice if this became part of python, though. It makes life
5433 5451 *a lot* easier in some cases.
5434 5452
5435 5453 * Simplified the prefilter code a bit. Now all handlers are
5436 5454 expected to explicitly return a value (at least a blank string).
5437 5455
5438 5456 * Heavy edits in ipplib. Removed the help system altogether. Now
5439 5457 obj?/?? is used for inspecting objects, a magic @doc prints
5440 5458 docstrings, and full-blown Python help is accessed via the 'help'
5441 5459 keyword. This cleans up a lot of code (less to maintain) and does
5442 5460 the job. Since 'help' is now a standard Python component, might as
5443 5461 well use it and remove duplicate functionality.
5444 5462
5445 5463 Also removed the option to use ipplib as a standalone program. By
5446 5464 now it's too dependent on other parts of IPython to function alone.
5447 5465
5448 5466 * Fixed bug in genutils.pager. It would crash if the pager was
5449 5467 exited immediately after opening (broken pipe).
5450 5468
5451 5469 * Trimmed down the VerboseTB reporting a little. The header is
5452 5470 much shorter now and the repeated exception arguments at the end
5453 5471 have been removed. For interactive use the old header seemed a bit
5454 5472 excessive.
5455 5473
5456 5474 * Fixed small bug in output of @whos for variables with multi-word
5457 5475 types (only first word was displayed).
5458 5476
5459 5477 2001-11-17 Fernando Perez <fperez@colorado.edu>
5460 5478
5461 5479 * Version 0.1.10 released, 0.1.11 opened for further work.
5462 5480
5463 5481 * Modified dirs and friends. dirs now *returns* the stack (not
5464 5482 prints), so one can manipulate it as a variable. Convenient to
5465 5483 travel along many directories.
5466 5484
5467 5485 * Fixed bug in magic_pdef: would only work with functions with
5468 5486 arguments with default values.
5469 5487
5470 5488 2001-11-14 Fernando Perez <fperez@colorado.edu>
5471 5489
5472 5490 * Added the PhysicsInput stuff to dot_ipython so it ships as an
5473 5491 example with IPython. Various other minor fixes and cleanups.
5474 5492
5475 5493 * Version 0.1.9 released, 0.1.10 opened for further work.
5476 5494
5477 5495 * Added sys.path to the list of directories searched in the
5478 5496 execfile= option. It used to be the current directory and the
5479 5497 user's IPYTHONDIR only.
5480 5498
5481 5499 2001-11-13 Fernando Perez <fperez@colorado.edu>
5482 5500
5483 5501 * Reinstated the raw_input/prefilter separation that Janko had
5484 5502 initially. This gives a more convenient setup for extending the
5485 5503 pre-processor from the outside: raw_input always gets a string,
5486 5504 and prefilter has to process it. We can then redefine prefilter
5487 5505 from the outside and implement extensions for special
5488 5506 purposes.
5489 5507
5490 5508 Today I got one for inputting PhysicalQuantity objects
5491 5509 (from Scientific) without needing any function calls at
5492 5510 all. Extremely convenient, and it's all done as a user-level
5493 5511 extension (no IPython code was touched). Now instead of:
5494 5512 a = PhysicalQuantity(4.2,'m/s**2')
5495 5513 one can simply say
5496 5514 a = 4.2 m/s**2
5497 5515 or even
5498 5516 a = 4.2 m/s^2
5499 5517
5500 5518 I use this, but it's also a proof of concept: IPython really is
5501 5519 fully user-extensible, even at the level of the parsing of the
5502 5520 command line. It's not trivial, but it's perfectly doable.
5503 5521
5504 5522 * Added 'add_flip' method to inclusion conflict resolver. Fixes
5505 5523 the problem of modules being loaded in the inverse order in which
5506 5524 they were defined in
5507 5525
5508 5526 * Version 0.1.8 released, 0.1.9 opened for further work.
5509 5527
5510 5528 * Added magics pdef, source and file. They respectively show the
5511 5529 definition line ('prototype' in C), source code and full python
5512 5530 file for any callable object. The object inspector oinfo uses
5513 5531 these to show the same information.
5514 5532
5515 5533 * Version 0.1.7 released, 0.1.8 opened for further work.
5516 5534
5517 5535 * Separated all the magic functions into a class called Magic. The
5518 5536 InteractiveShell class was becoming too big for Xemacs to handle
5519 5537 (de-indenting a line would lock it up for 10 seconds while it
5520 5538 backtracked on the whole class!)
5521 5539
5522 5540 FIXME: didn't work. It can be done, but right now namespaces are
5523 5541 all messed up. Do it later (reverted it for now, so at least
5524 5542 everything works as before).
5525 5543
5526 5544 * Got the object introspection system (magic_oinfo) working! I
5527 5545 think this is pretty much ready for release to Janko, so he can
5528 5546 test it for a while and then announce it. Pretty much 100% of what
5529 5547 I wanted for the 'phase 1' release is ready. Happy, tired.
5530 5548
5531 5549 2001-11-12 Fernando Perez <fperez@colorado.edu>
5532 5550
5533 5551 * Version 0.1.6 released, 0.1.7 opened for further work.
5534 5552
5535 5553 * Fixed bug in printing: it used to test for truth before
5536 5554 printing, so 0 wouldn't print. Now checks for None.
5537 5555
5538 5556 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
5539 5557 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
5540 5558 reaches by hand into the outputcache. Think of a better way to do
5541 5559 this later.
5542 5560
5543 5561 * Various small fixes thanks to Nathan's comments.
5544 5562
5545 5563 * Changed magic_pprint to magic_Pprint. This way it doesn't
5546 5564 collide with pprint() and the name is consistent with the command
5547 5565 line option.
5548 5566
5549 5567 * Changed prompt counter behavior to be fully like
5550 5568 Mathematica's. That is, even input that doesn't return a result
5551 5569 raises the prompt counter. The old behavior was kind of confusing
5552 5570 (getting the same prompt number several times if the operation
5553 5571 didn't return a result).
5554 5572
5555 5573 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
5556 5574
5557 5575 * Fixed -Classic mode (wasn't working anymore).
5558 5576
5559 5577 * Added colored prompts using Nathan's new code. Colors are
5560 5578 currently hardwired, they can be user-configurable. For
5561 5579 developers, they can be chosen in file ipythonlib.py, at the
5562 5580 beginning of the CachedOutput class def.
5563 5581
5564 5582 2001-11-11 Fernando Perez <fperez@colorado.edu>
5565 5583
5566 5584 * Version 0.1.5 released, 0.1.6 opened for further work.
5567 5585
5568 5586 * Changed magic_env to *return* the environment as a dict (not to
5569 5587 print it). This way it prints, but it can also be processed.
5570 5588
5571 5589 * Added Verbose exception reporting to interactive
5572 5590 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
5573 5591 traceback. Had to make some changes to the ultraTB file. This is
5574 5592 probably the last 'big' thing in my mental todo list. This ties
5575 5593 in with the next entry:
5576 5594
5577 5595 * Changed -Xi and -Xf to a single -xmode option. Now all the user
5578 5596 has to specify is Plain, Color or Verbose for all exception
5579 5597 handling.
5580 5598
5581 5599 * Removed ShellServices option. All this can really be done via
5582 5600 the magic system. It's easier to extend, cleaner and has automatic
5583 5601 namespace protection and documentation.
5584 5602
5585 5603 2001-11-09 Fernando Perez <fperez@colorado.edu>
5586 5604
5587 5605 * Fixed bug in output cache flushing (missing parameter to
5588 5606 __init__). Other small bugs fixed (found using pychecker).
5589 5607
5590 5608 * Version 0.1.4 opened for bugfixing.
5591 5609
5592 5610 2001-11-07 Fernando Perez <fperez@colorado.edu>
5593 5611
5594 5612 * Version 0.1.3 released, mainly because of the raw_input bug.
5595 5613
5596 5614 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
5597 5615 and when testing for whether things were callable, a call could
5598 5616 actually be made to certain functions. They would get called again
5599 5617 once 'really' executed, with a resulting double call. A disaster
5600 5618 in many cases (list.reverse() would never work!).
5601 5619
5602 5620 * Removed prefilter() function, moved its code to raw_input (which
5603 5621 after all was just a near-empty caller for prefilter). This saves
5604 5622 a function call on every prompt, and simplifies the class a tiny bit.
5605 5623
5606 5624 * Fix _ip to __ip name in magic example file.
5607 5625
5608 5626 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
5609 5627 work with non-gnu versions of tar.
5610 5628
5611 5629 2001-11-06 Fernando Perez <fperez@colorado.edu>
5612 5630
5613 5631 * Version 0.1.2. Just to keep track of the recent changes.
5614 5632
5615 5633 * Fixed nasty bug in output prompt routine. It used to check 'if
5616 5634 arg != None...'. Problem is, this fails if arg implements a
5617 5635 special comparison (__cmp__) which disallows comparing to
5618 5636 None. Found it when trying to use the PhysicalQuantity module from
5619 5637 ScientificPython.
5620 5638
5621 5639 2001-11-05 Fernando Perez <fperez@colorado.edu>
5622 5640
5623 5641 * Also added dirs. Now the pushd/popd/dirs family functions
5624 5642 basically like the shell, with the added convenience of going home
5625 5643 when called with no args.
5626 5644
5627 5645 * pushd/popd slightly modified to mimic shell behavior more
5628 5646 closely.
5629 5647
5630 5648 * Added env,pushd,popd from ShellServices as magic functions. I
5631 5649 think the cleanest will be to port all desired functions from
5632 5650 ShellServices as magics and remove ShellServices altogether. This
5633 5651 will provide a single, clean way of adding functionality
5634 5652 (shell-type or otherwise) to IP.
5635 5653
5636 5654 2001-11-04 Fernando Perez <fperez@colorado.edu>
5637 5655
5638 5656 * Added .ipython/ directory to sys.path. This way users can keep
5639 5657 customizations there and access them via import.
5640 5658
5641 5659 2001-11-03 Fernando Perez <fperez@colorado.edu>
5642 5660
5643 5661 * Opened version 0.1.1 for new changes.
5644 5662
5645 5663 * Changed version number to 0.1.0: first 'public' release, sent to
5646 5664 Nathan and Janko.
5647 5665
5648 5666 * Lots of small fixes and tweaks.
5649 5667
5650 5668 * Minor changes to whos format. Now strings are shown, snipped if
5651 5669 too long.
5652 5670
5653 5671 * Changed ShellServices to work on __main__ so they show up in @who
5654 5672
5655 5673 * Help also works with ? at the end of a line:
5656 5674 ?sin and sin?
5657 5675 both produce the same effect. This is nice, as often I use the
5658 5676 tab-complete to find the name of a method, but I used to then have
5659 5677 to go to the beginning of the line to put a ? if I wanted more
5660 5678 info. Now I can just add the ? and hit return. Convenient.
5661 5679
5662 5680 2001-11-02 Fernando Perez <fperez@colorado.edu>
5663 5681
5664 5682 * Python version check (>=2.1) added.
5665 5683
5666 5684 * Added LazyPython documentation. At this point the docs are quite
5667 5685 a mess. A cleanup is in order.
5668 5686
5669 5687 * Auto-installer created. For some bizarre reason, the zipfiles
5670 5688 module isn't working on my system. So I made a tar version
5671 5689 (hopefully the command line options in various systems won't kill
5672 5690 me).
5673 5691
5674 5692 * Fixes to Struct in genutils. Now all dictionary-like methods are
5675 5693 protected (reasonably).
5676 5694
5677 5695 * Added pager function to genutils and changed ? to print usage
5678 5696 note through it (it was too long).
5679 5697
5680 5698 * Added the LazyPython functionality. Works great! I changed the
5681 5699 auto-quote escape to ';', it's on home row and next to '. But
5682 5700 both auto-quote and auto-paren (still /) escapes are command-line
5683 5701 parameters.
5684 5702
5685 5703
5686 5704 2001-11-01 Fernando Perez <fperez@colorado.edu>
5687 5705
5688 5706 * Version changed to 0.0.7. Fairly large change: configuration now
5689 5707 is all stored in a directory, by default .ipython. There, all
5690 5708 config files have normal looking names (not .names)
5691 5709
5692 5710 * Version 0.0.6 Released first to Lucas and Archie as a test
5693 5711 run. Since it's the first 'semi-public' release, change version to
5694 5712 > 0.0.6 for any changes now.
5695 5713
5696 5714 * Stuff I had put in the ipplib.py changelog:
5697 5715
5698 5716 Changes to InteractiveShell:
5699 5717
5700 5718 - Made the usage message a parameter.
5701 5719
5702 5720 - Require the name of the shell variable to be given. It's a bit
5703 5721 of a hack, but allows the name 'shell' not to be hardwired in the
5704 5722 magic (@) handler, which is problematic b/c it requires
5705 5723 polluting the global namespace with 'shell'. This in turn is
5706 5724 fragile: if a user redefines a variable called shell, things
5707 5725 break.
5708 5726
5709 5727 - magic @: all functions available through @ need to be defined
5710 5728 as magic_<name>, even though they can be called simply as
5711 5729 @<name>. This allows the special command @magic to gather
5712 5730 information automatically about all existing magic functions,
5713 5731 even if they are run-time user extensions, by parsing the shell
5714 5732 instance __dict__ looking for special magic_ names.
5715 5733
5716 5734 - mainloop: added *two* local namespace parameters. This allows
5717 5735 the class to differentiate between parameters which were there
5718 5736 before and after command line initialization was processed. This
5719 5737 way, later @who can show things loaded at startup by the
5720 5738 user. This trick was necessary to make session saving/reloading
5721 5739 really work: ideally after saving/exiting/reloading a session,
5722 5740 *everything* should look the same, including the output of @who. I
5723 5741 was only able to make this work with this double namespace
5724 5742 trick.
5725 5743
5726 5744 - added a header to the logfile which allows (almost) full
5727 5745 session restoring.
5728 5746
5729 5747 - prepend lines beginning with @ or !, with a and log
5730 5748 them. Why? !lines: may be useful to know what you did @lines:
5731 5749 they may affect session state. So when restoring a session, at
5732 5750 least inform the user of their presence. I couldn't quite get
5733 5751 them to properly re-execute, but at least the user is warned.
5734 5752
5735 5753 * Started ChangeLog.
General Comments 0
You need to be logged in to leave comments. Login now