##// END OF EJS Templates
- thread-safety fixes...
fperez -
Show More
@@ -0,0 +1,23 b''
1 """Support for interactive macros in IPython"""
2
3 #*****************************************************************************
4 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
5 #
6 # Distributed under the terms of the BSD License. The full license is in
7 # the file COPYING, distributed as part of this software.
8 #*****************************************************************************
9
10 class Macro:
11 """Simple class to store the value of macros as strings.
12
13 This allows us to later exec them by checking when something is an
14 instance of this class."""
15
16 def __init__(self,data):
17
18 # store the macro value, as a single string which can be evaluated by
19 # runlines()
20 self.value = ''.join(data).rstrip()+'\n'
21
22 def __str__(self):
23 return self.value
@@ -1,2676 +1,2672 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3
3
4 $Id: Magic.py 974 2005-12-29 19:48:33Z fperez $"""
4 $Id: Magic.py 975 2005-12-29 23:50:22Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import sys
29 import sys
30 import re
30 import re
31 import tempfile
31 import tempfile
32 import time
32 import time
33 import cPickle as pickle
33 import cPickle as pickle
34 from cStringIO import StringIO
34 from cStringIO import StringIO
35 from getopt import getopt
35 from getopt import getopt
36 from pprint import pprint, pformat
36 from pprint import pprint, pformat
37
37
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 # Homebrewed
44 # Homebrewed
45 from IPython import Debugger, OInspect, wildcard
45 from IPython import Debugger, OInspect, wildcard
46 from IPython.FakeModule import FakeModule
46 from IPython.FakeModule import FakeModule
47 from IPython.Itpl import Itpl, itpl, printpl,itplns
47 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 from IPython.PyColorize import Parser
48 from IPython.PyColorize import Parser
49 from IPython.Struct import Struct
49 from IPython.Struct import Struct
50 from IPython.macro import Macro
50 from IPython.genutils import *
51 from IPython.genutils import *
51
52
52 #***************************************************************************
53 #***************************************************************************
53 # Utility functions
54 # Utility functions
54 def on_off(tag):
55 def on_off(tag):
55 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
56 return ['OFF','ON'][tag]
57 return ['OFF','ON'][tag]
57
58
58
59
59 #****************************************************************************
60 # Utility classes
61 class Macro(list):
62 """Simple class to store the value of macros as strings.
63
64 This allows us to later exec them by checking when something is an
65 instance of this class."""
66
67 def __init__(self,data):
68 list.__init__(self,data)
69 self.value = ''.join(data)
70
71 #***************************************************************************
60 #***************************************************************************
72 # Main class implementing Magic functionality
61 # Main class implementing Magic functionality
73 class Magic:
62 class Magic:
74 """Magic functions for InteractiveShell.
63 """Magic functions for InteractiveShell.
75
64
76 Shell functions which can be reached as %function_name. All magic
65 Shell functions which can be reached as %function_name. All magic
77 functions should accept a string, which they can parse for their own
66 functions should accept a string, which they can parse for their own
78 needs. This can make some functions easier to type, eg `%cd ../`
67 needs. This can make some functions easier to type, eg `%cd ../`
79 vs. `%cd("../")`
68 vs. `%cd("../")`
80
69
81 ALL definitions MUST begin with the prefix magic_. The user won't need it
70 ALL definitions MUST begin with the prefix magic_. The user won't need it
82 at the command line, but it is is needed in the definition. """
71 at the command line, but it is is needed in the definition. """
83
72
84 # class globals
73 # class globals
85 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
74 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
86 'Automagic is ON, % prefix NOT needed for magic functions.']
75 'Automagic is ON, % prefix NOT needed for magic functions.']
87
76
88 #......................................................................
77 #......................................................................
89 # some utility functions
78 # some utility functions
90
79
91 def __init__(self,shell):
80 def __init__(self,shell):
92
81
93 self.options_table = {}
82 self.options_table = {}
94 if profile is None:
83 if profile is None:
95 self.magic_prun = self.profile_missing_notice
84 self.magic_prun = self.profile_missing_notice
96 self.shell = shell
85 self.shell = shell
97
86
98 def profile_missing_notice(self, *args, **kwargs):
87 def profile_missing_notice(self, *args, **kwargs):
99 error("""\
88 error("""\
100 The profile module could not be found. If you are a Debian user,
89 The profile module could not be found. If you are a Debian user,
101 it has been removed from the standard Debian package because of its non-free
90 it has been removed from the standard Debian package because of its non-free
102 license. To use profiling, please install"python2.3-profiler" from non-free.""")
91 license. To use profiling, please install"python2.3-profiler" from non-free.""")
103
92
104 def default_option(self,fn,optstr):
93 def default_option(self,fn,optstr):
105 """Make an entry in the options_table for fn, with value optstr"""
94 """Make an entry in the options_table for fn, with value optstr"""
106
95
107 if fn not in self.lsmagic():
96 if fn not in self.lsmagic():
108 error("%s is not a magic function" % fn)
97 error("%s is not a magic function" % fn)
109 self.options_table[fn] = optstr
98 self.options_table[fn] = optstr
110
99
111 def lsmagic(self):
100 def lsmagic(self):
112 """Return a list of currently available magic functions.
101 """Return a list of currently available magic functions.
113
102
114 Gives a list of the bare names after mangling (['ls','cd', ...], not
103 Gives a list of the bare names after mangling (['ls','cd', ...], not
115 ['magic_ls','magic_cd',...]"""
104 ['magic_ls','magic_cd',...]"""
116
105
117 # FIXME. This needs a cleanup, in the way the magics list is built.
106 # FIXME. This needs a cleanup, in the way the magics list is built.
118
107
119 # magics in class definition
108 # magics in class definition
120 class_magic = lambda fn: fn.startswith('magic_') and \
109 class_magic = lambda fn: fn.startswith('magic_') and \
121 callable(Magic.__dict__[fn])
110 callable(Magic.__dict__[fn])
122 # in instance namespace (run-time user additions)
111 # in instance namespace (run-time user additions)
123 inst_magic = lambda fn: fn.startswith('magic_') and \
112 inst_magic = lambda fn: fn.startswith('magic_') and \
124 callable(self.__dict__[fn])
113 callable(self.__dict__[fn])
125 # and bound magics by user (so they can access self):
114 # and bound magics by user (so they can access self):
126 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
115 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
127 callable(self.__class__.__dict__[fn])
116 callable(self.__class__.__dict__[fn])
128 magics = filter(class_magic,Magic.__dict__.keys()) + \
117 magics = filter(class_magic,Magic.__dict__.keys()) + \
129 filter(inst_magic,self.__dict__.keys()) + \
118 filter(inst_magic,self.__dict__.keys()) + \
130 filter(inst_bound_magic,self.__class__.__dict__.keys())
119 filter(inst_bound_magic,self.__class__.__dict__.keys())
131 out = []
120 out = []
132 for fn in magics:
121 for fn in magics:
133 out.append(fn.replace('magic_','',1))
122 out.append(fn.replace('magic_','',1))
134 out.sort()
123 out.sort()
135 return out
124 return out
136
125
137 def extract_input_slices(self,slices):
126 def extract_input_slices(self,slices):
138 """Return as a string a set of input history slices.
127 """Return as a string a set of input history slices.
139
128
140 The set of slices is given as a list of strings (like ['1','4:8','9'],
129 The set of slices is given as a list of strings (like ['1','4:8','9'],
141 since this function is for use by magic functions which get their
130 since this function is for use by magic functions which get their
142 arguments as strings."""
131 arguments as strings."""
143
132
144 cmds = []
133 cmds = []
145 for chunk in slices:
134 for chunk in slices:
146 if ':' in chunk:
135 if ':' in chunk:
147 ini,fin = map(int,chunk.split(':'))
136 ini,fin = map(int,chunk.split(':'))
148 else:
137 else:
149 ini = int(chunk)
138 ini = int(chunk)
150 fin = ini+1
139 fin = ini+1
151 cmds.append(self.shell.input_hist[ini:fin])
140 cmds.append(self.shell.input_hist[ini:fin])
152 return cmds
141 return cmds
153
142
154 def _ofind(self,oname):
143 def _ofind(self,oname):
155 """Find an object in the available namespaces.
144 """Find an object in the available namespaces.
156
145
157 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
146 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
158
147
159 Has special code to detect magic functions.
148 Has special code to detect magic functions.
160 """
149 """
161
150
162 oname = oname.strip()
151 oname = oname.strip()
163
152
164 # Namespaces to search in:
153 # Namespaces to search in:
165 user_ns = self.shell.user_ns
154 user_ns = self.shell.user_ns
166 internal_ns = self.shell.internal_ns
155 internal_ns = self.shell.internal_ns
167 builtin_ns = __builtin__.__dict__
156 builtin_ns = __builtin__.__dict__
168 alias_ns = self.shell.alias_table
157 alias_ns = self.shell.alias_table
169
158
170 # Put them in a list. The order is important so that we find things in
159 # Put them in a list. The order is important so that we find things in
171 # the same order that Python finds them.
160 # the same order that Python finds them.
172 namespaces = [ ('Interactive',user_ns),
161 namespaces = [ ('Interactive',user_ns),
173 ('IPython internal',internal_ns),
162 ('IPython internal',internal_ns),
174 ('Python builtin',builtin_ns),
163 ('Python builtin',builtin_ns),
175 ('Alias',alias_ns),
164 ('Alias',alias_ns),
176 ]
165 ]
177
166
178 # initialize results to 'null'
167 # initialize results to 'null'
179 found = 0; obj = None; ospace = None; ds = None;
168 found = 0; obj = None; ospace = None; ds = None;
180 ismagic = 0; isalias = 0
169 ismagic = 0; isalias = 0
181
170
182 # Look for the given name by splitting it in parts. If the head is
171 # Look for the given name by splitting it in parts. If the head is
183 # found, then we look for all the remaining parts as members, and only
172 # found, then we look for all the remaining parts as members, and only
184 # declare success if we can find them all.
173 # declare success if we can find them all.
185 oname_parts = oname.split('.')
174 oname_parts = oname.split('.')
186 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
175 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
187 for nsname,ns in namespaces:
176 for nsname,ns in namespaces:
188 try:
177 try:
189 obj = ns[oname_head]
178 obj = ns[oname_head]
190 except KeyError:
179 except KeyError:
191 continue
180 continue
192 else:
181 else:
193 for part in oname_rest:
182 for part in oname_rest:
194 try:
183 try:
195 obj = getattr(obj,part)
184 obj = getattr(obj,part)
196 except:
185 except:
197 # Blanket except b/c some badly implemented objects
186 # Blanket except b/c some badly implemented objects
198 # allow __getattr__ to raise exceptions other than
187 # allow __getattr__ to raise exceptions other than
199 # AttributeError, which then crashes IPython.
188 # AttributeError, which then crashes IPython.
200 break
189 break
201 else:
190 else:
202 # If we finish the for loop (no break), we got all members
191 # If we finish the for loop (no break), we got all members
203 found = 1
192 found = 1
204 ospace = nsname
193 ospace = nsname
205 if ns == alias_ns:
194 if ns == alias_ns:
206 isalias = 1
195 isalias = 1
207 break # namespace loop
196 break # namespace loop
208
197
209 # Try to see if it's magic
198 # Try to see if it's magic
210 if not found:
199 if not found:
211 if oname.startswith(self.shell.ESC_MAGIC):
200 if oname.startswith(self.shell.ESC_MAGIC):
212 oname = oname[1:]
201 oname = oname[1:]
213 obj = getattr(self,'magic_'+oname,None)
202 obj = getattr(self,'magic_'+oname,None)
214 if obj is not None:
203 if obj is not None:
215 found = 1
204 found = 1
216 ospace = 'IPython internal'
205 ospace = 'IPython internal'
217 ismagic = 1
206 ismagic = 1
218
207
219 # Last try: special-case some literals like '', [], {}, etc:
208 # Last try: special-case some literals like '', [], {}, etc:
220 if not found and oname_head in ["''",'""','[]','{}','()']:
209 if not found and oname_head in ["''",'""','[]','{}','()']:
221 obj = eval(oname_head)
210 obj = eval(oname_head)
222 found = 1
211 found = 1
223 ospace = 'Interactive'
212 ospace = 'Interactive'
224
213
225 return {'found':found, 'obj':obj, 'namespace':ospace,
214 return {'found':found, 'obj':obj, 'namespace':ospace,
226 'ismagic':ismagic, 'isalias':isalias}
215 'ismagic':ismagic, 'isalias':isalias}
227
216
228 def arg_err(self,func):
217 def arg_err(self,func):
229 """Print docstring if incorrect arguments were passed"""
218 """Print docstring if incorrect arguments were passed"""
230 print 'Error in arguments:'
219 print 'Error in arguments:'
231 print OInspect.getdoc(func)
220 print OInspect.getdoc(func)
232
221
233
234 def format_latex(self,strng):
222 def format_latex(self,strng):
235 """Format a string for latex inclusion."""
223 """Format a string for latex inclusion."""
236
224
237 # Characters that need to be escaped for latex:
225 # Characters that need to be escaped for latex:
238 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
226 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
239 # Magic command names as headers:
227 # Magic command names as headers:
240 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
228 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
241 re.MULTILINE)
229 re.MULTILINE)
242 # Magic commands
230 # Magic commands
243 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
231 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
244 re.MULTILINE)
232 re.MULTILINE)
245 # Paragraph continue
233 # Paragraph continue
246 par_re = re.compile(r'\\$',re.MULTILINE)
234 par_re = re.compile(r'\\$',re.MULTILINE)
247
235
248 # The "\n" symbol
236 # The "\n" symbol
249 newline_re = re.compile(r'\\n')
237 newline_re = re.compile(r'\\n')
250
238
251 # Now build the string for output:
239 # Now build the string for output:
252 strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
240 strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
253 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
241 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
254 strng = par_re.sub(r'\\\\',strng)
242 strng = par_re.sub(r'\\\\',strng)
255 strng = escape_re.sub(r'\\\1',strng)
243 strng = escape_re.sub(r'\\\1',strng)
256 strng = newline_re.sub(r'\\textbackslash{}n',strng)
244 strng = newline_re.sub(r'\\textbackslash{}n',strng)
257 return strng
245 return strng
258
246
259 def format_screen(self,strng):
247 def format_screen(self,strng):
260 """Format a string for screen printing.
248 """Format a string for screen printing.
261
249
262 This removes some latex-type format codes."""
250 This removes some latex-type format codes."""
263 # Paragraph continue
251 # Paragraph continue
264 par_re = re.compile(r'\\$',re.MULTILINE)
252 par_re = re.compile(r'\\$',re.MULTILINE)
265 strng = par_re.sub('',strng)
253 strng = par_re.sub('',strng)
266 return strng
254 return strng
267
255
268 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
256 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
269 """Parse options passed to an argument string.
257 """Parse options passed to an argument string.
270
258
271 The interface is similar to that of getopt(), but it returns back a
259 The interface is similar to that of getopt(), but it returns back a
272 Struct with the options as keys and the stripped argument string still
260 Struct with the options as keys and the stripped argument string still
273 as a string.
261 as a string.
274
262
275 arg_str is quoted as a true sys.argv vector by using shlex.split.
263 arg_str is quoted as a true sys.argv vector by using shlex.split.
276 This allows us to easily expand variables, glob files, quote
264 This allows us to easily expand variables, glob files, quote
277 arguments, etc.
265 arguments, etc.
278
266
279 Options:
267 Options:
280 -mode: default 'string'. If given as 'list', the argument string is
268 -mode: default 'string'. If given as 'list', the argument string is
281 returned as a list (split on whitespace) instead of a string.
269 returned as a list (split on whitespace) instead of a string.
282
270
283 -list_all: put all option values in lists. Normally only options
271 -list_all: put all option values in lists. Normally only options
284 appearing more than once are put in a list."""
272 appearing more than once are put in a list."""
285
273
286 # inject default options at the beginning of the input line
274 # inject default options at the beginning of the input line
287 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
275 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
288 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
276 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
289
277
290 mode = kw.get('mode','string')
278 mode = kw.get('mode','string')
291 if mode not in ['string','list']:
279 if mode not in ['string','list']:
292 raise ValueError,'incorrect mode given: %s' % mode
280 raise ValueError,'incorrect mode given: %s' % mode
293 # Get options
281 # Get options
294 list_all = kw.get('list_all',0)
282 list_all = kw.get('list_all',0)
295
283
296 # Check if we have more than one argument to warrant extra processing:
284 # Check if we have more than one argument to warrant extra processing:
297 odict = {} # Dictionary with options
285 odict = {} # Dictionary with options
298 args = arg_str.split()
286 args = arg_str.split()
299 if len(args) >= 1:
287 if len(args) >= 1:
300 # If the list of inputs only has 0 or 1 thing in it, there's no
288 # If the list of inputs only has 0 or 1 thing in it, there's no
301 # need to look for options
289 # need to look for options
302 argv = shlex_split(arg_str)
290 argv = shlex_split(arg_str)
303 # Do regular option processing
291 # Do regular option processing
304 opts,args = getopt(argv,opt_str,*long_opts)
292 opts,args = getopt(argv,opt_str,*long_opts)
305 for o,a in opts:
293 for o,a in opts:
306 if o.startswith('--'):
294 if o.startswith('--'):
307 o = o[2:]
295 o = o[2:]
308 else:
296 else:
309 o = o[1:]
297 o = o[1:]
310 try:
298 try:
311 odict[o].append(a)
299 odict[o].append(a)
312 except AttributeError:
300 except AttributeError:
313 odict[o] = [odict[o],a]
301 odict[o] = [odict[o],a]
314 except KeyError:
302 except KeyError:
315 if list_all:
303 if list_all:
316 odict[o] = [a]
304 odict[o] = [a]
317 else:
305 else:
318 odict[o] = a
306 odict[o] = a
319
307
320 # Prepare opts,args for return
308 # Prepare opts,args for return
321 opts = Struct(odict)
309 opts = Struct(odict)
322 if mode == 'string':
310 if mode == 'string':
323 args = ' '.join(args)
311 args = ' '.join(args)
324
312
325 return opts,args
313 return opts,args
326
314
327 #......................................................................
315 #......................................................................
328 # And now the actual magic functions
316 # And now the actual magic functions
329
317
330 # Functions for IPython shell work (vars,funcs, config, etc)
318 # Functions for IPython shell work (vars,funcs, config, etc)
331 def magic_lsmagic(self, parameter_s = ''):
319 def magic_lsmagic(self, parameter_s = ''):
332 """List currently available magic functions."""
320 """List currently available magic functions."""
333 mesc = self.shell.ESC_MAGIC
321 mesc = self.shell.ESC_MAGIC
334 print 'Available magic functions:\n'+mesc+\
322 print 'Available magic functions:\n'+mesc+\
335 (' '+mesc).join(self.lsmagic())
323 (' '+mesc).join(self.lsmagic())
336 print '\n' + Magic.auto_status[self.shell.rc.automagic]
324 print '\n' + Magic.auto_status[self.shell.rc.automagic]
337 return None
325 return None
338
326
339 def magic_magic(self, parameter_s = ''):
327 def magic_magic(self, parameter_s = ''):
340 """Print information about the magic function system."""
328 """Print information about the magic function system."""
341
329
342 mode = ''
330 mode = ''
343 try:
331 try:
344 if parameter_s.split()[0] == '-latex':
332 if parameter_s.split()[0] == '-latex':
345 mode = 'latex'
333 mode = 'latex'
346 except:
334 except:
347 pass
335 pass
348
336
349 magic_docs = []
337 magic_docs = []
350 for fname in self.lsmagic():
338 for fname in self.lsmagic():
351 mname = 'magic_' + fname
339 mname = 'magic_' + fname
352 for space in (Magic,self,self.__class__):
340 for space in (Magic,self,self.__class__):
353 try:
341 try:
354 fn = space.__dict__[mname]
342 fn = space.__dict__[mname]
355 except KeyError:
343 except KeyError:
356 pass
344 pass
357 else:
345 else:
358 break
346 break
359 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
347 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
360 fname,fn.__doc__))
348 fname,fn.__doc__))
361 magic_docs = ''.join(magic_docs)
349 magic_docs = ''.join(magic_docs)
362
350
363 if mode == 'latex':
351 if mode == 'latex':
364 print self.format_latex(magic_docs)
352 print self.format_latex(magic_docs)
365 return
353 return
366 else:
354 else:
367 magic_docs = self.format_screen(magic_docs)
355 magic_docs = self.format_screen(magic_docs)
368
356
369 outmsg = """
357 outmsg = """
370 IPython's 'magic' functions
358 IPython's 'magic' functions
371 ===========================
359 ===========================
372
360
373 The magic function system provides a series of functions which allow you to
361 The magic function system provides a series of functions which allow you to
374 control the behavior of IPython itself, plus a lot of system-type
362 control the behavior of IPython itself, plus a lot of system-type
375 features. All these functions are prefixed with a % character, but parameters
363 features. All these functions are prefixed with a % character, but parameters
376 are given without parentheses or quotes.
364 are given without parentheses or quotes.
377
365
378 NOTE: If you have 'automagic' enabled (via the command line option or with the
366 NOTE: If you have 'automagic' enabled (via the command line option or with the
379 %automagic function), you don't need to type in the % explicitly. By default,
367 %automagic function), you don't need to type in the % explicitly. By default,
380 IPython ships with automagic on, so you should only rarely need the % escape.
368 IPython ships with automagic on, so you should only rarely need the % escape.
381
369
382 Example: typing '%cd mydir' (without the quotes) changes you working directory
370 Example: typing '%cd mydir' (without the quotes) changes you working directory
383 to 'mydir', if it exists.
371 to 'mydir', if it exists.
384
372
385 You can define your own magic functions to extend the system. See the supplied
373 You can define your own magic functions to extend the system. See the supplied
386 ipythonrc and example-magic.py files for details (in your ipython
374 ipythonrc and example-magic.py files for details (in your ipython
387 configuration directory, typically $HOME/.ipython/).
375 configuration directory, typically $HOME/.ipython/).
388
376
389 You can also define your own aliased names for magic functions. In your
377 You can also define your own aliased names for magic functions. In your
390 ipythonrc file, placing a line like:
378 ipythonrc file, placing a line like:
391
379
392 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
380 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
393
381
394 will define %pf as a new name for %profile.
382 will define %pf as a new name for %profile.
395
383
396 You can also call magics in code using the ipmagic() function, which IPython
384 You can also call magics in code using the ipmagic() function, which IPython
397 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
385 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
398
386
399 For a list of the available magic functions, use %lsmagic. For a description
387 For a list of the available magic functions, use %lsmagic. For a description
400 of any of them, type %magic_name?, e.g. '%cd?'.
388 of any of them, type %magic_name?, e.g. '%cd?'.
401
389
402 Currently the magic system has the following functions:\n"""
390 Currently the magic system has the following functions:\n"""
403
391
404 mesc = self.shell.ESC_MAGIC
392 mesc = self.shell.ESC_MAGIC
405 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
393 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
406 "\n\n%s%s\n\n%s" % (outmsg,
394 "\n\n%s%s\n\n%s" % (outmsg,
407 magic_docs,mesc,mesc,
395 magic_docs,mesc,mesc,
408 (' '+mesc).join(self.lsmagic()),
396 (' '+mesc).join(self.lsmagic()),
409 Magic.auto_status[self.shell.rc.automagic] ) )
397 Magic.auto_status[self.shell.rc.automagic] ) )
410
398
411 page(outmsg,screen_lines=self.shell.rc.screen_length)
399 page(outmsg,screen_lines=self.shell.rc.screen_length)
412
400
413 def magic_automagic(self, parameter_s = ''):
401 def magic_automagic(self, parameter_s = ''):
414 """Make magic functions callable without having to type the initial %.
402 """Make magic functions callable without having to type the initial %.
415
403
416 Toggles on/off (when off, you must call it as %automagic, of
404 Toggles on/off (when off, you must call it as %automagic, of
417 course). Note that magic functions have lowest priority, so if there's
405 course). Note that magic functions have lowest priority, so if there's
418 a variable whose name collides with that of a magic fn, automagic
406 a variable whose name collides with that of a magic fn, automagic
419 won't work for that function (you get the variable instead). However,
407 won't work for that function (you get the variable instead). However,
420 if you delete the variable (del var), the previously shadowed magic
408 if you delete the variable (del var), the previously shadowed magic
421 function becomes visible to automagic again."""
409 function becomes visible to automagic again."""
422
410
423 rc = self.shell.rc
411 rc = self.shell.rc
424 rc.automagic = not rc.automagic
412 rc.automagic = not rc.automagic
425 print '\n' + Magic.auto_status[rc.automagic]
413 print '\n' + Magic.auto_status[rc.automagic]
426
414
427 def magic_autocall(self, parameter_s = ''):
415 def magic_autocall(self, parameter_s = ''):
428 """Make functions callable without having to type parentheses.
416 """Make functions callable without having to type parentheses.
429
417
430 This toggles the autocall command line option on and off."""
418 This toggles the autocall command line option on and off."""
431
419
432 rc = self.shell.rc
420 rc = self.shell.rc
433 rc.autocall = not rc.autocall
421 rc.autocall = not rc.autocall
434 print "Automatic calling is:",['OFF','ON'][rc.autocall]
422 print "Automatic calling is:",['OFF','ON'][rc.autocall]
435
423
436 def magic_autoindent(self, parameter_s = ''):
424 def magic_autoindent(self, parameter_s = ''):
437 """Toggle autoindent on/off (if available)."""
425 """Toggle autoindent on/off (if available)."""
438
426
439 self.shell.set_autoindent()
427 self.shell.set_autoindent()
440 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
428 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
441
429
442 def magic_system_verbose(self, parameter_s = ''):
430 def magic_system_verbose(self, parameter_s = ''):
443 """Toggle verbose printing of system calls on/off."""
431 """Toggle verbose printing of system calls on/off."""
444
432
445 self.shell.rc_set_toggle('system_verbose')
433 self.shell.rc_set_toggle('system_verbose')
446 print "System verbose printing is:",\
434 print "System verbose printing is:",\
447 ['OFF','ON'][self.shell.rc.system_verbose]
435 ['OFF','ON'][self.shell.rc.system_verbose]
448
436
449 def magic_history(self, parameter_s = ''):
437 def magic_history(self, parameter_s = ''):
450 """Print input history (_i<n> variables), with most recent last.
438 """Print input history (_i<n> variables), with most recent last.
451
439
452 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
440 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
453 %history [-n] n -> print at most n inputs\\
441 %history [-n] n -> print at most n inputs\\
454 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
442 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
455
443
456 Each input's number <n> is shown, and is accessible as the
444 Each input's number <n> is shown, and is accessible as the
457 automatically generated variable _i<n>. Multi-line statements are
445 automatically generated variable _i<n>. Multi-line statements are
458 printed starting at a new line for easy copy/paste.
446 printed starting at a new line for easy copy/paste.
459
447
460 If option -n is used, input numbers are not printed. This is useful if
448 If option -n is used, input numbers are not printed. This is useful if
461 you want to get a printout of many lines which can be directly pasted
449 you want to get a printout of many lines which can be directly pasted
462 into a text editor.
450 into a text editor.
463
451
464 This feature is only available if numbered prompts are in use."""
452 This feature is only available if numbered prompts are in use."""
465
453
466 if not self.shell.outputcache.do_full_cache:
454 if not self.shell.outputcache.do_full_cache:
467 print 'This feature is only available if numbered prompts are in use.'
455 print 'This feature is only available if numbered prompts are in use.'
468 return
456 return
469 opts,args = self.parse_options(parameter_s,'n',mode='list')
457 opts,args = self.parse_options(parameter_s,'n',mode='list')
470
458
471 default_length = 40
459 default_length = 40
472 if len(args) == 0:
460 if len(args) == 0:
473 final = self.shell.outputcache.prompt_count
461 final = self.shell.outputcache.prompt_count
474 init = max(1,final-default_length)
462 init = max(1,final-default_length)
475 elif len(args) == 1:
463 elif len(args) == 1:
476 final = self.shell.outputcache.prompt_count
464 final = self.shell.outputcache.prompt_count
477 init = max(1,final-int(args[0]))
465 init = max(1,final-int(args[0]))
478 elif len(args) == 2:
466 elif len(args) == 2:
479 init,final = map(int,args)
467 init,final = map(int,args)
480 else:
468 else:
481 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
469 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
482 print self.magic_hist.__doc__
470 print self.magic_hist.__doc__
483 return
471 return
484 width = len(str(final))
472 width = len(str(final))
485 line_sep = ['','\n']
473 line_sep = ['','\n']
486 input_hist = self.shell.input_hist
474 input_hist = self.shell.input_hist
487 print_nums = not opts.has_key('n')
475 print_nums = not opts.has_key('n')
488 for in_num in range(init,final):
476 for in_num in range(init,final):
489 inline = input_hist[in_num]
477 inline = input_hist[in_num]
490 multiline = inline.count('\n') > 1
478 multiline = inline.count('\n') > 1
491 if print_nums:
479 if print_nums:
492 print str(in_num).ljust(width)+':'+ line_sep[multiline],
480 print str(in_num).ljust(width)+':'+ line_sep[multiline],
493 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
481 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
494 inline.startswith('#!'):
482 inline.startswith('#!'):
495 print inline[1:],
483 print inline[1:],
496 else:
484 else:
497 print inline,
485 print inline,
498
486
499 def magic_hist(self, parameter_s=''):
487 def magic_hist(self, parameter_s=''):
500 """Alternate name for %history."""
488 """Alternate name for %history."""
501 return self.magic_history(parameter_s)
489 return self.magic_history(parameter_s)
502
490
503 def magic_p(self, parameter_s=''):
491 def magic_p(self, parameter_s=''):
504 """Just a short alias for Python's 'print'."""
492 """Just a short alias for Python's 'print'."""
505 exec 'print ' + parameter_s in self.shell.user_ns
493 exec 'print ' + parameter_s in self.shell.user_ns
506
494
507 def magic_r(self, parameter_s=''):
495 def magic_r(self, parameter_s=''):
508 """Repeat previous input.
496 """Repeat previous input.
509
497
510 If given an argument, repeats the previous command which starts with
498 If given an argument, repeats the previous command which starts with
511 the same string, otherwise it just repeats the previous input.
499 the same string, otherwise it just repeats the previous input.
512
500
513 Shell escaped commands (with ! as first character) are not recognized
501 Shell escaped commands (with ! as first character) are not recognized
514 by this system, only pure python code and magic commands.
502 by this system, only pure python code and magic commands.
515 """
503 """
516
504
517 start = parameter_s.strip()
505 start = parameter_s.strip()
518 esc_magic = self.shell.ESC_MAGIC
506 esc_magic = self.shell.ESC_MAGIC
519 # Identify magic commands even if automagic is on (which means
507 # Identify magic commands even if automagic is on (which means
520 # the in-memory version is different from that typed by the user).
508 # the in-memory version is different from that typed by the user).
521 if self.shell.rc.automagic:
509 if self.shell.rc.automagic:
522 start_magic = esc_magic+start
510 start_magic = esc_magic+start
523 else:
511 else:
524 start_magic = start
512 start_magic = start
525 # Look through the input history in reverse
513 # Look through the input history in reverse
526 for n in range(len(self.shell.input_hist)-2,0,-1):
514 for n in range(len(self.shell.input_hist)-2,0,-1):
527 input = self.shell.input_hist[n]
515 input = self.shell.input_hist[n]
528 # skip plain 'r' lines so we don't recurse to infinity
516 # skip plain 'r' lines so we don't recurse to infinity
529 if input != 'ipmagic("r")\n' and \
517 if input != 'ipmagic("r")\n' and \
530 (input.startswith(start) or input.startswith(start_magic)):
518 (input.startswith(start) or input.startswith(start_magic)):
531 #print 'match',`input` # dbg
519 #print 'match',`input` # dbg
532 print 'Executing:',input,
520 print 'Executing:',input,
533 self.shell.runlines(input)
521 self.shell.runlines(input)
534 return
522 return
535 print 'No previous input matching `%s` found.' % start
523 print 'No previous input matching `%s` found.' % start
536
524
537 def magic_page(self, parameter_s=''):
525 def magic_page(self, parameter_s=''):
538 """Pretty print the object and display it through a pager.
526 """Pretty print the object and display it through a pager.
539
527
540 If no parameter is given, use _ (last output)."""
528 If no parameter is given, use _ (last output)."""
541 # After a function contributed by Olivier Aubert, slightly modified.
529 # After a function contributed by Olivier Aubert, slightly modified.
542
530
543 oname = parameter_s and parameter_s or '_'
531 oname = parameter_s and parameter_s or '_'
544 info = self._ofind(oname)
532 info = self._ofind(oname)
545 if info['found']:
533 if info['found']:
546 page(pformat(info['obj']))
534 page(pformat(info['obj']))
547 else:
535 else:
548 print 'Object `%s` not found' % oname
536 print 'Object `%s` not found' % oname
549
537
550 def magic_profile(self, parameter_s=''):
538 def magic_profile(self, parameter_s=''):
551 """Print your currently active IPyhton profile."""
539 """Print your currently active IPyhton profile."""
552 if self.shell.rc.profile:
540 if self.shell.rc.profile:
553 printpl('Current IPython profile: $self.shell.rc.profile.')
541 printpl('Current IPython profile: $self.shell.rc.profile.')
554 else:
542 else:
555 print 'No profile active.'
543 print 'No profile active.'
556
544
557 def _inspect(self,meth,oname,**kw):
545 def _inspect(self,meth,oname,**kw):
558 """Generic interface to the inspector system.
546 """Generic interface to the inspector system.
559
547
560 This function is meant to be called by pdef, pdoc & friends."""
548 This function is meant to be called by pdef, pdoc & friends."""
561
549
562 oname = oname.strip()
550 oname = oname.strip()
563 info = Struct(self._ofind(oname))
551 info = Struct(self._ofind(oname))
564 if info.found:
552 if info.found:
565 pmethod = getattr(self.shell.inspector,meth)
553 pmethod = getattr(self.shell.inspector,meth)
566 formatter = info.ismagic and self.format_screen or None
554 formatter = info.ismagic and self.format_screen or None
567 if meth == 'pdoc':
555 if meth == 'pdoc':
568 pmethod(info.obj,oname,formatter)
556 pmethod(info.obj,oname,formatter)
569 elif meth == 'pinfo':
557 elif meth == 'pinfo':
570 pmethod(info.obj,oname,formatter,info,**kw)
558 pmethod(info.obj,oname,formatter,info,**kw)
571 else:
559 else:
572 pmethod(info.obj,oname)
560 pmethod(info.obj,oname)
573 else:
561 else:
574 print 'Object `%s` not found.' % oname
562 print 'Object `%s` not found.' % oname
575 return 'not found' # so callers can take other action
563 return 'not found' # so callers can take other action
576
564
577 def magic_pdef(self, parameter_s=''):
565 def magic_pdef(self, parameter_s=''):
578 """Print the definition header for any callable object.
566 """Print the definition header for any callable object.
579
567
580 If the object is a class, print the constructor information."""
568 If the object is a class, print the constructor information."""
581 self._inspect('pdef',parameter_s)
569 self._inspect('pdef',parameter_s)
582
570
583 def magic_pdoc(self, parameter_s=''):
571 def magic_pdoc(self, parameter_s=''):
584 """Print the docstring for an object.
572 """Print the docstring for an object.
585
573
586 If the given object is a class, it will print both the class and the
574 If the given object is a class, it will print both the class and the
587 constructor docstrings."""
575 constructor docstrings."""
588 self._inspect('pdoc',parameter_s)
576 self._inspect('pdoc',parameter_s)
589
577
590 def magic_psource(self, parameter_s=''):
578 def magic_psource(self, parameter_s=''):
591 """Print (or run through pager) the source code for an object."""
579 """Print (or run through pager) the source code for an object."""
592 self._inspect('psource',parameter_s)
580 self._inspect('psource',parameter_s)
593
581
594 def magic_pfile(self, parameter_s=''):
582 def magic_pfile(self, parameter_s=''):
595 """Print (or run through pager) the file where an object is defined.
583 """Print (or run through pager) the file where an object is defined.
596
584
597 The file opens at the line where the object definition begins. IPython
585 The file opens at the line where the object definition begins. IPython
598 will honor the environment variable PAGER if set, and otherwise will
586 will honor the environment variable PAGER if set, and otherwise will
599 do its best to print the file in a convenient form.
587 do its best to print the file in a convenient form.
600
588
601 If the given argument is not an object currently defined, IPython will
589 If the given argument is not an object currently defined, IPython will
602 try to interpret it as a filename (automatically adding a .py extension
590 try to interpret it as a filename (automatically adding a .py extension
603 if needed). You can thus use %pfile as a syntax highlighting code
591 if needed). You can thus use %pfile as a syntax highlighting code
604 viewer."""
592 viewer."""
605
593
606 # first interpret argument as an object name
594 # first interpret argument as an object name
607 out = self._inspect('pfile',parameter_s)
595 out = self._inspect('pfile',parameter_s)
608 # if not, try the input as a filename
596 # if not, try the input as a filename
609 if out == 'not found':
597 if out == 'not found':
610 try:
598 try:
611 filename = get_py_filename(parameter_s)
599 filename = get_py_filename(parameter_s)
612 except IOError,msg:
600 except IOError,msg:
613 print msg
601 print msg
614 return
602 return
615 page(self.shell.inspector.format(file(filename).read()))
603 page(self.shell.inspector.format(file(filename).read()))
616
604
617 def magic_pinfo(self, parameter_s=''):
605 def magic_pinfo(self, parameter_s=''):
618 """Provide detailed information about an object.
606 """Provide detailed information about an object.
619
607
620 '%pinfo object' is just a synonym for object? or ?object."""
608 '%pinfo object' is just a synonym for object? or ?object."""
621
609
622 #print 'pinfo par: <%s>' % parameter_s # dbg
610 #print 'pinfo par: <%s>' % parameter_s # dbg
623
611
624 # detail_level: 0 -> obj? , 1 -> obj??
612 # detail_level: 0 -> obj? , 1 -> obj??
625 detail_level = 0
613 detail_level = 0
626 # We need to detect if we got called as 'pinfo pinfo foo', which can
614 # We need to detect if we got called as 'pinfo pinfo foo', which can
627 # happen if the user types 'pinfo foo?' at the cmd line.
615 # happen if the user types 'pinfo foo?' at the cmd line.
628 pinfo,qmark1,oname,qmark2 = \
616 pinfo,qmark1,oname,qmark2 = \
629 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
617 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
630 if pinfo or qmark1 or qmark2:
618 if pinfo or qmark1 or qmark2:
631 detail_level = 1
619 detail_level = 1
632 if "*" in oname:
620 if "*" in oname:
633 self.magic_psearch(oname)
621 self.magic_psearch(oname)
634 else:
622 else:
635 self._inspect('pinfo',oname,detail_level=detail_level)
623 self._inspect('pinfo',oname,detail_level=detail_level)
636
624
637 def magic_psearch(self, parameter_s=''):
625 def magic_psearch(self, parameter_s=''):
638 """Search for object in namespaces by wildcard.
626 """Search for object in namespaces by wildcard.
639
627
640 %psearch [options] PATTERN [OBJECT TYPE]
628 %psearch [options] PATTERN [OBJECT TYPE]
641
629
642 Note: ? can be used as a synonym for %psearch, at the beginning or at
630 Note: ? can be used as a synonym for %psearch, at the beginning or at
643 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
631 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
644 rest of the command line must be unchanged (options come first), so
632 rest of the command line must be unchanged (options come first), so
645 for example the following forms are equivalent
633 for example the following forms are equivalent
646
634
647 %psearch -i a* function
635 %psearch -i a* function
648 -i a* function?
636 -i a* function?
649 ?-i a* function
637 ?-i a* function
650
638
651 Arguments:
639 Arguments:
652
640
653 PATTERN
641 PATTERN
654
642
655 where PATTERN is a string containing * as a wildcard similar to its
643 where PATTERN is a string containing * as a wildcard similar to its
656 use in a shell. The pattern is matched in all namespaces on the
644 use in a shell. The pattern is matched in all namespaces on the
657 search path. By default objects starting with a single _ are not
645 search path. By default objects starting with a single _ are not
658 matched, many IPython generated objects have a single
646 matched, many IPython generated objects have a single
659 underscore. The default is case insensitive matching. Matching is
647 underscore. The default is case insensitive matching. Matching is
660 also done on the attributes of objects and not only on the objects
648 also done on the attributes of objects and not only on the objects
661 in a module.
649 in a module.
662
650
663 [OBJECT TYPE]
651 [OBJECT TYPE]
664
652
665 Is the name of a python type from the types module. The name is
653 Is the name of a python type from the types module. The name is
666 given in lowercase without the ending type, ex. StringType is
654 given in lowercase without the ending type, ex. StringType is
667 written string. By adding a type here only objects matching the
655 written string. By adding a type here only objects matching the
668 given type are matched. Using all here makes the pattern match all
656 given type are matched. Using all here makes the pattern match all
669 types (this is the default).
657 types (this is the default).
670
658
671 Options:
659 Options:
672
660
673 -a: makes the pattern match even objects whose names start with a
661 -a: makes the pattern match even objects whose names start with a
674 single underscore. These names are normally ommitted from the
662 single underscore. These names are normally ommitted from the
675 search.
663 search.
676
664
677 -i/-c: make the pattern case insensitive/sensitive. If neither of
665 -i/-c: make the pattern case insensitive/sensitive. If neither of
678 these options is given, the default is read from your ipythonrc
666 these options is given, the default is read from your ipythonrc
679 file. The option name which sets this value is
667 file. The option name which sets this value is
680 'wildcards_case_sensitive'. If this option is not specified in your
668 'wildcards_case_sensitive'. If this option is not specified in your
681 ipythonrc file, IPython's internal default is to do a case sensitive
669 ipythonrc file, IPython's internal default is to do a case sensitive
682 search.
670 search.
683
671
684 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
672 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
685 specifiy can be searched in any of the following namespaces:
673 specifiy can be searched in any of the following namespaces:
686 'builtin', 'user', 'user_global','internal', 'alias', where
674 'builtin', 'user', 'user_global','internal', 'alias', where
687 'builtin' and 'user' are the search defaults. Note that you should
675 'builtin' and 'user' are the search defaults. Note that you should
688 not use quotes when specifying namespaces.
676 not use quotes when specifying namespaces.
689
677
690 'Builtin' contains the python module builtin, 'user' contains all
678 'Builtin' contains the python module builtin, 'user' contains all
691 user data, 'alias' only contain the shell aliases and no python
679 user data, 'alias' only contain the shell aliases and no python
692 objects, 'internal' contains objects used by IPython. The
680 objects, 'internal' contains objects used by IPython. The
693 'user_global' namespace is only used by embedded IPython instances,
681 'user_global' namespace is only used by embedded IPython instances,
694 and it contains module-level globals. You can add namespaces to the
682 and it contains module-level globals. You can add namespaces to the
695 search with -s or exclude them with -e (these options can be given
683 search with -s or exclude them with -e (these options can be given
696 more than once).
684 more than once).
697
685
698 Examples:
686 Examples:
699
687
700 %psearch a* -> objects beginning with an a
688 %psearch a* -> objects beginning with an a
701 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
689 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
702 %psearch a* function -> all functions beginning with an a
690 %psearch a* function -> all functions beginning with an a
703 %psearch re.e* -> objects beginning with an e in module re
691 %psearch re.e* -> objects beginning with an e in module re
704 %psearch r*.e* -> objects that start with e in modules starting in r
692 %psearch r*.e* -> objects that start with e in modules starting in r
705 %psearch r*.* string -> all strings in modules beginning with r
693 %psearch r*.* string -> all strings in modules beginning with r
706
694
707 Case sensitve search:
695 Case sensitve search:
708
696
709 %psearch -c a* list all object beginning with lower case a
697 %psearch -c a* list all object beginning with lower case a
710
698
711 Show objects beginning with a single _:
699 Show objects beginning with a single _:
712
700
713 %psearch -a _* list objects beginning with a single underscore"""
701 %psearch -a _* list objects beginning with a single underscore"""
714
702
715 # default namespaces to be searched
703 # default namespaces to be searched
716 def_search = ['user','builtin']
704 def_search = ['user','builtin']
717
705
718 # Process options/args
706 # Process options/args
719 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
707 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
720 opt = opts.get
708 opt = opts.get
721 shell = self.shell
709 shell = self.shell
722 psearch = shell.inspector.psearch
710 psearch = shell.inspector.psearch
723
711
724 # select case options
712 # select case options
725 if opts.has_key('i'):
713 if opts.has_key('i'):
726 ignore_case = True
714 ignore_case = True
727 elif opts.has_key('c'):
715 elif opts.has_key('c'):
728 ignore_case = False
716 ignore_case = False
729 else:
717 else:
730 ignore_case = not shell.rc.wildcards_case_sensitive
718 ignore_case = not shell.rc.wildcards_case_sensitive
731
719
732 # Build list of namespaces to search from user options
720 # Build list of namespaces to search from user options
733 def_search.extend(opt('s',[]))
721 def_search.extend(opt('s',[]))
734 ns_exclude = ns_exclude=opt('e',[])
722 ns_exclude = ns_exclude=opt('e',[])
735 ns_search = [nm for nm in def_search if nm not in ns_exclude]
723 ns_search = [nm for nm in def_search if nm not in ns_exclude]
736
724
737 # Call the actual search
725 # Call the actual search
738 try:
726 try:
739 psearch(args,shell.ns_table,ns_search,
727 psearch(args,shell.ns_table,ns_search,
740 show_all=opt('a'),ignore_case=ignore_case)
728 show_all=opt('a'),ignore_case=ignore_case)
741 except:
729 except:
742 shell.showtraceback()
730 shell.showtraceback()
743
731
744 def magic_who_ls(self, parameter_s=''):
732 def magic_who_ls(self, parameter_s=''):
745 """Return a sorted list of all interactive variables.
733 """Return a sorted list of all interactive variables.
746
734
747 If arguments are given, only variables of types matching these
735 If arguments are given, only variables of types matching these
748 arguments are returned."""
736 arguments are returned."""
749
737
750 user_ns = self.shell.user_ns
738 user_ns = self.shell.user_ns
751 out = []
739 out = []
752 typelist = parameter_s.split()
740 typelist = parameter_s.split()
753 for i in self.shell.user_ns.keys():
741 for i in self.shell.user_ns.keys():
754 if not (i.startswith('_') or i.startswith('_i')) \
742 if not (i.startswith('_') or i.startswith('_i')) \
755 and not (self.shell.internal_ns.has_key(i) or
743 and not (self.shell.internal_ns.has_key(i) or
756 self.shell.user_config_ns.has_key(i)):
744 self.shell.user_config_ns.has_key(i)):
757 if typelist:
745 if typelist:
758 if type(user_ns[i]).__name__ in typelist:
746 if type(user_ns[i]).__name__ in typelist:
759 out.append(i)
747 out.append(i)
760 else:
748 else:
761 out.append(i)
749 out.append(i)
762 out.sort()
750 out.sort()
763 return out
751 return out
764
752
765 def magic_who(self, parameter_s=''):
753 def magic_who(self, parameter_s=''):
766 """Print all interactive variables, with some minimal formatting.
754 """Print all interactive variables, with some minimal formatting.
767
755
768 If any arguments are given, only variables whose type matches one of
756 If any arguments are given, only variables whose type matches one of
769 these are printed. For example:
757 these are printed. For example:
770
758
771 %who function str
759 %who function str
772
760
773 will only list functions and strings, excluding all other types of
761 will only list functions and strings, excluding all other types of
774 variables. To find the proper type names, simply use type(var) at a
762 variables. To find the proper type names, simply use type(var) at a
775 command line to see how python prints type names. For example:
763 command line to see how python prints type names. For example:
776
764
777 In [1]: type('hello')\\
765 In [1]: type('hello')\\
778 Out[1]: <type 'str'>
766 Out[1]: <type 'str'>
779
767
780 indicates that the type name for strings is 'str'.
768 indicates that the type name for strings is 'str'.
781
769
782 %who always excludes executed names loaded through your configuration
770 %who always excludes executed names loaded through your configuration
783 file and things which are internal to IPython.
771 file and things which are internal to IPython.
784
772
785 This is deliberate, as typically you may load many modules and the
773 This is deliberate, as typically you may load many modules and the
786 purpose of %who is to show you only what you've manually defined."""
774 purpose of %who is to show you only what you've manually defined."""
787
775
788 varlist = self.magic_who_ls(parameter_s)
776 varlist = self.magic_who_ls(parameter_s)
789 if not varlist:
777 if not varlist:
790 print 'Interactive namespace is empty.'
778 print 'Interactive namespace is empty.'
791 return
779 return
792
780
793 # if we have variables, move on...
781 # if we have variables, move on...
794
782
795 # stupid flushing problem: when prompts have no separators, stdout is
783 # stupid flushing problem: when prompts have no separators, stdout is
796 # getting lost. I'm starting to think this is a python bug. I'm having
784 # getting lost. I'm starting to think this is a python bug. I'm having
797 # to force a flush with a print because even a sys.stdout.flush
785 # to force a flush with a print because even a sys.stdout.flush
798 # doesn't seem to do anything!
786 # doesn't seem to do anything!
799
787
800 count = 0
788 count = 0
801 for i in varlist:
789 for i in varlist:
802 print i+'\t',
790 print i+'\t',
803 count += 1
791 count += 1
804 if count > 8:
792 if count > 8:
805 count = 0
793 count = 0
806 print
794 print
807 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
795 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
808
796
809 print # well, this does force a flush at the expense of an extra \n
797 print # well, this does force a flush at the expense of an extra \n
810
798
811 def magic_whos(self, parameter_s=''):
799 def magic_whos(self, parameter_s=''):
812 """Like %who, but gives some extra information about each variable.
800 """Like %who, but gives some extra information about each variable.
813
801
814 The same type filtering of %who can be applied here.
802 The same type filtering of %who can be applied here.
815
803
816 For all variables, the type is printed. Additionally it prints:
804 For all variables, the type is printed. Additionally it prints:
817
805
818 - For {},[],(): their length.
806 - For {},[],(): their length.
819
807
820 - For Numeric arrays, a summary with shape, number of elements,
808 - For Numeric arrays, a summary with shape, number of elements,
821 typecode and size in memory.
809 typecode and size in memory.
822
810
823 - Everything else: a string representation, snipping their middle if
811 - Everything else: a string representation, snipping their middle if
824 too long."""
812 too long."""
825
813
826 varnames = self.magic_who_ls(parameter_s)
814 varnames = self.magic_who_ls(parameter_s)
827 if not varnames:
815 if not varnames:
828 print 'Interactive namespace is empty.'
816 print 'Interactive namespace is empty.'
829 return
817 return
830
818
831 # if we have variables, move on...
819 # if we have variables, move on...
832
820
833 # for these types, show len() instead of data:
821 # for these types, show len() instead of data:
834 seq_types = [types.DictType,types.ListType,types.TupleType]
822 seq_types = [types.DictType,types.ListType,types.TupleType]
835
823
836 # for Numeric arrays, display summary info
824 # for Numeric arrays, display summary info
837 try:
825 try:
838 import Numeric
826 import Numeric
839 except ImportError:
827 except ImportError:
840 array_type = None
828 array_type = None
841 else:
829 else:
842 array_type = Numeric.ArrayType.__name__
830 array_type = Numeric.ArrayType.__name__
843
831
844 # Find all variable names and types so we can figure out column sizes
832 # Find all variable names and types so we can figure out column sizes
845 get_vars = lambda i: self.shell.user_ns[i]
833 get_vars = lambda i: self.shell.user_ns[i]
846 type_name = lambda v: type(v).__name__
834 type_name = lambda v: type(v).__name__
847 varlist = map(get_vars,varnames)
835 varlist = map(get_vars,varnames)
848 typelist = map(type_name,varlist)
836
837 typelist = []
838 for vv in varlist:
839 tt = type_name(vv)
840 if tt=='instance':
841 typelist.append(str(vv.__class__))
842 else:
843 typelist.append(tt)
844
849 # column labels and # of spaces as separator
845 # column labels and # of spaces as separator
850 varlabel = 'Variable'
846 varlabel = 'Variable'
851 typelabel = 'Type'
847 typelabel = 'Type'
852 datalabel = 'Data/Info'
848 datalabel = 'Data/Info'
853 colsep = 3
849 colsep = 3
854 # variable format strings
850 # variable format strings
855 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
851 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
856 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
852 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
857 aformat = "%s: %s elems, type `%s`, %s bytes"
853 aformat = "%s: %s elems, type `%s`, %s bytes"
858 # find the size of the columns to format the output nicely
854 # find the size of the columns to format the output nicely
859 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
855 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
860 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
856 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
861 # table header
857 # table header
862 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
858 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
863 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
859 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
864 # and the table itself
860 # and the table itself
865 kb = 1024
861 kb = 1024
866 Mb = 1048576 # kb**2
862 Mb = 1048576 # kb**2
867 for vname,var,vtype in zip(varnames,varlist,typelist):
863 for vname,var,vtype in zip(varnames,varlist,typelist):
868 print itpl(vformat),
864 print itpl(vformat),
869 if vtype in seq_types:
865 if vtype in seq_types:
870 print len(var)
866 print len(var)
871 elif vtype==array_type:
867 elif vtype==array_type:
872 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
868 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
873 vsize = Numeric.size(var)
869 vsize = Numeric.size(var)
874 vbytes = vsize*var.itemsize()
870 vbytes = vsize*var.itemsize()
875 if vbytes < 100000:
871 if vbytes < 100000:
876 print aformat % (vshape,vsize,var.typecode(),vbytes)
872 print aformat % (vshape,vsize,var.typecode(),vbytes)
877 else:
873 else:
878 print aformat % (vshape,vsize,var.typecode(),vbytes),
874 print aformat % (vshape,vsize,var.typecode(),vbytes),
879 if vbytes < Mb:
875 if vbytes < Mb:
880 print '(%s kb)' % (vbytes/kb,)
876 print '(%s kb)' % (vbytes/kb,)
881 else:
877 else:
882 print '(%s Mb)' % (vbytes/Mb,)
878 print '(%s Mb)' % (vbytes/Mb,)
883 else:
879 else:
884 vstr = str(var)
880 vstr = str(var).replace('\n','\\n')
885 if len(vstr) < 50:
881 if len(vstr) < 50:
886 print vstr
882 print vstr
887 else:
883 else:
888 printpl(vfmt_short)
884 printpl(vfmt_short)
889
885
890 def magic_reset(self, parameter_s=''):
886 def magic_reset(self, parameter_s=''):
891 """Resets the namespace by removing all names defined by the user.
887 """Resets the namespace by removing all names defined by the user.
892
888
893 Input/Output history are left around in case you need them."""
889 Input/Output history are left around in case you need them."""
894
890
895 ans = raw_input(
891 ans = raw_input(
896 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
892 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
897 if not ans.lower() == 'y':
893 if not ans.lower() == 'y':
898 print 'Nothing done.'
894 print 'Nothing done.'
899 return
895 return
900 user_ns = self.shell.user_ns
896 user_ns = self.shell.user_ns
901 for i in self.magic_who_ls():
897 for i in self.magic_who_ls():
902 del(user_ns[i])
898 del(user_ns[i])
903
899
904 def magic_config(self,parameter_s=''):
900 def magic_config(self,parameter_s=''):
905 """Show IPython's internal configuration."""
901 """Show IPython's internal configuration."""
906
902
907 page('Current configuration structure:\n'+
903 page('Current configuration structure:\n'+
908 pformat(self.shell.rc.dict()))
904 pformat(self.shell.rc.dict()))
909
905
910 def magic_logstart(self,parameter_s=''):
906 def magic_logstart(self,parameter_s=''):
911 """Start logging anywhere in a session.
907 """Start logging anywhere in a session.
912
908
913 %logstart [-o|-t] [log_name [log_mode]]
909 %logstart [-o|-t] [log_name [log_mode]]
914
910
915 If no name is given, it defaults to a file named 'ipython_log.py' in your
911 If no name is given, it defaults to a file named 'ipython_log.py' in your
916 current directory, in 'rotate' mode (see below).
912 current directory, in 'rotate' mode (see below).
917
913
918 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
914 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
919 history up to that point and then continues logging.
915 history up to that point and then continues logging.
920
916
921 %logstart takes a second optional parameter: logging mode. This can be one
917 %logstart takes a second optional parameter: logging mode. This can be one
922 of (note that the modes are given unquoted):\\
918 of (note that the modes are given unquoted):\\
923 append: well, that says it.\\
919 append: well, that says it.\\
924 backup: rename (if exists) to name~ and start name.\\
920 backup: rename (if exists) to name~ and start name.\\
925 global: single logfile in your home dir, appended to.\\
921 global: single logfile in your home dir, appended to.\\
926 over : overwrite existing log.\\
922 over : overwrite existing log.\\
927 rotate: create rotating logs name.1~, name.2~, etc.
923 rotate: create rotating logs name.1~, name.2~, etc.
928
924
929 Options:
925 Options:
930
926
931 -o: log also IPython's output. In this mode, all commands which
927 -o: log also IPython's output. In this mode, all commands which
932 generate an Out[NN] prompt are recorded to the logfile, right after
928 generate an Out[NN] prompt are recorded to the logfile, right after
933 their corresponding input line. The output lines are always
929 their corresponding input line. The output lines are always
934 prepended with a '#[Out]# ' marker, so that the log remains valid
930 prepended with a '#[Out]# ' marker, so that the log remains valid
935 Python code.
931 Python code.
936
932
937 Since this marker is always the same, filtering only the output from
933 Since this marker is always the same, filtering only the output from
938 a log is very easy, using for example a simple awk call:
934 a log is very easy, using for example a simple awk call:
939
935
940 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
936 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
941
937
942 -t: put timestamps before each input line logged (these are put in
938 -t: put timestamps before each input line logged (these are put in
943 comments)."""
939 comments)."""
944
940
945 opts,par = self.parse_options(parameter_s,'ot')
941 opts,par = self.parse_options(parameter_s,'ot')
946 log_output = 'o' in opts
942 log_output = 'o' in opts
947 timestamp = 't' in opts
943 timestamp = 't' in opts
948
944
949 rc = self.shell.rc
945 rc = self.shell.rc
950 logger = self.shell.logger
946 logger = self.shell.logger
951
947
952 # if no args are given, the defaults set in the logger constructor by
948 # if no args are given, the defaults set in the logger constructor by
953 # ipytohn remain valid
949 # ipytohn remain valid
954 if par:
950 if par:
955 try:
951 try:
956 logfname,logmode = par.split()
952 logfname,logmode = par.split()
957 except:
953 except:
958 logfname = par
954 logfname = par
959 logmode = 'backup'
955 logmode = 'backup'
960 else:
956 else:
961 logfname = logger.logfname
957 logfname = logger.logfname
962 logmode = logger.logmode
958 logmode = logger.logmode
963 # put logfname into rc struct as if it had been called on the command
959 # put logfname into rc struct as if it had been called on the command
964 # line, so it ends up saved in the log header Save it in case we need
960 # line, so it ends up saved in the log header Save it in case we need
965 # to restore it...
961 # to restore it...
966 old_logfile = rc.opts.get('logfile','')
962 old_logfile = rc.opts.get('logfile','')
967 if logfname:
963 if logfname:
968 logfname = os.path.expanduser(logfname)
964 logfname = os.path.expanduser(logfname)
969 rc.opts.logfile = logfname
965 rc.opts.logfile = logfname
970 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
966 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
971 try:
967 try:
972 started = logger.logstart(logfname,loghead,logmode,
968 started = logger.logstart(logfname,loghead,logmode,
973 log_output,timestamp)
969 log_output,timestamp)
974 except:
970 except:
975 rc.opts.logfile = old_logfile
971 rc.opts.logfile = old_logfile
976 warn("Couldn't start log: %s" % sys.exc_info()[1])
972 warn("Couldn't start log: %s" % sys.exc_info()[1])
977 else:
973 else:
978 # log input history up to this point, optionally interleaving
974 # log input history up to this point, optionally interleaving
979 # output if requested
975 # output if requested
980
976
981 if timestamp:
977 if timestamp:
982 # disable timestamping for the previous history, since we've
978 # disable timestamping for the previous history, since we've
983 # lost those already (no time machine here).
979 # lost those already (no time machine here).
984 logger.timestamp = False
980 logger.timestamp = False
985 if log_output:
981 if log_output:
986 log_write = logger.log_write
982 log_write = logger.log_write
987 input_hist = self.shell.input_hist
983 input_hist = self.shell.input_hist
988 output_hist = self.shell.output_hist
984 output_hist = self.shell.output_hist
989 for n in range(1,len(input_hist)-1):
985 for n in range(1,len(input_hist)-1):
990 log_write(input_hist[n].rstrip())
986 log_write(input_hist[n].rstrip())
991 if n in output_hist:
987 if n in output_hist:
992 log_write(repr(output_hist[n]),'output')
988 log_write(repr(output_hist[n]),'output')
993 else:
989 else:
994 logger.log_write(self.shell.input_hist[1:])
990 logger.log_write(self.shell.input_hist[1:])
995 if timestamp:
991 if timestamp:
996 # re-enable timestamping
992 # re-enable timestamping
997 logger.timestamp = True
993 logger.timestamp = True
998
994
999 print ('Activating auto-logging. '
995 print ('Activating auto-logging. '
1000 'Current session state plus future input saved.')
996 'Current session state plus future input saved.')
1001 logger.logstate()
997 logger.logstate()
1002
998
1003 def magic_logoff(self,parameter_s=''):
999 def magic_logoff(self,parameter_s=''):
1004 """Temporarily stop logging.
1000 """Temporarily stop logging.
1005
1001
1006 You must have previously started logging."""
1002 You must have previously started logging."""
1007 self.shell.logger.switch_log(0)
1003 self.shell.logger.switch_log(0)
1008
1004
1009 def magic_logon(self,parameter_s=''):
1005 def magic_logon(self,parameter_s=''):
1010 """Restart logging.
1006 """Restart logging.
1011
1007
1012 This function is for restarting logging which you've temporarily
1008 This function is for restarting logging which you've temporarily
1013 stopped with %logoff. For starting logging for the first time, you
1009 stopped with %logoff. For starting logging for the first time, you
1014 must use the %logstart function, which allows you to specify an
1010 must use the %logstart function, which allows you to specify an
1015 optional log filename."""
1011 optional log filename."""
1016
1012
1017 self.shell.logger.switch_log(1)
1013 self.shell.logger.switch_log(1)
1018
1014
1019 def magic_logstate(self,parameter_s=''):
1015 def magic_logstate(self,parameter_s=''):
1020 """Print the status of the logging system."""
1016 """Print the status of the logging system."""
1021
1017
1022 self.shell.logger.logstate()
1018 self.shell.logger.logstate()
1023
1019
1024 def magic_pdb(self, parameter_s=''):
1020 def magic_pdb(self, parameter_s=''):
1025 """Control the calling of the pdb interactive debugger.
1021 """Control the calling of the pdb interactive debugger.
1026
1022
1027 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1023 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1028 argument it works as a toggle.
1024 argument it works as a toggle.
1029
1025
1030 When an exception is triggered, IPython can optionally call the
1026 When an exception is triggered, IPython can optionally call the
1031 interactive pdb debugger after the traceback printout. %pdb toggles
1027 interactive pdb debugger after the traceback printout. %pdb toggles
1032 this feature on and off."""
1028 this feature on and off."""
1033
1029
1034 par = parameter_s.strip().lower()
1030 par = parameter_s.strip().lower()
1035
1031
1036 if par:
1032 if par:
1037 try:
1033 try:
1038 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1034 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1039 except KeyError:
1035 except KeyError:
1040 print ('Incorrect argument. Use on/1, off/0, '
1036 print ('Incorrect argument. Use on/1, off/0, '
1041 'or nothing for a toggle.')
1037 'or nothing for a toggle.')
1042 return
1038 return
1043 else:
1039 else:
1044 # toggle
1040 # toggle
1045 new_pdb = not self.shell.InteractiveTB.call_pdb
1041 new_pdb = not self.shell.InteractiveTB.call_pdb
1046
1042
1047 # set on the shell
1043 # set on the shell
1048 self.shell.call_pdb = new_pdb
1044 self.shell.call_pdb = new_pdb
1049 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1045 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1050
1046
1051 def magic_prun(self, parameter_s ='',user_mode=1,
1047 def magic_prun(self, parameter_s ='',user_mode=1,
1052 opts=None,arg_lst=None,prog_ns=None):
1048 opts=None,arg_lst=None,prog_ns=None):
1053
1049
1054 """Run a statement through the python code profiler.
1050 """Run a statement through the python code profiler.
1055
1051
1056 Usage:\\
1052 Usage:\\
1057 %prun [options] statement
1053 %prun [options] statement
1058
1054
1059 The given statement (which doesn't require quote marks) is run via the
1055 The given statement (which doesn't require quote marks) is run via the
1060 python profiler in a manner similar to the profile.run() function.
1056 python profiler in a manner similar to the profile.run() function.
1061 Namespaces are internally managed to work correctly; profile.run
1057 Namespaces are internally managed to work correctly; profile.run
1062 cannot be used in IPython because it makes certain assumptions about
1058 cannot be used in IPython because it makes certain assumptions about
1063 namespaces which do not hold under IPython.
1059 namespaces which do not hold under IPython.
1064
1060
1065 Options:
1061 Options:
1066
1062
1067 -l <limit>: you can place restrictions on what or how much of the
1063 -l <limit>: you can place restrictions on what or how much of the
1068 profile gets printed. The limit value can be:
1064 profile gets printed. The limit value can be:
1069
1065
1070 * A string: only information for function names containing this string
1066 * A string: only information for function names containing this string
1071 is printed.
1067 is printed.
1072
1068
1073 * An integer: only these many lines are printed.
1069 * An integer: only these many lines are printed.
1074
1070
1075 * A float (between 0 and 1): this fraction of the report is printed
1071 * A float (between 0 and 1): this fraction of the report is printed
1076 (for example, use a limit of 0.4 to see the topmost 40% only).
1072 (for example, use a limit of 0.4 to see the topmost 40% only).
1077
1073
1078 You can combine several limits with repeated use of the option. For
1074 You can combine several limits with repeated use of the option. For
1079 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1075 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1080 information about class constructors.
1076 information about class constructors.
1081
1077
1082 -r: return the pstats.Stats object generated by the profiling. This
1078 -r: return the pstats.Stats object generated by the profiling. This
1083 object has all the information about the profile in it, and you can
1079 object has all the information about the profile in it, and you can
1084 later use it for further analysis or in other functions.
1080 later use it for further analysis or in other functions.
1085
1081
1086 Since magic functions have a particular form of calling which prevents
1082 Since magic functions have a particular form of calling which prevents
1087 you from writing something like:\\
1083 you from writing something like:\\
1088 In [1]: p = %prun -r print 4 # invalid!\\
1084 In [1]: p = %prun -r print 4 # invalid!\\
1089 you must instead use IPython's automatic variables to assign this:\\
1085 you must instead use IPython's automatic variables to assign this:\\
1090 In [1]: %prun -r print 4 \\
1086 In [1]: %prun -r print 4 \\
1091 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1087 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1092 In [2]: stats = _
1088 In [2]: stats = _
1093
1089
1094 If you really need to assign this value via an explicit function call,
1090 If you really need to assign this value via an explicit function call,
1095 you can always tap directly into the true name of the magic function
1091 you can always tap directly into the true name of the magic function
1096 by using the ipmagic function (which IPython automatically adds to the
1092 by using the ipmagic function (which IPython automatically adds to the
1097 builtins):\\
1093 builtins):\\
1098 In [3]: stats = ipmagic('prun','-r print 4')
1094 In [3]: stats = ipmagic('prun','-r print 4')
1099
1095
1100 You can type ipmagic? for more details on ipmagic.
1096 You can type ipmagic? for more details on ipmagic.
1101
1097
1102 -s <key>: sort profile by given key. You can provide more than one key
1098 -s <key>: sort profile by given key. You can provide more than one key
1103 by using the option several times: '-s key1 -s key2 -s key3...'. The
1099 by using the option several times: '-s key1 -s key2 -s key3...'. The
1104 default sorting key is 'time'.
1100 default sorting key is 'time'.
1105
1101
1106 The following is copied verbatim from the profile documentation
1102 The following is copied verbatim from the profile documentation
1107 referenced below:
1103 referenced below:
1108
1104
1109 When more than one key is provided, additional keys are used as
1105 When more than one key is provided, additional keys are used as
1110 secondary criteria when the there is equality in all keys selected
1106 secondary criteria when the there is equality in all keys selected
1111 before them.
1107 before them.
1112
1108
1113 Abbreviations can be used for any key names, as long as the
1109 Abbreviations can be used for any key names, as long as the
1114 abbreviation is unambiguous. The following are the keys currently
1110 abbreviation is unambiguous. The following are the keys currently
1115 defined:
1111 defined:
1116
1112
1117 Valid Arg Meaning\\
1113 Valid Arg Meaning\\
1118 "calls" call count\\
1114 "calls" call count\\
1119 "cumulative" cumulative time\\
1115 "cumulative" cumulative time\\
1120 "file" file name\\
1116 "file" file name\\
1121 "module" file name\\
1117 "module" file name\\
1122 "pcalls" primitive call count\\
1118 "pcalls" primitive call count\\
1123 "line" line number\\
1119 "line" line number\\
1124 "name" function name\\
1120 "name" function name\\
1125 "nfl" name/file/line\\
1121 "nfl" name/file/line\\
1126 "stdname" standard name\\
1122 "stdname" standard name\\
1127 "time" internal time
1123 "time" internal time
1128
1124
1129 Note that all sorts on statistics are in descending order (placing
1125 Note that all sorts on statistics are in descending order (placing
1130 most time consuming items first), where as name, file, and line number
1126 most time consuming items first), where as name, file, and line number
1131 searches are in ascending order (i.e., alphabetical). The subtle
1127 searches are in ascending order (i.e., alphabetical). The subtle
1132 distinction between "nfl" and "stdname" is that the standard name is a
1128 distinction between "nfl" and "stdname" is that the standard name is a
1133 sort of the name as printed, which means that the embedded line
1129 sort of the name as printed, which means that the embedded line
1134 numbers get compared in an odd way. For example, lines 3, 20, and 40
1130 numbers get compared in an odd way. For example, lines 3, 20, and 40
1135 would (if the file names were the same) appear in the string order
1131 would (if the file names were the same) appear in the string order
1136 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1132 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1137 line numbers. In fact, sort_stats("nfl") is the same as
1133 line numbers. In fact, sort_stats("nfl") is the same as
1138 sort_stats("name", "file", "line").
1134 sort_stats("name", "file", "line").
1139
1135
1140 -T <filename>: save profile results as shown on screen to a text
1136 -T <filename>: save profile results as shown on screen to a text
1141 file. The profile is still shown on screen.
1137 file. The profile is still shown on screen.
1142
1138
1143 -D <filename>: save (via dump_stats) profile statistics to given
1139 -D <filename>: save (via dump_stats) profile statistics to given
1144 filename. This data is in a format understod by the pstats module, and
1140 filename. This data is in a format understod by the pstats module, and
1145 is generated by a call to the dump_stats() method of profile
1141 is generated by a call to the dump_stats() method of profile
1146 objects. The profile is still shown on screen.
1142 objects. The profile is still shown on screen.
1147
1143
1148 If you want to run complete programs under the profiler's control, use
1144 If you want to run complete programs under the profiler's control, use
1149 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1145 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1150 contains profiler specific options as described here.
1146 contains profiler specific options as described here.
1151
1147
1152 You can read the complete documentation for the profile module with:\\
1148 You can read the complete documentation for the profile module with:\\
1153 In [1]: import profile; profile.help() """
1149 In [1]: import profile; profile.help() """
1154
1150
1155 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1151 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1156 # protect user quote marks
1152 # protect user quote marks
1157 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1153 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1158
1154
1159 if user_mode: # regular user call
1155 if user_mode: # regular user call
1160 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1156 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1161 list_all=1)
1157 list_all=1)
1162 namespace = self.shell.user_ns
1158 namespace = self.shell.user_ns
1163 else: # called to run a program by %run -p
1159 else: # called to run a program by %run -p
1164 try:
1160 try:
1165 filename = get_py_filename(arg_lst[0])
1161 filename = get_py_filename(arg_lst[0])
1166 except IOError,msg:
1162 except IOError,msg:
1167 error(msg)
1163 error(msg)
1168 return
1164 return
1169
1165
1170 arg_str = 'execfile(filename,prog_ns)'
1166 arg_str = 'execfile(filename,prog_ns)'
1171 namespace = locals()
1167 namespace = locals()
1172
1168
1173 opts.merge(opts_def)
1169 opts.merge(opts_def)
1174
1170
1175 prof = profile.Profile()
1171 prof = profile.Profile()
1176 try:
1172 try:
1177 prof = prof.runctx(arg_str,namespace,namespace)
1173 prof = prof.runctx(arg_str,namespace,namespace)
1178 sys_exit = ''
1174 sys_exit = ''
1179 except SystemExit:
1175 except SystemExit:
1180 sys_exit = """*** SystemExit exception caught in code being profiled."""
1176 sys_exit = """*** SystemExit exception caught in code being profiled."""
1181
1177
1182 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1178 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1183
1179
1184 lims = opts.l
1180 lims = opts.l
1185 if lims:
1181 if lims:
1186 lims = [] # rebuild lims with ints/floats/strings
1182 lims = [] # rebuild lims with ints/floats/strings
1187 for lim in opts.l:
1183 for lim in opts.l:
1188 try:
1184 try:
1189 lims.append(int(lim))
1185 lims.append(int(lim))
1190 except ValueError:
1186 except ValueError:
1191 try:
1187 try:
1192 lims.append(float(lim))
1188 lims.append(float(lim))
1193 except ValueError:
1189 except ValueError:
1194 lims.append(lim)
1190 lims.append(lim)
1195
1191
1196 # trap output
1192 # trap output
1197 sys_stdout = sys.stdout
1193 sys_stdout = sys.stdout
1198 stdout_trap = StringIO()
1194 stdout_trap = StringIO()
1199 try:
1195 try:
1200 sys.stdout = stdout_trap
1196 sys.stdout = stdout_trap
1201 stats.print_stats(*lims)
1197 stats.print_stats(*lims)
1202 finally:
1198 finally:
1203 sys.stdout = sys_stdout
1199 sys.stdout = sys_stdout
1204 output = stdout_trap.getvalue()
1200 output = stdout_trap.getvalue()
1205 output = output.rstrip()
1201 output = output.rstrip()
1206
1202
1207 page(output,screen_lines=self.shell.rc.screen_length)
1203 page(output,screen_lines=self.shell.rc.screen_length)
1208 print sys_exit,
1204 print sys_exit,
1209
1205
1210 dump_file = opts.D[0]
1206 dump_file = opts.D[0]
1211 text_file = opts.T[0]
1207 text_file = opts.T[0]
1212 if dump_file:
1208 if dump_file:
1213 prof.dump_stats(dump_file)
1209 prof.dump_stats(dump_file)
1214 print '\n*** Profile stats marshalled to file',\
1210 print '\n*** Profile stats marshalled to file',\
1215 `dump_file`+'.',sys_exit
1211 `dump_file`+'.',sys_exit
1216 if text_file:
1212 if text_file:
1217 file(text_file,'w').write(output)
1213 file(text_file,'w').write(output)
1218 print '\n*** Profile printout saved to text file',\
1214 print '\n*** Profile printout saved to text file',\
1219 `text_file`+'.',sys_exit
1215 `text_file`+'.',sys_exit
1220
1216
1221 if opts.has_key('r'):
1217 if opts.has_key('r'):
1222 return stats
1218 return stats
1223 else:
1219 else:
1224 return None
1220 return None
1225
1221
1226 def magic_run(self, parameter_s ='',runner=None):
1222 def magic_run(self, parameter_s ='',runner=None):
1227 """Run the named file inside IPython as a program.
1223 """Run the named file inside IPython as a program.
1228
1224
1229 Usage:\\
1225 Usage:\\
1230 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1226 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1231
1227
1232 Parameters after the filename are passed as command-line arguments to
1228 Parameters after the filename are passed as command-line arguments to
1233 the program (put in sys.argv). Then, control returns to IPython's
1229 the program (put in sys.argv). Then, control returns to IPython's
1234 prompt.
1230 prompt.
1235
1231
1236 This is similar to running at a system prompt:\\
1232 This is similar to running at a system prompt:\\
1237 $ python file args\\
1233 $ python file args\\
1238 but with the advantage of giving you IPython's tracebacks, and of
1234 but with the advantage of giving you IPython's tracebacks, and of
1239 loading all variables into your interactive namespace for further use
1235 loading all variables into your interactive namespace for further use
1240 (unless -p is used, see below).
1236 (unless -p is used, see below).
1241
1237
1242 The file is executed in a namespace initially consisting only of
1238 The file is executed in a namespace initially consisting only of
1243 __name__=='__main__' and sys.argv constructed as indicated. It thus
1239 __name__=='__main__' and sys.argv constructed as indicated. It thus
1244 sees its environment as if it were being run as a stand-alone
1240 sees its environment as if it were being run as a stand-alone
1245 program. But after execution, the IPython interactive namespace gets
1241 program. But after execution, the IPython interactive namespace gets
1246 updated with all variables defined in the program (except for __name__
1242 updated with all variables defined in the program (except for __name__
1247 and sys.argv). This allows for very convenient loading of code for
1243 and sys.argv). This allows for very convenient loading of code for
1248 interactive work, while giving each program a 'clean sheet' to run in.
1244 interactive work, while giving each program a 'clean sheet' to run in.
1249
1245
1250 Options:
1246 Options:
1251
1247
1252 -n: __name__ is NOT set to '__main__', but to the running file's name
1248 -n: __name__ is NOT set to '__main__', but to the running file's name
1253 without extension (as python does under import). This allows running
1249 without extension (as python does under import). This allows running
1254 scripts and reloading the definitions in them without calling code
1250 scripts and reloading the definitions in them without calling code
1255 protected by an ' if __name__ == "__main__" ' clause.
1251 protected by an ' if __name__ == "__main__" ' clause.
1256
1252
1257 -i: run the file in IPython's namespace instead of an empty one. This
1253 -i: run the file in IPython's namespace instead of an empty one. This
1258 is useful if you are experimenting with code written in a text editor
1254 is useful if you are experimenting with code written in a text editor
1259 which depends on variables defined interactively.
1255 which depends on variables defined interactively.
1260
1256
1261 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1257 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1262 being run. This is particularly useful if IPython is being used to
1258 being run. This is particularly useful if IPython is being used to
1263 run unittests, which always exit with a sys.exit() call. In such
1259 run unittests, which always exit with a sys.exit() call. In such
1264 cases you are interested in the output of the test results, not in
1260 cases you are interested in the output of the test results, not in
1265 seeing a traceback of the unittest module.
1261 seeing a traceback of the unittest module.
1266
1262
1267 -t: print timing information at the end of the run. IPython will give
1263 -t: print timing information at the end of the run. IPython will give
1268 you an estimated CPU time consumption for your script, which under
1264 you an estimated CPU time consumption for your script, which under
1269 Unix uses the resource module to avoid the wraparound problems of
1265 Unix uses the resource module to avoid the wraparound problems of
1270 time.clock(). Under Unix, an estimate of time spent on system tasks
1266 time.clock(). Under Unix, an estimate of time spent on system tasks
1271 is also given (for Windows platforms this is reported as 0.0).
1267 is also given (for Windows platforms this is reported as 0.0).
1272
1268
1273 If -t is given, an additional -N<N> option can be given, where <N>
1269 If -t is given, an additional -N<N> option can be given, where <N>
1274 must be an integer indicating how many times you want the script to
1270 must be an integer indicating how many times you want the script to
1275 run. The final timing report will include total and per run results.
1271 run. The final timing report will include total and per run results.
1276
1272
1277 For example (testing the script uniq_stable.py):
1273 For example (testing the script uniq_stable.py):
1278
1274
1279 In [1]: run -t uniq_stable
1275 In [1]: run -t uniq_stable
1280
1276
1281 IPython CPU timings (estimated):\\
1277 IPython CPU timings (estimated):\\
1282 User : 0.19597 s.\\
1278 User : 0.19597 s.\\
1283 System: 0.0 s.\\
1279 System: 0.0 s.\\
1284
1280
1285 In [2]: run -t -N5 uniq_stable
1281 In [2]: run -t -N5 uniq_stable
1286
1282
1287 IPython CPU timings (estimated):\\
1283 IPython CPU timings (estimated):\\
1288 Total runs performed: 5\\
1284 Total runs performed: 5\\
1289 Times : Total Per run\\
1285 Times : Total Per run\\
1290 User : 0.910862 s, 0.1821724 s.\\
1286 User : 0.910862 s, 0.1821724 s.\\
1291 System: 0.0 s, 0.0 s.
1287 System: 0.0 s, 0.0 s.
1292
1288
1293 -d: run your program under the control of pdb, the Python debugger.
1289 -d: run your program under the control of pdb, the Python debugger.
1294 This allows you to execute your program step by step, watch variables,
1290 This allows you to execute your program step by step, watch variables,
1295 etc. Internally, what IPython does is similar to calling:
1291 etc. Internally, what IPython does is similar to calling:
1296
1292
1297 pdb.run('execfile("YOURFILENAME")')
1293 pdb.run('execfile("YOURFILENAME")')
1298
1294
1299 with a breakpoint set on line 1 of your file. You can change the line
1295 with a breakpoint set on line 1 of your file. You can change the line
1300 number for this automatic breakpoint to be <N> by using the -bN option
1296 number for this automatic breakpoint to be <N> by using the -bN option
1301 (where N must be an integer). For example:
1297 (where N must be an integer). For example:
1302
1298
1303 %run -d -b40 myscript
1299 %run -d -b40 myscript
1304
1300
1305 will set the first breakpoint at line 40 in myscript.py. Note that
1301 will set the first breakpoint at line 40 in myscript.py. Note that
1306 the first breakpoint must be set on a line which actually does
1302 the first breakpoint must be set on a line which actually does
1307 something (not a comment or docstring) for it to stop execution.
1303 something (not a comment or docstring) for it to stop execution.
1308
1304
1309 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1305 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1310 first enter 'c' (without qoutes) to start execution up to the first
1306 first enter 'c' (without qoutes) to start execution up to the first
1311 breakpoint.
1307 breakpoint.
1312
1308
1313 Entering 'help' gives information about the use of the debugger. You
1309 Entering 'help' gives information about the use of the debugger. You
1314 can easily see pdb's full documentation with "import pdb;pdb.help()"
1310 can easily see pdb's full documentation with "import pdb;pdb.help()"
1315 at a prompt.
1311 at a prompt.
1316
1312
1317 -p: run program under the control of the Python profiler module (which
1313 -p: run program under the control of the Python profiler module (which
1318 prints a detailed report of execution times, function calls, etc).
1314 prints a detailed report of execution times, function calls, etc).
1319
1315
1320 You can pass other options after -p which affect the behavior of the
1316 You can pass other options after -p which affect the behavior of the
1321 profiler itself. See the docs for %prun for details.
1317 profiler itself. See the docs for %prun for details.
1322
1318
1323 In this mode, the program's variables do NOT propagate back to the
1319 In this mode, the program's variables do NOT propagate back to the
1324 IPython interactive namespace (because they remain in the namespace
1320 IPython interactive namespace (because they remain in the namespace
1325 where the profiler executes them).
1321 where the profiler executes them).
1326
1322
1327 Internally this triggers a call to %prun, see its documentation for
1323 Internally this triggers a call to %prun, see its documentation for
1328 details on the options available specifically for profiling."""
1324 details on the options available specifically for profiling."""
1329
1325
1330 # get arguments and set sys.argv for program to be run.
1326 # get arguments and set sys.argv for program to be run.
1331 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1327 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1332 mode='list',list_all=1)
1328 mode='list',list_all=1)
1333
1329
1334 try:
1330 try:
1335 filename = get_py_filename(arg_lst[0])
1331 filename = get_py_filename(arg_lst[0])
1336 except IndexError:
1332 except IndexError:
1337 warn('you must provide at least a filename.')
1333 warn('you must provide at least a filename.')
1338 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1334 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1339 return
1335 return
1340 except IOError,msg:
1336 except IOError,msg:
1341 error(msg)
1337 error(msg)
1342 return
1338 return
1343
1339
1344 # Control the response to exit() calls made by the script being run
1340 # Control the response to exit() calls made by the script being run
1345 exit_ignore = opts.has_key('e')
1341 exit_ignore = opts.has_key('e')
1346
1342
1347 # Make sure that the running script gets a proper sys.argv as if it
1343 # Make sure that the running script gets a proper sys.argv as if it
1348 # were run from a system shell.
1344 # were run from a system shell.
1349 save_argv = sys.argv # save it for later restoring
1345 save_argv = sys.argv # save it for later restoring
1350 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1346 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1351
1347
1352 if opts.has_key('i'):
1348 if opts.has_key('i'):
1353 prog_ns = self.shell.user_ns
1349 prog_ns = self.shell.user_ns
1354 __name__save = self.shell.user_ns['__name__']
1350 __name__save = self.shell.user_ns['__name__']
1355 prog_ns['__name__'] = '__main__'
1351 prog_ns['__name__'] = '__main__'
1356 else:
1352 else:
1357 if opts.has_key('n'):
1353 if opts.has_key('n'):
1358 name = os.path.splitext(os.path.basename(filename))[0]
1354 name = os.path.splitext(os.path.basename(filename))[0]
1359 else:
1355 else:
1360 name = '__main__'
1356 name = '__main__'
1361 prog_ns = {'__name__':name}
1357 prog_ns = {'__name__':name}
1362
1358
1363 # pickle fix. See iplib for an explanation
1359 # pickle fix. See iplib for an explanation
1364 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1360 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1365
1361
1366 stats = None
1362 stats = None
1367 try:
1363 try:
1368 if opts.has_key('p'):
1364 if opts.has_key('p'):
1369 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1365 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1370 else:
1366 else:
1371 if opts.has_key('d'):
1367 if opts.has_key('d'):
1372 deb = Debugger.Pdb(self.shell.rc.colors)
1368 deb = Debugger.Pdb(self.shell.rc.colors)
1373 # reset Breakpoint state, which is moronically kept
1369 # reset Breakpoint state, which is moronically kept
1374 # in a class
1370 # in a class
1375 bdb.Breakpoint.next = 1
1371 bdb.Breakpoint.next = 1
1376 bdb.Breakpoint.bplist = {}
1372 bdb.Breakpoint.bplist = {}
1377 bdb.Breakpoint.bpbynumber = [None]
1373 bdb.Breakpoint.bpbynumber = [None]
1378 # Set an initial breakpoint to stop execution
1374 # Set an initial breakpoint to stop execution
1379 maxtries = 10
1375 maxtries = 10
1380 bp = int(opts.get('b',[1])[0])
1376 bp = int(opts.get('b',[1])[0])
1381 checkline = deb.checkline(filename,bp)
1377 checkline = deb.checkline(filename,bp)
1382 if not checkline:
1378 if not checkline:
1383 for bp in range(bp+1,bp+maxtries+1):
1379 for bp in range(bp+1,bp+maxtries+1):
1384 if deb.checkline(filename,bp):
1380 if deb.checkline(filename,bp):
1385 break
1381 break
1386 else:
1382 else:
1387 msg = ("\nI failed to find a valid line to set "
1383 msg = ("\nI failed to find a valid line to set "
1388 "a breakpoint\n"
1384 "a breakpoint\n"
1389 "after trying up to line: %s.\n"
1385 "after trying up to line: %s.\n"
1390 "Please set a valid breakpoint manually "
1386 "Please set a valid breakpoint manually "
1391 "with the -b option." % bp)
1387 "with the -b option." % bp)
1392 error(msg)
1388 error(msg)
1393 return
1389 return
1394 # if we find a good linenumber, set the breakpoint
1390 # if we find a good linenumber, set the breakpoint
1395 deb.do_break('%s:%s' % (filename,bp))
1391 deb.do_break('%s:%s' % (filename,bp))
1396 # Start file run
1392 # Start file run
1397 print "NOTE: Enter 'c' at the",
1393 print "NOTE: Enter 'c' at the",
1398 print "ipdb> prompt to start your script."
1394 print "ipdb> prompt to start your script."
1399 try:
1395 try:
1400 deb.run('execfile("%s")' % filename,prog_ns)
1396 deb.run('execfile("%s")' % filename,prog_ns)
1401 except:
1397 except:
1402 etype, value, tb = sys.exc_info()
1398 etype, value, tb = sys.exc_info()
1403 # Skip three frames in the traceback: the %run one,
1399 # Skip three frames in the traceback: the %run one,
1404 # one inside bdb.py, and the command-line typed by the
1400 # one inside bdb.py, and the command-line typed by the
1405 # user (run by exec in pdb itself).
1401 # user (run by exec in pdb itself).
1406 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1402 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1407 else:
1403 else:
1408 if runner is None:
1404 if runner is None:
1409 runner = self.shell.safe_execfile
1405 runner = self.shell.safe_execfile
1410 if opts.has_key('t'):
1406 if opts.has_key('t'):
1411 try:
1407 try:
1412 nruns = int(opts['N'][0])
1408 nruns = int(opts['N'][0])
1413 if nruns < 1:
1409 if nruns < 1:
1414 error('Number of runs must be >=1')
1410 error('Number of runs must be >=1')
1415 return
1411 return
1416 except (KeyError):
1412 except (KeyError):
1417 nruns = 1
1413 nruns = 1
1418 if nruns == 1:
1414 if nruns == 1:
1419 t0 = clock2()
1415 t0 = clock2()
1420 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1416 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1421 t1 = clock2()
1417 t1 = clock2()
1422 t_usr = t1[0]-t0[0]
1418 t_usr = t1[0]-t0[0]
1423 t_sys = t1[1]-t1[1]
1419 t_sys = t1[1]-t1[1]
1424 print "\nIPython CPU timings (estimated):"
1420 print "\nIPython CPU timings (estimated):"
1425 print " User : %10s s." % t_usr
1421 print " User : %10s s." % t_usr
1426 print " System: %10s s." % t_sys
1422 print " System: %10s s." % t_sys
1427 else:
1423 else:
1428 runs = range(nruns)
1424 runs = range(nruns)
1429 t0 = clock2()
1425 t0 = clock2()
1430 for nr in runs:
1426 for nr in runs:
1431 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1427 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1432 t1 = clock2()
1428 t1 = clock2()
1433 t_usr = t1[0]-t0[0]
1429 t_usr = t1[0]-t0[0]
1434 t_sys = t1[1]-t1[1]
1430 t_sys = t1[1]-t1[1]
1435 print "\nIPython CPU timings (estimated):"
1431 print "\nIPython CPU timings (estimated):"
1436 print "Total runs performed:",nruns
1432 print "Total runs performed:",nruns
1437 print " Times : %10s %10s" % ('Total','Per run')
1433 print " Times : %10s %10s" % ('Total','Per run')
1438 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1434 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1439 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1435 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1440
1436
1441 else:
1437 else:
1442 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1438 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1443 if opts.has_key('i'):
1439 if opts.has_key('i'):
1444 self.shell.user_ns['__name__'] = __name__save
1440 self.shell.user_ns['__name__'] = __name__save
1445 else:
1441 else:
1446 # update IPython interactive namespace
1442 # update IPython interactive namespace
1447 del prog_ns['__name__']
1443 del prog_ns['__name__']
1448 self.shell.user_ns.update(prog_ns)
1444 self.shell.user_ns.update(prog_ns)
1449 finally:
1445 finally:
1450 sys.argv = save_argv
1446 sys.argv = save_argv
1451 return stats
1447 return stats
1452
1448
1453 def magic_runlog(self, parameter_s =''):
1449 def magic_runlog(self, parameter_s =''):
1454 """Run files as logs.
1450 """Run files as logs.
1455
1451
1456 Usage:\\
1452 Usage:\\
1457 %runlog file1 file2 ...
1453 %runlog file1 file2 ...
1458
1454
1459 Run the named files (treating them as log files) in sequence inside
1455 Run the named files (treating them as log files) in sequence inside
1460 the interpreter, and return to the prompt. This is much slower than
1456 the interpreter, and return to the prompt. This is much slower than
1461 %run because each line is executed in a try/except block, but it
1457 %run because each line is executed in a try/except block, but it
1462 allows running files with syntax errors in them.
1458 allows running files with syntax errors in them.
1463
1459
1464 Normally IPython will guess when a file is one of its own logfiles, so
1460 Normally IPython will guess when a file is one of its own logfiles, so
1465 you can typically use %run even for logs. This shorthand allows you to
1461 you can typically use %run even for logs. This shorthand allows you to
1466 force any file to be treated as a log file."""
1462 force any file to be treated as a log file."""
1467
1463
1468 for f in parameter_s.split():
1464 for f in parameter_s.split():
1469 self.shell.safe_execfile(f,self.shell.user_ns,
1465 self.shell.safe_execfile(f,self.shell.user_ns,
1470 self.shell.user_ns,islog=1)
1466 self.shell.user_ns,islog=1)
1471
1467
1472 def magic_time(self,parameter_s = ''):
1468 def magic_time(self,parameter_s = ''):
1473 """Time execution of a Python statement or expression.
1469 """Time execution of a Python statement or expression.
1474
1470
1475 The CPU and wall clock times are printed, and the value of the
1471 The CPU and wall clock times are printed, and the value of the
1476 expression (if any) is returned. Note that under Win32, system time
1472 expression (if any) is returned. Note that under Win32, system time
1477 is always reported as 0, since it can not be measured.
1473 is always reported as 0, since it can not be measured.
1478
1474
1479 This function provides very basic timing functionality. In Python
1475 This function provides very basic timing functionality. In Python
1480 2.3, the timeit module offers more control and sophistication, but for
1476 2.3, the timeit module offers more control and sophistication, but for
1481 now IPython supports Python 2.2, so we can not rely on timeit being
1477 now IPython supports Python 2.2, so we can not rely on timeit being
1482 present.
1478 present.
1483
1479
1484 Some examples:
1480 Some examples:
1485
1481
1486 In [1]: time 2**128
1482 In [1]: time 2**128
1487 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1483 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1488 Wall time: 0.00
1484 Wall time: 0.00
1489 Out[1]: 340282366920938463463374607431768211456L
1485 Out[1]: 340282366920938463463374607431768211456L
1490
1486
1491 In [2]: n = 1000000
1487 In [2]: n = 1000000
1492
1488
1493 In [3]: time sum(range(n))
1489 In [3]: time sum(range(n))
1494 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1490 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1495 Wall time: 1.37
1491 Wall time: 1.37
1496 Out[3]: 499999500000L
1492 Out[3]: 499999500000L
1497
1493
1498 In [4]: time print 'hello world'
1494 In [4]: time print 'hello world'
1499 hello world
1495 hello world
1500 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1496 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1501 Wall time: 0.00
1497 Wall time: 0.00
1502 """
1498 """
1503
1499
1504 # fail immediately if the given expression can't be compiled
1500 # fail immediately if the given expression can't be compiled
1505 try:
1501 try:
1506 mode = 'eval'
1502 mode = 'eval'
1507 code = compile(parameter_s,'<timed eval>',mode)
1503 code = compile(parameter_s,'<timed eval>',mode)
1508 except SyntaxError:
1504 except SyntaxError:
1509 mode = 'exec'
1505 mode = 'exec'
1510 code = compile(parameter_s,'<timed exec>',mode)
1506 code = compile(parameter_s,'<timed exec>',mode)
1511 # skew measurement as little as possible
1507 # skew measurement as little as possible
1512 glob = self.shell.user_ns
1508 glob = self.shell.user_ns
1513 clk = clock2
1509 clk = clock2
1514 wtime = time.time
1510 wtime = time.time
1515 # time execution
1511 # time execution
1516 wall_st = wtime()
1512 wall_st = wtime()
1517 if mode=='eval':
1513 if mode=='eval':
1518 st = clk()
1514 st = clk()
1519 out = eval(code,glob)
1515 out = eval(code,glob)
1520 end = clk()
1516 end = clk()
1521 else:
1517 else:
1522 st = clk()
1518 st = clk()
1523 exec code in glob
1519 exec code in glob
1524 end = clk()
1520 end = clk()
1525 out = None
1521 out = None
1526 wall_end = wtime()
1522 wall_end = wtime()
1527 # Compute actual times and report
1523 # Compute actual times and report
1528 wall_time = wall_end-wall_st
1524 wall_time = wall_end-wall_st
1529 cpu_user = end[0]-st[0]
1525 cpu_user = end[0]-st[0]
1530 cpu_sys = end[1]-st[1]
1526 cpu_sys = end[1]-st[1]
1531 cpu_tot = cpu_user+cpu_sys
1527 cpu_tot = cpu_user+cpu_sys
1532 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1528 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1533 (cpu_user,cpu_sys,cpu_tot)
1529 (cpu_user,cpu_sys,cpu_tot)
1534 print "Wall time: %.2f" % wall_time
1530 print "Wall time: %.2f" % wall_time
1535 return out
1531 return out
1536
1532
1537 def magic_macro(self,parameter_s = ''):
1533 def magic_macro(self,parameter_s = ''):
1538 """Define a set of input lines as a macro for future re-execution.
1534 """Define a set of input lines as a macro for future re-execution.
1539
1535
1540 Usage:\\
1536 Usage:\\
1541 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1537 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1542
1538
1543 This will define a global variable called `name` which is a string
1539 This will define a global variable called `name` which is a string
1544 made of joining the slices and lines you specify (n1,n2,... numbers
1540 made of joining the slices and lines you specify (n1,n2,... numbers
1545 above) from your input history into a single string. This variable
1541 above) from your input history into a single string. This variable
1546 acts like an automatic function which re-executes those lines as if
1542 acts like an automatic function which re-executes those lines as if
1547 you had typed them. You just type 'name' at the prompt and the code
1543 you had typed them. You just type 'name' at the prompt and the code
1548 executes.
1544 executes.
1549
1545
1550 Note that the slices use the standard Python slicing notation (5:8
1546 Note that the slices use the standard Python slicing notation (5:8
1551 means include lines numbered 5,6,7).
1547 means include lines numbered 5,6,7).
1552
1548
1553 For example, if your history contains (%hist prints it):
1549 For example, if your history contains (%hist prints it):
1554
1550
1555 44: x=1\\
1551 44: x=1\\
1556 45: y=3\\
1552 45: y=3\\
1557 46: z=x+y\\
1553 46: z=x+y\\
1558 47: print x\\
1554 47: print x\\
1559 48: a=5\\
1555 48: a=5\\
1560 49: print 'x',x,'y',y\\
1556 49: print 'x',x,'y',y\\
1561
1557
1562 you can create a macro with lines 44 through 47 (included) and line 49
1558 you can create a macro with lines 44 through 47 (included) and line 49
1563 called my_macro with:
1559 called my_macro with:
1564
1560
1565 In [51]: %macro my_macro 44:48 49
1561 In [51]: %macro my_macro 44:48 49
1566
1562
1567 Now, typing `my_macro` (without quotes) will re-execute all this code
1563 Now, typing `my_macro` (without quotes) will re-execute all this code
1568 in one pass.
1564 in one pass.
1569
1565
1570 You don't need to give the line-numbers in order, and any given line
1566 You don't need to give the line-numbers in order, and any given line
1571 number can appear multiple times. You can assemble macros with any
1567 number can appear multiple times. You can assemble macros with any
1572 lines from your input history in any order.
1568 lines from your input history in any order.
1573
1569
1574 The macro is a simple object which holds its value in an attribute,
1570 The macro is a simple object which holds its value in an attribute,
1575 but IPython's display system checks for macros and executes them as
1571 but IPython's display system checks for macros and executes them as
1576 code instead of printing them when you type their name.
1572 code instead of printing them when you type their name.
1577
1573
1578 You can view a macro's contents by explicitly printing it with:
1574 You can view a macro's contents by explicitly printing it with:
1579
1575
1580 'print macro_name'.
1576 'print macro_name'.
1581
1577
1582 For one-off cases which DON'T contain magic function calls in them you
1578 For one-off cases which DON'T contain magic function calls in them you
1583 can obtain similar results by explicitly executing slices from your
1579 can obtain similar results by explicitly executing slices from your
1584 input history with:
1580 input history with:
1585
1581
1586 In [60]: exec In[44:48]+In[49]"""
1582 In [60]: exec In[44:48]+In[49]"""
1587
1583
1588 args = parameter_s.split()
1584 args = parameter_s.split()
1589 name,ranges = args[0], args[1:]
1585 name,ranges = args[0], args[1:]
1590 #print 'rng',ranges # dbg
1586 #print 'rng',ranges # dbg
1591 lines = self.extract_input_slices(ranges)
1587 lines = self.extract_input_slices(ranges)
1592 macro = Macro(lines)
1588 macro = Macro(lines)
1593 self.shell.user_ns.update({name:macro})
1589 self.shell.user_ns.update({name:macro})
1594 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1590 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1595 print 'Macro contents:'
1591 print 'Macro contents:'
1596 print macro
1592 print macro,
1597
1593
1598 def magic_save(self,parameter_s = ''):
1594 def magic_save(self,parameter_s = ''):
1599 """Save a set of lines to a given filename.
1595 """Save a set of lines to a given filename.
1600
1596
1601 Usage:\\
1597 Usage:\\
1602 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1598 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1603
1599
1604 This function uses the same syntax as %macro for line extraction, but
1600 This function uses the same syntax as %macro for line extraction, but
1605 instead of creating a macro it saves the resulting string to the
1601 instead of creating a macro it saves the resulting string to the
1606 filename you specify.
1602 filename you specify.
1607
1603
1608 It adds a '.py' extension to the file if you don't do so yourself, and
1604 It adds a '.py' extension to the file if you don't do so yourself, and
1609 it asks for confirmation before overwriting existing files."""
1605 it asks for confirmation before overwriting existing files."""
1610
1606
1611 args = parameter_s.split()
1607 args = parameter_s.split()
1612 fname,ranges = args[0], args[1:]
1608 fname,ranges = args[0], args[1:]
1613 if not fname.endswith('.py'):
1609 if not fname.endswith('.py'):
1614 fname += '.py'
1610 fname += '.py'
1615 if os.path.isfile(fname):
1611 if os.path.isfile(fname):
1616 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1612 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1617 if ans.lower() not in ['y','yes']:
1613 if ans.lower() not in ['y','yes']:
1618 print 'Operation cancelled.'
1614 print 'Operation cancelled.'
1619 return
1615 return
1620 cmds = ''.join(self.extract_input_slices(ranges))
1616 cmds = ''.join(self.extract_input_slices(ranges))
1621 f = file(fname,'w')
1617 f = file(fname,'w')
1622 f.write(cmds)
1618 f.write(cmds)
1623 f.close()
1619 f.close()
1624 print 'The following commands were written to file `%s`:' % fname
1620 print 'The following commands were written to file `%s`:' % fname
1625 print cmds
1621 print cmds
1626
1622
1627 def magic_ed(self,parameter_s = ''):
1623 def magic_ed(self,parameter_s = ''):
1628 """Alias to %edit."""
1624 """Alias to %edit."""
1629 return self.magic_edit(parameter_s)
1625 return self.magic_edit(parameter_s)
1630
1626
1631 def magic_edit(self,parameter_s = '',last_call=['','']):
1627 def magic_edit(self,parameter_s = '',last_call=['','']):
1632 """Bring up an editor and execute the resulting code.
1628 """Bring up an editor and execute the resulting code.
1633
1629
1634 Usage:
1630 Usage:
1635 %edit [options] [args]
1631 %edit [options] [args]
1636
1632
1637 %edit runs IPython's editor hook. The default version of this hook is
1633 %edit runs IPython's editor hook. The default version of this hook is
1638 set to call the __IPYTHON__.rc.editor command. This is read from your
1634 set to call the __IPYTHON__.rc.editor command. This is read from your
1639 environment variable $EDITOR. If this isn't found, it will default to
1635 environment variable $EDITOR. If this isn't found, it will default to
1640 vi under Linux/Unix and to notepad under Windows. See the end of this
1636 vi under Linux/Unix and to notepad under Windows. See the end of this
1641 docstring for how to change the editor hook.
1637 docstring for how to change the editor hook.
1642
1638
1643 You can also set the value of this editor via the command line option
1639 You can also set the value of this editor via the command line option
1644 '-editor' or in your ipythonrc file. This is useful if you wish to use
1640 '-editor' or in your ipythonrc file. This is useful if you wish to use
1645 specifically for IPython an editor different from your typical default
1641 specifically for IPython an editor different from your typical default
1646 (and for Windows users who typically don't set environment variables).
1642 (and for Windows users who typically don't set environment variables).
1647
1643
1648 This command allows you to conveniently edit multi-line code right in
1644 This command allows you to conveniently edit multi-line code right in
1649 your IPython session.
1645 your IPython session.
1650
1646
1651 If called without arguments, %edit opens up an empty editor with a
1647 If called without arguments, %edit opens up an empty editor with a
1652 temporary file and will execute the contents of this file when you
1648 temporary file and will execute the contents of this file when you
1653 close it (don't forget to save it!).
1649 close it (don't forget to save it!).
1654
1650
1655 Options:
1651 Options:
1656
1652
1657 -p: this will call the editor with the same data as the previous time
1653 -p: this will call the editor with the same data as the previous time
1658 it was used, regardless of how long ago (in your current session) it
1654 it was used, regardless of how long ago (in your current session) it
1659 was.
1655 was.
1660
1656
1661 -x: do not execute the edited code immediately upon exit. This is
1657 -x: do not execute the edited code immediately upon exit. This is
1662 mainly useful if you are editing programs which need to be called with
1658 mainly useful if you are editing programs which need to be called with
1663 command line arguments, which you can then do using %run.
1659 command line arguments, which you can then do using %run.
1664
1660
1665 Arguments:
1661 Arguments:
1666
1662
1667 If arguments are given, the following possibilites exist:
1663 If arguments are given, the following possibilites exist:
1668
1664
1669 - The arguments are numbers or pairs of colon-separated numbers (like
1665 - The arguments are numbers or pairs of colon-separated numbers (like
1670 1 4:8 9). These are interpreted as lines of previous input to be
1666 1 4:8 9). These are interpreted as lines of previous input to be
1671 loaded into the editor. The syntax is the same of the %macro command.
1667 loaded into the editor. The syntax is the same of the %macro command.
1672
1668
1673 - If the argument doesn't start with a number, it is evaluated as a
1669 - If the argument doesn't start with a number, it is evaluated as a
1674 variable and its contents loaded into the editor. You can thus edit
1670 variable and its contents loaded into the editor. You can thus edit
1675 any string which contains python code (including the result of
1671 any string which contains python code (including the result of
1676 previous edits).
1672 previous edits).
1677
1673
1678 - If the argument is the name of an object (other than a string),
1674 - If the argument is the name of an object (other than a string),
1679 IPython will try to locate the file where it was defined and open the
1675 IPython will try to locate the file where it was defined and open the
1680 editor at the point where it is defined. You can use `%edit function`
1676 editor at the point where it is defined. You can use `%edit function`
1681 to load an editor exactly at the point where 'function' is defined,
1677 to load an editor exactly at the point where 'function' is defined,
1682 edit it and have the file be executed automatically.
1678 edit it and have the file be executed automatically.
1683
1679
1684 Note: opening at an exact line is only supported under Unix, and some
1680 Note: opening at an exact line is only supported under Unix, and some
1685 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1681 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1686 '+NUMBER' parameter necessary for this feature. Good editors like
1682 '+NUMBER' parameter necessary for this feature. Good editors like
1687 (X)Emacs, vi, jed, pico and joe all do.
1683 (X)Emacs, vi, jed, pico and joe all do.
1688
1684
1689 - If the argument is not found as a variable, IPython will look for a
1685 - If the argument is not found as a variable, IPython will look for a
1690 file with that name (adding .py if necessary) and load it into the
1686 file with that name (adding .py if necessary) and load it into the
1691 editor. It will execute its contents with execfile() when you exit,
1687 editor. It will execute its contents with execfile() when you exit,
1692 loading any code in the file into your interactive namespace.
1688 loading any code in the file into your interactive namespace.
1693
1689
1694 After executing your code, %edit will return as output the code you
1690 After executing your code, %edit will return as output the code you
1695 typed in the editor (except when it was an existing file). This way
1691 typed in the editor (except when it was an existing file). This way
1696 you can reload the code in further invocations of %edit as a variable,
1692 you can reload the code in further invocations of %edit as a variable,
1697 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1693 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1698 the output.
1694 the output.
1699
1695
1700 Note that %edit is also available through the alias %ed.
1696 Note that %edit is also available through the alias %ed.
1701
1697
1702 This is an example of creating a simple function inside the editor and
1698 This is an example of creating a simple function inside the editor and
1703 then modifying it. First, start up the editor:
1699 then modifying it. First, start up the editor:
1704
1700
1705 In [1]: ed\\
1701 In [1]: ed\\
1706 Editing... done. Executing edited code...\\
1702 Editing... done. Executing edited code...\\
1707 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1703 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1708
1704
1709 We can then call the function foo():
1705 We can then call the function foo():
1710
1706
1711 In [2]: foo()\\
1707 In [2]: foo()\\
1712 foo() was defined in an editing session
1708 foo() was defined in an editing session
1713
1709
1714 Now we edit foo. IPython automatically loads the editor with the
1710 Now we edit foo. IPython automatically loads the editor with the
1715 (temporary) file where foo() was previously defined:
1711 (temporary) file where foo() was previously defined:
1716
1712
1717 In [3]: ed foo\\
1713 In [3]: ed foo\\
1718 Editing... done. Executing edited code...
1714 Editing... done. Executing edited code...
1719
1715
1720 And if we call foo() again we get the modified version:
1716 And if we call foo() again we get the modified version:
1721
1717
1722 In [4]: foo()\\
1718 In [4]: foo()\\
1723 foo() has now been changed!
1719 foo() has now been changed!
1724
1720
1725 Here is an example of how to edit a code snippet successive
1721 Here is an example of how to edit a code snippet successive
1726 times. First we call the editor:
1722 times. First we call the editor:
1727
1723
1728 In [8]: ed\\
1724 In [8]: ed\\
1729 Editing... done. Executing edited code...\\
1725 Editing... done. Executing edited code...\\
1730 hello\\
1726 hello\\
1731 Out[8]: "print 'hello'\\n"
1727 Out[8]: "print 'hello'\\n"
1732
1728
1733 Now we call it again with the previous output (stored in _):
1729 Now we call it again with the previous output (stored in _):
1734
1730
1735 In [9]: ed _\\
1731 In [9]: ed _\\
1736 Editing... done. Executing edited code...\\
1732 Editing... done. Executing edited code...\\
1737 hello world\\
1733 hello world\\
1738 Out[9]: "print 'hello world'\\n"
1734 Out[9]: "print 'hello world'\\n"
1739
1735
1740 Now we call it with the output #8 (stored in _8, also as Out[8]):
1736 Now we call it with the output #8 (stored in _8, also as Out[8]):
1741
1737
1742 In [10]: ed _8\\
1738 In [10]: ed _8\\
1743 Editing... done. Executing edited code...\\
1739 Editing... done. Executing edited code...\\
1744 hello again\\
1740 hello again\\
1745 Out[10]: "print 'hello again'\\n"
1741 Out[10]: "print 'hello again'\\n"
1746
1742
1747
1743
1748 Changing the default editor hook:
1744 Changing the default editor hook:
1749
1745
1750 If you wish to write your own editor hook, you can put it in a
1746 If you wish to write your own editor hook, you can put it in a
1751 configuration file which you load at startup time. The default hook
1747 configuration file which you load at startup time. The default hook
1752 is defined in the IPython.hooks module, and you can use that as a
1748 is defined in the IPython.hooks module, and you can use that as a
1753 starting example for further modifications. That file also has
1749 starting example for further modifications. That file also has
1754 general instructions on how to set a new hook for use once you've
1750 general instructions on how to set a new hook for use once you've
1755 defined it."""
1751 defined it."""
1756
1752
1757 # FIXME: This function has become a convoluted mess. It needs a
1753 # FIXME: This function has become a convoluted mess. It needs a
1758 # ground-up rewrite with clean, simple logic.
1754 # ground-up rewrite with clean, simple logic.
1759
1755
1760 def make_filename(arg):
1756 def make_filename(arg):
1761 "Make a filename from the given args"
1757 "Make a filename from the given args"
1762 try:
1758 try:
1763 filename = get_py_filename(arg)
1759 filename = get_py_filename(arg)
1764 except IOError:
1760 except IOError:
1765 if args.endswith('.py'):
1761 if args.endswith('.py'):
1766 filename = arg
1762 filename = arg
1767 else:
1763 else:
1768 filename = None
1764 filename = None
1769 return filename
1765 return filename
1770
1766
1771 # custom exceptions
1767 # custom exceptions
1772 class DataIsObject(Exception): pass
1768 class DataIsObject(Exception): pass
1773
1769
1774 opts,args = self.parse_options(parameter_s,'px')
1770 opts,args = self.parse_options(parameter_s,'px')
1775
1771
1776 # Default line number value
1772 # Default line number value
1777 lineno = None
1773 lineno = None
1778 if opts.has_key('p'):
1774 if opts.has_key('p'):
1779 args = '_%s' % last_call[0]
1775 args = '_%s' % last_call[0]
1780 if not self.shell.user_ns.has_key(args):
1776 if not self.shell.user_ns.has_key(args):
1781 args = last_call[1]
1777 args = last_call[1]
1782
1778
1783 # use last_call to remember the state of the previous call, but don't
1779 # use last_call to remember the state of the previous call, but don't
1784 # let it be clobbered by successive '-p' calls.
1780 # let it be clobbered by successive '-p' calls.
1785 try:
1781 try:
1786 last_call[0] = self.shell.outputcache.prompt_count
1782 last_call[0] = self.shell.outputcache.prompt_count
1787 if not opts.has_key('p'):
1783 if not opts.has_key('p'):
1788 last_call[1] = parameter_s
1784 last_call[1] = parameter_s
1789 except:
1785 except:
1790 pass
1786 pass
1791
1787
1792 # by default this is done with temp files, except when the given
1788 # by default this is done with temp files, except when the given
1793 # arg is a filename
1789 # arg is a filename
1794 use_temp = 1
1790 use_temp = 1
1795
1791
1796 if re.match(r'\d',args):
1792 if re.match(r'\d',args):
1797 # Mode where user specifies ranges of lines, like in %macro.
1793 # Mode where user specifies ranges of lines, like in %macro.
1798 # This means that you can't edit files whose names begin with
1794 # This means that you can't edit files whose names begin with
1799 # numbers this way. Tough.
1795 # numbers this way. Tough.
1800 ranges = args.split()
1796 ranges = args.split()
1801 data = ''.join(self.extract_input_slices(ranges))
1797 data = ''.join(self.extract_input_slices(ranges))
1802 elif args.endswith('.py'):
1798 elif args.endswith('.py'):
1803 filename = make_filename(args)
1799 filename = make_filename(args)
1804 data = ''
1800 data = ''
1805 use_temp = 0
1801 use_temp = 0
1806 elif args:
1802 elif args:
1807 try:
1803 try:
1808 # Load the parameter given as a variable. If not a string,
1804 # Load the parameter given as a variable. If not a string,
1809 # process it as an object instead (below)
1805 # process it as an object instead (below)
1810
1806
1811 #print '*** args',args,'type',type(args) # dbg
1807 #print '*** args',args,'type',type(args) # dbg
1812 data = eval(args,self.shell.user_ns)
1808 data = eval(args,self.shell.user_ns)
1813 if not type(data) in StringTypes:
1809 if not type(data) in StringTypes:
1814 raise DataIsObject
1810 raise DataIsObject
1815 except (NameError,SyntaxError):
1811 except (NameError,SyntaxError):
1816 # given argument is not a variable, try as a filename
1812 # given argument is not a variable, try as a filename
1817 filename = make_filename(args)
1813 filename = make_filename(args)
1818 if filename is None:
1814 if filename is None:
1819 warn("Argument given (%s) can't be found as a variable "
1815 warn("Argument given (%s) can't be found as a variable "
1820 "or as a filename." % args)
1816 "or as a filename." % args)
1821 return
1817 return
1822 data = ''
1818 data = ''
1823 use_temp = 0
1819 use_temp = 0
1824 except DataIsObject:
1820 except DataIsObject:
1825 # For objects, try to edit the file where they are defined
1821 # For objects, try to edit the file where they are defined
1826 try:
1822 try:
1827 filename = inspect.getabsfile(data)
1823 filename = inspect.getabsfile(data)
1828 datafile = 1
1824 datafile = 1
1829 except TypeError:
1825 except TypeError:
1830 filename = make_filename(args)
1826 filename = make_filename(args)
1831 datafile = 1
1827 datafile = 1
1832 warn('Could not find file where `%s` is defined.\n'
1828 warn('Could not find file where `%s` is defined.\n'
1833 'Opening a file named `%s`' % (args,filename))
1829 'Opening a file named `%s`' % (args,filename))
1834 # Now, make sure we can actually read the source (if it was in
1830 # Now, make sure we can actually read the source (if it was in
1835 # a temp file it's gone by now).
1831 # a temp file it's gone by now).
1836 if datafile:
1832 if datafile:
1837 try:
1833 try:
1838 lineno = inspect.getsourcelines(data)[1]
1834 lineno = inspect.getsourcelines(data)[1]
1839 except IOError:
1835 except IOError:
1840 filename = make_filename(args)
1836 filename = make_filename(args)
1841 if filename is None:
1837 if filename is None:
1842 warn('The file `%s` where `%s` was defined cannot '
1838 warn('The file `%s` where `%s` was defined cannot '
1843 'be read.' % (filename,data))
1839 'be read.' % (filename,data))
1844 return
1840 return
1845 use_temp = 0
1841 use_temp = 0
1846 else:
1842 else:
1847 data = ''
1843 data = ''
1848
1844
1849 if use_temp:
1845 if use_temp:
1850 filename = tempfile.mktemp('.py')
1846 filename = tempfile.mktemp('.py')
1851 self.shell.tempfiles.append(filename)
1847 self.shell.tempfiles.append(filename)
1852
1848
1853 if data and use_temp:
1849 if data and use_temp:
1854 tmp_file = open(filename,'w')
1850 tmp_file = open(filename,'w')
1855 tmp_file.write(data)
1851 tmp_file.write(data)
1856 tmp_file.close()
1852 tmp_file.close()
1857
1853
1858 # do actual editing here
1854 # do actual editing here
1859 print 'Editing...',
1855 print 'Editing...',
1860 sys.stdout.flush()
1856 sys.stdout.flush()
1861 self.shell.hooks.editor(filename,lineno)
1857 self.shell.hooks.editor(filename,lineno)
1862 if opts.has_key('x'): # -x prevents actual execution
1858 if opts.has_key('x'): # -x prevents actual execution
1863 print
1859 print
1864 else:
1860 else:
1865 print 'done. Executing edited code...'
1861 print 'done. Executing edited code...'
1866 try:
1862 try:
1867 self.shell.safe_execfile(filename,self.shell.user_ns)
1863 self.shell.safe_execfile(filename,self.shell.user_ns)
1868 except IOError,msg:
1864 except IOError,msg:
1869 if msg.filename == filename:
1865 if msg.filename == filename:
1870 warn('File not found. Did you forget to save?')
1866 warn('File not found. Did you forget to save?')
1871 return
1867 return
1872 else:
1868 else:
1873 self.shell.showtraceback()
1869 self.shell.showtraceback()
1874 except:
1870 except:
1875 self.shell.showtraceback()
1871 self.shell.showtraceback()
1876 if use_temp:
1872 if use_temp:
1877 contents = open(filename).read()
1873 contents = open(filename).read()
1878 return contents
1874 return contents
1879
1875
1880 def magic_xmode(self,parameter_s = ''):
1876 def magic_xmode(self,parameter_s = ''):
1881 """Switch modes for the exception handlers.
1877 """Switch modes for the exception handlers.
1882
1878
1883 Valid modes: Plain, Context and Verbose.
1879 Valid modes: Plain, Context and Verbose.
1884
1880
1885 If called without arguments, acts as a toggle."""
1881 If called without arguments, acts as a toggle."""
1886
1882
1887 def xmode_switch_err(name):
1883 def xmode_switch_err(name):
1888 warn('Error changing %s exception modes.\n%s' %
1884 warn('Error changing %s exception modes.\n%s' %
1889 (name,sys.exc_info()[1]))
1885 (name,sys.exc_info()[1]))
1890
1886
1891 shell = self.shell
1887 shell = self.shell
1892 new_mode = parameter_s.strip().capitalize()
1888 new_mode = parameter_s.strip().capitalize()
1893 try:
1889 try:
1894 shell.InteractiveTB.set_mode(mode=new_mode)
1890 shell.InteractiveTB.set_mode(mode=new_mode)
1895 print 'Exception reporting mode:',shell.InteractiveTB.mode
1891 print 'Exception reporting mode:',shell.InteractiveTB.mode
1896 except:
1892 except:
1897 xmode_switch_err('user')
1893 xmode_switch_err('user')
1898
1894
1899 # threaded shells use a special handler in sys.excepthook
1895 # threaded shells use a special handler in sys.excepthook
1900 if shell.isthreaded:
1896 if shell.isthreaded:
1901 try:
1897 try:
1902 shell.sys_excepthook.set_mode(mode=new_mode)
1898 shell.sys_excepthook.set_mode(mode=new_mode)
1903 except:
1899 except:
1904 xmode_switch_err('threaded')
1900 xmode_switch_err('threaded')
1905
1901
1906 def magic_colors(self,parameter_s = ''):
1902 def magic_colors(self,parameter_s = ''):
1907 """Switch color scheme for prompts, info system and exception handlers.
1903 """Switch color scheme for prompts, info system and exception handlers.
1908
1904
1909 Currently implemented schemes: NoColor, Linux, LightBG.
1905 Currently implemented schemes: NoColor, Linux, LightBG.
1910
1906
1911 Color scheme names are not case-sensitive."""
1907 Color scheme names are not case-sensitive."""
1912
1908
1913 def color_switch_err(name):
1909 def color_switch_err(name):
1914 warn('Error changing %s color schemes.\n%s' %
1910 warn('Error changing %s color schemes.\n%s' %
1915 (name,sys.exc_info()[1]))
1911 (name,sys.exc_info()[1]))
1916
1912
1917
1913
1918 new_scheme = parameter_s.strip()
1914 new_scheme = parameter_s.strip()
1919 if not new_scheme:
1915 if not new_scheme:
1920 print 'You must specify a color scheme.'
1916 print 'You must specify a color scheme.'
1921 return
1917 return
1922 # Under Windows, check for Gary Bishop's readline, which is necessary
1918 # Under Windows, check for Gary Bishop's readline, which is necessary
1923 # for ANSI coloring
1919 # for ANSI coloring
1924 if os.name in ['nt','dos']:
1920 if os.name in ['nt','dos']:
1925 try:
1921 try:
1926 import readline
1922 import readline
1927 except ImportError:
1923 except ImportError:
1928 has_readline = 0
1924 has_readline = 0
1929 else:
1925 else:
1930 try:
1926 try:
1931 readline.GetOutputFile()
1927 readline.GetOutputFile()
1932 except AttributeError:
1928 except AttributeError:
1933 has_readline = 0
1929 has_readline = 0
1934 else:
1930 else:
1935 has_readline = 1
1931 has_readline = 1
1936 if not has_readline:
1932 if not has_readline:
1937 msg = """\
1933 msg = """\
1938 Proper color support under MS Windows requires Gary Bishop's readline library.
1934 Proper color support under MS Windows requires Gary Bishop's readline library.
1939 You can find it at:
1935 You can find it at:
1940 http://sourceforge.net/projects/uncpythontools
1936 http://sourceforge.net/projects/uncpythontools
1941 Gary's readline needs the ctypes module, from:
1937 Gary's readline needs the ctypes module, from:
1942 http://starship.python.net/crew/theller/ctypes
1938 http://starship.python.net/crew/theller/ctypes
1943
1939
1944 Defaulting color scheme to 'NoColor'"""
1940 Defaulting color scheme to 'NoColor'"""
1945 new_scheme = 'NoColor'
1941 new_scheme = 'NoColor'
1946 warn(msg)
1942 warn(msg)
1947 # local shortcut
1943 # local shortcut
1948 shell = self.shell
1944 shell = self.shell
1949
1945
1950 # Set prompt colors
1946 # Set prompt colors
1951 try:
1947 try:
1952 shell.outputcache.set_colors(new_scheme)
1948 shell.outputcache.set_colors(new_scheme)
1953 except:
1949 except:
1954 color_switch_err('prompt')
1950 color_switch_err('prompt')
1955 else:
1951 else:
1956 shell.rc.colors = \
1952 shell.rc.colors = \
1957 shell.outputcache.color_table.active_scheme_name
1953 shell.outputcache.color_table.active_scheme_name
1958 # Set exception colors
1954 # Set exception colors
1959 try:
1955 try:
1960 shell.InteractiveTB.set_colors(scheme = new_scheme)
1956 shell.InteractiveTB.set_colors(scheme = new_scheme)
1961 shell.SyntaxTB.set_colors(scheme = new_scheme)
1957 shell.SyntaxTB.set_colors(scheme = new_scheme)
1962 except:
1958 except:
1963 color_switch_err('exception')
1959 color_switch_err('exception')
1964
1960
1965 # threaded shells use a verbose traceback in sys.excepthook
1961 # threaded shells use a verbose traceback in sys.excepthook
1966 if shell.isthreaded:
1962 if shell.isthreaded:
1967 try:
1963 try:
1968 shell.sys_excepthook.set_colors(scheme=new_scheme)
1964 shell.sys_excepthook.set_colors(scheme=new_scheme)
1969 except:
1965 except:
1970 color_switch_err('system exception handler')
1966 color_switch_err('system exception handler')
1971
1967
1972 # Set info (for 'object?') colors
1968 # Set info (for 'object?') colors
1973 if shell.rc.color_info:
1969 if shell.rc.color_info:
1974 try:
1970 try:
1975 shell.inspector.set_active_scheme(new_scheme)
1971 shell.inspector.set_active_scheme(new_scheme)
1976 except:
1972 except:
1977 color_switch_err('object inspector')
1973 color_switch_err('object inspector')
1978 else:
1974 else:
1979 shell.inspector.set_active_scheme('NoColor')
1975 shell.inspector.set_active_scheme('NoColor')
1980
1976
1981 def magic_color_info(self,parameter_s = ''):
1977 def magic_color_info(self,parameter_s = ''):
1982 """Toggle color_info.
1978 """Toggle color_info.
1983
1979
1984 The color_info configuration parameter controls whether colors are
1980 The color_info configuration parameter controls whether colors are
1985 used for displaying object details (by things like %psource, %pfile or
1981 used for displaying object details (by things like %psource, %pfile or
1986 the '?' system). This function toggles this value with each call.
1982 the '?' system). This function toggles this value with each call.
1987
1983
1988 Note that unless you have a fairly recent pager (less works better
1984 Note that unless you have a fairly recent pager (less works better
1989 than more) in your system, using colored object information displays
1985 than more) in your system, using colored object information displays
1990 will not work properly. Test it and see."""
1986 will not work properly. Test it and see."""
1991
1987
1992 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1988 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1993 self.magic_colors(self.shell.rc.colors)
1989 self.magic_colors(self.shell.rc.colors)
1994 print 'Object introspection functions have now coloring:',
1990 print 'Object introspection functions have now coloring:',
1995 print ['OFF','ON'][self.shell.rc.color_info]
1991 print ['OFF','ON'][self.shell.rc.color_info]
1996
1992
1997 def magic_Pprint(self, parameter_s=''):
1993 def magic_Pprint(self, parameter_s=''):
1998 """Toggle pretty printing on/off."""
1994 """Toggle pretty printing on/off."""
1999
1995
2000 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1996 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2001 print 'Pretty printing has been turned', \
1997 print 'Pretty printing has been turned', \
2002 ['OFF','ON'][self.shell.outputcache.Pprint]
1998 ['OFF','ON'][self.shell.outputcache.Pprint]
2003
1999
2004 def magic_exit(self, parameter_s=''):
2000 def magic_exit(self, parameter_s=''):
2005 """Exit IPython, confirming if configured to do so.
2001 """Exit IPython, confirming if configured to do so.
2006
2002
2007 You can configure whether IPython asks for confirmation upon exit by
2003 You can configure whether IPython asks for confirmation upon exit by
2008 setting the confirm_exit flag in the ipythonrc file."""
2004 setting the confirm_exit flag in the ipythonrc file."""
2009
2005
2010 self.shell.exit()
2006 self.shell.exit()
2011
2007
2012 def magic_quit(self, parameter_s=''):
2008 def magic_quit(self, parameter_s=''):
2013 """Exit IPython, confirming if configured to do so (like %exit)"""
2009 """Exit IPython, confirming if configured to do so (like %exit)"""
2014
2010
2015 self.shell.exit()
2011 self.shell.exit()
2016
2012
2017 def magic_Exit(self, parameter_s=''):
2013 def magic_Exit(self, parameter_s=''):
2018 """Exit IPython without confirmation."""
2014 """Exit IPython without confirmation."""
2019
2015
2020 self.shell.exit_now = True
2016 self.shell.exit_now = True
2021
2017
2022 def magic_Quit(self, parameter_s=''):
2018 def magic_Quit(self, parameter_s=''):
2023 """Exit IPython without confirmation (like %Exit)."""
2019 """Exit IPython without confirmation (like %Exit)."""
2024
2020
2025 self.shell.exit_now = True
2021 self.shell.exit_now = True
2026
2022
2027 #......................................................................
2023 #......................................................................
2028 # Functions to implement unix shell-type things
2024 # Functions to implement unix shell-type things
2029
2025
2030 def magic_alias(self, parameter_s = ''):
2026 def magic_alias(self, parameter_s = ''):
2031 """Define an alias for a system command.
2027 """Define an alias for a system command.
2032
2028
2033 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2029 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2034
2030
2035 Then, typing 'alias_name params' will execute the system command 'cmd
2031 Then, typing 'alias_name params' will execute the system command 'cmd
2036 params' (from your underlying operating system).
2032 params' (from your underlying operating system).
2037
2033
2038 Aliases have lower precedence than magic functions and Python normal
2034 Aliases have lower precedence than magic functions and Python normal
2039 variables, so if 'foo' is both a Python variable and an alias, the
2035 variables, so if 'foo' is both a Python variable and an alias, the
2040 alias can not be executed until 'del foo' removes the Python variable.
2036 alias can not be executed until 'del foo' removes the Python variable.
2041
2037
2042 You can use the %l specifier in an alias definition to represent the
2038 You can use the %l specifier in an alias definition to represent the
2043 whole line when the alias is called. For example:
2039 whole line when the alias is called. For example:
2044
2040
2045 In [2]: alias all echo "Input in brackets: <%l>"\\
2041 In [2]: alias all echo "Input in brackets: <%l>"\\
2046 In [3]: all hello world\\
2042 In [3]: all hello world\\
2047 Input in brackets: <hello world>
2043 Input in brackets: <hello world>
2048
2044
2049 You can also define aliases with parameters using %s specifiers (one
2045 You can also define aliases with parameters using %s specifiers (one
2050 per parameter):
2046 per parameter):
2051
2047
2052 In [1]: alias parts echo first %s second %s\\
2048 In [1]: alias parts echo first %s second %s\\
2053 In [2]: %parts A B\\
2049 In [2]: %parts A B\\
2054 first A second B\\
2050 first A second B\\
2055 In [3]: %parts A\\
2051 In [3]: %parts A\\
2056 Incorrect number of arguments: 2 expected.\\
2052 Incorrect number of arguments: 2 expected.\\
2057 parts is an alias to: 'echo first %s second %s'
2053 parts is an alias to: 'echo first %s second %s'
2058
2054
2059 Note that %l and %s are mutually exclusive. You can only use one or
2055 Note that %l and %s are mutually exclusive. You can only use one or
2060 the other in your aliases.
2056 the other in your aliases.
2061
2057
2062 Aliases expand Python variables just like system calls using ! or !!
2058 Aliases expand Python variables just like system calls using ! or !!
2063 do: all expressions prefixed with '$' get expanded. For details of
2059 do: all expressions prefixed with '$' get expanded. For details of
2064 the semantic rules, see PEP-215:
2060 the semantic rules, see PEP-215:
2065 http://www.python.org/peps/pep-0215.html. This is the library used by
2061 http://www.python.org/peps/pep-0215.html. This is the library used by
2066 IPython for variable expansion. If you want to access a true shell
2062 IPython for variable expansion. If you want to access a true shell
2067 variable, an extra $ is necessary to prevent its expansion by IPython:
2063 variable, an extra $ is necessary to prevent its expansion by IPython:
2068
2064
2069 In [6]: alias show echo\\
2065 In [6]: alias show echo\\
2070 In [7]: PATH='A Python string'\\
2066 In [7]: PATH='A Python string'\\
2071 In [8]: show $PATH\\
2067 In [8]: show $PATH\\
2072 A Python string\\
2068 A Python string\\
2073 In [9]: show $$PATH\\
2069 In [9]: show $$PATH\\
2074 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2070 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2075
2071
2076 You can use the alias facility to acess all of $PATH. See the %rehash
2072 You can use the alias facility to acess all of $PATH. See the %rehash
2077 and %rehashx functions, which automatically create aliases for the
2073 and %rehashx functions, which automatically create aliases for the
2078 contents of your $PATH.
2074 contents of your $PATH.
2079
2075
2080 If called with no parameters, %alias prints the current alias table."""
2076 If called with no parameters, %alias prints the current alias table."""
2081
2077
2082 par = parameter_s.strip()
2078 par = parameter_s.strip()
2083 if not par:
2079 if not par:
2084 if self.shell.rc.automagic:
2080 if self.shell.rc.automagic:
2085 prechar = ''
2081 prechar = ''
2086 else:
2082 else:
2087 prechar = self.shell.ESC_MAGIC
2083 prechar = self.shell.ESC_MAGIC
2088 print 'Alias\t\tSystem Command\n'+'-'*30
2084 print 'Alias\t\tSystem Command\n'+'-'*30
2089 atab = self.shell.alias_table
2085 atab = self.shell.alias_table
2090 aliases = atab.keys()
2086 aliases = atab.keys()
2091 aliases.sort()
2087 aliases.sort()
2092 for alias in aliases:
2088 for alias in aliases:
2093 print prechar+alias+'\t\t'+atab[alias][1]
2089 print prechar+alias+'\t\t'+atab[alias][1]
2094 print '-'*30+'\nTotal number of aliases:',len(aliases)
2090 print '-'*30+'\nTotal number of aliases:',len(aliases)
2095 return
2091 return
2096 try:
2092 try:
2097 alias,cmd = par.split(None,1)
2093 alias,cmd = par.split(None,1)
2098 except:
2094 except:
2099 print OInspect.getdoc(self.magic_alias)
2095 print OInspect.getdoc(self.magic_alias)
2100 else:
2096 else:
2101 nargs = cmd.count('%s')
2097 nargs = cmd.count('%s')
2102 if nargs>0 and cmd.find('%l')>=0:
2098 if nargs>0 and cmd.find('%l')>=0:
2103 error('The %s and %l specifiers are mutually exclusive '
2099 error('The %s and %l specifiers are mutually exclusive '
2104 'in alias definitions.')
2100 'in alias definitions.')
2105 else: # all looks OK
2101 else: # all looks OK
2106 self.shell.alias_table[alias] = (nargs,cmd)
2102 self.shell.alias_table[alias] = (nargs,cmd)
2107 self.shell.alias_table_validate(verbose=1)
2103 self.shell.alias_table_validate(verbose=1)
2108 # end magic_alias
2104 # end magic_alias
2109
2105
2110 def magic_unalias(self, parameter_s = ''):
2106 def magic_unalias(self, parameter_s = ''):
2111 """Remove an alias"""
2107 """Remove an alias"""
2112
2108
2113 aname = parameter_s.strip()
2109 aname = parameter_s.strip()
2114 if aname in self.shell.alias_table:
2110 if aname in self.shell.alias_table:
2115 del self.shell.alias_table[aname]
2111 del self.shell.alias_table[aname]
2116
2112
2117 def magic_rehash(self, parameter_s = ''):
2113 def magic_rehash(self, parameter_s = ''):
2118 """Update the alias table with all entries in $PATH.
2114 """Update the alias table with all entries in $PATH.
2119
2115
2120 This version does no checks on execute permissions or whether the
2116 This version does no checks on execute permissions or whether the
2121 contents of $PATH are truly files (instead of directories or something
2117 contents of $PATH are truly files (instead of directories or something
2122 else). For such a safer (but slower) version, use %rehashx."""
2118 else). For such a safer (but slower) version, use %rehashx."""
2123
2119
2124 # This function (and rehashx) manipulate the alias_table directly
2120 # This function (and rehashx) manipulate the alias_table directly
2125 # rather than calling magic_alias, for speed reasons. A rehash on a
2121 # rather than calling magic_alias, for speed reasons. A rehash on a
2126 # typical Linux box involves several thousand entries, so efficiency
2122 # typical Linux box involves several thousand entries, so efficiency
2127 # here is a top concern.
2123 # here is a top concern.
2128
2124
2129 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2125 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2130 alias_table = self.shell.alias_table
2126 alias_table = self.shell.alias_table
2131 for pdir in path:
2127 for pdir in path:
2132 for ff in os.listdir(pdir):
2128 for ff in os.listdir(pdir):
2133 # each entry in the alias table must be (N,name), where
2129 # each entry in the alias table must be (N,name), where
2134 # N is the number of positional arguments of the alias.
2130 # N is the number of positional arguments of the alias.
2135 alias_table[ff] = (0,ff)
2131 alias_table[ff] = (0,ff)
2136 # Make sure the alias table doesn't contain keywords or builtins
2132 # Make sure the alias table doesn't contain keywords or builtins
2137 self.shell.alias_table_validate()
2133 self.shell.alias_table_validate()
2138 # Call again init_auto_alias() so we get 'rm -i' and other modified
2134 # Call again init_auto_alias() so we get 'rm -i' and other modified
2139 # aliases since %rehash will probably clobber them
2135 # aliases since %rehash will probably clobber them
2140 self.shell.init_auto_alias()
2136 self.shell.init_auto_alias()
2141
2137
2142 def magic_rehashx(self, parameter_s = ''):
2138 def magic_rehashx(self, parameter_s = ''):
2143 """Update the alias table with all executable files in $PATH.
2139 """Update the alias table with all executable files in $PATH.
2144
2140
2145 This version explicitly checks that every entry in $PATH is a file
2141 This version explicitly checks that every entry in $PATH is a file
2146 with execute access (os.X_OK), so it is much slower than %rehash.
2142 with execute access (os.X_OK), so it is much slower than %rehash.
2147
2143
2148 Under Windows, it checks executability as a match agains a
2144 Under Windows, it checks executability as a match agains a
2149 '|'-separated string of extensions, stored in the IPython config
2145 '|'-separated string of extensions, stored in the IPython config
2150 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2146 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2151
2147
2152 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2148 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2153 alias_table = self.shell.alias_table
2149 alias_table = self.shell.alias_table
2154
2150
2155 if os.name == 'posix':
2151 if os.name == 'posix':
2156 isexec = lambda fname:os.path.isfile(fname) and \
2152 isexec = lambda fname:os.path.isfile(fname) and \
2157 os.access(fname,os.X_OK)
2153 os.access(fname,os.X_OK)
2158 else:
2154 else:
2159
2155
2160 try:
2156 try:
2161 winext = os.environ['pathext'].replace(';','|').replace('.','')
2157 winext = os.environ['pathext'].replace(';','|').replace('.','')
2162 except KeyError:
2158 except KeyError:
2163 winext = 'exe|com|bat'
2159 winext = 'exe|com|bat'
2164
2160
2165 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2161 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2166 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2162 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2167 savedir = os.getcwd()
2163 savedir = os.getcwd()
2168 try:
2164 try:
2169 # write the whole loop for posix/Windows so we don't have an if in
2165 # write the whole loop for posix/Windows so we don't have an if in
2170 # the innermost part
2166 # the innermost part
2171 if os.name == 'posix':
2167 if os.name == 'posix':
2172 for pdir in path:
2168 for pdir in path:
2173 os.chdir(pdir)
2169 os.chdir(pdir)
2174 for ff in os.listdir(pdir):
2170 for ff in os.listdir(pdir):
2175 if isexec(ff):
2171 if isexec(ff):
2176 # each entry in the alias table must be (N,name),
2172 # each entry in the alias table must be (N,name),
2177 # where N is the number of positional arguments of the
2173 # where N is the number of positional arguments of the
2178 # alias.
2174 # alias.
2179 alias_table[ff] = (0,ff)
2175 alias_table[ff] = (0,ff)
2180 else:
2176 else:
2181 for pdir in path:
2177 for pdir in path:
2182 os.chdir(pdir)
2178 os.chdir(pdir)
2183 for ff in os.listdir(pdir):
2179 for ff in os.listdir(pdir):
2184 if isexec(ff):
2180 if isexec(ff):
2185 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2181 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2186 # Make sure the alias table doesn't contain keywords or builtins
2182 # Make sure the alias table doesn't contain keywords or builtins
2187 self.shell.alias_table_validate()
2183 self.shell.alias_table_validate()
2188 # Call again init_auto_alias() so we get 'rm -i' and other
2184 # Call again init_auto_alias() so we get 'rm -i' and other
2189 # modified aliases since %rehashx will probably clobber them
2185 # modified aliases since %rehashx will probably clobber them
2190 self.shell.init_auto_alias()
2186 self.shell.init_auto_alias()
2191 finally:
2187 finally:
2192 os.chdir(savedir)
2188 os.chdir(savedir)
2193
2189
2194 def magic_pwd(self, parameter_s = ''):
2190 def magic_pwd(self, parameter_s = ''):
2195 """Return the current working directory path."""
2191 """Return the current working directory path."""
2196 return os.getcwd()
2192 return os.getcwd()
2197
2193
2198 def magic_cd(self, parameter_s=''):
2194 def magic_cd(self, parameter_s=''):
2199 """Change the current working directory.
2195 """Change the current working directory.
2200
2196
2201 This command automatically maintains an internal list of directories
2197 This command automatically maintains an internal list of directories
2202 you visit during your IPython session, in the variable _dh. The
2198 you visit during your IPython session, in the variable _dh. The
2203 command %dhist shows this history nicely formatted.
2199 command %dhist shows this history nicely formatted.
2204
2200
2205 Usage:
2201 Usage:
2206
2202
2207 cd 'dir': changes to directory 'dir'.
2203 cd 'dir': changes to directory 'dir'.
2208
2204
2209 cd -: changes to the last visited directory.
2205 cd -: changes to the last visited directory.
2210
2206
2211 cd -<n>: changes to the n-th directory in the directory history.
2207 cd -<n>: changes to the n-th directory in the directory history.
2212
2208
2213 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2209 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2214 (note: cd <bookmark_name> is enough if there is no
2210 (note: cd <bookmark_name> is enough if there is no
2215 directory <bookmark_name>, but a bookmark with the name exists.)
2211 directory <bookmark_name>, but a bookmark with the name exists.)
2216
2212
2217 Options:
2213 Options:
2218
2214
2219 -q: quiet. Do not print the working directory after the cd command is
2215 -q: quiet. Do not print the working directory after the cd command is
2220 executed. By default IPython's cd command does print this directory,
2216 executed. By default IPython's cd command does print this directory,
2221 since the default prompts do not display path information.
2217 since the default prompts do not display path information.
2222
2218
2223 Note that !cd doesn't work for this purpose because the shell where
2219 Note that !cd doesn't work for this purpose because the shell where
2224 !command runs is immediately discarded after executing 'command'."""
2220 !command runs is immediately discarded after executing 'command'."""
2225
2221
2226 parameter_s = parameter_s.strip()
2222 parameter_s = parameter_s.strip()
2227 bkms = self.shell.persist.get("bookmarks",{})
2223 bkms = self.shell.persist.get("bookmarks",{})
2228
2224
2229 numcd = re.match(r'(-)(\d+)$',parameter_s)
2225 numcd = re.match(r'(-)(\d+)$',parameter_s)
2230 # jump in directory history by number
2226 # jump in directory history by number
2231 if numcd:
2227 if numcd:
2232 nn = int(numcd.group(2))
2228 nn = int(numcd.group(2))
2233 try:
2229 try:
2234 ps = self.shell.user_ns['_dh'][nn]
2230 ps = self.shell.user_ns['_dh'][nn]
2235 except IndexError:
2231 except IndexError:
2236 print 'The requested directory does not exist in history.'
2232 print 'The requested directory does not exist in history.'
2237 return
2233 return
2238 else:
2234 else:
2239 opts = {}
2235 opts = {}
2240 else:
2236 else:
2241 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2237 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2242 # jump to previous
2238 # jump to previous
2243 if ps == '-':
2239 if ps == '-':
2244 try:
2240 try:
2245 ps = self.shell.user_ns['_dh'][-2]
2241 ps = self.shell.user_ns['_dh'][-2]
2246 except IndexError:
2242 except IndexError:
2247 print 'No previous directory to change to.'
2243 print 'No previous directory to change to.'
2248 return
2244 return
2249 # jump to bookmark
2245 # jump to bookmark
2250 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2246 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2251 if bkms.has_key(ps):
2247 if bkms.has_key(ps):
2252 target = bkms[ps]
2248 target = bkms[ps]
2253 print '(bookmark:%s) -> %s' % (ps,target)
2249 print '(bookmark:%s) -> %s' % (ps,target)
2254 ps = target
2250 ps = target
2255 else:
2251 else:
2256 if bkms:
2252 if bkms:
2257 error("Bookmark '%s' not found. "
2253 error("Bookmark '%s' not found. "
2258 "Use '%bookmark -l' to see your bookmarks." % ps)
2254 "Use '%bookmark -l' to see your bookmarks." % ps)
2259 else:
2255 else:
2260 print "Bookmarks not set - use %bookmark <bookmarkname>"
2256 print "Bookmarks not set - use %bookmark <bookmarkname>"
2261 return
2257 return
2262
2258
2263 # at this point ps should point to the target dir
2259 # at this point ps should point to the target dir
2264 if ps:
2260 if ps:
2265 try:
2261 try:
2266 os.chdir(os.path.expanduser(ps))
2262 os.chdir(os.path.expanduser(ps))
2267 except OSError:
2263 except OSError:
2268 print sys.exc_info()[1]
2264 print sys.exc_info()[1]
2269 else:
2265 else:
2270 self.shell.user_ns['_dh'].append(os.getcwd())
2266 self.shell.user_ns['_dh'].append(os.getcwd())
2271 else:
2267 else:
2272 os.chdir(self.shell.home_dir)
2268 os.chdir(self.shell.home_dir)
2273 self.shell.user_ns['_dh'].append(os.getcwd())
2269 self.shell.user_ns['_dh'].append(os.getcwd())
2274 if not 'q' in opts:
2270 if not 'q' in opts:
2275 print self.shell.user_ns['_dh'][-1]
2271 print self.shell.user_ns['_dh'][-1]
2276
2272
2277 def magic_dhist(self, parameter_s=''):
2273 def magic_dhist(self, parameter_s=''):
2278 """Print your history of visited directories.
2274 """Print your history of visited directories.
2279
2275
2280 %dhist -> print full history\\
2276 %dhist -> print full history\\
2281 %dhist n -> print last n entries only\\
2277 %dhist n -> print last n entries only\\
2282 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2278 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2283
2279
2284 This history is automatically maintained by the %cd command, and
2280 This history is automatically maintained by the %cd command, and
2285 always available as the global list variable _dh. You can use %cd -<n>
2281 always available as the global list variable _dh. You can use %cd -<n>
2286 to go to directory number <n>."""
2282 to go to directory number <n>."""
2287
2283
2288 dh = self.shell.user_ns['_dh']
2284 dh = self.shell.user_ns['_dh']
2289 if parameter_s:
2285 if parameter_s:
2290 try:
2286 try:
2291 args = map(int,parameter_s.split())
2287 args = map(int,parameter_s.split())
2292 except:
2288 except:
2293 self.arg_err(Magic.magic_dhist)
2289 self.arg_err(Magic.magic_dhist)
2294 return
2290 return
2295 if len(args) == 1:
2291 if len(args) == 1:
2296 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2292 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2297 elif len(args) == 2:
2293 elif len(args) == 2:
2298 ini,fin = args
2294 ini,fin = args
2299 else:
2295 else:
2300 self.arg_err(Magic.magic_dhist)
2296 self.arg_err(Magic.magic_dhist)
2301 return
2297 return
2302 else:
2298 else:
2303 ini,fin = 0,len(dh)
2299 ini,fin = 0,len(dh)
2304 nlprint(dh,
2300 nlprint(dh,
2305 header = 'Directory history (kept in _dh)',
2301 header = 'Directory history (kept in _dh)',
2306 start=ini,stop=fin)
2302 start=ini,stop=fin)
2307
2303
2308 def magic_env(self, parameter_s=''):
2304 def magic_env(self, parameter_s=''):
2309 """List environment variables."""
2305 """List environment variables."""
2310
2306
2311 return os.environ.data
2307 return os.environ.data
2312
2308
2313 def magic_pushd(self, parameter_s=''):
2309 def magic_pushd(self, parameter_s=''):
2314 """Place the current dir on stack and change directory.
2310 """Place the current dir on stack and change directory.
2315
2311
2316 Usage:\\
2312 Usage:\\
2317 %pushd ['dirname']
2313 %pushd ['dirname']
2318
2314
2319 %pushd with no arguments does a %pushd to your home directory.
2315 %pushd with no arguments does a %pushd to your home directory.
2320 """
2316 """
2321 if parameter_s == '': parameter_s = '~'
2317 if parameter_s == '': parameter_s = '~'
2322 dir_s = self.shell.dir_stack
2318 dir_s = self.shell.dir_stack
2323 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2319 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2324 os.path.expanduser(self.shell.dir_stack[0]):
2320 os.path.expanduser(self.shell.dir_stack[0]):
2325 try:
2321 try:
2326 self.magic_cd(parameter_s)
2322 self.magic_cd(parameter_s)
2327 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2323 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2328 self.magic_dirs()
2324 self.magic_dirs()
2329 except:
2325 except:
2330 print 'Invalid directory'
2326 print 'Invalid directory'
2331 else:
2327 else:
2332 print 'You are already there!'
2328 print 'You are already there!'
2333
2329
2334 def magic_popd(self, parameter_s=''):
2330 def magic_popd(self, parameter_s=''):
2335 """Change to directory popped off the top of the stack.
2331 """Change to directory popped off the top of the stack.
2336 """
2332 """
2337 if len (self.shell.dir_stack) > 1:
2333 if len (self.shell.dir_stack) > 1:
2338 self.shell.dir_stack.pop(0)
2334 self.shell.dir_stack.pop(0)
2339 self.magic_cd(self.shell.dir_stack[0])
2335 self.magic_cd(self.shell.dir_stack[0])
2340 print self.shell.dir_stack[0]
2336 print self.shell.dir_stack[0]
2341 else:
2337 else:
2342 print "You can't remove the starting directory from the stack:",\
2338 print "You can't remove the starting directory from the stack:",\
2343 self.shell.dir_stack
2339 self.shell.dir_stack
2344
2340
2345 def magic_dirs(self, parameter_s=''):
2341 def magic_dirs(self, parameter_s=''):
2346 """Return the current directory stack."""
2342 """Return the current directory stack."""
2347
2343
2348 return self.shell.dir_stack[:]
2344 return self.shell.dir_stack[:]
2349
2345
2350 def magic_sc(self, parameter_s=''):
2346 def magic_sc(self, parameter_s=''):
2351 """Shell capture - execute a shell command and capture its output.
2347 """Shell capture - execute a shell command and capture its output.
2352
2348
2353 %sc [options] varname=command
2349 %sc [options] varname=command
2354
2350
2355 IPython will run the given command using commands.getoutput(), and
2351 IPython will run the given command using commands.getoutput(), and
2356 will then update the user's interactive namespace with a variable
2352 will then update the user's interactive namespace with a variable
2357 called varname, containing the value of the call. Your command can
2353 called varname, containing the value of the call. Your command can
2358 contain shell wildcards, pipes, etc.
2354 contain shell wildcards, pipes, etc.
2359
2355
2360 The '=' sign in the syntax is mandatory, and the variable name you
2356 The '=' sign in the syntax is mandatory, and the variable name you
2361 supply must follow Python's standard conventions for valid names.
2357 supply must follow Python's standard conventions for valid names.
2362
2358
2363 Options:
2359 Options:
2364
2360
2365 -l: list output. Split the output on newlines into a list before
2361 -l: list output. Split the output on newlines into a list before
2366 assigning it to the given variable. By default the output is stored
2362 assigning it to the given variable. By default the output is stored
2367 as a single string.
2363 as a single string.
2368
2364
2369 -v: verbose. Print the contents of the variable.
2365 -v: verbose. Print the contents of the variable.
2370
2366
2371 In most cases you should not need to split as a list, because the
2367 In most cases you should not need to split as a list, because the
2372 returned value is a special type of string which can automatically
2368 returned value is a special type of string which can automatically
2373 provide its contents either as a list (split on newlines) or as a
2369 provide its contents either as a list (split on newlines) or as a
2374 space-separated string. These are convenient, respectively, either
2370 space-separated string. These are convenient, respectively, either
2375 for sequential processing or to be passed to a shell command.
2371 for sequential processing or to be passed to a shell command.
2376
2372
2377 For example:
2373 For example:
2378
2374
2379 # Capture into variable a
2375 # Capture into variable a
2380 In [9]: sc a=ls *py
2376 In [9]: sc a=ls *py
2381
2377
2382 # a is a string with embedded newlines
2378 # a is a string with embedded newlines
2383 In [10]: a
2379 In [10]: a
2384 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2380 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2385
2381
2386 # which can be seen as a list:
2382 # which can be seen as a list:
2387 In [11]: a.l
2383 In [11]: a.l
2388 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2384 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2389
2385
2390 # or as a whitespace-separated string:
2386 # or as a whitespace-separated string:
2391 In [12]: a.s
2387 In [12]: a.s
2392 Out[12]: 'setup.py win32_manual_post_install.py'
2388 Out[12]: 'setup.py win32_manual_post_install.py'
2393
2389
2394 # a.s is useful to pass as a single command line:
2390 # a.s is useful to pass as a single command line:
2395 In [13]: !wc -l $a.s
2391 In [13]: !wc -l $a.s
2396 146 setup.py
2392 146 setup.py
2397 130 win32_manual_post_install.py
2393 130 win32_manual_post_install.py
2398 276 total
2394 276 total
2399
2395
2400 # while the list form is useful to loop over:
2396 # while the list form is useful to loop over:
2401 In [14]: for f in a.l:
2397 In [14]: for f in a.l:
2402 ....: !wc -l $f
2398 ....: !wc -l $f
2403 ....:
2399 ....:
2404 146 setup.py
2400 146 setup.py
2405 130 win32_manual_post_install.py
2401 130 win32_manual_post_install.py
2406
2402
2407 Similiarly, the lists returned by the -l option are also special, in
2403 Similiarly, the lists returned by the -l option are also special, in
2408 the sense that you can equally invoke the .s attribute on them to
2404 the sense that you can equally invoke the .s attribute on them to
2409 automatically get a whitespace-separated string from their contents:
2405 automatically get a whitespace-separated string from their contents:
2410
2406
2411 In [1]: sc -l b=ls *py
2407 In [1]: sc -l b=ls *py
2412
2408
2413 In [2]: b
2409 In [2]: b
2414 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2410 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2415
2411
2416 In [3]: b.s
2412 In [3]: b.s
2417 Out[3]: 'setup.py win32_manual_post_install.py'
2413 Out[3]: 'setup.py win32_manual_post_install.py'
2418
2414
2419 In summary, both the lists and strings used for ouptut capture have
2415 In summary, both the lists and strings used for ouptut capture have
2420 the following special attributes:
2416 the following special attributes:
2421
2417
2422 .l (or .list) : value as list.
2418 .l (or .list) : value as list.
2423 .n (or .nlstr): value as newline-separated string.
2419 .n (or .nlstr): value as newline-separated string.
2424 .s (or .spstr): value as space-separated string.
2420 .s (or .spstr): value as space-separated string.
2425 """
2421 """
2426
2422
2427 opts,args = self.parse_options(parameter_s,'lv')
2423 opts,args = self.parse_options(parameter_s,'lv')
2428 # Try to get a variable name and command to run
2424 # Try to get a variable name and command to run
2429 try:
2425 try:
2430 # the variable name must be obtained from the parse_options
2426 # the variable name must be obtained from the parse_options
2431 # output, which uses shlex.split to strip options out.
2427 # output, which uses shlex.split to strip options out.
2432 var,_ = args.split('=',1)
2428 var,_ = args.split('=',1)
2433 var = var.strip()
2429 var = var.strip()
2434 # But the the command has to be extracted from the original input
2430 # But the the command has to be extracted from the original input
2435 # parameter_s, not on what parse_options returns, to avoid the
2431 # parameter_s, not on what parse_options returns, to avoid the
2436 # quote stripping which shlex.split performs on it.
2432 # quote stripping which shlex.split performs on it.
2437 _,cmd = parameter_s.split('=',1)
2433 _,cmd = parameter_s.split('=',1)
2438 except ValueError:
2434 except ValueError:
2439 var,cmd = '',''
2435 var,cmd = '',''
2440 if not var:
2436 if not var:
2441 error('you must specify a variable to assign the command to.')
2437 error('you must specify a variable to assign the command to.')
2442 return
2438 return
2443 # If all looks ok, proceed
2439 # If all looks ok, proceed
2444 out,err = self.shell.getoutputerror(cmd)
2440 out,err = self.shell.getoutputerror(cmd)
2445 if err:
2441 if err:
2446 print >> Term.cerr,err
2442 print >> Term.cerr,err
2447 if opts.has_key('l'):
2443 if opts.has_key('l'):
2448 out = SList(out.split('\n'))
2444 out = SList(out.split('\n'))
2449 else:
2445 else:
2450 out = LSString(out)
2446 out = LSString(out)
2451 if opts.has_key('v'):
2447 if opts.has_key('v'):
2452 print '%s ==\n%s' % (var,pformat(out))
2448 print '%s ==\n%s' % (var,pformat(out))
2453 self.shell.user_ns.update({var:out})
2449 self.shell.user_ns.update({var:out})
2454
2450
2455 def magic_sx(self, parameter_s=''):
2451 def magic_sx(self, parameter_s=''):
2456 """Shell execute - run a shell command and capture its output.
2452 """Shell execute - run a shell command and capture its output.
2457
2453
2458 %sx command
2454 %sx command
2459
2455
2460 IPython will run the given command using commands.getoutput(), and
2456 IPython will run the given command using commands.getoutput(), and
2461 return the result formatted as a list (split on '\\n'). Since the
2457 return the result formatted as a list (split on '\\n'). Since the
2462 output is _returned_, it will be stored in ipython's regular output
2458 output is _returned_, it will be stored in ipython's regular output
2463 cache Out[N] and in the '_N' automatic variables.
2459 cache Out[N] and in the '_N' automatic variables.
2464
2460
2465 Notes:
2461 Notes:
2466
2462
2467 1) If an input line begins with '!!', then %sx is automatically
2463 1) If an input line begins with '!!', then %sx is automatically
2468 invoked. That is, while:
2464 invoked. That is, while:
2469 !ls
2465 !ls
2470 causes ipython to simply issue system('ls'), typing
2466 causes ipython to simply issue system('ls'), typing
2471 !!ls
2467 !!ls
2472 is a shorthand equivalent to:
2468 is a shorthand equivalent to:
2473 %sx ls
2469 %sx ls
2474
2470
2475 2) %sx differs from %sc in that %sx automatically splits into a list,
2471 2) %sx differs from %sc in that %sx automatically splits into a list,
2476 like '%sc -l'. The reason for this is to make it as easy as possible
2472 like '%sc -l'. The reason for this is to make it as easy as possible
2477 to process line-oriented shell output via further python commands.
2473 to process line-oriented shell output via further python commands.
2478 %sc is meant to provide much finer control, but requires more
2474 %sc is meant to provide much finer control, but requires more
2479 typing.
2475 typing.
2480
2476
2481 3) Just like %sc -l, this is a list with special attributes:
2477 3) Just like %sc -l, this is a list with special attributes:
2482
2478
2483 .l (or .list) : value as list.
2479 .l (or .list) : value as list.
2484 .n (or .nlstr): value as newline-separated string.
2480 .n (or .nlstr): value as newline-separated string.
2485 .s (or .spstr): value as whitespace-separated string.
2481 .s (or .spstr): value as whitespace-separated string.
2486
2482
2487 This is very useful when trying to use such lists as arguments to
2483 This is very useful when trying to use such lists as arguments to
2488 system commands."""
2484 system commands."""
2489
2485
2490 if parameter_s:
2486 if parameter_s:
2491 out,err = self.shell.getoutputerror(parameter_s)
2487 out,err = self.shell.getoutputerror(parameter_s)
2492 if err:
2488 if err:
2493 print >> Term.cerr,err
2489 print >> Term.cerr,err
2494 return SList(out.split('\n'))
2490 return SList(out.split('\n'))
2495
2491
2496 def magic_bg(self, parameter_s=''):
2492 def magic_bg(self, parameter_s=''):
2497 """Run a job in the background, in a separate thread.
2493 """Run a job in the background, in a separate thread.
2498
2494
2499 For example,
2495 For example,
2500
2496
2501 %bg myfunc(x,y,z=1)
2497 %bg myfunc(x,y,z=1)
2502
2498
2503 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2499 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2504 execution starts, a message will be printed indicating the job
2500 execution starts, a message will be printed indicating the job
2505 number. If your job number is 5, you can use
2501 number. If your job number is 5, you can use
2506
2502
2507 myvar = jobs.result(5) or myvar = jobs[5].result
2503 myvar = jobs.result(5) or myvar = jobs[5].result
2508
2504
2509 to assign this result to variable 'myvar'.
2505 to assign this result to variable 'myvar'.
2510
2506
2511 IPython has a job manager, accessible via the 'jobs' object. You can
2507 IPython has a job manager, accessible via the 'jobs' object. You can
2512 type jobs? to get more information about it, and use jobs.<TAB> to see
2508 type jobs? to get more information about it, and use jobs.<TAB> to see
2513 its attributes. All attributes not starting with an underscore are
2509 its attributes. All attributes not starting with an underscore are
2514 meant for public use.
2510 meant for public use.
2515
2511
2516 In particular, look at the jobs.new() method, which is used to create
2512 In particular, look at the jobs.new() method, which is used to create
2517 new jobs. This magic %bg function is just a convenience wrapper
2513 new jobs. This magic %bg function is just a convenience wrapper
2518 around jobs.new(), for expression-based jobs. If you want to create a
2514 around jobs.new(), for expression-based jobs. If you want to create a
2519 new job with an explicit function object and arguments, you must call
2515 new job with an explicit function object and arguments, you must call
2520 jobs.new() directly.
2516 jobs.new() directly.
2521
2517
2522 The jobs.new docstring also describes in detail several important
2518 The jobs.new docstring also describes in detail several important
2523 caveats associated with a thread-based model for background job
2519 caveats associated with a thread-based model for background job
2524 execution. Type jobs.new? for details.
2520 execution. Type jobs.new? for details.
2525
2521
2526 You can check the status of all jobs with jobs.status().
2522 You can check the status of all jobs with jobs.status().
2527
2523
2528 The jobs variable is set by IPython into the Python builtin namespace.
2524 The jobs variable is set by IPython into the Python builtin namespace.
2529 If you ever declare a variable named 'jobs', you will shadow this
2525 If you ever declare a variable named 'jobs', you will shadow this
2530 name. You can either delete your global jobs variable to regain
2526 name. You can either delete your global jobs variable to regain
2531 access to the job manager, or make a new name and assign it manually
2527 access to the job manager, or make a new name and assign it manually
2532 to the manager (stored in IPython's namespace). For example, to
2528 to the manager (stored in IPython's namespace). For example, to
2533 assign the job manager to the Jobs name, use:
2529 assign the job manager to the Jobs name, use:
2534
2530
2535 Jobs = __builtins__.jobs"""
2531 Jobs = __builtins__.jobs"""
2536
2532
2537 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2533 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2538
2534
2539 def magic_store(self, parameter_s=''):
2535 def magic_store(self, parameter_s=''):
2540 """Lightweight persistence for python variables.
2536 """Lightweight persistence for python variables.
2541
2537
2542 Example:
2538 Example:
2543
2539
2544 ville@badger[~]|1> A = ['hello',10,'world']\\
2540 ville@badger[~]|1> A = ['hello',10,'world']\\
2545 ville@badger[~]|2> %store A\\
2541 ville@badger[~]|2> %store A\\
2546 ville@badger[~]|3> Exit
2542 ville@badger[~]|3> Exit
2547
2543
2548 (IPython session is closed and started again...)
2544 (IPython session is closed and started again...)
2549
2545
2550 ville@badger:~$ ipython -p pysh\\
2546 ville@badger:~$ ipython -p pysh\\
2551 ville@badger[~]|1> print A
2547 ville@badger[~]|1> print A
2552
2548
2553 ['hello', 10, 'world']
2549 ['hello', 10, 'world']
2554
2550
2555 Usage:
2551 Usage:
2556
2552
2557 %store - Show list of all variables and their current values\\
2553 %store - Show list of all variables and their current values\\
2558 %store <var> - Store the *current* value of the variable to disk\\
2554 %store <var> - Store the *current* value of the variable to disk\\
2559 %store -d - Remove the variable and its value from storage\\
2555 %store -d - Remove the variable and its value from storage\\
2560 %store -r - Remove all variables from storage
2556 %store -r - Remove all variables from storage
2561
2557
2562 It should be noted that if you change the value of a variable, you
2558 It should be noted that if you change the value of a variable, you
2563 need to %store it again if you want to persist the new value.
2559 need to %store it again if you want to persist the new value.
2564
2560
2565 Note also that the variables will need to be pickleable; most basic
2561 Note also that the variables will need to be pickleable; most basic
2566 python types can be safely %stored.
2562 python types can be safely %stored.
2567 """
2563 """
2568
2564
2569 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2565 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2570 # delete
2566 # delete
2571 if opts.has_key('d'):
2567 if opts.has_key('d'):
2572 try:
2568 try:
2573 todel = args[0]
2569 todel = args[0]
2574 except IndexError:
2570 except IndexError:
2575 error('You must provide the variable to forget')
2571 error('You must provide the variable to forget')
2576 else:
2572 else:
2577 try:
2573 try:
2578 del self.shell.persist['S:' + todel]
2574 del self.shell.persist['S:' + todel]
2579 except:
2575 except:
2580 error("Can't delete variable '%s'" % todel)
2576 error("Can't delete variable '%s'" % todel)
2581 # reset
2577 # reset
2582 elif opts.has_key('r'):
2578 elif opts.has_key('r'):
2583 for k in self.shell.persist.keys():
2579 for k in self.shell.persist.keys():
2584 if k.startswith('S:'):
2580 if k.startswith('S:'):
2585 del self.shell.persist[k]
2581 del self.shell.persist[k]
2586
2582
2587 # run without arguments -> list variables & values
2583 # run without arguments -> list variables & values
2588 elif not args:
2584 elif not args:
2589 vars = [v[2:] for v in self.shell.persist.keys()
2585 vars = [v[2:] for v in self.shell.persist.keys()
2590 if v.startswith('S:')]
2586 if v.startswith('S:')]
2591 vars.sort()
2587 vars.sort()
2592 if vars:
2588 if vars:
2593 size = max(map(len,vars))
2589 size = max(map(len,vars))
2594 else:
2590 else:
2595 size = 0
2591 size = 0
2596
2592
2597 print 'Stored variables and their in-memory values:'
2593 print 'Stored variables and their in-memory values:'
2598 fmt = '%-'+str(size)+'s -> %s'
2594 fmt = '%-'+str(size)+'s -> %s'
2599 get = self.shell.user_ns.get
2595 get = self.shell.user_ns.get
2600 for var in vars:
2596 for var in vars:
2601 # print 30 first characters from every var
2597 # print 30 first characters from every var
2602 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2598 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2603
2599
2604 # default action - store the variable
2600 # default action - store the variable
2605 else:
2601 else:
2606 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2602 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2607 self.shell.persist[ 'S:' + args[0] ] = pickled
2603 self.shell.persist[ 'S:' + args[0] ] = pickled
2608 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2604 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2609
2605
2610 def magic_bookmark(self, parameter_s=''):
2606 def magic_bookmark(self, parameter_s=''):
2611 """Manage IPython's bookmark system.
2607 """Manage IPython's bookmark system.
2612
2608
2613 %bookmark <name> - set bookmark to current dir
2609 %bookmark <name> - set bookmark to current dir
2614 %bookmark <name> <dir> - set bookmark to <dir>
2610 %bookmark <name> <dir> - set bookmark to <dir>
2615 %bookmark -l - list all bookmarks
2611 %bookmark -l - list all bookmarks
2616 %bookmark -d <name> - remove bookmark
2612 %bookmark -d <name> - remove bookmark
2617 %bookmark -r - remove all bookmarks
2613 %bookmark -r - remove all bookmarks
2618
2614
2619 You can later on access a bookmarked folder with:
2615 You can later on access a bookmarked folder with:
2620 %cd -b <name>
2616 %cd -b <name>
2621 or simply '%cd <name>' if there is no directory called <name> AND
2617 or simply '%cd <name>' if there is no directory called <name> AND
2622 there is such a bookmark defined.
2618 there is such a bookmark defined.
2623
2619
2624 Your bookmarks persist through IPython sessions, but they are
2620 Your bookmarks persist through IPython sessions, but they are
2625 associated with each profile."""
2621 associated with each profile."""
2626
2622
2627 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2623 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2628 if len(args) > 2:
2624 if len(args) > 2:
2629 error('You can only give at most two arguments')
2625 error('You can only give at most two arguments')
2630 return
2626 return
2631
2627
2632 bkms = self.shell.persist.get('bookmarks',{})
2628 bkms = self.shell.persist.get('bookmarks',{})
2633
2629
2634 if opts.has_key('d'):
2630 if opts.has_key('d'):
2635 try:
2631 try:
2636 todel = args[0]
2632 todel = args[0]
2637 except IndexError:
2633 except IndexError:
2638 error('You must provide a bookmark to delete')
2634 error('You must provide a bookmark to delete')
2639 else:
2635 else:
2640 try:
2636 try:
2641 del bkms[todel]
2637 del bkms[todel]
2642 except:
2638 except:
2643 error("Can't delete bookmark '%s'" % todel)
2639 error("Can't delete bookmark '%s'" % todel)
2644 elif opts.has_key('r'):
2640 elif opts.has_key('r'):
2645 bkms = {}
2641 bkms = {}
2646 elif opts.has_key('l'):
2642 elif opts.has_key('l'):
2647 bks = bkms.keys()
2643 bks = bkms.keys()
2648 bks.sort()
2644 bks.sort()
2649 if bks:
2645 if bks:
2650 size = max(map(len,bks))
2646 size = max(map(len,bks))
2651 else:
2647 else:
2652 size = 0
2648 size = 0
2653 fmt = '%-'+str(size)+'s -> %s'
2649 fmt = '%-'+str(size)+'s -> %s'
2654 print 'Current bookmarks:'
2650 print 'Current bookmarks:'
2655 for bk in bks:
2651 for bk in bks:
2656 print fmt % (bk,bkms[bk])
2652 print fmt % (bk,bkms[bk])
2657 else:
2653 else:
2658 if not args:
2654 if not args:
2659 error("You must specify the bookmark name")
2655 error("You must specify the bookmark name")
2660 elif len(args)==1:
2656 elif len(args)==1:
2661 bkms[args[0]] = os.getcwd()
2657 bkms[args[0]] = os.getcwd()
2662 elif len(args)==2:
2658 elif len(args)==2:
2663 bkms[args[0]] = args[1]
2659 bkms[args[0]] = args[1]
2664 self.shell.persist['bookmarks'] = bkms
2660 self.shell.persist['bookmarks'] = bkms
2665
2661
2666 def magic_pycat(self, parameter_s=''):
2662 def magic_pycat(self, parameter_s=''):
2667 """Show a syntax-highlighted file through a pager.
2663 """Show a syntax-highlighted file through a pager.
2668
2664
2669 This magic is similar to the cat utility, but it will assume the file
2665 This magic is similar to the cat utility, but it will assume the file
2670 to be Python source and will show it with syntax highlighting. """
2666 to be Python source and will show it with syntax highlighting. """
2671
2667
2672 filename = get_py_filename(parameter_s)
2668 filename = get_py_filename(parameter_s)
2673 page(self.shell.colorize(file_read(filename)),
2669 page(self.shell.colorize(file_read(filename)),
2674 screen_lines=self.shell.rc.screen_length)
2670 screen_lines=self.shell.rc.screen_length)
2675
2671
2676 # end Magic
2672 # end Magic
@@ -1,583 +1,583 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Classes for handling input/output prompts.
3 Classes for handling input/output prompts.
4
4
5 $Id: Prompts.py 966 2005-12-29 08:34:07Z fperez $"""
5 $Id: Prompts.py 975 2005-12-29 23:50:22Z fperez $"""
6
6
7 #*****************************************************************************
7 #*****************************************************************************
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 from IPython import Release
14 from IPython import Release
15 __author__ = '%s <%s>' % Release.authors['Fernando']
15 __author__ = '%s <%s>' % Release.authors['Fernando']
16 __license__ = Release.license
16 __license__ = Release.license
17 __version__ = Release.version
17 __version__ = Release.version
18
18
19 #****************************************************************************
19 #****************************************************************************
20 # Required modules
20 # Required modules
21 import __builtin__
21 import __builtin__
22 import os
22 import os
23 import socket
23 import socket
24 import sys
24 import sys
25 import time
25 import time
26 from pprint import pprint,pformat
26 from pprint import pprint,pformat
27
27
28 # IPython's own
28 # IPython's own
29 from IPython.genutils import *
30 from IPython.Struct import Struct
31 from IPython.Magic import Macro
32 from IPython.Itpl import ItplNS
33 from IPython import ColorANSI
29 from IPython import ColorANSI
30 from IPython.Itpl import ItplNS
31 from IPython.Struct import Struct
32 from IPython.macro import Macro
33 from IPython.genutils import *
34
34
35 #****************************************************************************
35 #****************************************************************************
36 #Color schemes for Prompts.
36 #Color schemes for Prompts.
37
37
38 PromptColors = ColorANSI.ColorSchemeTable()
38 PromptColors = ColorANSI.ColorSchemeTable()
39 InputColors = ColorANSI.InputTermColors # just a shorthand
39 InputColors = ColorANSI.InputTermColors # just a shorthand
40 Colors = ColorANSI.TermColors # just a shorthand
40 Colors = ColorANSI.TermColors # just a shorthand
41
41
42 PromptColors.add_scheme(ColorANSI.ColorScheme(
42 PromptColors.add_scheme(ColorANSI.ColorScheme(
43 'NoColor',
43 'NoColor',
44 in_prompt = InputColors.NoColor, # Input prompt
44 in_prompt = InputColors.NoColor, # Input prompt
45 in_number = InputColors.NoColor, # Input prompt number
45 in_number = InputColors.NoColor, # Input prompt number
46 in_prompt2 = InputColors.NoColor, # Continuation prompt
46 in_prompt2 = InputColors.NoColor, # Continuation prompt
47 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
47 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
48
48
49 out_prompt = Colors.NoColor, # Output prompt
49 out_prompt = Colors.NoColor, # Output prompt
50 out_number = Colors.NoColor, # Output prompt number
50 out_number = Colors.NoColor, # Output prompt number
51
51
52 normal = Colors.NoColor # color off (usu. Colors.Normal)
52 normal = Colors.NoColor # color off (usu. Colors.Normal)
53 ))
53 ))
54
54
55 # make some schemes as instances so we can copy them for modification easily:
55 # make some schemes as instances so we can copy them for modification easily:
56 __PColLinux = ColorANSI.ColorScheme(
56 __PColLinux = ColorANSI.ColorScheme(
57 'Linux',
57 'Linux',
58 in_prompt = InputColors.Green,
58 in_prompt = InputColors.Green,
59 in_number = InputColors.LightGreen,
59 in_number = InputColors.LightGreen,
60 in_prompt2 = InputColors.Green,
60 in_prompt2 = InputColors.Green,
61 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
61 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
62
62
63 out_prompt = Colors.Red,
63 out_prompt = Colors.Red,
64 out_number = Colors.LightRed,
64 out_number = Colors.LightRed,
65
65
66 normal = Colors.Normal
66 normal = Colors.Normal
67 )
67 )
68 # Don't forget to enter it into the table!
68 # Don't forget to enter it into the table!
69 PromptColors.add_scheme(__PColLinux)
69 PromptColors.add_scheme(__PColLinux)
70
70
71 # Slightly modified Linux for light backgrounds
71 # Slightly modified Linux for light backgrounds
72 __PColLightBG = __PColLinux.copy('LightBG')
72 __PColLightBG = __PColLinux.copy('LightBG')
73
73
74 __PColLightBG.colors.update(
74 __PColLightBG.colors.update(
75 in_prompt = InputColors.Blue,
75 in_prompt = InputColors.Blue,
76 in_number = InputColors.LightBlue,
76 in_number = InputColors.LightBlue,
77 in_prompt2 = InputColors.Blue
77 in_prompt2 = InputColors.Blue
78 )
78 )
79 PromptColors.add_scheme(__PColLightBG)
79 PromptColors.add_scheme(__PColLightBG)
80
80
81 del Colors,InputColors
81 del Colors,InputColors
82
82
83 #-----------------------------------------------------------------------------
83 #-----------------------------------------------------------------------------
84 def multiple_replace(dict, text):
84 def multiple_replace(dict, text):
85 """ Replace in 'text' all occurences of any key in the given
85 """ Replace in 'text' all occurences of any key in the given
86 dictionary by its corresponding value. Returns the new string."""
86 dictionary by its corresponding value. Returns the new string."""
87
87
88 # Function by Xavier Defrang, originally found at:
88 # Function by Xavier Defrang, originally found at:
89 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
89 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
90
90
91 # Create a regular expression from the dictionary keys
91 # Create a regular expression from the dictionary keys
92 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
92 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
93 # For each match, look-up corresponding value in dictionary
93 # For each match, look-up corresponding value in dictionary
94 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
94 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
95
95
96 #-----------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------
97 # Special characters that can be used in prompt templates, mainly bash-like
97 # Special characters that can be used in prompt templates, mainly bash-like
98
98
99 # If $HOME isn't defined (Windows), make it an absurd string so that it can
99 # If $HOME isn't defined (Windows), make it an absurd string so that it can
100 # never be expanded out into '~'. Basically anything which can never be a
100 # never be expanded out into '~'. Basically anything which can never be a
101 # reasonable directory name will do, we just want the $HOME -> '~' operation
101 # reasonable directory name will do, we just want the $HOME -> '~' operation
102 # to become a no-op. We pre-compute $HOME here so it's not done on every
102 # to become a no-op. We pre-compute $HOME here so it's not done on every
103 # prompt call.
103 # prompt call.
104
104
105 # FIXME:
105 # FIXME:
106
106
107 # - This should be turned into a class which does proper namespace management,
107 # - This should be turned into a class which does proper namespace management,
108 # since the prompt specials need to be evaluated in a certain namespace.
108 # since the prompt specials need to be evaluated in a certain namespace.
109 # Currently it's just globals, which need to be managed manually by code
109 # Currently it's just globals, which need to be managed manually by code
110 # below.
110 # below.
111
111
112 # - I also need to split up the color schemes from the prompt specials
112 # - I also need to split up the color schemes from the prompt specials
113 # somehow. I don't have a clean design for that quite yet.
113 # somehow. I don't have a clean design for that quite yet.
114
114
115 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
115 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
116
116
117 # We precompute a few more strings here for the prompt_specials, which are
117 # We precompute a few more strings here for the prompt_specials, which are
118 # fixed once ipython starts. This reduces the runtime overhead of computing
118 # fixed once ipython starts. This reduces the runtime overhead of computing
119 # prompt strings.
119 # prompt strings.
120 USER = os.environ.get("USER")
120 USER = os.environ.get("USER")
121 HOSTNAME = socket.gethostname()
121 HOSTNAME = socket.gethostname()
122 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
122 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
123 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
123 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
124
124
125 prompt_specials_color = {
125 prompt_specials_color = {
126 # Prompt/history count
126 # Prompt/history count
127 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
127 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
128 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
128 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
129 # Prompt/history count, with the actual digits replaced by dots. Used
129 # Prompt/history count, with the actual digits replaced by dots. Used
130 # mainly in continuation prompts (prompt_in2)
130 # mainly in continuation prompts (prompt_in2)
131 '\\D': '${"."*len(str(self.cache.prompt_count))}',
131 '\\D': '${"."*len(str(self.cache.prompt_count))}',
132 # Current working directory
132 # Current working directory
133 '\\w': '${os.getcwd()}',
133 '\\w': '${os.getcwd()}',
134 # Current time
134 # Current time
135 '\\t' : '${time.strftime("%H:%M:%S")}',
135 '\\t' : '${time.strftime("%H:%M:%S")}',
136 # Basename of current working directory.
136 # Basename of current working directory.
137 # (use os.sep to make this portable across OSes)
137 # (use os.sep to make this portable across OSes)
138 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
138 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
139 # These X<N> are an extension to the normal bash prompts. They return
139 # These X<N> are an extension to the normal bash prompts. They return
140 # N terms of the path, after replacing $HOME with '~'
140 # N terms of the path, after replacing $HOME with '~'
141 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
141 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
142 '\\X1': '${self.cwd_filt(1)}',
142 '\\X1': '${self.cwd_filt(1)}',
143 '\\X2': '${self.cwd_filt(2)}',
143 '\\X2': '${self.cwd_filt(2)}',
144 '\\X3': '${self.cwd_filt(3)}',
144 '\\X3': '${self.cwd_filt(3)}',
145 '\\X4': '${self.cwd_filt(4)}',
145 '\\X4': '${self.cwd_filt(4)}',
146 '\\X5': '${self.cwd_filt(5)}',
146 '\\X5': '${self.cwd_filt(5)}',
147 # Y<N> are similar to X<N>, but they show '~' if it's the directory
147 # Y<N> are similar to X<N>, but they show '~' if it's the directory
148 # N+1 in the list. Somewhat like %cN in tcsh.
148 # N+1 in the list. Somewhat like %cN in tcsh.
149 '\\Y0': '${self.cwd_filt2(0)}',
149 '\\Y0': '${self.cwd_filt2(0)}',
150 '\\Y1': '${self.cwd_filt2(1)}',
150 '\\Y1': '${self.cwd_filt2(1)}',
151 '\\Y2': '${self.cwd_filt2(2)}',
151 '\\Y2': '${self.cwd_filt2(2)}',
152 '\\Y3': '${self.cwd_filt2(3)}',
152 '\\Y3': '${self.cwd_filt2(3)}',
153 '\\Y4': '${self.cwd_filt2(4)}',
153 '\\Y4': '${self.cwd_filt2(4)}',
154 '\\Y5': '${self.cwd_filt2(5)}',
154 '\\Y5': '${self.cwd_filt2(5)}',
155 # Hostname up to first .
155 # Hostname up to first .
156 '\\h': HOSTNAME_SHORT,
156 '\\h': HOSTNAME_SHORT,
157 # Full hostname
157 # Full hostname
158 '\\H': HOSTNAME,
158 '\\H': HOSTNAME,
159 # Username of current user
159 # Username of current user
160 '\\u': USER,
160 '\\u': USER,
161 # Escaped '\'
161 # Escaped '\'
162 '\\\\': '\\',
162 '\\\\': '\\',
163 # Newline
163 # Newline
164 '\\n': '\n',
164 '\\n': '\n',
165 # Carriage return
165 # Carriage return
166 '\\r': '\r',
166 '\\r': '\r',
167 # Release version
167 # Release version
168 '\\v': __version__,
168 '\\v': __version__,
169 # Root symbol ($ or #)
169 # Root symbol ($ or #)
170 '\\$': ROOT_SYMBOL,
170 '\\$': ROOT_SYMBOL,
171 }
171 }
172
172
173 # A copy of the prompt_specials dictionary but with all color escapes removed,
173 # A copy of the prompt_specials dictionary but with all color escapes removed,
174 # so we can correctly compute the prompt length for the auto_rewrite method.
174 # so we can correctly compute the prompt length for the auto_rewrite method.
175 prompt_specials_nocolor = prompt_specials_color.copy()
175 prompt_specials_nocolor = prompt_specials_color.copy()
176 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
176 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
177 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
177 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
178
178
179 # Add in all the InputTermColors color escapes as valid prompt characters.
179 # Add in all the InputTermColors color escapes as valid prompt characters.
180 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
180 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
181 # with a color name which may begin with a letter used by any other of the
181 # with a color name which may begin with a letter used by any other of the
182 # allowed specials. This of course means that \\C will never be allowed for
182 # allowed specials. This of course means that \\C will never be allowed for
183 # anything else.
183 # anything else.
184 input_colors = ColorANSI.InputTermColors
184 input_colors = ColorANSI.InputTermColors
185 for _color in dir(input_colors):
185 for _color in dir(input_colors):
186 if _color[0] != '_':
186 if _color[0] != '_':
187 c_name = '\\C_'+_color
187 c_name = '\\C_'+_color
188 prompt_specials_color[c_name] = getattr(input_colors,_color)
188 prompt_specials_color[c_name] = getattr(input_colors,_color)
189 prompt_specials_nocolor[c_name] = ''
189 prompt_specials_nocolor[c_name] = ''
190
190
191 # we default to no color for safety. Note that prompt_specials is a global
191 # we default to no color for safety. Note that prompt_specials is a global
192 # variable used by all prompt objects.
192 # variable used by all prompt objects.
193 prompt_specials = prompt_specials_nocolor
193 prompt_specials = prompt_specials_nocolor
194
194
195 #-----------------------------------------------------------------------------
195 #-----------------------------------------------------------------------------
196 def str_safe(arg):
196 def str_safe(arg):
197 """Convert to a string, without ever raising an exception.
197 """Convert to a string, without ever raising an exception.
198
198
199 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
199 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
200 error message."""
200 error message."""
201
201
202 try:
202 try:
203 out = str(arg)
203 out = str(arg)
204 except UnicodeError:
204 except UnicodeError:
205 try:
205 try:
206 out = arg.encode('utf_8','replace')
206 out = arg.encode('utf_8','replace')
207 except Exception,msg:
207 except Exception,msg:
208 # let's keep this little duplication here, so that the most common
208 # let's keep this little duplication here, so that the most common
209 # case doesn't suffer from a double try wrapping.
209 # case doesn't suffer from a double try wrapping.
210 out = '<ERROR: %s>' % msg
210 out = '<ERROR: %s>' % msg
211 except Exception,msg:
211 except Exception,msg:
212 out = '<ERROR: %s>' % msg
212 out = '<ERROR: %s>' % msg
213 return out
213 return out
214
214
215 class BasePrompt:
215 class BasePrompt:
216 """Interactive prompt similar to Mathematica's."""
216 """Interactive prompt similar to Mathematica's."""
217 def __init__(self,cache,sep,prompt,pad_left=False):
217 def __init__(self,cache,sep,prompt,pad_left=False):
218
218
219 # Hack: we access information about the primary prompt through the
219 # Hack: we access information about the primary prompt through the
220 # cache argument. We need this, because we want the secondary prompt
220 # cache argument. We need this, because we want the secondary prompt
221 # to be aligned with the primary one. Color table info is also shared
221 # to be aligned with the primary one. Color table info is also shared
222 # by all prompt classes through the cache. Nice OO spaghetti code!
222 # by all prompt classes through the cache. Nice OO spaghetti code!
223 self.cache = cache
223 self.cache = cache
224 self.sep = sep
224 self.sep = sep
225
225
226 # regexp to count the number of spaces at the end of a prompt
226 # regexp to count the number of spaces at the end of a prompt
227 # expression, useful for prompt auto-rewriting
227 # expression, useful for prompt auto-rewriting
228 self.rspace = re.compile(r'(\s*)$')
228 self.rspace = re.compile(r'(\s*)$')
229 # Flag to left-pad prompt strings to match the length of the primary
229 # Flag to left-pad prompt strings to match the length of the primary
230 # prompt
230 # prompt
231 self.pad_left = pad_left
231 self.pad_left = pad_left
232 # Set template to create each actual prompt (where numbers change)
232 # Set template to create each actual prompt (where numbers change)
233 self.p_template = prompt
233 self.p_template = prompt
234 self.set_p_str()
234 self.set_p_str()
235
235
236 def set_p_str(self):
236 def set_p_str(self):
237 """ Set the interpolating prompt strings.
237 """ Set the interpolating prompt strings.
238
238
239 This must be called every time the color settings change, because the
239 This must be called every time the color settings change, because the
240 prompt_specials global may have changed."""
240 prompt_specials global may have changed."""
241
241
242 import os,time # needed in locals for prompt string handling
242 import os,time # needed in locals for prompt string handling
243 loc = locals()
243 loc = locals()
244 self.p_str = ItplNS('%s%s%s' %
244 self.p_str = ItplNS('%s%s%s' %
245 ('${self.sep}${self.col_p}',
245 ('${self.sep}${self.col_p}',
246 multiple_replace(prompt_specials, self.p_template),
246 multiple_replace(prompt_specials, self.p_template),
247 '${self.col_norm}'),self.cache.user_ns,loc)
247 '${self.col_norm}'),self.cache.user_ns,loc)
248
248
249 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
249 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
250 self.p_template),
250 self.p_template),
251 self.cache.user_ns,loc)
251 self.cache.user_ns,loc)
252
252
253 def write(self,msg): # dbg
253 def write(self,msg): # dbg
254 sys.stdout.write(msg)
254 sys.stdout.write(msg)
255 return ''
255 return ''
256
256
257 def __str__(self):
257 def __str__(self):
258 """Return a string form of the prompt.
258 """Return a string form of the prompt.
259
259
260 This for is useful for continuation and output prompts, since it is
260 This for is useful for continuation and output prompts, since it is
261 left-padded to match lengths with the primary one (if the
261 left-padded to match lengths with the primary one (if the
262 self.pad_left attribute is set)."""
262 self.pad_left attribute is set)."""
263
263
264 out_str = str_safe(self.p_str)
264 out_str = str_safe(self.p_str)
265 if self.pad_left:
265 if self.pad_left:
266 # We must find the amount of padding required to match lengths,
266 # We must find the amount of padding required to match lengths,
267 # taking the color escapes (which are invisible on-screen) into
267 # taking the color escapes (which are invisible on-screen) into
268 # account.
268 # account.
269 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
269 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
270 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
270 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
271 return format % out_str
271 return format % out_str
272 else:
272 else:
273 return out_str
273 return out_str
274
274
275 # these path filters are put in as methods so that we can control the
275 # these path filters are put in as methods so that we can control the
276 # namespace where the prompt strings get evaluated
276 # namespace where the prompt strings get evaluated
277 def cwd_filt(self,depth):
277 def cwd_filt(self,depth):
278 """Return the last depth elements of the current working directory.
278 """Return the last depth elements of the current working directory.
279
279
280 $HOME is always replaced with '~'.
280 $HOME is always replaced with '~'.
281 If depth==0, the full path is returned."""
281 If depth==0, the full path is returned."""
282
282
283 cwd = os.getcwd().replace(HOME,"~")
283 cwd = os.getcwd().replace(HOME,"~")
284 out = os.sep.join(cwd.split(os.sep)[-depth:])
284 out = os.sep.join(cwd.split(os.sep)[-depth:])
285 if out:
285 if out:
286 return out
286 return out
287 else:
287 else:
288 return os.sep
288 return os.sep
289
289
290 def cwd_filt2(self,depth):
290 def cwd_filt2(self,depth):
291 """Return the last depth elements of the current working directory.
291 """Return the last depth elements of the current working directory.
292
292
293 $HOME is always replaced with '~'.
293 $HOME is always replaced with '~'.
294 If depth==0, the full path is returned."""
294 If depth==0, the full path is returned."""
295
295
296 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
296 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
297 if '~' in cwd and len(cwd) == depth+1:
297 if '~' in cwd and len(cwd) == depth+1:
298 depth += 1
298 depth += 1
299 out = os.sep.join(cwd[-depth:])
299 out = os.sep.join(cwd[-depth:])
300 if out:
300 if out:
301 return out
301 return out
302 else:
302 else:
303 return os.sep
303 return os.sep
304
304
305 class Prompt1(BasePrompt):
305 class Prompt1(BasePrompt):
306 """Input interactive prompt similar to Mathematica's."""
306 """Input interactive prompt similar to Mathematica's."""
307
307
308 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
308 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
309 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
309 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
310
310
311 def set_colors(self):
311 def set_colors(self):
312 self.set_p_str()
312 self.set_p_str()
313 Colors = self.cache.color_table.active_colors # shorthand
313 Colors = self.cache.color_table.active_colors # shorthand
314 self.col_p = Colors.in_prompt
314 self.col_p = Colors.in_prompt
315 self.col_num = Colors.in_number
315 self.col_num = Colors.in_number
316 self.col_norm = Colors.in_normal
316 self.col_norm = Colors.in_normal
317 # We need a non-input version of these escapes for the '--->'
317 # We need a non-input version of these escapes for the '--->'
318 # auto-call prompts used in the auto_rewrite() method.
318 # auto-call prompts used in the auto_rewrite() method.
319 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
319 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
320 self.col_norm_ni = Colors.normal
320 self.col_norm_ni = Colors.normal
321
321
322 def __str__(self):
322 def __str__(self):
323 self.cache.prompt_count += 1
323 self.cache.prompt_count += 1
324 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
324 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
325 return str_safe(self.p_str)
325 return str_safe(self.p_str)
326
326
327 def auto_rewrite(self):
327 def auto_rewrite(self):
328 """Print a string of the form '--->' which lines up with the previous
328 """Print a string of the form '--->' which lines up with the previous
329 input string. Useful for systems which re-write the user input when
329 input string. Useful for systems which re-write the user input when
330 handling automatically special syntaxes."""
330 handling automatically special syntaxes."""
331
331
332 curr = str(self.cache.last_prompt)
332 curr = str(self.cache.last_prompt)
333 nrspaces = len(self.rspace.search(curr).group())
333 nrspaces = len(self.rspace.search(curr).group())
334 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
334 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
335 ' '*nrspaces,self.col_norm_ni)
335 ' '*nrspaces,self.col_norm_ni)
336
336
337 class PromptOut(BasePrompt):
337 class PromptOut(BasePrompt):
338 """Output interactive prompt similar to Mathematica's."""
338 """Output interactive prompt similar to Mathematica's."""
339
339
340 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
340 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
341 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
341 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
342 if not self.p_template:
342 if not self.p_template:
343 self.__str__ = lambda: ''
343 self.__str__ = lambda: ''
344
344
345 def set_colors(self):
345 def set_colors(self):
346 self.set_p_str()
346 self.set_p_str()
347 Colors = self.cache.color_table.active_colors # shorthand
347 Colors = self.cache.color_table.active_colors # shorthand
348 self.col_p = Colors.out_prompt
348 self.col_p = Colors.out_prompt
349 self.col_num = Colors.out_number
349 self.col_num = Colors.out_number
350 self.col_norm = Colors.normal
350 self.col_norm = Colors.normal
351
351
352 class Prompt2(BasePrompt):
352 class Prompt2(BasePrompt):
353 """Interactive continuation prompt."""
353 """Interactive continuation prompt."""
354
354
355 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
355 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
356 self.cache = cache
356 self.cache = cache
357 self.p_template = prompt
357 self.p_template = prompt
358 self.pad_left = pad_left
358 self.pad_left = pad_left
359 self.set_p_str()
359 self.set_p_str()
360
360
361 def set_p_str(self):
361 def set_p_str(self):
362 import os,time # needed in locals for prompt string handling
362 import os,time # needed in locals for prompt string handling
363 loc = locals()
363 loc = locals()
364 self.p_str = ItplNS('%s%s%s' %
364 self.p_str = ItplNS('%s%s%s' %
365 ('${self.col_p2}',
365 ('${self.col_p2}',
366 multiple_replace(prompt_specials, self.p_template),
366 multiple_replace(prompt_specials, self.p_template),
367 '$self.col_norm'),
367 '$self.col_norm'),
368 self.cache.user_ns,loc)
368 self.cache.user_ns,loc)
369 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
369 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
370 self.p_template),
370 self.p_template),
371 self.cache.user_ns,loc)
371 self.cache.user_ns,loc)
372
372
373 def set_colors(self):
373 def set_colors(self):
374 self.set_p_str()
374 self.set_p_str()
375 Colors = self.cache.color_table.active_colors
375 Colors = self.cache.color_table.active_colors
376 self.col_p2 = Colors.in_prompt2
376 self.col_p2 = Colors.in_prompt2
377 self.col_norm = Colors.in_normal
377 self.col_norm = Colors.in_normal
378 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
378 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
379 # updated their prompt_in2 definitions. Remove eventually.
379 # updated their prompt_in2 definitions. Remove eventually.
380 self.col_p = Colors.out_prompt
380 self.col_p = Colors.out_prompt
381 self.col_num = Colors.out_number
381 self.col_num = Colors.out_number
382
382
383 #-----------------------------------------------------------------------------
383 #-----------------------------------------------------------------------------
384 class CachedOutput:
384 class CachedOutput:
385 """Class for printing output from calculations while keeping a cache of
385 """Class for printing output from calculations while keeping a cache of
386 reults. It dynamically creates global variables prefixed with _ which
386 reults. It dynamically creates global variables prefixed with _ which
387 contain these results.
387 contain these results.
388
388
389 Meant to be used as a sys.displayhook replacement, providing numbered
389 Meant to be used as a sys.displayhook replacement, providing numbered
390 prompts and cache services.
390 prompts and cache services.
391
391
392 Initialize with initial and final values for cache counter (this defines
392 Initialize with initial and final values for cache counter (this defines
393 the maximum size of the cache."""
393 the maximum size of the cache."""
394
394
395 def __init__(self,shell,cache_size,Pprint,
395 def __init__(self,shell,cache_size,Pprint,
396 colors='NoColor',input_sep='\n',
396 colors='NoColor',input_sep='\n',
397 output_sep='\n',output_sep2='',
397 output_sep='\n',output_sep2='',
398 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
398 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
399
399
400 cache_size_min = 20
400 cache_size_min = 20
401 if cache_size <= 0:
401 if cache_size <= 0:
402 self.do_full_cache = 0
402 self.do_full_cache = 0
403 cache_size = 0
403 cache_size = 0
404 elif cache_size < cache_size_min:
404 elif cache_size < cache_size_min:
405 self.do_full_cache = 0
405 self.do_full_cache = 0
406 cache_size = 0
406 cache_size = 0
407 warn('caching was disabled (min value for cache size is %s).' %
407 warn('caching was disabled (min value for cache size is %s).' %
408 cache_size_min,level=3)
408 cache_size_min,level=3)
409 else:
409 else:
410 self.do_full_cache = 1
410 self.do_full_cache = 1
411
411
412 self.cache_size = cache_size
412 self.cache_size = cache_size
413 self.input_sep = input_sep
413 self.input_sep = input_sep
414
414
415 # we need a reference to the user-level namespace
415 # we need a reference to the user-level namespace
416 self.shell = shell
416 self.shell = shell
417 self.user_ns = shell.user_ns
417 self.user_ns = shell.user_ns
418 # and to the user's input
418 # and to the user's input
419 self.input_hist = shell.input_hist
419 self.input_hist = shell.input_hist
420 # and to the user's logger, for logging output
420 # and to the user's logger, for logging output
421 self.logger = shell.logger
421 self.logger = shell.logger
422
422
423 # Set input prompt strings and colors
423 # Set input prompt strings and colors
424 if cache_size == 0:
424 if cache_size == 0:
425 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
425 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
426 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
426 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
427 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
427 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
428 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
428 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
429 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
429 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
430
430
431 self.color_table = PromptColors
431 self.color_table = PromptColors
432 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
432 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
433 pad_left=pad_left)
433 pad_left=pad_left)
434 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
434 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
435 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
435 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
436 pad_left=pad_left)
436 pad_left=pad_left)
437 self.set_colors(colors)
437 self.set_colors(colors)
438
438
439 # other more normal stuff
439 # other more normal stuff
440 # b/c each call to the In[] prompt raises it by 1, even the first.
440 # b/c each call to the In[] prompt raises it by 1, even the first.
441 self.prompt_count = 0
441 self.prompt_count = 0
442 self.cache_count = 1
442 self.cache_count = 1
443 # Store the last prompt string each time, we need it for aligning
443 # Store the last prompt string each time, we need it for aligning
444 # continuation and auto-rewrite prompts
444 # continuation and auto-rewrite prompts
445 self.last_prompt = ''
445 self.last_prompt = ''
446 self.entries = [None] # output counter starts at 1 for the user
446 self.entries = [None] # output counter starts at 1 for the user
447 self.Pprint = Pprint
447 self.Pprint = Pprint
448 self.output_sep = output_sep
448 self.output_sep = output_sep
449 self.output_sep2 = output_sep2
449 self.output_sep2 = output_sep2
450 self._,self.__,self.___ = '','',''
450 self._,self.__,self.___ = '','',''
451 self.pprint_types = map(type,[(),[],{}])
451 self.pprint_types = map(type,[(),[],{}])
452
452
453 # these are deliberately global:
453 # these are deliberately global:
454 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
454 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
455 self.user_ns.update(to_user_ns)
455 self.user_ns.update(to_user_ns)
456
456
457 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
457 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
458 if p_str is None:
458 if p_str is None:
459 if self.do_full_cache:
459 if self.do_full_cache:
460 return cache_def
460 return cache_def
461 else:
461 else:
462 return no_cache_def
462 return no_cache_def
463 else:
463 else:
464 return p_str
464 return p_str
465
465
466 def set_colors(self,colors):
466 def set_colors(self,colors):
467 """Set the active color scheme and configure colors for the three
467 """Set the active color scheme and configure colors for the three
468 prompt subsystems."""
468 prompt subsystems."""
469
469
470 # FIXME: the prompt_specials global should be gobbled inside this
470 # FIXME: the prompt_specials global should be gobbled inside this
471 # class instead. Do it when cleaning up the whole 3-prompt system.
471 # class instead. Do it when cleaning up the whole 3-prompt system.
472 global prompt_specials
472 global prompt_specials
473 if colors.lower()=='nocolor':
473 if colors.lower()=='nocolor':
474 prompt_specials = prompt_specials_nocolor
474 prompt_specials = prompt_specials_nocolor
475 else:
475 else:
476 prompt_specials = prompt_specials_color
476 prompt_specials = prompt_specials_color
477
477
478 self.color_table.set_active_scheme(colors)
478 self.color_table.set_active_scheme(colors)
479 self.prompt1.set_colors()
479 self.prompt1.set_colors()
480 self.prompt2.set_colors()
480 self.prompt2.set_colors()
481 self.prompt_out.set_colors()
481 self.prompt_out.set_colors()
482
482
483 def __call__(self,arg=None):
483 def __call__(self,arg=None):
484 """Printing with history cache management.
484 """Printing with history cache management.
485
485
486 This is invoked everytime the interpreter needs to print, and is
486 This is invoked everytime the interpreter needs to print, and is
487 activated by setting the variable sys.displayhook to it."""
487 activated by setting the variable sys.displayhook to it."""
488
488
489 # If something injected a '_' variable in __builtin__, delete
489 # If something injected a '_' variable in __builtin__, delete
490 # ipython's automatic one so we don't clobber that. gettext() in
490 # ipython's automatic one so we don't clobber that. gettext() in
491 # particular uses _, so we need to stay away from it.
491 # particular uses _, so we need to stay away from it.
492 if '_' in __builtin__.__dict__:
492 if '_' in __builtin__.__dict__:
493 try:
493 try:
494 del self.user_ns['_']
494 del self.user_ns['_']
495 except KeyError:
495 except KeyError:
496 pass
496 pass
497 if arg is not None:
497 if arg is not None:
498 cout_write = Term.cout.write # fast lookup
498 cout_write = Term.cout.write # fast lookup
499 # first handle the cache and counters
499 # first handle the cache and counters
500 # but avoid recursive reference when displaying _oh/Out
500 # but avoid recursive reference when displaying _oh/Out
501 if arg is not self.user_ns['_oh']:
501 if arg is not self.user_ns['_oh']:
502 self.update(arg)
502 self.update(arg)
503 # do not print output if input ends in ';'
503 # do not print output if input ends in ';'
504 if self.input_hist[self.prompt_count].endswith(';\n'):
504 if self.input_hist[self.prompt_count].endswith(';\n'):
505 return
505 return
506 # don't use print, puts an extra space
506 # don't use print, puts an extra space
507 cout_write(self.output_sep)
507 cout_write(self.output_sep)
508 if self.do_full_cache:
508 if self.do_full_cache:
509 cout_write(str(self.prompt_out))
509 cout_write(str(self.prompt_out))
510
510
511 if isinstance(arg,Macro):
511 if isinstance(arg,Macro):
512 print 'Executing Macro...'
512 print 'Executing Macro...'
513 # in case the macro takes a long time to execute
513 # in case the macro takes a long time to execute
514 Term.cout.flush()
514 Term.cout.flush()
515 self.shell.runlines(arg.value)
515 self.shell.runlines(arg.value)
516 return None
516 return None
517
517
518 # and now call a possibly user-defined print mechanism
518 # and now call a possibly user-defined print mechanism
519 self.display(arg)
519 self.display(arg)
520 if self.logger.log_output:
520 if self.logger.log_output:
521 self.logger.log_write(repr(arg),'output')
521 self.logger.log_write(repr(arg),'output')
522 cout_write(self.output_sep2)
522 cout_write(self.output_sep2)
523 Term.cout.flush()
523 Term.cout.flush()
524
524
525 def _display(self,arg):
525 def _display(self,arg):
526 """Default printer method, uses pprint.
526 """Default printer method, uses pprint.
527
527
528 This can be over-ridden by the users to implement special formatting
528 This can be over-ridden by the users to implement special formatting
529 of certain types of output."""
529 of certain types of output."""
530
530
531 if self.Pprint:
531 if self.Pprint:
532 out = pformat(arg)
532 out = pformat(arg)
533 if '\n' in out:
533 if '\n' in out:
534 # So that multi-line strings line up with the left column of
534 # So that multi-line strings line up with the left column of
535 # the screen, instead of having the output prompt mess up
535 # the screen, instead of having the output prompt mess up
536 # their first line.
536 # their first line.
537 Term.cout.write('\n')
537 Term.cout.write('\n')
538 print >>Term.cout, out
538 print >>Term.cout, out
539 else:
539 else:
540 print >>Term.cout, arg
540 print >>Term.cout, arg
541
541
542 # Assign the default display method:
542 # Assign the default display method:
543 display = _display
543 display = _display
544
544
545 def update(self,arg):
545 def update(self,arg):
546 #print '***cache_count', self.cache_count # dbg
546 #print '***cache_count', self.cache_count # dbg
547 if self.cache_count >= self.cache_size and self.do_full_cache:
547 if self.cache_count >= self.cache_size and self.do_full_cache:
548 self.flush()
548 self.flush()
549 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
549 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
550 # we cause buggy behavior for things like gettext).
550 # we cause buggy behavior for things like gettext).
551 if '_' not in __builtin__.__dict__:
551 if '_' not in __builtin__.__dict__:
552 self.___ = self.__
552 self.___ = self.__
553 self.__ = self._
553 self.__ = self._
554 self._ = arg
554 self._ = arg
555 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
555 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
556
556
557 # hackish access to top-level namespace to create _1,_2... dynamically
557 # hackish access to top-level namespace to create _1,_2... dynamically
558 to_main = {}
558 to_main = {}
559 if self.do_full_cache:
559 if self.do_full_cache:
560 self.cache_count += 1
560 self.cache_count += 1
561 self.entries.append(arg)
561 self.entries.append(arg)
562 new_result = '_'+`self.prompt_count`
562 new_result = '_'+`self.prompt_count`
563 to_main[new_result] = self.entries[-1]
563 to_main[new_result] = self.entries[-1]
564 self.user_ns.update(to_main)
564 self.user_ns.update(to_main)
565 self.user_ns['_oh'][self.prompt_count] = arg
565 self.user_ns['_oh'][self.prompt_count] = arg
566
566
567 def flush(self):
567 def flush(self):
568 if not self.do_full_cache:
568 if not self.do_full_cache:
569 raise ValueError,"You shouldn't have reached the cache flush "\
569 raise ValueError,"You shouldn't have reached the cache flush "\
570 "if full caching is not enabled!"
570 "if full caching is not enabled!"
571 warn('Output cache limit (currently '+\
571 warn('Output cache limit (currently '+\
572 `self.cache_count`+' entries) hit.\n'
572 `self.cache_count`+' entries) hit.\n'
573 'Flushing cache and resetting history counter...\n'
573 'Flushing cache and resetting history counter...\n'
574 'The only history variables available will be _,__,___ and _1\n'
574 'The only history variables available will be _,__,___ and _1\n'
575 'with the current result.')
575 'with the current result.')
576 # delete auto-generated vars from global namespace
576 # delete auto-generated vars from global namespace
577 for n in range(1,self.prompt_count + 1):
577 for n in range(1,self.prompt_count + 1):
578 key = '_'+`n`
578 key = '_'+`n`
579 try:
579 try:
580 del self.user_ns[key]
580 del self.user_ns[key]
581 except: pass
581 except: pass
582 self.prompt_count = 1
582 self.prompt_count = 1
583 self.cache_count = 1
583 self.cache_count = 1
@@ -1,2051 +1,2056 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or newer.
5 Requires Python 2.1 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 $Id: iplib.py 968 2005-12-29 17:15:38Z fperez $
9 $Id: iplib.py 975 2005-12-29 23:50:22Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, all of that class has been copied
20 # Python standard library. Over time, all of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. At this point, there are no dependencies at all on the code
22 # subclassing. At this point, there are no dependencies at all on the code
23 # module anymore (it is not even imported). The Python License (sec. 2)
23 # module anymore (it is not even imported). The Python License (sec. 2)
24 # allows for this, but it's always nice to acknowledge credit where credit is
24 # allows for this, but it's always nice to acknowledge credit where credit is
25 # due.
25 # due.
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 #****************************************************************************
28 #****************************************************************************
29 # Modules and globals
29 # Modules and globals
30
30
31 from __future__ import generators # for 2.2 backwards-compatibility
31 from __future__ import generators # for 2.2 backwards-compatibility
32
32
33 from IPython import Release
33 from IPython import Release
34 __author__ = '%s <%s>\n%s <%s>' % \
34 __author__ = '%s <%s>\n%s <%s>' % \
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 __license__ = Release.license
36 __license__ = Release.license
37 __version__ = Release.version
37 __version__ = Release.version
38
38
39 # Python standard modules
39 # Python standard modules
40 import __main__
40 import __main__
41 import __builtin__
41 import __builtin__
42 import StringIO
42 import StringIO
43 import bdb
43 import bdb
44 import cPickle as pickle
44 import cPickle as pickle
45 import codeop
45 import codeop
46 import exceptions
46 import exceptions
47 import glob
47 import glob
48 import inspect
48 import inspect
49 import keyword
49 import keyword
50 import new
50 import new
51 import os
51 import os
52 import pdb
52 import pdb
53 import pydoc
53 import pydoc
54 import re
54 import re
55 import shutil
55 import shutil
56 import string
56 import string
57 import sys
57 import sys
58 import traceback
58 import traceback
59 import types
59 import types
60
60
61 from pprint import pprint, pformat
61 from pprint import pprint, pformat
62
62
63 # IPython's own modules
63 # IPython's own modules
64 import IPython
64 import IPython
65 from IPython import OInspect,PyColorize,ultraTB
65 from IPython import OInspect,PyColorize,ultraTB
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 from IPython.FakeModule import FakeModule
67 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
69 from IPython.Logger import Logger
70 from IPython.Magic import Magic
70 from IPython.Magic import Magic
71 from IPython.Prompts import CachedOutput
71 from IPython.Prompts import CachedOutput
72 from IPython.Struct import Struct
72 from IPython.Struct import Struct
73 from IPython.background_jobs import BackgroundJobManager
73 from IPython.background_jobs import BackgroundJobManager
74 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.genutils import *
75 from IPython.genutils import *
76
76
77 # store the builtin raw_input globally, and use this always, in case user code
77 # store the builtin raw_input globally, and use this always, in case user code
78 # overwrites it (like wx.py.PyShell does)
78 # overwrites it (like wx.py.PyShell does)
79 raw_input_original = raw_input
79 raw_input_original = raw_input
80
80
81 # compiled regexps for autoindent management
82 ini_spaces_re = re.compile(r'^(\s+)')
83 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
84
81 #****************************************************************************
85 #****************************************************************************
82 # Some utility function definitions
86 # Some utility function definitions
83
87
84 def softspace(file, newvalue):
88 def softspace(file, newvalue):
85 """Copied from code.py, to remove the dependency"""
89 """Copied from code.py, to remove the dependency"""
86 oldvalue = 0
90 oldvalue = 0
87 try:
91 try:
88 oldvalue = file.softspace
92 oldvalue = file.softspace
89 except AttributeError:
93 except AttributeError:
90 pass
94 pass
91 try:
95 try:
92 file.softspace = newvalue
96 file.softspace = newvalue
93 except (AttributeError, TypeError):
97 except (AttributeError, TypeError):
94 # "attribute-less object" or "read-only attributes"
98 # "attribute-less object" or "read-only attributes"
95 pass
99 pass
96 return oldvalue
100 return oldvalue
97
101
98 #****************************************************************************
102 #****************************************************************************
99 # These special functions get installed in the builtin namespace, to provide
103 # These special functions get installed in the builtin namespace, to provide
100 # programmatic (pure python) access to magics and aliases. This is important
104 # programmatic (pure python) access to magics and aliases. This is important
101 # for logging, user scripting, and more.
105 # for logging, user scripting, and more.
102
106
103 def ipmagic(arg_s):
107 def ipmagic(arg_s):
104 """Call a magic function by name.
108 """Call a magic function by name.
105
109
106 Input: a string containing the name of the magic function to call and any
110 Input: a string containing the name of the magic function to call and any
107 additional arguments to be passed to the magic.
111 additional arguments to be passed to the magic.
108
112
109 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
113 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
110 prompt:
114 prompt:
111
115
112 In[1]: %name -opt foo bar
116 In[1]: %name -opt foo bar
113
117
114 To call a magic without arguments, simply use ipmagic('name').
118 To call a magic without arguments, simply use ipmagic('name').
115
119
116 This provides a proper Python function to call IPython's magics in any
120 This provides a proper Python function to call IPython's magics in any
117 valid Python code you can type at the interpreter, including loops and
121 valid Python code you can type at the interpreter, including loops and
118 compound statements. It is added by IPython to the Python builtin
122 compound statements. It is added by IPython to the Python builtin
119 namespace upon initialization."""
123 namespace upon initialization."""
120
124
121 args = arg_s.split(' ',1)
125 args = arg_s.split(' ',1)
122 magic_name = args[0]
126 magic_name = args[0]
123 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
127 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
124 magic_name = magic_name[1:]
128 magic_name = magic_name[1:]
125 try:
129 try:
126 magic_args = args[1]
130 magic_args = args[1]
127 except IndexError:
131 except IndexError:
128 magic_args = ''
132 magic_args = ''
129 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
133 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
130 if fn is None:
134 if fn is None:
131 error("Magic function `%s` not found." % magic_name)
135 error("Magic function `%s` not found." % magic_name)
132 else:
136 else:
133 magic_args = __IPYTHON__.var_expand(magic_args)
137 magic_args = __IPYTHON__.var_expand(magic_args)
134 return fn(magic_args)
138 return fn(magic_args)
135
139
136 def ipalias(arg_s):
140 def ipalias(arg_s):
137 """Call an alias by name.
141 """Call an alias by name.
138
142
139 Input: a string containing the name of the alias to call and any
143 Input: a string containing the name of the alias to call and any
140 additional arguments to be passed to the magic.
144 additional arguments to be passed to the magic.
141
145
142 ipalias('name -opt foo bar') is equivalent to typing at the ipython
146 ipalias('name -opt foo bar') is equivalent to typing at the ipython
143 prompt:
147 prompt:
144
148
145 In[1]: name -opt foo bar
149 In[1]: name -opt foo bar
146
150
147 To call an alias without arguments, simply use ipalias('name').
151 To call an alias without arguments, simply use ipalias('name').
148
152
149 This provides a proper Python function to call IPython's aliases in any
153 This provides a proper Python function to call IPython's aliases in any
150 valid Python code you can type at the interpreter, including loops and
154 valid Python code you can type at the interpreter, including loops and
151 compound statements. It is added by IPython to the Python builtin
155 compound statements. It is added by IPython to the Python builtin
152 namespace upon initialization."""
156 namespace upon initialization."""
153
157
154 args = arg_s.split(' ',1)
158 args = arg_s.split(' ',1)
155 alias_name = args[0]
159 alias_name = args[0]
156 try:
160 try:
157 alias_args = args[1]
161 alias_args = args[1]
158 except IndexError:
162 except IndexError:
159 alias_args = ''
163 alias_args = ''
160 if alias_name in __IPYTHON__.alias_table:
164 if alias_name in __IPYTHON__.alias_table:
161 __IPYTHON__.call_alias(alias_name,alias_args)
165 __IPYTHON__.call_alias(alias_name,alias_args)
162 else:
166 else:
163 error("Alias `%s` not found." % alias_name)
167 error("Alias `%s` not found." % alias_name)
164
168
165 #****************************************************************************
169 #****************************************************************************
166 # Local use exceptions
170 # Local use exceptions
167 class SpaceInInput(exceptions.Exception): pass
171 class SpaceInInput(exceptions.Exception): pass
168
172
169 #****************************************************************************
173 #****************************************************************************
170 # Local use classes
174 # Local use classes
171 class Bunch: pass
175 class Bunch: pass
172
176
173 class InputList(list):
177 class InputList(list):
174 """Class to store user input.
178 """Class to store user input.
175
179
176 It's basically a list, but slices return a string instead of a list, thus
180 It's basically a list, but slices return a string instead of a list, thus
177 allowing things like (assuming 'In' is an instance):
181 allowing things like (assuming 'In' is an instance):
178
182
179 exec In[4:7]
183 exec In[4:7]
180
184
181 or
185 or
182
186
183 exec In[5:9] + In[14] + In[21:25]"""
187 exec In[5:9] + In[14] + In[21:25]"""
184
188
185 def __getslice__(self,i,j):
189 def __getslice__(self,i,j):
186 return ''.join(list.__getslice__(self,i,j))
190 return ''.join(list.__getslice__(self,i,j))
187
191
188 class SyntaxTB(ultraTB.ListTB):
192 class SyntaxTB(ultraTB.ListTB):
189 """Extension which holds some state: the last exception value"""
193 """Extension which holds some state: the last exception value"""
190
194
191 def __init__(self,color_scheme = 'NoColor'):
195 def __init__(self,color_scheme = 'NoColor'):
192 ultraTB.ListTB.__init__(self,color_scheme)
196 ultraTB.ListTB.__init__(self,color_scheme)
193 self.last_syntax_error = None
197 self.last_syntax_error = None
194
198
195 def __call__(self, etype, value, elist):
199 def __call__(self, etype, value, elist):
196 self.last_syntax_error = value
200 self.last_syntax_error = value
197 ultraTB.ListTB.__call__(self,etype,value,elist)
201 ultraTB.ListTB.__call__(self,etype,value,elist)
198
202
199 def clear_err_state(self):
203 def clear_err_state(self):
200 """Return the current error state and clear it"""
204 """Return the current error state and clear it"""
201 e = self.last_syntax_error
205 e = self.last_syntax_error
202 self.last_syntax_error = None
206 self.last_syntax_error = None
203 return e
207 return e
204
208
205 #****************************************************************************
209 #****************************************************************************
206 # Main IPython class
210 # Main IPython class
207
211
208 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
212 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
209 # until a full rewrite is made. I've cleaned all cross-class uses of
213 # until a full rewrite is made. I've cleaned all cross-class uses of
210 # attributes and methods, but too much user code out there relies on the
214 # attributes and methods, but too much user code out there relies on the
211 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
215 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
212 #
216 #
213 # But at least now, all the pieces have been separated and we could, in
217 # But at least now, all the pieces have been separated and we could, in
214 # principle, stop using the mixin. This will ease the transition to the
218 # principle, stop using the mixin. This will ease the transition to the
215 # chainsaw branch.
219 # chainsaw branch.
216
220
217 # For reference, the following is the list of 'self.foo' uses in the Magic
221 # For reference, the following is the list of 'self.foo' uses in the Magic
218 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
222 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
219 # class, to prevent clashes.
223 # class, to prevent clashes.
220
224
221 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
225 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
222 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
226 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
223 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
227 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
224 # 'self.value']
228 # 'self.value']
225
229
226 class InteractiveShell(Magic):
230 class InteractiveShell(Magic):
227 """An enhanced console for Python."""
231 """An enhanced console for Python."""
228
232
229 # class attribute to indicate whether the class supports threads or not.
233 # class attribute to indicate whether the class supports threads or not.
230 # Subclasses with thread support should override this as needed.
234 # Subclasses with thread support should override this as needed.
231 isthreaded = False
235 isthreaded = False
232
236
233 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
237 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
234 user_ns = None,user_global_ns=None,banner2='',
238 user_ns = None,user_global_ns=None,banner2='',
235 custom_exceptions=((),None),embedded=False):
239 custom_exceptions=((),None),embedded=False):
236
240
237 # some minimal strict typechecks. For some core data structures, I
241 # some minimal strict typechecks. For some core data structures, I
238 # want actual basic python types, not just anything that looks like
242 # want actual basic python types, not just anything that looks like
239 # one. This is especially true for namespaces.
243 # one. This is especially true for namespaces.
240 for ns in (user_ns,user_global_ns):
244 for ns in (user_ns,user_global_ns):
241 if ns is not None and type(ns) != types.DictType:
245 if ns is not None and type(ns) != types.DictType:
242 raise TypeError,'namespace must be a dictionary'
246 raise TypeError,'namespace must be a dictionary'
243
247
244 # Put a reference to self in builtins so that any form of embedded or
248 # Put a reference to self in builtins so that any form of embedded or
245 # imported code can test for being inside IPython.
249 # imported code can test for being inside IPython.
246 __builtin__.__IPYTHON__ = self
250 __builtin__.__IPYTHON__ = self
247
251
248 # And load into builtins ipmagic/ipalias as well
252 # And load into builtins ipmagic/ipalias as well
249 __builtin__.ipmagic = ipmagic
253 __builtin__.ipmagic = ipmagic
250 __builtin__.ipalias = ipalias
254 __builtin__.ipalias = ipalias
251
255
252 # Add to __builtin__ other parts of IPython's public API
256 # Add to __builtin__ other parts of IPython's public API
253 __builtin__.ip_set_hook = self.set_hook
257 __builtin__.ip_set_hook = self.set_hook
254
258
255 # Keep in the builtins a flag for when IPython is active. We set it
259 # Keep in the builtins a flag for when IPython is active. We set it
256 # with setdefault so that multiple nested IPythons don't clobber one
260 # with setdefault so that multiple nested IPythons don't clobber one
257 # another. Each will increase its value by one upon being activated,
261 # another. Each will increase its value by one upon being activated,
258 # which also gives us a way to determine the nesting level.
262 # which also gives us a way to determine the nesting level.
259 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
263 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
260
264
261 # Do the intuitively correct thing for quit/exit: we remove the
265 # Do the intuitively correct thing for quit/exit: we remove the
262 # builtins if they exist, and our own prefilter routine will handle
266 # builtins if they exist, and our own prefilter routine will handle
263 # these special cases
267 # these special cases
264 try:
268 try:
265 del __builtin__.exit, __builtin__.quit
269 del __builtin__.exit, __builtin__.quit
266 except AttributeError:
270 except AttributeError:
267 pass
271 pass
268
272
269 # Store the actual shell's name
273 # Store the actual shell's name
270 self.name = name
274 self.name = name
271
275
272 # We need to know whether the instance is meant for embedding, since
276 # We need to know whether the instance is meant for embedding, since
273 # global/local namespaces need to be handled differently in that case
277 # global/local namespaces need to be handled differently in that case
274 self.embedded = embedded
278 self.embedded = embedded
275
279
276 # command compiler
280 # command compiler
277 self.compile = codeop.CommandCompiler()
281 self.compile = codeop.CommandCompiler()
278
282
279 # User input buffer
283 # User input buffer
280 self.buffer = []
284 self.buffer = []
281
285
282 # Default name given in compilation of code
286 # Default name given in compilation of code
283 self.filename = '<ipython console>'
287 self.filename = '<ipython console>'
284
288
285 # Create the namespace where the user will operate. user_ns is
289 # Create the namespace where the user will operate. user_ns is
286 # normally the only one used, and it is passed to the exec calls as
290 # normally the only one used, and it is passed to the exec calls as
287 # the locals argument. But we do carry a user_global_ns namespace
291 # the locals argument. But we do carry a user_global_ns namespace
288 # given as the exec 'globals' argument, This is useful in embedding
292 # given as the exec 'globals' argument, This is useful in embedding
289 # situations where the ipython shell opens in a context where the
293 # situations where the ipython shell opens in a context where the
290 # distinction between locals and globals is meaningful.
294 # distinction between locals and globals is meaningful.
291
295
292 # FIXME. For some strange reason, __builtins__ is showing up at user
296 # FIXME. For some strange reason, __builtins__ is showing up at user
293 # level as a dict instead of a module. This is a manual fix, but I
297 # level as a dict instead of a module. This is a manual fix, but I
294 # should really track down where the problem is coming from. Alex
298 # should really track down where the problem is coming from. Alex
295 # Schmolck reported this problem first.
299 # Schmolck reported this problem first.
296
300
297 # A useful post by Alex Martelli on this topic:
301 # A useful post by Alex Martelli on this topic:
298 # Re: inconsistent value from __builtins__
302 # Re: inconsistent value from __builtins__
299 # Von: Alex Martelli <aleaxit@yahoo.com>
303 # Von: Alex Martelli <aleaxit@yahoo.com>
300 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
304 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
301 # Gruppen: comp.lang.python
305 # Gruppen: comp.lang.python
302
306
303 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
307 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
304 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
308 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
305 # > <type 'dict'>
309 # > <type 'dict'>
306 # > >>> print type(__builtins__)
310 # > >>> print type(__builtins__)
307 # > <type 'module'>
311 # > <type 'module'>
308 # > Is this difference in return value intentional?
312 # > Is this difference in return value intentional?
309
313
310 # Well, it's documented that '__builtins__' can be either a dictionary
314 # Well, it's documented that '__builtins__' can be either a dictionary
311 # or a module, and it's been that way for a long time. Whether it's
315 # or a module, and it's been that way for a long time. Whether it's
312 # intentional (or sensible), I don't know. In any case, the idea is
316 # intentional (or sensible), I don't know. In any case, the idea is
313 # that if you need to access the built-in namespace directly, you
317 # that if you need to access the built-in namespace directly, you
314 # should start with "import __builtin__" (note, no 's') which will
318 # should start with "import __builtin__" (note, no 's') which will
315 # definitely give you a module. Yeah, it's somewhatΒ confusing:-(.
319 # definitely give you a module. Yeah, it's somewhatΒ confusing:-(.
316
320
317 if user_ns is None:
321 if user_ns is None:
318 # Set __name__ to __main__ to better match the behavior of the
322 # Set __name__ to __main__ to better match the behavior of the
319 # normal interpreter.
323 # normal interpreter.
320 user_ns = {'__name__' :'__main__',
324 user_ns = {'__name__' :'__main__',
321 '__builtins__' : __builtin__,
325 '__builtins__' : __builtin__,
322 }
326 }
323
327
324 if user_global_ns is None:
328 if user_global_ns is None:
325 user_global_ns = {}
329 user_global_ns = {}
326
330
327 # Assign namespaces
331 # Assign namespaces
328 # This is the namespace where all normal user variables live
332 # This is the namespace where all normal user variables live
329 self.user_ns = user_ns
333 self.user_ns = user_ns
330 # Embedded instances require a separate namespace for globals.
334 # Embedded instances require a separate namespace for globals.
331 # Normally this one is unused by non-embedded instances.
335 # Normally this one is unused by non-embedded instances.
332 self.user_global_ns = user_global_ns
336 self.user_global_ns = user_global_ns
333 # A namespace to keep track of internal data structures to prevent
337 # A namespace to keep track of internal data structures to prevent
334 # them from cluttering user-visible stuff. Will be updated later
338 # them from cluttering user-visible stuff. Will be updated later
335 self.internal_ns = {}
339 self.internal_ns = {}
336
340
337 # Namespace of system aliases. Each entry in the alias
341 # Namespace of system aliases. Each entry in the alias
338 # table must be a 2-tuple of the form (N,name), where N is the number
342 # table must be a 2-tuple of the form (N,name), where N is the number
339 # of positional arguments of the alias.
343 # of positional arguments of the alias.
340 self.alias_table = {}
344 self.alias_table = {}
341
345
342 # A table holding all the namespaces IPython deals with, so that
346 # A table holding all the namespaces IPython deals with, so that
343 # introspection facilities can search easily.
347 # introspection facilities can search easily.
344 self.ns_table = {'user':user_ns,
348 self.ns_table = {'user':user_ns,
345 'user_global':user_global_ns,
349 'user_global':user_global_ns,
346 'alias':self.alias_table,
350 'alias':self.alias_table,
347 'internal':self.internal_ns,
351 'internal':self.internal_ns,
348 'builtin':__builtin__.__dict__
352 'builtin':__builtin__.__dict__
349 }
353 }
350
354
351 # The user namespace MUST have a pointer to the shell itself.
355 # The user namespace MUST have a pointer to the shell itself.
352 self.user_ns[name] = self
356 self.user_ns[name] = self
353
357
354 # We need to insert into sys.modules something that looks like a
358 # We need to insert into sys.modules something that looks like a
355 # module but which accesses the IPython namespace, for shelve and
359 # module but which accesses the IPython namespace, for shelve and
356 # pickle to work interactively. Normally they rely on getting
360 # pickle to work interactively. Normally they rely on getting
357 # everything out of __main__, but for embedding purposes each IPython
361 # everything out of __main__, but for embedding purposes each IPython
358 # instance has its own private namespace, so we can't go shoving
362 # instance has its own private namespace, so we can't go shoving
359 # everything into __main__.
363 # everything into __main__.
360
364
361 # note, however, that we should only do this for non-embedded
365 # note, however, that we should only do this for non-embedded
362 # ipythons, which really mimic the __main__.__dict__ with their own
366 # ipythons, which really mimic the __main__.__dict__ with their own
363 # namespace. Embedded instances, on the other hand, should not do
367 # namespace. Embedded instances, on the other hand, should not do
364 # this because they need to manage the user local/global namespaces
368 # this because they need to manage the user local/global namespaces
365 # only, but they live within a 'normal' __main__ (meaning, they
369 # only, but they live within a 'normal' __main__ (meaning, they
366 # shouldn't overtake the execution environment of the script they're
370 # shouldn't overtake the execution environment of the script they're
367 # embedded in).
371 # embedded in).
368
372
369 if not embedded:
373 if not embedded:
370 try:
374 try:
371 main_name = self.user_ns['__name__']
375 main_name = self.user_ns['__name__']
372 except KeyError:
376 except KeyError:
373 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
377 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
374 else:
378 else:
375 #print "pickle hack in place" # dbg
379 #print "pickle hack in place" # dbg
376 sys.modules[main_name] = FakeModule(self.user_ns)
380 sys.modules[main_name] = FakeModule(self.user_ns)
377
381
378 # List of input with multi-line handling.
382 # List of input with multi-line handling.
379 # Fill its zero entry, user counter starts at 1
383 # Fill its zero entry, user counter starts at 1
380 self.input_hist = InputList(['\n'])
384 self.input_hist = InputList(['\n'])
381
385
382 # list of visited directories
386 # list of visited directories
383 try:
387 try:
384 self.dir_hist = [os.getcwd()]
388 self.dir_hist = [os.getcwd()]
385 except IOError, e:
389 except IOError, e:
386 self.dir_hist = []
390 self.dir_hist = []
387
391
388 # dict of output history
392 # dict of output history
389 self.output_hist = {}
393 self.output_hist = {}
390
394
391 # dict of things NOT to alias (keywords, builtins and some magics)
395 # dict of things NOT to alias (keywords, builtins and some magics)
392 no_alias = {}
396 no_alias = {}
393 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
397 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
394 for key in keyword.kwlist + no_alias_magics:
398 for key in keyword.kwlist + no_alias_magics:
395 no_alias[key] = 1
399 no_alias[key] = 1
396 no_alias.update(__builtin__.__dict__)
400 no_alias.update(__builtin__.__dict__)
397 self.no_alias = no_alias
401 self.no_alias = no_alias
398
402
399 # make global variables for user access to these
403 # make global variables for user access to these
400 self.user_ns['_ih'] = self.input_hist
404 self.user_ns['_ih'] = self.input_hist
401 self.user_ns['_oh'] = self.output_hist
405 self.user_ns['_oh'] = self.output_hist
402 self.user_ns['_dh'] = self.dir_hist
406 self.user_ns['_dh'] = self.dir_hist
403
407
404 # user aliases to input and output histories
408 # user aliases to input and output histories
405 self.user_ns['In'] = self.input_hist
409 self.user_ns['In'] = self.input_hist
406 self.user_ns['Out'] = self.output_hist
410 self.user_ns['Out'] = self.output_hist
407
411
408 # Object variable to store code object waiting execution. This is
412 # Object variable to store code object waiting execution. This is
409 # used mainly by the multithreaded shells, but it can come in handy in
413 # used mainly by the multithreaded shells, but it can come in handy in
410 # other situations. No need to use a Queue here, since it's a single
414 # other situations. No need to use a Queue here, since it's a single
411 # item which gets cleared once run.
415 # item which gets cleared once run.
412 self.code_to_run = None
416 self.code_to_run = None
413
417
414 # Job manager (for jobs run as background threads)
418 # Job manager (for jobs run as background threads)
415 self.jobs = BackgroundJobManager()
419 self.jobs = BackgroundJobManager()
416 # Put the job manager into builtins so it's always there.
420 # Put the job manager into builtins so it's always there.
417 __builtin__.jobs = self.jobs
421 __builtin__.jobs = self.jobs
418
422
419 # escapes for automatic behavior on the command line
423 # escapes for automatic behavior on the command line
420 self.ESC_SHELL = '!'
424 self.ESC_SHELL = '!'
421 self.ESC_HELP = '?'
425 self.ESC_HELP = '?'
422 self.ESC_MAGIC = '%'
426 self.ESC_MAGIC = '%'
423 self.ESC_QUOTE = ','
427 self.ESC_QUOTE = ','
424 self.ESC_QUOTE2 = ';'
428 self.ESC_QUOTE2 = ';'
425 self.ESC_PAREN = '/'
429 self.ESC_PAREN = '/'
426
430
427 # And their associated handlers
431 # And their associated handlers
428 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
432 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
429 self.ESC_QUOTE : self.handle_auto,
433 self.ESC_QUOTE : self.handle_auto,
430 self.ESC_QUOTE2 : self.handle_auto,
434 self.ESC_QUOTE2 : self.handle_auto,
431 self.ESC_MAGIC : self.handle_magic,
435 self.ESC_MAGIC : self.handle_magic,
432 self.ESC_HELP : self.handle_help,
436 self.ESC_HELP : self.handle_help,
433 self.ESC_SHELL : self.handle_shell_escape,
437 self.ESC_SHELL : self.handle_shell_escape,
434 }
438 }
435
439
436 # class initializations
440 # class initializations
437 Magic.__init__(self,self)
441 Magic.__init__(self,self)
438
442
439 # Python source parser/formatter for syntax highlighting
443 # Python source parser/formatter for syntax highlighting
440 pyformat = PyColorize.Parser().format
444 pyformat = PyColorize.Parser().format
441 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
445 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
442
446
443 # hooks holds pointers used for user-side customizations
447 # hooks holds pointers used for user-side customizations
444 self.hooks = Struct()
448 self.hooks = Struct()
445
449
446 # Set all default hooks, defined in the IPython.hooks module.
450 # Set all default hooks, defined in the IPython.hooks module.
447 hooks = IPython.hooks
451 hooks = IPython.hooks
448 for hook_name in hooks.__all__:
452 for hook_name in hooks.__all__:
449 self.set_hook(hook_name,getattr(hooks,hook_name))
453 self.set_hook(hook_name,getattr(hooks,hook_name))
450
454
451 # Flag to mark unconditional exit
455 # Flag to mark unconditional exit
452 self.exit_now = False
456 self.exit_now = False
453
457
454 self.usage_min = """\
458 self.usage_min = """\
455 An enhanced console for Python.
459 An enhanced console for Python.
456 Some of its features are:
460 Some of its features are:
457 - Readline support if the readline library is present.
461 - Readline support if the readline library is present.
458 - Tab completion in the local namespace.
462 - Tab completion in the local namespace.
459 - Logging of input, see command-line options.
463 - Logging of input, see command-line options.
460 - System shell escape via ! , eg !ls.
464 - System shell escape via ! , eg !ls.
461 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
465 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
462 - Keeps track of locally defined variables via %who, %whos.
466 - Keeps track of locally defined variables via %who, %whos.
463 - Show object information with a ? eg ?x or x? (use ?? for more info).
467 - Show object information with a ? eg ?x or x? (use ?? for more info).
464 """
468 """
465 if usage: self.usage = usage
469 if usage: self.usage = usage
466 else: self.usage = self.usage_min
470 else: self.usage = self.usage_min
467
471
468 # Storage
472 # Storage
469 self.rc = rc # This will hold all configuration information
473 self.rc = rc # This will hold all configuration information
470 self.inputcache = []
474 self.inputcache = []
471 self._boundcache = []
475 self._boundcache = []
472 self.pager = 'less'
476 self.pager = 'less'
473 # temporary files used for various purposes. Deleted at exit.
477 # temporary files used for various purposes. Deleted at exit.
474 self.tempfiles = []
478 self.tempfiles = []
475
479
476 # Keep track of readline usage (later set by init_readline)
480 # Keep track of readline usage (later set by init_readline)
477 self.has_readline = False
481 self.has_readline = False
478
482
479 # template for logfile headers. It gets resolved at runtime by the
483 # template for logfile headers. It gets resolved at runtime by the
480 # logstart method.
484 # logstart method.
481 self.loghead_tpl = \
485 self.loghead_tpl = \
482 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
486 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
483 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
487 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
484 #log# opts = %s
488 #log# opts = %s
485 #log# args = %s
489 #log# args = %s
486 #log# It is safe to make manual edits below here.
490 #log# It is safe to make manual edits below here.
487 #log#-----------------------------------------------------------------------
491 #log#-----------------------------------------------------------------------
488 """
492 """
489 # for pushd/popd management
493 # for pushd/popd management
490 try:
494 try:
491 self.home_dir = get_home_dir()
495 self.home_dir = get_home_dir()
492 except HomeDirError,msg:
496 except HomeDirError,msg:
493 fatal(msg)
497 fatal(msg)
494
498
495 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
499 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
496
500
497 # Functions to call the underlying shell.
501 # Functions to call the underlying shell.
498
502
499 # utility to expand user variables via Itpl
503 # utility to expand user variables via Itpl
500 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
504 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
501 self.user_ns))
505 self.user_ns))
502 # The first is similar to os.system, but it doesn't return a value,
506 # The first is similar to os.system, but it doesn't return a value,
503 # and it allows interpolation of variables in the user's namespace.
507 # and it allows interpolation of variables in the user's namespace.
504 self.system = lambda cmd: shell(self.var_expand(cmd),
508 self.system = lambda cmd: shell(self.var_expand(cmd),
505 header='IPython system call: ',
509 header='IPython system call: ',
506 verbose=self.rc.system_verbose)
510 verbose=self.rc.system_verbose)
507 # These are for getoutput and getoutputerror:
511 # These are for getoutput and getoutputerror:
508 self.getoutput = lambda cmd: \
512 self.getoutput = lambda cmd: \
509 getoutput(self.var_expand(cmd),
513 getoutput(self.var_expand(cmd),
510 header='IPython system call: ',
514 header='IPython system call: ',
511 verbose=self.rc.system_verbose)
515 verbose=self.rc.system_verbose)
512 self.getoutputerror = lambda cmd: \
516 self.getoutputerror = lambda cmd: \
513 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
517 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
514 self.user_ns)),
518 self.user_ns)),
515 header='IPython system call: ',
519 header='IPython system call: ',
516 verbose=self.rc.system_verbose)
520 verbose=self.rc.system_verbose)
517
521
518 # RegExp for splitting line contents into pre-char//first
522 # RegExp for splitting line contents into pre-char//first
519 # word-method//rest. For clarity, each group in on one line.
523 # word-method//rest. For clarity, each group in on one line.
520
524
521 # WARNING: update the regexp if the above escapes are changed, as they
525 # WARNING: update the regexp if the above escapes are changed, as they
522 # are hardwired in.
526 # are hardwired in.
523
527
524 # Don't get carried away with trying to make the autocalling catch too
528 # Don't get carried away with trying to make the autocalling catch too
525 # much: it's better to be conservative rather than to trigger hidden
529 # much: it's better to be conservative rather than to trigger hidden
526 # evals() somewhere and end up causing side effects.
530 # evals() somewhere and end up causing side effects.
527
531
528 self.line_split = re.compile(r'^([\s*,;/])'
532 self.line_split = re.compile(r'^([\s*,;/])'
529 r'([\?\w\.]+\w*\s*)'
533 r'([\?\w\.]+\w*\s*)'
530 r'(\(?.*$)')
534 r'(\(?.*$)')
531
535
532 # Original re, keep around for a while in case changes break something
536 # Original re, keep around for a while in case changes break something
533 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
537 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
534 # r'(\s*[\?\w\.]+\w*\s*)'
538 # r'(\s*[\?\w\.]+\w*\s*)'
535 # r'(\(?.*$)')
539 # r'(\(?.*$)')
536
540
537 # RegExp to identify potential function names
541 # RegExp to identify potential function names
538 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
542 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
539 # RegExp to exclude strings with this start from autocalling
543 # RegExp to exclude strings with this start from autocalling
540 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
544 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
541
545
542 # try to catch also methods for stuff in lists/tuples/dicts: off
546 # try to catch also methods for stuff in lists/tuples/dicts: off
543 # (experimental). For this to work, the line_split regexp would need
547 # (experimental). For this to work, the line_split regexp would need
544 # to be modified so it wouldn't break things at '['. That line is
548 # to be modified so it wouldn't break things at '['. That line is
545 # nasty enough that I shouldn't change it until I can test it _well_.
549 # nasty enough that I shouldn't change it until I can test it _well_.
546 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
550 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
547
551
548 # keep track of where we started running (mainly for crash post-mortem)
552 # keep track of where we started running (mainly for crash post-mortem)
549 self.starting_dir = os.getcwd()
553 self.starting_dir = os.getcwd()
550
554
551 # Various switches which can be set
555 # Various switches which can be set
552 self.CACHELENGTH = 5000 # this is cheap, it's just text
556 self.CACHELENGTH = 5000 # this is cheap, it's just text
553 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
557 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
554 self.banner2 = banner2
558 self.banner2 = banner2
555
559
556 # TraceBack handlers:
560 # TraceBack handlers:
557
561
558 # Syntax error handler.
562 # Syntax error handler.
559 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
563 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
560
564
561 # The interactive one is initialized with an offset, meaning we always
565 # The interactive one is initialized with an offset, meaning we always
562 # want to remove the topmost item in the traceback, which is our own
566 # want to remove the topmost item in the traceback, which is our own
563 # internal code. Valid modes: ['Plain','Context','Verbose']
567 # internal code. Valid modes: ['Plain','Context','Verbose']
564 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
568 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
565 color_scheme='NoColor',
569 color_scheme='NoColor',
566 tb_offset = 1)
570 tb_offset = 1)
567
571
568 # IPython itself shouldn't crash. This will produce a detailed
572 # IPython itself shouldn't crash. This will produce a detailed
569 # post-mortem if it does. But we only install the crash handler for
573 # post-mortem if it does. But we only install the crash handler for
570 # non-threaded shells, the threaded ones use a normal verbose reporter
574 # non-threaded shells, the threaded ones use a normal verbose reporter
571 # and lose the crash handler. This is because exceptions in the main
575 # and lose the crash handler. This is because exceptions in the main
572 # thread (such as in GUI code) propagate directly to sys.excepthook,
576 # thread (such as in GUI code) propagate directly to sys.excepthook,
573 # and there's no point in printing crash dumps for every user exception.
577 # and there's no point in printing crash dumps for every user exception.
574 if self.isthreaded:
578 if self.isthreaded:
575 sys.excepthook = ultraTB.FormattedTB()
579 sys.excepthook = ultraTB.FormattedTB()
576 else:
580 else:
577 from IPython import CrashHandler
581 from IPython import CrashHandler
578 sys.excepthook = CrashHandler.CrashHandler(self)
582 sys.excepthook = CrashHandler.CrashHandler(self)
579
583
580 # The instance will store a pointer to this, so that runtime code
584 # The instance will store a pointer to this, so that runtime code
581 # (such as magics) can access it. This is because during the
585 # (such as magics) can access it. This is because during the
582 # read-eval loop, it gets temporarily overwritten (to deal with GUI
586 # read-eval loop, it gets temporarily overwritten (to deal with GUI
583 # frameworks).
587 # frameworks).
584 self.sys_excepthook = sys.excepthook
588 self.sys_excepthook = sys.excepthook
585
589
586 # and add any custom exception handlers the user may have specified
590 # and add any custom exception handlers the user may have specified
587 self.set_custom_exc(*custom_exceptions)
591 self.set_custom_exc(*custom_exceptions)
588
592
589 # Object inspector
593 # Object inspector
590 self.inspector = OInspect.Inspector(OInspect.InspectColors,
594 self.inspector = OInspect.Inspector(OInspect.InspectColors,
591 PyColorize.ANSICodeColors,
595 PyColorize.ANSICodeColors,
592 'NoColor')
596 'NoColor')
593 # indentation management
597 # indentation management
594 self.autoindent = False
598 self.autoindent = False
595 self.indent_current_nsp = 0
599 self.indent_current_nsp = 0
596 self.indent_current = '' # actual indent string
600 self.indent_current = '' # actual indent string
597
601
598 # Make some aliases automatically
602 # Make some aliases automatically
599 # Prepare list of shell aliases to auto-define
603 # Prepare list of shell aliases to auto-define
600 if os.name == 'posix':
604 if os.name == 'posix':
601 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
605 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
602 'mv mv -i','rm rm -i','cp cp -i',
606 'mv mv -i','rm rm -i','cp cp -i',
603 'cat cat','less less','clear clear',
607 'cat cat','less less','clear clear',
604 # a better ls
608 # a better ls
605 'ls ls -F',
609 'ls ls -F',
606 # long ls
610 # long ls
607 'll ls -lF',
611 'll ls -lF',
608 # color ls
612 # color ls
609 'lc ls -F -o --color',
613 'lc ls -F -o --color',
610 # ls normal files only
614 # ls normal files only
611 'lf ls -F -o --color %l | grep ^-',
615 'lf ls -F -o --color %l | grep ^-',
612 # ls symbolic links
616 # ls symbolic links
613 'lk ls -F -o --color %l | grep ^l',
617 'lk ls -F -o --color %l | grep ^l',
614 # directories or links to directories,
618 # directories or links to directories,
615 'ldir ls -F -o --color %l | grep /$',
619 'ldir ls -F -o --color %l | grep /$',
616 # things which are executable
620 # things which are executable
617 'lx ls -F -o --color %l | grep ^-..x',
621 'lx ls -F -o --color %l | grep ^-..x',
618 )
622 )
619 elif os.name in ['nt','dos']:
623 elif os.name in ['nt','dos']:
620 auto_alias = ('dir dir /on', 'ls dir /on',
624 auto_alias = ('dir dir /on', 'ls dir /on',
621 'ddir dir /ad /on', 'ldir dir /ad /on',
625 'ddir dir /ad /on', 'ldir dir /ad /on',
622 'mkdir mkdir','rmdir rmdir','echo echo',
626 'mkdir mkdir','rmdir rmdir','echo echo',
623 'ren ren','cls cls','copy copy')
627 'ren ren','cls cls','copy copy')
624 else:
628 else:
625 auto_alias = ()
629 auto_alias = ()
626 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
630 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
627 # Call the actual (public) initializer
631 # Call the actual (public) initializer
628 self.init_auto_alias()
632 self.init_auto_alias()
629 # end __init__
633 # end __init__
630
634
631 def post_config_initialization(self):
635 def post_config_initialization(self):
632 """Post configuration init method
636 """Post configuration init method
633
637
634 This is called after the configuration files have been processed to
638 This is called after the configuration files have been processed to
635 'finalize' the initialization."""
639 'finalize' the initialization."""
636
640
637 rc = self.rc
641 rc = self.rc
638
642
639 # Load readline proper
643 # Load readline proper
640 if rc.readline:
644 if rc.readline:
641 self.init_readline()
645 self.init_readline()
642
646
643 # log system
647 # log system
644 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
648 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
645 # local shortcut, this is used a LOT
649 # local shortcut, this is used a LOT
646 self.log = self.logger.log
650 self.log = self.logger.log
647
651
648 # Initialize cache, set in/out prompts and printing system
652 # Initialize cache, set in/out prompts and printing system
649 self.outputcache = CachedOutput(self,
653 self.outputcache = CachedOutput(self,
650 rc.cache_size,
654 rc.cache_size,
651 rc.pprint,
655 rc.pprint,
652 input_sep = rc.separate_in,
656 input_sep = rc.separate_in,
653 output_sep = rc.separate_out,
657 output_sep = rc.separate_out,
654 output_sep2 = rc.separate_out2,
658 output_sep2 = rc.separate_out2,
655 ps1 = rc.prompt_in1,
659 ps1 = rc.prompt_in1,
656 ps2 = rc.prompt_in2,
660 ps2 = rc.prompt_in2,
657 ps_out = rc.prompt_out,
661 ps_out = rc.prompt_out,
658 pad_left = rc.prompts_pad_left)
662 pad_left = rc.prompts_pad_left)
659
663
660 # user may have over-ridden the default print hook:
664 # user may have over-ridden the default print hook:
661 try:
665 try:
662 self.outputcache.__class__.display = self.hooks.display
666 self.outputcache.__class__.display = self.hooks.display
663 except AttributeError:
667 except AttributeError:
664 pass
668 pass
665
669
666 # I don't like assigning globally to sys, because it means when embedding
670 # I don't like assigning globally to sys, because it means when embedding
667 # instances, each embedded instance overrides the previous choice. But
671 # instances, each embedded instance overrides the previous choice. But
668 # sys.displayhook seems to be called internally by exec, so I don't see a
672 # sys.displayhook seems to be called internally by exec, so I don't see a
669 # way around it.
673 # way around it.
670 sys.displayhook = self.outputcache
674 sys.displayhook = self.outputcache
671
675
672 # Set user colors (don't do it in the constructor above so that it
676 # Set user colors (don't do it in the constructor above so that it
673 # doesn't crash if colors option is invalid)
677 # doesn't crash if colors option is invalid)
674 self.magic_colors(rc.colors)
678 self.magic_colors(rc.colors)
675
679
676 # Set calling of pdb on exceptions
680 # Set calling of pdb on exceptions
677 self.call_pdb = rc.pdb
681 self.call_pdb = rc.pdb
678
682
679 # Load user aliases
683 # Load user aliases
680 for alias in rc.alias:
684 for alias in rc.alias:
681 self.magic_alias(alias)
685 self.magic_alias(alias)
682
686
683 # dynamic data that survives through sessions
687 # dynamic data that survives through sessions
684 # XXX make the filename a config option?
688 # XXX make the filename a config option?
685 persist_base = 'persist'
689 persist_base = 'persist'
686 if rc.profile:
690 if rc.profile:
687 persist_base += '_%s' % rc.profile
691 persist_base += '_%s' % rc.profile
688 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
692 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
689
693
690 try:
694 try:
691 self.persist = pickle.load(file(self.persist_fname))
695 self.persist = pickle.load(file(self.persist_fname))
692 except:
696 except:
693 self.persist = {}
697 self.persist = {}
694
698
695
699
696 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
700 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
697 try:
701 try:
698 obj = pickle.loads(value)
702 obj = pickle.loads(value)
699 except:
703 except:
700
704
701 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
705 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
702 print "The error was:",sys.exc_info()[0]
706 print "The error was:",sys.exc_info()[0]
703 continue
707 continue
704
708
705
709
706 self.user_ns[key] = obj
710 self.user_ns[key] = obj
707
711
708
712
709
713
710
714
711 def set_hook(self,name,hook):
715 def set_hook(self,name,hook):
712 """set_hook(name,hook) -> sets an internal IPython hook.
716 """set_hook(name,hook) -> sets an internal IPython hook.
713
717
714 IPython exposes some of its internal API as user-modifiable hooks. By
718 IPython exposes some of its internal API as user-modifiable hooks. By
715 resetting one of these hooks, you can modify IPython's behavior to
719 resetting one of these hooks, you can modify IPython's behavior to
716 call at runtime your own routines."""
720 call at runtime your own routines."""
717
721
718 # At some point in the future, this should validate the hook before it
722 # At some point in the future, this should validate the hook before it
719 # accepts it. Probably at least check that the hook takes the number
723 # accepts it. Probably at least check that the hook takes the number
720 # of args it's supposed to.
724 # of args it's supposed to.
721 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
725 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
722
726
723 def set_custom_exc(self,exc_tuple,handler):
727 def set_custom_exc(self,exc_tuple,handler):
724 """set_custom_exc(exc_tuple,handler)
728 """set_custom_exc(exc_tuple,handler)
725
729
726 Set a custom exception handler, which will be called if any of the
730 Set a custom exception handler, which will be called if any of the
727 exceptions in exc_tuple occur in the mainloop (specifically, in the
731 exceptions in exc_tuple occur in the mainloop (specifically, in the
728 runcode() method.
732 runcode() method.
729
733
730 Inputs:
734 Inputs:
731
735
732 - exc_tuple: a *tuple* of valid exceptions to call the defined
736 - exc_tuple: a *tuple* of valid exceptions to call the defined
733 handler for. It is very important that you use a tuple, and NOT A
737 handler for. It is very important that you use a tuple, and NOT A
734 LIST here, because of the way Python's except statement works. If
738 LIST here, because of the way Python's except statement works. If
735 you only want to trap a single exception, use a singleton tuple:
739 you only want to trap a single exception, use a singleton tuple:
736
740
737 exc_tuple == (MyCustomException,)
741 exc_tuple == (MyCustomException,)
738
742
739 - handler: this must be defined as a function with the following
743 - handler: this must be defined as a function with the following
740 basic interface: def my_handler(self,etype,value,tb).
744 basic interface: def my_handler(self,etype,value,tb).
741
745
742 This will be made into an instance method (via new.instancemethod)
746 This will be made into an instance method (via new.instancemethod)
743 of IPython itself, and it will be called if any of the exceptions
747 of IPython itself, and it will be called if any of the exceptions
744 listed in the exc_tuple are caught. If the handler is None, an
748 listed in the exc_tuple are caught. If the handler is None, an
745 internal basic one is used, which just prints basic info.
749 internal basic one is used, which just prints basic info.
746
750
747 WARNING: by putting in your own exception handler into IPython's main
751 WARNING: by putting in your own exception handler into IPython's main
748 execution loop, you run a very good chance of nasty crashes. This
752 execution loop, you run a very good chance of nasty crashes. This
749 facility should only be used if you really know what you are doing."""
753 facility should only be used if you really know what you are doing."""
750
754
751 assert type(exc_tuple)==type(()) , \
755 assert type(exc_tuple)==type(()) , \
752 "The custom exceptions must be given AS A TUPLE."
756 "The custom exceptions must be given AS A TUPLE."
753
757
754 def dummy_handler(self,etype,value,tb):
758 def dummy_handler(self,etype,value,tb):
755 print '*** Simple custom exception handler ***'
759 print '*** Simple custom exception handler ***'
756 print 'Exception type :',etype
760 print 'Exception type :',etype
757 print 'Exception value:',value
761 print 'Exception value:',value
758 print 'Traceback :',tb
762 print 'Traceback :',tb
759 print 'Source code :','\n'.join(self.buffer)
763 print 'Source code :','\n'.join(self.buffer)
760
764
761 if handler is None: handler = dummy_handler
765 if handler is None: handler = dummy_handler
762
766
763 self.CustomTB = new.instancemethod(handler,self,self.__class__)
767 self.CustomTB = new.instancemethod(handler,self,self.__class__)
764 self.custom_exceptions = exc_tuple
768 self.custom_exceptions = exc_tuple
765
769
766 def set_custom_completer(self,completer,pos=0):
770 def set_custom_completer(self,completer,pos=0):
767 """set_custom_completer(completer,pos=0)
771 """set_custom_completer(completer,pos=0)
768
772
769 Adds a new custom completer function.
773 Adds a new custom completer function.
770
774
771 The position argument (defaults to 0) is the index in the completers
775 The position argument (defaults to 0) is the index in the completers
772 list where you want the completer to be inserted."""
776 list where you want the completer to be inserted."""
773
777
774 newcomp = new.instancemethod(completer,self.Completer,
778 newcomp = new.instancemethod(completer,self.Completer,
775 self.Completer.__class__)
779 self.Completer.__class__)
776 self.Completer.matchers.insert(pos,newcomp)
780 self.Completer.matchers.insert(pos,newcomp)
777
781
778 def _get_call_pdb(self):
782 def _get_call_pdb(self):
779 return self._call_pdb
783 return self._call_pdb
780
784
781 def _set_call_pdb(self,val):
785 def _set_call_pdb(self,val):
782
786
783 if val not in (0,1,False,True):
787 if val not in (0,1,False,True):
784 raise ValueError,'new call_pdb value must be boolean'
788 raise ValueError,'new call_pdb value must be boolean'
785
789
786 # store value in instance
790 # store value in instance
787 self._call_pdb = val
791 self._call_pdb = val
788
792
789 # notify the actual exception handlers
793 # notify the actual exception handlers
790 self.InteractiveTB.call_pdb = val
794 self.InteractiveTB.call_pdb = val
791 if self.isthreaded:
795 if self.isthreaded:
792 try:
796 try:
793 self.sys_excepthook.call_pdb = val
797 self.sys_excepthook.call_pdb = val
794 except:
798 except:
795 warn('Failed to activate pdb for threaded exception handler')
799 warn('Failed to activate pdb for threaded exception handler')
796
800
797 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
801 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
798 'Control auto-activation of pdb at exceptions')
802 'Control auto-activation of pdb at exceptions')
799
803
800 def complete(self,text):
804 def complete(self,text):
801 """Return a sorted list of all possible completions on text.
805 """Return a sorted list of all possible completions on text.
802
806
803 Inputs:
807 Inputs:
804
808
805 - text: a string of text to be completed on.
809 - text: a string of text to be completed on.
806
810
807 This is a wrapper around the completion mechanism, similar to what
811 This is a wrapper around the completion mechanism, similar to what
808 readline does at the command line when the TAB key is hit. By
812 readline does at the command line when the TAB key is hit. By
809 exposing it as a method, it can be used by other non-readline
813 exposing it as a method, it can be used by other non-readline
810 environments (such as GUIs) for text completion.
814 environments (such as GUIs) for text completion.
811
815
812 Simple usage example:
816 Simple usage example:
813
817
814 In [1]: x = 'hello'
818 In [1]: x = 'hello'
815
819
816 In [2]: __IP.complete('x.l')
820 In [2]: __IP.complete('x.l')
817 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
821 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
818
822
819 complete = self.Completer.complete
823 complete = self.Completer.complete
820 state = 0
824 state = 0
821 # use a dict so we get unique keys, since ipyhton's multiple
825 # use a dict so we get unique keys, since ipyhton's multiple
822 # completers can return duplicates.
826 # completers can return duplicates.
823 comps = {}
827 comps = {}
824 while True:
828 while True:
825 newcomp = complete(text,state)
829 newcomp = complete(text,state)
826 if newcomp is None:
830 if newcomp is None:
827 break
831 break
828 comps[newcomp] = 1
832 comps[newcomp] = 1
829 state += 1
833 state += 1
830 outcomps = comps.keys()
834 outcomps = comps.keys()
831 outcomps.sort()
835 outcomps.sort()
832 return outcomps
836 return outcomps
833
837
834 def set_completer_frame(self, frame):
838 def set_completer_frame(self, frame):
835 if frame:
839 if frame:
836 self.Completer.namespace = frame.f_locals
840 self.Completer.namespace = frame.f_locals
837 self.Completer.global_namespace = frame.f_globals
841 self.Completer.global_namespace = frame.f_globals
838 else:
842 else:
839 self.Completer.namespace = self.user_ns
843 self.Completer.namespace = self.user_ns
840 self.Completer.global_namespace = self.user_global_ns
844 self.Completer.global_namespace = self.user_global_ns
841
845
842 def init_auto_alias(self):
846 def init_auto_alias(self):
843 """Define some aliases automatically.
847 """Define some aliases automatically.
844
848
845 These are ALL parameter-less aliases"""
849 These are ALL parameter-less aliases"""
846 for alias,cmd in self.auto_alias:
850 for alias,cmd in self.auto_alias:
847 self.alias_table[alias] = (0,cmd)
851 self.alias_table[alias] = (0,cmd)
848
852
849 def alias_table_validate(self,verbose=0):
853 def alias_table_validate(self,verbose=0):
850 """Update information about the alias table.
854 """Update information about the alias table.
851
855
852 In particular, make sure no Python keywords/builtins are in it."""
856 In particular, make sure no Python keywords/builtins are in it."""
853
857
854 no_alias = self.no_alias
858 no_alias = self.no_alias
855 for k in self.alias_table.keys():
859 for k in self.alias_table.keys():
856 if k in no_alias:
860 if k in no_alias:
857 del self.alias_table[k]
861 del self.alias_table[k]
858 if verbose:
862 if verbose:
859 print ("Deleting alias <%s>, it's a Python "
863 print ("Deleting alias <%s>, it's a Python "
860 "keyword or builtin." % k)
864 "keyword or builtin." % k)
861
865
862 def set_autoindent(self,value=None):
866 def set_autoindent(self,value=None):
863 """Set the autoindent flag, checking for readline support.
867 """Set the autoindent flag, checking for readline support.
864
868
865 If called with no arguments, it acts as a toggle."""
869 If called with no arguments, it acts as a toggle."""
866
870
867 if not self.has_readline:
871 if not self.has_readline:
868 if os.name == 'posix':
872 if os.name == 'posix':
869 warn("The auto-indent feature requires the readline library")
873 warn("The auto-indent feature requires the readline library")
870 self.autoindent = 0
874 self.autoindent = 0
871 return
875 return
872 if value is None:
876 if value is None:
873 self.autoindent = not self.autoindent
877 self.autoindent = not self.autoindent
874 else:
878 else:
875 self.autoindent = value
879 self.autoindent = value
876
880
877 def rc_set_toggle(self,rc_field,value=None):
881 def rc_set_toggle(self,rc_field,value=None):
878 """Set or toggle a field in IPython's rc config. structure.
882 """Set or toggle a field in IPython's rc config. structure.
879
883
880 If called with no arguments, it acts as a toggle.
884 If called with no arguments, it acts as a toggle.
881
885
882 If called with a non-existent field, the resulting AttributeError
886 If called with a non-existent field, the resulting AttributeError
883 exception will propagate out."""
887 exception will propagate out."""
884
888
885 rc_val = getattr(self.rc,rc_field)
889 rc_val = getattr(self.rc,rc_field)
886 if value is None:
890 if value is None:
887 value = not rc_val
891 value = not rc_val
888 setattr(self.rc,rc_field,value)
892 setattr(self.rc,rc_field,value)
889
893
890 def user_setup(self,ipythondir,rc_suffix,mode='install'):
894 def user_setup(self,ipythondir,rc_suffix,mode='install'):
891 """Install the user configuration directory.
895 """Install the user configuration directory.
892
896
893 Can be called when running for the first time or to upgrade the user's
897 Can be called when running for the first time or to upgrade the user's
894 .ipython/ directory with the mode parameter. Valid modes are 'install'
898 .ipython/ directory with the mode parameter. Valid modes are 'install'
895 and 'upgrade'."""
899 and 'upgrade'."""
896
900
897 def wait():
901 def wait():
898 try:
902 try:
899 raw_input("Please press <RETURN> to start IPython.")
903 raw_input("Please press <RETURN> to start IPython.")
900 except EOFError:
904 except EOFError:
901 print >> Term.cout
905 print >> Term.cout
902 print '*'*70
906 print '*'*70
903
907
904 cwd = os.getcwd() # remember where we started
908 cwd = os.getcwd() # remember where we started
905 glb = glob.glob
909 glb = glob.glob
906 print '*'*70
910 print '*'*70
907 if mode == 'install':
911 if mode == 'install':
908 print \
912 print \
909 """Welcome to IPython. I will try to create a personal configuration directory
913 """Welcome to IPython. I will try to create a personal configuration directory
910 where you can customize many aspects of IPython's functionality in:\n"""
914 where you can customize many aspects of IPython's functionality in:\n"""
911 else:
915 else:
912 print 'I am going to upgrade your configuration in:'
916 print 'I am going to upgrade your configuration in:'
913
917
914 print ipythondir
918 print ipythondir
915
919
916 rcdirend = os.path.join('IPython','UserConfig')
920 rcdirend = os.path.join('IPython','UserConfig')
917 cfg = lambda d: os.path.join(d,rcdirend)
921 cfg = lambda d: os.path.join(d,rcdirend)
918 try:
922 try:
919 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
923 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
920 except IOError:
924 except IOError:
921 warning = """
925 warning = """
922 Installation error. IPython's directory was not found.
926 Installation error. IPython's directory was not found.
923
927
924 Check the following:
928 Check the following:
925
929
926 The ipython/IPython directory should be in a directory belonging to your
930 The ipython/IPython directory should be in a directory belonging to your
927 PYTHONPATH environment variable (that is, it should be in a directory
931 PYTHONPATH environment variable (that is, it should be in a directory
928 belonging to sys.path). You can copy it explicitly there or just link to it.
932 belonging to sys.path). You can copy it explicitly there or just link to it.
929
933
930 IPython will proceed with builtin defaults.
934 IPython will proceed with builtin defaults.
931 """
935 """
932 warn(warning)
936 warn(warning)
933 wait()
937 wait()
934 return
938 return
935
939
936 if mode == 'install':
940 if mode == 'install':
937 try:
941 try:
938 shutil.copytree(rcdir,ipythondir)
942 shutil.copytree(rcdir,ipythondir)
939 os.chdir(ipythondir)
943 os.chdir(ipythondir)
940 rc_files = glb("ipythonrc*")
944 rc_files = glb("ipythonrc*")
941 for rc_file in rc_files:
945 for rc_file in rc_files:
942 os.rename(rc_file,rc_file+rc_suffix)
946 os.rename(rc_file,rc_file+rc_suffix)
943 except:
947 except:
944 warning = """
948 warning = """
945
949
946 There was a problem with the installation:
950 There was a problem with the installation:
947 %s
951 %s
948 Try to correct it or contact the developers if you think it's a bug.
952 Try to correct it or contact the developers if you think it's a bug.
949 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
953 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
950 warn(warning)
954 warn(warning)
951 wait()
955 wait()
952 return
956 return
953
957
954 elif mode == 'upgrade':
958 elif mode == 'upgrade':
955 try:
959 try:
956 os.chdir(ipythondir)
960 os.chdir(ipythondir)
957 except:
961 except:
958 print """
962 print """
959 Can not upgrade: changing to directory %s failed. Details:
963 Can not upgrade: changing to directory %s failed. Details:
960 %s
964 %s
961 """ % (ipythondir,sys.exc_info()[1])
965 """ % (ipythondir,sys.exc_info()[1])
962 wait()
966 wait()
963 return
967 return
964 else:
968 else:
965 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
969 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
966 for new_full_path in sources:
970 for new_full_path in sources:
967 new_filename = os.path.basename(new_full_path)
971 new_filename = os.path.basename(new_full_path)
968 if new_filename.startswith('ipythonrc'):
972 if new_filename.startswith('ipythonrc'):
969 new_filename = new_filename + rc_suffix
973 new_filename = new_filename + rc_suffix
970 # The config directory should only contain files, skip any
974 # The config directory should only contain files, skip any
971 # directories which may be there (like CVS)
975 # directories which may be there (like CVS)
972 if os.path.isdir(new_full_path):
976 if os.path.isdir(new_full_path):
973 continue
977 continue
974 if os.path.exists(new_filename):
978 if os.path.exists(new_filename):
975 old_file = new_filename+'.old'
979 old_file = new_filename+'.old'
976 if os.path.exists(old_file):
980 if os.path.exists(old_file):
977 os.remove(old_file)
981 os.remove(old_file)
978 os.rename(new_filename,old_file)
982 os.rename(new_filename,old_file)
979 shutil.copy(new_full_path,new_filename)
983 shutil.copy(new_full_path,new_filename)
980 else:
984 else:
981 raise ValueError,'unrecognized mode for install:',`mode`
985 raise ValueError,'unrecognized mode for install:',`mode`
982
986
983 # Fix line-endings to those native to each platform in the config
987 # Fix line-endings to those native to each platform in the config
984 # directory.
988 # directory.
985 try:
989 try:
986 os.chdir(ipythondir)
990 os.chdir(ipythondir)
987 except:
991 except:
988 print """
992 print """
989 Problem: changing to directory %s failed.
993 Problem: changing to directory %s failed.
990 Details:
994 Details:
991 %s
995 %s
992
996
993 Some configuration files may have incorrect line endings. This should not
997 Some configuration files may have incorrect line endings. This should not
994 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
998 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
995 wait()
999 wait()
996 else:
1000 else:
997 for fname in glb('ipythonrc*'):
1001 for fname in glb('ipythonrc*'):
998 try:
1002 try:
999 native_line_ends(fname,backup=0)
1003 native_line_ends(fname,backup=0)
1000 except IOError:
1004 except IOError:
1001 pass
1005 pass
1002
1006
1003 if mode == 'install':
1007 if mode == 'install':
1004 print """
1008 print """
1005 Successful installation!
1009 Successful installation!
1006
1010
1007 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1011 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1008 IPython manual (there are both HTML and PDF versions supplied with the
1012 IPython manual (there are both HTML and PDF versions supplied with the
1009 distribution) to make sure that your system environment is properly configured
1013 distribution) to make sure that your system environment is properly configured
1010 to take advantage of IPython's features."""
1014 to take advantage of IPython's features."""
1011 else:
1015 else:
1012 print """
1016 print """
1013 Successful upgrade!
1017 Successful upgrade!
1014
1018
1015 All files in your directory:
1019 All files in your directory:
1016 %(ipythondir)s
1020 %(ipythondir)s
1017 which would have been overwritten by the upgrade were backed up with a .old
1021 which would have been overwritten by the upgrade were backed up with a .old
1018 extension. If you had made particular customizations in those files you may
1022 extension. If you had made particular customizations in those files you may
1019 want to merge them back into the new files.""" % locals()
1023 want to merge them back into the new files.""" % locals()
1020 wait()
1024 wait()
1021 os.chdir(cwd)
1025 os.chdir(cwd)
1022 # end user_setup()
1026 # end user_setup()
1023
1027
1024 def atexit_operations(self):
1028 def atexit_operations(self):
1025 """This will be executed at the time of exit.
1029 """This will be executed at the time of exit.
1026
1030
1027 Saving of persistent data should be performed here. """
1031 Saving of persistent data should be performed here. """
1028
1032
1029 # input history
1033 # input history
1030 self.savehist()
1034 self.savehist()
1031
1035
1032 # Cleanup all tempfiles left around
1036 # Cleanup all tempfiles left around
1033 for tfile in self.tempfiles:
1037 for tfile in self.tempfiles:
1034 try:
1038 try:
1035 os.unlink(tfile)
1039 os.unlink(tfile)
1036 except OSError:
1040 except OSError:
1037 pass
1041 pass
1038
1042
1039 # save the "persistent data" catch-all dictionary
1043 # save the "persistent data" catch-all dictionary
1040 try:
1044 try:
1041 pickle.dump(self.persist, open(self.persist_fname,"w"))
1045 pickle.dump(self.persist, open(self.persist_fname,"w"))
1042 except:
1046 except:
1043 print "*** ERROR *** persistent data saving failed."
1047 print "*** ERROR *** persistent data saving failed."
1044
1048
1045 def savehist(self):
1049 def savehist(self):
1046 """Save input history to a file (via readline library)."""
1050 """Save input history to a file (via readline library)."""
1047 try:
1051 try:
1048 self.readline.write_history_file(self.histfile)
1052 self.readline.write_history_file(self.histfile)
1049 except:
1053 except:
1050 print 'Unable to save IPython command history to file: ' + \
1054 print 'Unable to save IPython command history to file: ' + \
1051 `self.histfile`
1055 `self.histfile`
1052
1056
1053 def pre_readline(self):
1057 def pre_readline(self):
1054 """readline hook to be used at the start of each line.
1058 """readline hook to be used at the start of each line.
1055
1059
1056 Currently it handles auto-indent only."""
1060 Currently it handles auto-indent only."""
1057
1061
1058 self.readline.insert_text(self.indent_current)
1062 self.readline.insert_text(self.indent_current)
1059
1063
1060 def init_readline(self):
1064 def init_readline(self):
1061 """Command history completion/saving/reloading."""
1065 """Command history completion/saving/reloading."""
1062 try:
1066 try:
1063 import readline
1067 import readline
1064 except ImportError:
1068 except ImportError:
1065 self.has_readline = 0
1069 self.has_readline = 0
1066 self.readline = None
1070 self.readline = None
1067 # no point in bugging windows users with this every time:
1071 # no point in bugging windows users with this every time:
1068 if os.name == 'posix':
1072 if os.name == 'posix':
1069 warn('Readline services not available on this platform.')
1073 warn('Readline services not available on this platform.')
1070 else:
1074 else:
1071 import atexit
1075 import atexit
1072 from IPython.completer import IPCompleter
1076 from IPython.completer import IPCompleter
1073 self.Completer = IPCompleter(self,
1077 self.Completer = IPCompleter(self,
1074 self.user_ns,
1078 self.user_ns,
1075 self.user_global_ns,
1079 self.user_global_ns,
1076 self.rc.readline_omit__names,
1080 self.rc.readline_omit__names,
1077 self.alias_table)
1081 self.alias_table)
1078
1082
1079 # Platform-specific configuration
1083 # Platform-specific configuration
1080 if os.name == 'nt':
1084 if os.name == 'nt':
1081 self.readline_startup_hook = readline.set_pre_input_hook
1085 self.readline_startup_hook = readline.set_pre_input_hook
1082 else:
1086 else:
1083 self.readline_startup_hook = readline.set_startup_hook
1087 self.readline_startup_hook = readline.set_startup_hook
1084
1088
1085 # Load user's initrc file (readline config)
1089 # Load user's initrc file (readline config)
1086 inputrc_name = os.environ.get('INPUTRC')
1090 inputrc_name = os.environ.get('INPUTRC')
1087 if inputrc_name is None:
1091 if inputrc_name is None:
1088 home_dir = get_home_dir()
1092 home_dir = get_home_dir()
1089 if home_dir is not None:
1093 if home_dir is not None:
1090 inputrc_name = os.path.join(home_dir,'.inputrc')
1094 inputrc_name = os.path.join(home_dir,'.inputrc')
1091 if os.path.isfile(inputrc_name):
1095 if os.path.isfile(inputrc_name):
1092 try:
1096 try:
1093 readline.read_init_file(inputrc_name)
1097 readline.read_init_file(inputrc_name)
1094 except:
1098 except:
1095 warn('Problems reading readline initialization file <%s>'
1099 warn('Problems reading readline initialization file <%s>'
1096 % inputrc_name)
1100 % inputrc_name)
1097
1101
1098 self.has_readline = 1
1102 self.has_readline = 1
1099 self.readline = readline
1103 self.readline = readline
1100 # save this in sys so embedded copies can restore it properly
1104 # save this in sys so embedded copies can restore it properly
1101 sys.ipcompleter = self.Completer.complete
1105 sys.ipcompleter = self.Completer.complete
1102 readline.set_completer(self.Completer.complete)
1106 readline.set_completer(self.Completer.complete)
1103
1107
1104 # Configure readline according to user's prefs
1108 # Configure readline according to user's prefs
1105 for rlcommand in self.rc.readline_parse_and_bind:
1109 for rlcommand in self.rc.readline_parse_and_bind:
1106 readline.parse_and_bind(rlcommand)
1110 readline.parse_and_bind(rlcommand)
1107
1111
1108 # remove some chars from the delimiters list
1112 # remove some chars from the delimiters list
1109 delims = readline.get_completer_delims()
1113 delims = readline.get_completer_delims()
1110 delims = delims.translate(string._idmap,
1114 delims = delims.translate(string._idmap,
1111 self.rc.readline_remove_delims)
1115 self.rc.readline_remove_delims)
1112 readline.set_completer_delims(delims)
1116 readline.set_completer_delims(delims)
1113 # otherwise we end up with a monster history after a while:
1117 # otherwise we end up with a monster history after a while:
1114 readline.set_history_length(1000)
1118 readline.set_history_length(1000)
1115 try:
1119 try:
1116 #print '*** Reading readline history' # dbg
1120 #print '*** Reading readline history' # dbg
1117 readline.read_history_file(self.histfile)
1121 readline.read_history_file(self.histfile)
1118 except IOError:
1122 except IOError:
1119 pass # It doesn't exist yet.
1123 pass # It doesn't exist yet.
1120
1124
1121 atexit.register(self.atexit_operations)
1125 atexit.register(self.atexit_operations)
1122 del atexit
1126 del atexit
1123
1127
1124 # Configure auto-indent for all platforms
1128 # Configure auto-indent for all platforms
1125 self.set_autoindent(self.rc.autoindent)
1129 self.set_autoindent(self.rc.autoindent)
1126
1130
1127 def _should_recompile(self,e):
1131 def _should_recompile(self,e):
1128 """Utility routine for edit_syntax_error"""
1132 """Utility routine for edit_syntax_error"""
1129
1133
1130 if e.filename in ('<ipython console>','<input>','<string>',
1134 if e.filename in ('<ipython console>','<input>','<string>',
1131 '<console>'):
1135 '<console>'):
1132 return False
1136 return False
1133 try:
1137 try:
1134 if not ask_yes_no('Return to editor to correct syntax error? '
1138 if not ask_yes_no('Return to editor to correct syntax error? '
1135 '[Y/n] ','y'):
1139 '[Y/n] ','y'):
1136 return False
1140 return False
1137 except EOFError:
1141 except EOFError:
1138 return False
1142 return False
1139 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1143 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1140 return True
1144 return True
1141
1145
1142 def edit_syntax_error(self):
1146 def edit_syntax_error(self):
1143 """The bottom half of the syntax error handler called in the main loop.
1147 """The bottom half of the syntax error handler called in the main loop.
1144
1148
1145 Loop until syntax error is fixed or user cancels.
1149 Loop until syntax error is fixed or user cancels.
1146 """
1150 """
1147
1151
1148 while self.SyntaxTB.last_syntax_error:
1152 while self.SyntaxTB.last_syntax_error:
1149 # copy and clear last_syntax_error
1153 # copy and clear last_syntax_error
1150 err = self.SyntaxTB.clear_err_state()
1154 err = self.SyntaxTB.clear_err_state()
1151 if not self._should_recompile(err):
1155 if not self._should_recompile(err):
1152 return
1156 return
1153 try:
1157 try:
1154 # may set last_syntax_error again if a SyntaxError is raised
1158 # may set last_syntax_error again if a SyntaxError is raised
1155 self.safe_execfile(err.filename,self.shell.user_ns)
1159 self.safe_execfile(err.filename,self.shell.user_ns)
1156 except:
1160 except:
1157 self.showtraceback()
1161 self.showtraceback()
1158 else:
1162 else:
1159 f = file(err.filename)
1163 f = file(err.filename)
1160 try:
1164 try:
1161 sys.displayhook(f.read())
1165 sys.displayhook(f.read())
1162 finally:
1166 finally:
1163 f.close()
1167 f.close()
1164
1168
1165 def showsyntaxerror(self, filename=None):
1169 def showsyntaxerror(self, filename=None):
1166 """Display the syntax error that just occurred.
1170 """Display the syntax error that just occurred.
1167
1171
1168 This doesn't display a stack trace because there isn't one.
1172 This doesn't display a stack trace because there isn't one.
1169
1173
1170 If a filename is given, it is stuffed in the exception instead
1174 If a filename is given, it is stuffed in the exception instead
1171 of what was there before (because Python's parser always uses
1175 of what was there before (because Python's parser always uses
1172 "<string>" when reading from a string).
1176 "<string>" when reading from a string).
1173 """
1177 """
1174 type, value, sys.last_traceback = sys.exc_info()
1178 etype, value, last_traceback = sys.exc_info()
1175 sys.last_type = type
1179 if filename and etype is SyntaxError:
1176 sys.last_value = value
1177 if filename and type is SyntaxError:
1178 # Work hard to stuff the correct filename in the exception
1180 # Work hard to stuff the correct filename in the exception
1179 try:
1181 try:
1180 msg, (dummy_filename, lineno, offset, line) = value
1182 msg, (dummy_filename, lineno, offset, line) = value
1181 except:
1183 except:
1182 # Not the format we expect; leave it alone
1184 # Not the format we expect; leave it alone
1183 pass
1185 pass
1184 else:
1186 else:
1185 # Stuff in the right filename
1187 # Stuff in the right filename
1186 try:
1188 try:
1187 # Assume SyntaxError is a class exception
1189 # Assume SyntaxError is a class exception
1188 value = SyntaxError(msg, (filename, lineno, offset, line))
1190 value = SyntaxError(msg, (filename, lineno, offset, line))
1189 except:
1191 except:
1190 # If that failed, assume SyntaxError is a string
1192 # If that failed, assume SyntaxError is a string
1191 value = msg, (filename, lineno, offset, line)
1193 value = msg, (filename, lineno, offset, line)
1192 self.SyntaxTB(type,value,[])
1194 self.SyntaxTB(etype,value,[])
1193
1195
1194 def debugger(self):
1196 def debugger(self):
1195 """Call the pdb debugger."""
1197 """Call the pdb debugger."""
1196
1198
1197 if not self.rc.pdb:
1199 if not self.rc.pdb:
1198 return
1200 return
1199 pdb.pm()
1201 pdb.pm()
1200
1202
1201 def showtraceback(self,exc_tuple = None,filename=None):
1203 def showtraceback(self,exc_tuple = None,filename=None):
1202 """Display the exception that just occurred."""
1204 """Display the exception that just occurred."""
1203
1205
1204 # Though this won't be called by syntax errors in the input line,
1206 # Though this won't be called by syntax errors in the input line,
1205 # there may be SyntaxError cases whith imported code.
1207 # there may be SyntaxError cases whith imported code.
1206 if exc_tuple is None:
1208 if exc_tuple is None:
1207 type, value, tb = sys.exc_info()
1209 type, value, tb = sys.exc_info()
1208 else:
1210 else:
1209 type, value, tb = exc_tuple
1211 type, value, tb = exc_tuple
1210 if type is SyntaxError:
1212 if type is SyntaxError:
1211 self.showsyntaxerror(filename)
1213 self.showsyntaxerror(filename)
1212 else:
1214 else:
1213 sys.last_type = type
1214 sys.last_value = value
1215 sys.last_traceback = tb
1216 self.InteractiveTB()
1215 self.InteractiveTB()
1217 if self.InteractiveTB.call_pdb and self.has_readline:
1216 if self.InteractiveTB.call_pdb and self.has_readline:
1218 # pdb mucks up readline, fix it back
1217 # pdb mucks up readline, fix it back
1219 self.readline.set_completer(self.Completer.complete)
1218 self.readline.set_completer(self.Completer.complete)
1220
1219
1221 def update_cache(self, line):
1220 def update_cache(self, line):
1222 """puts line into cache"""
1221 """puts line into cache"""
1223 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1222 return # dbg
1223
1224 # This copies the cache every time ... :-(
1225 self.inputcache.insert(0, line)
1224 if len(self.inputcache) >= self.CACHELENGTH:
1226 if len(self.inputcache) >= self.CACHELENGTH:
1225 self.inputcache.pop() # This doesn't :-)
1227 self.inputcache.pop() # This doesn't :-)
1226
1228
1227 def mainloop(self,banner=None):
1229 def mainloop(self,banner=None):
1228 """Creates the local namespace and starts the mainloop.
1230 """Creates the local namespace and starts the mainloop.
1229
1231
1230 If an optional banner argument is given, it will override the
1232 If an optional banner argument is given, it will override the
1231 internally created default banner."""
1233 internally created default banner."""
1232
1234
1233 if self.rc.c: # Emulate Python's -c option
1235 if self.rc.c: # Emulate Python's -c option
1234 self.exec_init_cmd()
1236 self.exec_init_cmd()
1235 if banner is None:
1237 if banner is None:
1236 if self.rc.banner:
1238 if self.rc.banner:
1237 banner = self.BANNER+self.banner2
1239 banner = self.BANNER+self.banner2
1238 else:
1240 else:
1239 banner = ''
1241 banner = ''
1240 self.interact(banner)
1242 self.interact(banner)
1241
1243
1242 def exec_init_cmd(self):
1244 def exec_init_cmd(self):
1243 """Execute a command given at the command line.
1245 """Execute a command given at the command line.
1244
1246
1245 This emulates Python's -c option."""
1247 This emulates Python's -c option."""
1246
1248
1247 sys.argv = ['-c']
1249 sys.argv = ['-c']
1248 self.push(self.rc.c)
1250 self.push(self.rc.c)
1249
1251
1250 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1252 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1251 """Embeds IPython into a running python program.
1253 """Embeds IPython into a running python program.
1252
1254
1253 Input:
1255 Input:
1254
1256
1255 - header: An optional header message can be specified.
1257 - header: An optional header message can be specified.
1256
1258
1257 - local_ns, global_ns: working namespaces. If given as None, the
1259 - local_ns, global_ns: working namespaces. If given as None, the
1258 IPython-initialized one is updated with __main__.__dict__, so that
1260 IPython-initialized one is updated with __main__.__dict__, so that
1259 program variables become visible but user-specific configuration
1261 program variables become visible but user-specific configuration
1260 remains possible.
1262 remains possible.
1261
1263
1262 - stack_depth: specifies how many levels in the stack to go to
1264 - stack_depth: specifies how many levels in the stack to go to
1263 looking for namespaces (when local_ns and global_ns are None). This
1265 looking for namespaces (when local_ns and global_ns are None). This
1264 allows an intermediate caller to make sure that this function gets
1266 allows an intermediate caller to make sure that this function gets
1265 the namespace from the intended level in the stack. By default (0)
1267 the namespace from the intended level in the stack. By default (0)
1266 it will get its locals and globals from the immediate caller.
1268 it will get its locals and globals from the immediate caller.
1267
1269
1268 Warning: it's possible to use this in a program which is being run by
1270 Warning: it's possible to use this in a program which is being run by
1269 IPython itself (via %run), but some funny things will happen (a few
1271 IPython itself (via %run), but some funny things will happen (a few
1270 globals get overwritten). In the future this will be cleaned up, as
1272 globals get overwritten). In the future this will be cleaned up, as
1271 there is no fundamental reason why it can't work perfectly."""
1273 there is no fundamental reason why it can't work perfectly."""
1272
1274
1273 # Get locals and globals from caller
1275 # Get locals and globals from caller
1274 if local_ns is None or global_ns is None:
1276 if local_ns is None or global_ns is None:
1275 call_frame = sys._getframe(stack_depth).f_back
1277 call_frame = sys._getframe(stack_depth).f_back
1276
1278
1277 if local_ns is None:
1279 if local_ns is None:
1278 local_ns = call_frame.f_locals
1280 local_ns = call_frame.f_locals
1279 if global_ns is None:
1281 if global_ns is None:
1280 global_ns = call_frame.f_globals
1282 global_ns = call_frame.f_globals
1281
1283
1282 # Update namespaces and fire up interpreter
1284 # Update namespaces and fire up interpreter
1283 self.user_ns = local_ns
1285 self.user_ns = local_ns
1284 self.user_global_ns = global_ns
1286 self.user_global_ns = global_ns
1285
1287
1286 # Patch for global embedding to make sure that things don't overwrite
1288 # Patch for global embedding to make sure that things don't overwrite
1287 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1289 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1288 # FIXME. Test this a bit more carefully (the if.. is new)
1290 # FIXME. Test this a bit more carefully (the if.. is new)
1289 if local_ns is None and global_ns is None:
1291 if local_ns is None and global_ns is None:
1290 self.user_global_ns.update(__main__.__dict__)
1292 self.user_global_ns.update(__main__.__dict__)
1291
1293
1292 # make sure the tab-completer has the correct frame information, so it
1294 # make sure the tab-completer has the correct frame information, so it
1293 # actually completes using the frame's locals/globals
1295 # actually completes using the frame's locals/globals
1294 self.set_completer_frame(call_frame)
1296 self.set_completer_frame(call_frame)
1295
1297
1296 self.interact(header)
1298 self.interact(header)
1297
1299
1298 def interact(self, banner=None):
1300 def interact(self, banner=None):
1299 """Closely emulate the interactive Python console.
1301 """Closely emulate the interactive Python console.
1300
1302
1301 The optional banner argument specify the banner to print
1303 The optional banner argument specify the banner to print
1302 before the first interaction; by default it prints a banner
1304 before the first interaction; by default it prints a banner
1303 similar to the one printed by the real Python interpreter,
1305 similar to the one printed by the real Python interpreter,
1304 followed by the current class name in parentheses (so as not
1306 followed by the current class name in parentheses (so as not
1305 to confuse this with the real interpreter -- since it's so
1307 to confuse this with the real interpreter -- since it's so
1306 close!).
1308 close!).
1307
1309
1308 """
1310 """
1309 cprt = 'Type "copyright", "credits" or "license" for more information.'
1311 cprt = 'Type "copyright", "credits" or "license" for more information.'
1310 if banner is None:
1312 if banner is None:
1311 self.write("Python %s on %s\n%s\n(%s)\n" %
1313 self.write("Python %s on %s\n%s\n(%s)\n" %
1312 (sys.version, sys.platform, cprt,
1314 (sys.version, sys.platform, cprt,
1313 self.__class__.__name__))
1315 self.__class__.__name__))
1314 else:
1316 else:
1315 self.write(banner)
1317 self.write(banner)
1316
1318
1317 more = 0
1319 more = 0
1318
1320
1319 # Mark activity in the builtins
1321 # Mark activity in the builtins
1320 __builtin__.__dict__['__IPYTHON__active'] += 1
1322 __builtin__.__dict__['__IPYTHON__active'] += 1
1321
1323
1322 # compiled regexps for autoindent management
1323 ini_spaces_re = re.compile(r'^(\s+)')
1324 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
1325
1326 # exit_now is set by a call to %Exit or %Quit
1324 # exit_now is set by a call to %Exit or %Quit
1327 while not self.exit_now:
1325 while not self.exit_now:
1328 try:
1326 try:
1329 if more:
1327 if more:
1330 prompt = self.outputcache.prompt2
1328 prompt = self.outputcache.prompt2
1331 if self.autoindent:
1329 if self.autoindent:
1332 self.readline_startup_hook(self.pre_readline)
1330 self.readline_startup_hook(self.pre_readline)
1333 else:
1331 else:
1334 prompt = self.outputcache.prompt1
1332 prompt = self.outputcache.prompt1
1335 try:
1333 try:
1336 line = self.raw_input(prompt,more)
1334 line = self.raw_input(prompt,more)
1337 if self.autoindent:
1335 if self.autoindent:
1338 self.readline_startup_hook(None)
1336 self.readline_startup_hook(None)
1339 except EOFError:
1337 except EOFError:
1340 if self.autoindent:
1338 if self.autoindent:
1341 self.readline_startup_hook(None)
1339 self.readline_startup_hook(None)
1342 self.write("\n")
1340 self.write("\n")
1343 self.exit()
1341 self.exit()
1344 else:
1342 else:
1345 more = self.push(line)
1343 more = self.push(line)
1346 # Auto-indent management
1347 if self.autoindent:
1348 if line:
1349 ini_spaces = ini_spaces_re.match(line)
1350 if ini_spaces:
1351 nspaces = ini_spaces.end()
1352 else:
1353 nspaces = 0
1354 self.indent_current_nsp = nspaces
1355
1356 if line[-1] == ':':
1357 self.indent_current_nsp += 4
1358 elif dedent_re.match(line):
1359 self.indent_current_nsp -= 4
1360 else:
1361 self.indent_current_nsp = 0
1362
1363 # indent_current is the actual string to be inserted
1364 # by the readline hooks for indentation
1365 self.indent_current = ' '* self.indent_current_nsp
1366
1344
1367 if (self.SyntaxTB.last_syntax_error and
1345 if (self.SyntaxTB.last_syntax_error and
1368 self.rc.autoedit_syntax):
1346 self.rc.autoedit_syntax):
1369 self.edit_syntax_error()
1347 self.edit_syntax_error()
1370
1348
1371 except KeyboardInterrupt:
1349 except KeyboardInterrupt:
1372 self.write("\nKeyboardInterrupt\n")
1350 self.write("\nKeyboardInterrupt\n")
1373 self.resetbuffer()
1351 self.resetbuffer()
1374 more = 0
1352 more = 0
1375 # keep cache in sync with the prompt counter:
1353 # keep cache in sync with the prompt counter:
1376 self.outputcache.prompt_count -= 1
1354 self.outputcache.prompt_count -= 1
1377
1355
1378 if self.autoindent:
1356 if self.autoindent:
1379 self.indent_current_nsp = 0
1357 self.indent_current_nsp = 0
1380 self.indent_current = ' '* self.indent_current_nsp
1358 self.indent_current = ' '* self.indent_current_nsp
1381
1359
1382 except bdb.BdbQuit:
1360 except bdb.BdbQuit:
1383 warn("The Python debugger has exited with a BdbQuit exception.\n"
1361 warn("The Python debugger has exited with a BdbQuit exception.\n"
1384 "Because of how pdb handles the stack, it is impossible\n"
1362 "Because of how pdb handles the stack, it is impossible\n"
1385 "for IPython to properly format this particular exception.\n"
1363 "for IPython to properly format this particular exception.\n"
1386 "IPython will resume normal operation.")
1364 "IPython will resume normal operation.")
1387
1365
1388 # We are off again...
1366 # We are off again...
1389 __builtin__.__dict__['__IPYTHON__active'] -= 1
1367 __builtin__.__dict__['__IPYTHON__active'] -= 1
1390
1368
1391 def excepthook(self, type, value, tb):
1369 def excepthook(self, type, value, tb):
1392 """One more defense for GUI apps that call sys.excepthook.
1370 """One more defense for GUI apps that call sys.excepthook.
1393
1371
1394 GUI frameworks like wxPython trap exceptions and call
1372 GUI frameworks like wxPython trap exceptions and call
1395 sys.excepthook themselves. I guess this is a feature that
1373 sys.excepthook themselves. I guess this is a feature that
1396 enables them to keep running after exceptions that would
1374 enables them to keep running after exceptions that would
1397 otherwise kill their mainloop. This is a bother for IPython
1375 otherwise kill their mainloop. This is a bother for IPython
1398 which excepts to catch all of the program exceptions with a try:
1376 which excepts to catch all of the program exceptions with a try:
1399 except: statement.
1377 except: statement.
1400
1378
1401 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1379 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1402 any app directly invokes sys.excepthook, it will look to the user like
1380 any app directly invokes sys.excepthook, it will look to the user like
1403 IPython crashed. In order to work around this, we can disable the
1381 IPython crashed. In order to work around this, we can disable the
1404 CrashHandler and replace it with this excepthook instead, which prints a
1382 CrashHandler and replace it with this excepthook instead, which prints a
1405 regular traceback using our InteractiveTB. In this fashion, apps which
1383 regular traceback using our InteractiveTB. In this fashion, apps which
1406 call sys.excepthook will generate a regular-looking exception from
1384 call sys.excepthook will generate a regular-looking exception from
1407 IPython, and the CrashHandler will only be triggered by real IPython
1385 IPython, and the CrashHandler will only be triggered by real IPython
1408 crashes.
1386 crashes.
1409
1387
1410 This hook should be used sparingly, only in places which are not likely
1388 This hook should be used sparingly, only in places which are not likely
1411 to be true IPython errors.
1389 to be true IPython errors.
1412 """
1390 """
1413
1391
1414 self.InteractiveTB(type, value, tb, tb_offset=0)
1392 self.InteractiveTB(type, value, tb, tb_offset=0)
1415 if self.InteractiveTB.call_pdb and self.has_readline:
1393 if self.InteractiveTB.call_pdb and self.has_readline:
1416 self.readline.set_completer(self.Completer.complete)
1394 self.readline.set_completer(self.Completer.complete)
1417
1395
1418 def call_alias(self,alias,rest=''):
1396 def call_alias(self,alias,rest=''):
1419 """Call an alias given its name and the rest of the line.
1397 """Call an alias given its name and the rest of the line.
1420
1398
1421 This function MUST be given a proper alias, because it doesn't make
1399 This function MUST be given a proper alias, because it doesn't make
1422 any checks when looking up into the alias table. The caller is
1400 any checks when looking up into the alias table. The caller is
1423 responsible for invoking it only with a valid alias."""
1401 responsible for invoking it only with a valid alias."""
1424
1402
1425 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1403 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1426 nargs,cmd = self.alias_table[alias]
1404 nargs,cmd = self.alias_table[alias]
1427 # Expand the %l special to be the user's input line
1405 # Expand the %l special to be the user's input line
1428 if cmd.find('%l') >= 0:
1406 if cmd.find('%l') >= 0:
1429 cmd = cmd.replace('%l',rest)
1407 cmd = cmd.replace('%l',rest)
1430 rest = ''
1408 rest = ''
1431 if nargs==0:
1409 if nargs==0:
1432 # Simple, argument-less aliases
1410 # Simple, argument-less aliases
1433 cmd = '%s %s' % (cmd,rest)
1411 cmd = '%s %s' % (cmd,rest)
1434 else:
1412 else:
1435 # Handle aliases with positional arguments
1413 # Handle aliases with positional arguments
1436 args = rest.split(None,nargs)
1414 args = rest.split(None,nargs)
1437 if len(args)< nargs:
1415 if len(args)< nargs:
1438 error('Alias <%s> requires %s arguments, %s given.' %
1416 error('Alias <%s> requires %s arguments, %s given.' %
1439 (alias,nargs,len(args)))
1417 (alias,nargs,len(args)))
1440 return
1418 return
1441 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1419 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1442 # Now call the macro, evaluating in the user's namespace
1420 # Now call the macro, evaluating in the user's namespace
1443 try:
1421 try:
1444 self.system(cmd)
1422 self.system(cmd)
1445 except:
1423 except:
1446 self.showtraceback()
1424 self.showtraceback()
1447
1425
1426 def autoindent_update(self,line):
1427 """Keep track of the indent level."""
1428 if self.autoindent:
1429 if line:
1430 ini_spaces = ini_spaces_re.match(line)
1431 if ini_spaces:
1432 nspaces = ini_spaces.end()
1433 else:
1434 nspaces = 0
1435 self.indent_current_nsp = nspaces
1436
1437 if line[-1] == ':':
1438 self.indent_current_nsp += 4
1439 elif dedent_re.match(line):
1440 self.indent_current_nsp -= 4
1441 else:
1442 self.indent_current_nsp = 0
1443
1444 # indent_current is the actual string to be inserted
1445 # by the readline hooks for indentation
1446 self.indent_current = ' '* self.indent_current_nsp
1447
1448 def runlines(self,lines):
1448 def runlines(self,lines):
1449 """Run a string of one or more lines of source.
1449 """Run a string of one or more lines of source.
1450
1450
1451 This method is capable of running a string containing multiple source
1451 This method is capable of running a string containing multiple source
1452 lines, as if they had been entered at the IPython prompt. Since it
1452 lines, as if they had been entered at the IPython prompt. Since it
1453 exposes IPython's processing machinery, the given strings can contain
1453 exposes IPython's processing machinery, the given strings can contain
1454 magic calls (%magic), special shell access (!cmd), etc."""
1454 magic calls (%magic), special shell access (!cmd), etc."""
1455
1455
1456 # We must start with a clean buffer, in case this is run from an
1456 # We must start with a clean buffer, in case this is run from an
1457 # interactive IPython session (via a magic, for example).
1457 # interactive IPython session (via a magic, for example).
1458 self.resetbuffer()
1458 self.resetbuffer()
1459 lines = lines.split('\n')
1459 lines = lines.split('\n')
1460 more = 0
1460 more = 0
1461 for line in lines:
1461 for line in lines:
1462 # skip blank lines so we don't mess up the prompt counter, but do
1462 # skip blank lines so we don't mess up the prompt counter, but do
1463 # NOT skip even a blank line if we are in a code block (more is
1463 # NOT skip even a blank line if we are in a code block (more is
1464 # true)
1464 # true)
1465 #print 'rl line:<%s>' % line # dbg
1465 if line or more:
1466 if line or more:
1466 more = self.push((self.prefilter(line,more)))
1467 #print 'doit' # dbg
1468 newline = self.prefilter(line,more)
1469 more = self.push(newline)
1467 # IPython's runsource returns None if there was an error
1470 # IPython's runsource returns None if there was an error
1468 # compiling the code. This allows us to stop processing right
1471 # compiling the code. This allows us to stop processing right
1469 # away, so the user gets the error message at the right place.
1472 # away, so the user gets the error message at the right place.
1470 if more is None:
1473 if more is None:
1471 break
1474 break
1472 # final newline in case the input didn't have it, so that the code
1475 # final newline in case the input didn't have it, so that the code
1473 # actually does get executed
1476 # actually does get executed
1474 if more:
1477 if more:
1475 self.push('\n')
1478 self.push('\n')
1476
1479
1477 def runsource(self, source, filename='<input>', symbol='single'):
1480 def runsource(self, source, filename='<input>', symbol='single'):
1478 """Compile and run some source in the interpreter.
1481 """Compile and run some source in the interpreter.
1479
1482
1480 Arguments are as for compile_command().
1483 Arguments are as for compile_command().
1481
1484
1482 One several things can happen:
1485 One several things can happen:
1483
1486
1484 1) The input is incorrect; compile_command() raised an
1487 1) The input is incorrect; compile_command() raised an
1485 exception (SyntaxError or OverflowError). A syntax traceback
1488 exception (SyntaxError or OverflowError). A syntax traceback
1486 will be printed by calling the showsyntaxerror() method.
1489 will be printed by calling the showsyntaxerror() method.
1487
1490
1488 2) The input is incomplete, and more input is required;
1491 2) The input is incomplete, and more input is required;
1489 compile_command() returned None. Nothing happens.
1492 compile_command() returned None. Nothing happens.
1490
1493
1491 3) The input is complete; compile_command() returned a code
1494 3) The input is complete; compile_command() returned a code
1492 object. The code is executed by calling self.runcode() (which
1495 object. The code is executed by calling self.runcode() (which
1493 also handles run-time exceptions, except for SystemExit).
1496 also handles run-time exceptions, except for SystemExit).
1494
1497
1495 The return value is:
1498 The return value is:
1496
1499
1497 - True in case 2
1500 - True in case 2
1498
1501
1499 - False in the other cases, unless an exception is raised, where
1502 - False in the other cases, unless an exception is raised, where
1500 None is returned instead. This can be used by external callers to
1503 None is returned instead. This can be used by external callers to
1501 know whether to continue feeding input or not.
1504 know whether to continue feeding input or not.
1502
1505
1503 The return value can be used to decide whether to use sys.ps1 or
1506 The return value can be used to decide whether to use sys.ps1 or
1504 sys.ps2 to prompt the next line."""
1507 sys.ps2 to prompt the next line."""
1505
1508
1506 try:
1509 try:
1507 code = self.compile(source,filename,symbol)
1510 code = self.compile(source,filename,symbol)
1508 except (OverflowError, SyntaxError, ValueError):
1511 except (OverflowError, SyntaxError, ValueError):
1509 # Case 1
1512 # Case 1
1510 self.showsyntaxerror(filename)
1513 self.showsyntaxerror(filename)
1511 return None
1514 return None
1512
1515
1513 if code is None:
1516 if code is None:
1514 # Case 2
1517 # Case 2
1515 return True
1518 return True
1516
1519
1517 # Case 3
1520 # Case 3
1518 # We store the code object so that threaded shells and
1521 # We store the code object so that threaded shells and
1519 # custom exception handlers can access all this info if needed.
1522 # custom exception handlers can access all this info if needed.
1520 # The source corresponding to this can be obtained from the
1523 # The source corresponding to this can be obtained from the
1521 # buffer attribute as '\n'.join(self.buffer).
1524 # buffer attribute as '\n'.join(self.buffer).
1522 self.code_to_run = code
1525 self.code_to_run = code
1523 # now actually execute the code object
1526 # now actually execute the code object
1524 if self.runcode(code) == 0:
1527 if self.runcode(code) == 0:
1525 return False
1528 return False
1526 else:
1529 else:
1527 return None
1530 return None
1528
1531
1529 def runcode(self,code_obj):
1532 def runcode(self,code_obj):
1530 """Execute a code object.
1533 """Execute a code object.
1531
1534
1532 When an exception occurs, self.showtraceback() is called to display a
1535 When an exception occurs, self.showtraceback() is called to display a
1533 traceback.
1536 traceback.
1534
1537
1535 Return value: a flag indicating whether the code to be run completed
1538 Return value: a flag indicating whether the code to be run completed
1536 successfully:
1539 successfully:
1537
1540
1538 - 0: successful execution.
1541 - 0: successful execution.
1539 - 1: an error occurred.
1542 - 1: an error occurred.
1540 """
1543 """
1541
1544
1542 # Set our own excepthook in case the user code tries to call it
1545 # Set our own excepthook in case the user code tries to call it
1543 # directly, so that the IPython crash handler doesn't get triggered
1546 # directly, so that the IPython crash handler doesn't get triggered
1544 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1547 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1545
1548
1546 # we save the original sys.excepthook in the instance, in case config
1549 # we save the original sys.excepthook in the instance, in case config
1547 # code (such as magics) needs access to it.
1550 # code (such as magics) needs access to it.
1548 self.sys_excepthook = old_excepthook
1551 self.sys_excepthook = old_excepthook
1549 outflag = 1 # happens in more places, so it's easier as default
1552 outflag = 1 # happens in more places, so it's easier as default
1550 try:
1553 try:
1551 try:
1554 try:
1552 # Embedded instances require separate global/local namespaces
1555 # Embedded instances require separate global/local namespaces
1553 # so they can see both the surrounding (local) namespace and
1556 # so they can see both the surrounding (local) namespace and
1554 # the module-level globals when called inside another function.
1557 # the module-level globals when called inside another function.
1555 if self.embedded:
1558 if self.embedded:
1556 exec code_obj in self.user_global_ns, self.user_ns
1559 exec code_obj in self.user_global_ns, self.user_ns
1557 # Normal (non-embedded) instances should only have a single
1560 # Normal (non-embedded) instances should only have a single
1558 # namespace for user code execution, otherwise functions won't
1561 # namespace for user code execution, otherwise functions won't
1559 # see interactive top-level globals.
1562 # see interactive top-level globals.
1560 else:
1563 else:
1561 exec code_obj in self.user_ns
1564 exec code_obj in self.user_ns
1562 finally:
1565 finally:
1563 # Reset our crash handler in place
1566 # Reset our crash handler in place
1564 sys.excepthook = old_excepthook
1567 sys.excepthook = old_excepthook
1565 except SystemExit:
1568 except SystemExit:
1566 self.resetbuffer()
1569 self.resetbuffer()
1567 self.showtraceback()
1570 self.showtraceback()
1568 warn("Type exit or quit to exit IPython "
1571 warn("Type exit or quit to exit IPython "
1569 "(%Exit or %Quit do so unconditionally).",level=1)
1572 "(%Exit or %Quit do so unconditionally).",level=1)
1570 except self.custom_exceptions:
1573 except self.custom_exceptions:
1571 etype,value,tb = sys.exc_info()
1574 etype,value,tb = sys.exc_info()
1572 self.CustomTB(etype,value,tb)
1575 self.CustomTB(etype,value,tb)
1573 except:
1576 except:
1574 self.showtraceback()
1577 self.showtraceback()
1575 else:
1578 else:
1576 outflag = 0
1579 outflag = 0
1577 if softspace(sys.stdout, 0):
1580 if softspace(sys.stdout, 0):
1578 print
1581 print
1579 # Flush out code object which has been run (and source)
1582 # Flush out code object which has been run (and source)
1580 self.code_to_run = None
1583 self.code_to_run = None
1581 return outflag
1584 return outflag
1582
1585
1583 def push(self, line):
1586 def push(self, line):
1584 """Push a line to the interpreter.
1587 """Push a line to the interpreter.
1585
1588
1586 The line should not have a trailing newline; it may have
1589 The line should not have a trailing newline; it may have
1587 internal newlines. The line is appended to a buffer and the
1590 internal newlines. The line is appended to a buffer and the
1588 interpreter's runsource() method is called with the
1591 interpreter's runsource() method is called with the
1589 concatenated contents of the buffer as source. If this
1592 concatenated contents of the buffer as source. If this
1590 indicates that the command was executed or invalid, the buffer
1593 indicates that the command was executed or invalid, the buffer
1591 is reset; otherwise, the command is incomplete, and the buffer
1594 is reset; otherwise, the command is incomplete, and the buffer
1592 is left as it was after the line was appended. The return
1595 is left as it was after the line was appended. The return
1593 value is 1 if more input is required, 0 if the line was dealt
1596 value is 1 if more input is required, 0 if the line was dealt
1594 with in some way (this is the same as runsource()).
1597 with in some way (this is the same as runsource()).
1595
1598
1596 """
1599 """
1597 self.buffer.append(line)
1600 self.buffer.append(line)
1598 more = self.runsource('\n'.join(self.buffer), self.filename)
1601 more = self.runsource('\n'.join(self.buffer), self.filename)
1599 if not more:
1602 if not more:
1600 self.resetbuffer()
1603 self.resetbuffer()
1601 return more
1604 return more
1602
1605
1603 def resetbuffer(self):
1606 def resetbuffer(self):
1604 """Reset the input buffer."""
1607 """Reset the input buffer."""
1605 self.buffer[:] = []
1608 self.buffer[:] = []
1606
1609
1607 def raw_input(self,prompt='',continue_prompt=False):
1610 def raw_input(self,prompt='',continue_prompt=False):
1608 """Write a prompt and read a line.
1611 """Write a prompt and read a line.
1609
1612
1610 The returned line does not include the trailing newline.
1613 The returned line does not include the trailing newline.
1611 When the user enters the EOF key sequence, EOFError is raised.
1614 When the user enters the EOF key sequence, EOFError is raised.
1612
1615
1613 Optional inputs:
1616 Optional inputs:
1614
1617
1615 - prompt(''): a string to be printed to prompt the user.
1618 - prompt(''): a string to be printed to prompt the user.
1616
1619
1617 - continue_prompt(False): whether this line is the first one or a
1620 - continue_prompt(False): whether this line is the first one or a
1618 continuation in a sequence of inputs.
1621 continuation in a sequence of inputs.
1619 """
1622 """
1620
1623
1621 line = raw_input_original(prompt)
1624 line = raw_input_original(prompt)
1622 # Try to be reasonably smart about not re-indenting pasted input more
1625 # Try to be reasonably smart about not re-indenting pasted input more
1623 # than necessary. We do this by trimming out the auto-indent initial
1626 # than necessary. We do this by trimming out the auto-indent initial
1624 # spaces, if the user's actual input started itself with whitespace.
1627 # spaces, if the user's actual input started itself with whitespace.
1625 if self.autoindent:
1628 if self.autoindent:
1626 line2 = line[self.indent_current_nsp:]
1629 line2 = line[self.indent_current_nsp:]
1627 if line2[0:1] in (' ','\t'):
1630 if line2[0:1] in (' ','\t'):
1628 line = line2
1631 line = line2
1629 return self.prefilter(line,continue_prompt)
1632 return self.prefilter(line,continue_prompt)
1630
1633
1631 def split_user_input(self,line):
1634 def split_user_input(self,line):
1632 """Split user input into pre-char, function part and rest."""
1635 """Split user input into pre-char, function part and rest."""
1633
1636
1634 lsplit = self.line_split.match(line)
1637 lsplit = self.line_split.match(line)
1635 if lsplit is None: # no regexp match returns None
1638 if lsplit is None: # no regexp match returns None
1636 try:
1639 try:
1637 iFun,theRest = line.split(None,1)
1640 iFun,theRest = line.split(None,1)
1638 except ValueError:
1641 except ValueError:
1639 iFun,theRest = line,''
1642 iFun,theRest = line,''
1640 pre = re.match('^(\s*)(.*)',line).groups()[0]
1643 pre = re.match('^(\s*)(.*)',line).groups()[0]
1641 else:
1644 else:
1642 pre,iFun,theRest = lsplit.groups()
1645 pre,iFun,theRest = lsplit.groups()
1643
1646
1644 #print 'line:<%s>' % line # dbg
1647 #print 'line:<%s>' % line # dbg
1645 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1648 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1646 return pre,iFun.strip(),theRest
1649 return pre,iFun.strip(),theRest
1647
1650
1648 def _prefilter(self, line, continue_prompt):
1651 def _prefilter(self, line, continue_prompt):
1649 """Calls different preprocessors, depending on the form of line."""
1652 """Calls different preprocessors, depending on the form of line."""
1650
1653
1651 # All handlers *must* return a value, even if it's blank ('').
1654 # All handlers *must* return a value, even if it's blank ('').
1652
1655
1653 # Lines are NOT logged here. Handlers should process the line as
1656 # Lines are NOT logged here. Handlers should process the line as
1654 # needed, update the cache AND log it (so that the input cache array
1657 # needed, update the cache AND log it (so that the input cache array
1655 # stays synced).
1658 # stays synced).
1656
1659
1657 # This function is _very_ delicate, and since it's also the one which
1660 # This function is _very_ delicate, and since it's also the one which
1658 # determines IPython's response to user input, it must be as efficient
1661 # determines IPython's response to user input, it must be as efficient
1659 # as possible. For this reason it has _many_ returns in it, trying
1662 # as possible. For this reason it has _many_ returns in it, trying
1660 # always to exit as quickly as it can figure out what it needs to do.
1663 # always to exit as quickly as it can figure out what it needs to do.
1661
1664
1662 # This function is the main responsible for maintaining IPython's
1665 # This function is the main responsible for maintaining IPython's
1663 # behavior respectful of Python's semantics. So be _very_ careful if
1666 # behavior respectful of Python's semantics. So be _very_ careful if
1664 # making changes to anything here.
1667 # making changes to anything here.
1665
1668
1666 #.....................................................................
1669 #.....................................................................
1667 # Code begins
1670 # Code begins
1668
1671
1669 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1672 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1670
1673
1671 # save the line away in case we crash, so the post-mortem handler can
1674 # save the line away in case we crash, so the post-mortem handler can
1672 # record it
1675 # record it
1673 self._last_input_line = line
1676 self._last_input_line = line
1674
1677
1675 #print '***line: <%s>' % line # dbg
1678 #print '***line: <%s>' % line # dbg
1676
1679
1677 # the input history needs to track even empty lines
1680 # the input history needs to track even empty lines
1678 if not line.strip():
1681 if not line.strip():
1679 if not continue_prompt:
1682 if not continue_prompt:
1680 self.outputcache.prompt_count -= 1
1683 self.outputcache.prompt_count -= 1
1681 return self.handle_normal(line,continue_prompt)
1684 return self.handle_normal(line,continue_prompt)
1682 #return self.handle_normal('',continue_prompt)
1685 #return self.handle_normal('',continue_prompt)
1683
1686
1684 # print '***cont',continue_prompt # dbg
1687 # print '***cont',continue_prompt # dbg
1685 # special handlers are only allowed for single line statements
1688 # special handlers are only allowed for single line statements
1686 if continue_prompt and not self.rc.multi_line_specials:
1689 if continue_prompt and not self.rc.multi_line_specials:
1687 return self.handle_normal(line,continue_prompt)
1690 return self.handle_normal(line,continue_prompt)
1688
1691
1689 # For the rest, we need the structure of the input
1692 # For the rest, we need the structure of the input
1690 pre,iFun,theRest = self.split_user_input(line)
1693 pre,iFun,theRest = self.split_user_input(line)
1691 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1694 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1692
1695
1693 # First check for explicit escapes in the last/first character
1696 # First check for explicit escapes in the last/first character
1694 handler = None
1697 handler = None
1695 if line[-1] == self.ESC_HELP:
1698 if line[-1] == self.ESC_HELP:
1696 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1699 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1697 if handler is None:
1700 if handler is None:
1698 # look at the first character of iFun, NOT of line, so we skip
1701 # look at the first character of iFun, NOT of line, so we skip
1699 # leading whitespace in multiline input
1702 # leading whitespace in multiline input
1700 handler = self.esc_handlers.get(iFun[0:1])
1703 handler = self.esc_handlers.get(iFun[0:1])
1701 if handler is not None:
1704 if handler is not None:
1702 return handler(line,continue_prompt,pre,iFun,theRest)
1705 return handler(line,continue_prompt,pre,iFun,theRest)
1703 # Emacs ipython-mode tags certain input lines
1706 # Emacs ipython-mode tags certain input lines
1704 if line.endswith('# PYTHON-MODE'):
1707 if line.endswith('# PYTHON-MODE'):
1705 return self.handle_emacs(line,continue_prompt)
1708 return self.handle_emacs(line,continue_prompt)
1706
1709
1707 # Next, check if we can automatically execute this thing
1710 # Next, check if we can automatically execute this thing
1708
1711
1709 # Allow ! in multi-line statements if multi_line_specials is on:
1712 # Allow ! in multi-line statements if multi_line_specials is on:
1710 if continue_prompt and self.rc.multi_line_specials and \
1713 if continue_prompt and self.rc.multi_line_specials and \
1711 iFun.startswith(self.ESC_SHELL):
1714 iFun.startswith(self.ESC_SHELL):
1712 return self.handle_shell_escape(line,continue_prompt,
1715 return self.handle_shell_escape(line,continue_prompt,
1713 pre=pre,iFun=iFun,
1716 pre=pre,iFun=iFun,
1714 theRest=theRest)
1717 theRest=theRest)
1715
1718
1716 # Let's try to find if the input line is a magic fn
1719 # Let's try to find if the input line is a magic fn
1717 oinfo = None
1720 oinfo = None
1718 if hasattr(self,'magic_'+iFun):
1721 if hasattr(self,'magic_'+iFun):
1722 # WARNING: _ofind uses getattr(), so it can consume generators and
1723 # cause other side effects.
1719 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1724 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1720 if oinfo['ismagic']:
1725 if oinfo['ismagic']:
1721 # Be careful not to call magics when a variable assignment is
1726 # Be careful not to call magics when a variable assignment is
1722 # being made (ls='hi', for example)
1727 # being made (ls='hi', for example)
1723 if self.rc.automagic and \
1728 if self.rc.automagic and \
1724 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1729 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1725 (self.rc.multi_line_specials or not continue_prompt):
1730 (self.rc.multi_line_specials or not continue_prompt):
1726 return self.handle_magic(line,continue_prompt,
1731 return self.handle_magic(line,continue_prompt,
1727 pre,iFun,theRest)
1732 pre,iFun,theRest)
1728 else:
1733 else:
1729 return self.handle_normal(line,continue_prompt)
1734 return self.handle_normal(line,continue_prompt)
1730
1735
1731 # If the rest of the line begins with an (in)equality, assginment or
1736 # If the rest of the line begins with an (in)equality, assginment or
1732 # function call, we should not call _ofind but simply execute it.
1737 # function call, we should not call _ofind but simply execute it.
1733 # This avoids spurious geattr() accesses on objects upon assignment.
1738 # This avoids spurious geattr() accesses on objects upon assignment.
1734 #
1739 #
1735 # It also allows users to assign to either alias or magic names true
1740 # It also allows users to assign to either alias or magic names true
1736 # python variables (the magic/alias systems always take second seat to
1741 # python variables (the magic/alias systems always take second seat to
1737 # true python code).
1742 # true python code).
1738 if theRest and theRest[0] in '!=()':
1743 if theRest and theRest[0] in '!=()':
1739 return self.handle_normal(line,continue_prompt)
1744 return self.handle_normal(line,continue_prompt)
1740
1745
1741 if oinfo is None:
1746 if oinfo is None:
1742 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1747 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1743
1748
1744 if not oinfo['found']:
1749 if not oinfo['found']:
1745 return self.handle_normal(line,continue_prompt)
1750 return self.handle_normal(line,continue_prompt)
1746 else:
1751 else:
1747 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1752 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1748 if oinfo['isalias']:
1753 if oinfo['isalias']:
1749 return self.handle_alias(line,continue_prompt,
1754 return self.handle_alias(line,continue_prompt,
1750 pre,iFun,theRest)
1755 pre,iFun,theRest)
1751
1756
1752 if self.rc.autocall and \
1757 if self.rc.autocall and \
1753 not self.re_exclude_auto.match(theRest) and \
1758 not self.re_exclude_auto.match(theRest) and \
1754 self.re_fun_name.match(iFun) and \
1759 self.re_fun_name.match(iFun) and \
1755 callable(oinfo['obj']) :
1760 callable(oinfo['obj']) :
1756 #print 'going auto' # dbg
1761 #print 'going auto' # dbg
1757 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1762 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1758 else:
1763 else:
1759 #print 'was callable?', callable(oinfo['obj']) # dbg
1764 #print 'was callable?', callable(oinfo['obj']) # dbg
1760 return self.handle_normal(line,continue_prompt)
1765 return self.handle_normal(line,continue_prompt)
1761
1766
1762 # If we get here, we have a normal Python line. Log and return.
1767 # If we get here, we have a normal Python line. Log and return.
1763 return self.handle_normal(line,continue_prompt)
1768 return self.handle_normal(line,continue_prompt)
1764
1769
1765 def _prefilter_dumb(self, line, continue_prompt):
1770 def _prefilter_dumb(self, line, continue_prompt):
1766 """simple prefilter function, for debugging"""
1771 """simple prefilter function, for debugging"""
1767 return self.handle_normal(line,continue_prompt)
1772 return self.handle_normal(line,continue_prompt)
1768
1773
1769 # Set the default prefilter() function (this can be user-overridden)
1774 # Set the default prefilter() function (this can be user-overridden)
1770 prefilter = _prefilter
1775 prefilter = _prefilter
1771
1776
1772 def handle_normal(self,line,continue_prompt=None,
1777 def handle_normal(self,line,continue_prompt=None,
1773 pre=None,iFun=None,theRest=None):
1778 pre=None,iFun=None,theRest=None):
1774 """Handle normal input lines. Use as a template for handlers."""
1779 """Handle normal input lines. Use as a template for handlers."""
1775
1780
1776 # With autoindent on, we need some way to exit the input loop, and I
1781 # With autoindent on, we need some way to exit the input loop, and I
1777 # don't want to force the user to have to backspace all the way to
1782 # don't want to force the user to have to backspace all the way to
1778 # clear the line. The rule will be in this case, that either two
1783 # clear the line. The rule will be in this case, that either two
1779 # lines of pure whitespace in a row, or a line of pure whitespace but
1784 # lines of pure whitespace in a row, or a line of pure whitespace but
1780 # of a size different to the indent level, will exit the input loop.
1785 # of a size different to the indent level, will exit the input loop.
1781 if (continue_prompt and self.autoindent and isspace(line) and
1786 if (continue_prompt and self.autoindent and isspace(line) and
1782 (line != self.indent_current or isspace(self.buffer[-1]))):
1787 (line != self.indent_current or isspace(self.buffer[-1]))):
1783 line = ''
1788 line = ''
1784
1789
1785 self.log(line,continue_prompt)
1790 self.log(line,continue_prompt)
1786 self.update_cache(line)
1791 self.update_cache(line)
1787 return line
1792 return line
1788
1793
1789 def handle_alias(self,line,continue_prompt=None,
1794 def handle_alias(self,line,continue_prompt=None,
1790 pre=None,iFun=None,theRest=None):
1795 pre=None,iFun=None,theRest=None):
1791 """Handle alias input lines. """
1796 """Handle alias input lines. """
1792
1797
1793 theRest = esc_quotes(theRest)
1798 theRest = esc_quotes(theRest)
1794 # log the ipalias form, which doesn't depend on the instance name
1799 # log the ipalias form, which doesn't depend on the instance name
1795 line_log = 'ipalias("%s %s")' % (iFun,theRest)
1800 line_log = 'ipalias("%s %s")' % (iFun,theRest)
1796 self.log(line_log,continue_prompt)
1801 self.log(line_log,continue_prompt)
1797 self.update_cache(line_log)
1802 self.update_cache(line_log)
1798 # this is what actually gets executed
1803 # this is what actually gets executed
1799 return "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1804 return "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1800
1805
1801 def handle_shell_escape(self, line, continue_prompt=None,
1806 def handle_shell_escape(self, line, continue_prompt=None,
1802 pre=None,iFun=None,theRest=None):
1807 pre=None,iFun=None,theRest=None):
1803 """Execute the line in a shell, empty return value"""
1808 """Execute the line in a shell, empty return value"""
1804
1809
1805 #print 'line in :', `line` # dbg
1810 #print 'line in :', `line` # dbg
1806 # Example of a special handler. Others follow a similar pattern.
1811 # Example of a special handler. Others follow a similar pattern.
1807 if continue_prompt: # multi-line statements
1812 if continue_prompt: # multi-line statements
1808 if iFun.startswith('!!'):
1813 if iFun.startswith('!!'):
1809 print 'SyntaxError: !! is not allowed in multiline statements'
1814 print 'SyntaxError: !! is not allowed in multiline statements'
1810 return pre
1815 return pre
1811 else:
1816 else:
1812 cmd = ("%s %s" % (iFun[1:],theRest)) #.replace('"','\\"')
1817 cmd = ("%s %s" % (iFun[1:],theRest)) #.replace('"','\\"')
1813 #line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1818 #line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1814 line_out = '%s%s.system(r"""%s"""[:-1])' % (pre,self.name,cmd + "_")
1819 line_out = '%s%s.system(r"""%s"""[:-1])' % (pre,self.name,cmd + "_")
1815 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1820 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1816 else: # single-line input
1821 else: # single-line input
1817 if line.startswith('!!'):
1822 if line.startswith('!!'):
1818 # rewrite iFun/theRest to properly hold the call to %sx and
1823 # rewrite iFun/theRest to properly hold the call to %sx and
1819 # the actual command to be executed, so handle_magic can work
1824 # the actual command to be executed, so handle_magic can work
1820 # correctly
1825 # correctly
1821 theRest = '%s %s' % (iFun[2:],theRest)
1826 theRest = '%s %s' % (iFun[2:],theRest)
1822 iFun = 'sx'
1827 iFun = 'sx'
1823 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1828 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1824 continue_prompt,pre,iFun,theRest)
1829 continue_prompt,pre,iFun,theRest)
1825 else:
1830 else:
1826 #cmd = esc_quotes(line[1:])
1831 #cmd = esc_quotes(line[1:])
1827 cmd=line[1:]
1832 cmd=line[1:]
1828 #line_out = '%s.system("%s")' % (self.name,cmd)
1833 #line_out = '%s.system("%s")' % (self.name,cmd)
1829 line_out = '%s.system(r"""%s"""[:-1])' % (self.name,cmd +"_")
1834 line_out = '%s.system(r"""%s"""[:-1])' % (self.name,cmd +"_")
1830 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1835 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1831 # update cache/log and return
1836 # update cache/log and return
1832 self.log(line_out,continue_prompt)
1837 self.log(line_out,continue_prompt)
1833 self.update_cache(line_out) # readline cache gets normal line
1838 self.update_cache(line_out) # readline cache gets normal line
1834 #print 'line out r:', `line_out` # dbg
1839 #print 'line out r:', `line_out` # dbg
1835 #print 'line out s:', line_out # dbg
1840 #print 'line out s:', line_out # dbg
1836 return line_out
1841 return line_out
1837
1842
1838 def handle_magic(self, line, continue_prompt=None,
1843 def handle_magic(self, line, continue_prompt=None,
1839 pre=None,iFun=None,theRest=None):
1844 pre=None,iFun=None,theRest=None):
1840 """Execute magic functions.
1845 """Execute magic functions.
1841
1846
1842 Also log them with a prepended # so the log is clean Python."""
1847 Also log them with a prepended # so the log is clean Python."""
1843
1848
1844 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1849 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1845 self.log(cmd,continue_prompt)
1850 self.log(cmd,continue_prompt)
1846 self.update_cache(line)
1851 self.update_cache(line)
1847 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1852 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1848 return cmd
1853 return cmd
1849
1854
1850 def handle_auto(self, line, continue_prompt=None,
1855 def handle_auto(self, line, continue_prompt=None,
1851 pre=None,iFun=None,theRest=None):
1856 pre=None,iFun=None,theRest=None):
1852 """Hande lines which can be auto-executed, quoting if requested."""
1857 """Hande lines which can be auto-executed, quoting if requested."""
1853
1858
1854 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1859 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1855
1860
1856 # This should only be active for single-line input!
1861 # This should only be active for single-line input!
1857 if continue_prompt:
1862 if continue_prompt:
1858 return line
1863 return line
1859
1864
1860 if pre == self.ESC_QUOTE:
1865 if pre == self.ESC_QUOTE:
1861 # Auto-quote splitting on whitespace
1866 # Auto-quote splitting on whitespace
1862 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1867 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1863 elif pre == self.ESC_QUOTE2:
1868 elif pre == self.ESC_QUOTE2:
1864 # Auto-quote whole string
1869 # Auto-quote whole string
1865 newcmd = '%s("%s")' % (iFun,theRest)
1870 newcmd = '%s("%s")' % (iFun,theRest)
1866 else:
1871 else:
1867 # Auto-paren
1872 # Auto-paren
1868 if theRest[0:1] in ('=','['):
1873 if theRest[0:1] in ('=','['):
1869 # Don't autocall in these cases. They can be either
1874 # Don't autocall in these cases. They can be either
1870 # rebindings of an existing callable's name, or item access
1875 # rebindings of an existing callable's name, or item access
1871 # for an object which is BOTH callable and implements
1876 # for an object which is BOTH callable and implements
1872 # __getitem__.
1877 # __getitem__.
1873 return '%s %s' % (iFun,theRest)
1878 return '%s %s' % (iFun,theRest)
1874 if theRest.endswith(';'):
1879 if theRest.endswith(';'):
1875 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1880 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1876 else:
1881 else:
1877 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1882 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1878
1883
1879 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1884 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1880 # log what is now valid Python, not the actual user input (without the
1885 # log what is now valid Python, not the actual user input (without the
1881 # final newline)
1886 # final newline)
1882 self.log(newcmd,continue_prompt)
1887 self.log(newcmd,continue_prompt)
1883 return newcmd
1888 return newcmd
1884
1889
1885 def handle_help(self, line, continue_prompt=None,
1890 def handle_help(self, line, continue_prompt=None,
1886 pre=None,iFun=None,theRest=None):
1891 pre=None,iFun=None,theRest=None):
1887 """Try to get some help for the object.
1892 """Try to get some help for the object.
1888
1893
1889 obj? or ?obj -> basic information.
1894 obj? or ?obj -> basic information.
1890 obj?? or ??obj -> more details.
1895 obj?? or ??obj -> more details.
1891 """
1896 """
1892
1897
1893 # We need to make sure that we don't process lines which would be
1898 # We need to make sure that we don't process lines which would be
1894 # otherwise valid python, such as "x=1 # what?"
1899 # otherwise valid python, such as "x=1 # what?"
1895 try:
1900 try:
1896 codeop.compile_command(line)
1901 codeop.compile_command(line)
1897 except SyntaxError:
1902 except SyntaxError:
1898 # We should only handle as help stuff which is NOT valid syntax
1903 # We should only handle as help stuff which is NOT valid syntax
1899 if line[0]==self.ESC_HELP:
1904 if line[0]==self.ESC_HELP:
1900 line = line[1:]
1905 line = line[1:]
1901 elif line[-1]==self.ESC_HELP:
1906 elif line[-1]==self.ESC_HELP:
1902 line = line[:-1]
1907 line = line[:-1]
1903 self.log('#?'+line)
1908 self.log('#?'+line)
1904 self.update_cache(line)
1909 self.update_cache(line)
1905 if line:
1910 if line:
1906 self.magic_pinfo(line)
1911 self.magic_pinfo(line)
1907 else:
1912 else:
1908 page(self.usage,screen_lines=self.rc.screen_length)
1913 page(self.usage,screen_lines=self.rc.screen_length)
1909 return '' # Empty string is needed here!
1914 return '' # Empty string is needed here!
1910 except:
1915 except:
1911 # Pass any other exceptions through to the normal handler
1916 # Pass any other exceptions through to the normal handler
1912 return self.handle_normal(line,continue_prompt)
1917 return self.handle_normal(line,continue_prompt)
1913 else:
1918 else:
1914 # If the code compiles ok, we should handle it normally
1919 # If the code compiles ok, we should handle it normally
1915 return self.handle_normal(line,continue_prompt)
1920 return self.handle_normal(line,continue_prompt)
1916
1921
1917 def handle_emacs(self,line,continue_prompt=None,
1922 def handle_emacs(self,line,continue_prompt=None,
1918 pre=None,iFun=None,theRest=None):
1923 pre=None,iFun=None,theRest=None):
1919 """Handle input lines marked by python-mode."""
1924 """Handle input lines marked by python-mode."""
1920
1925
1921 # Currently, nothing is done. Later more functionality can be added
1926 # Currently, nothing is done. Later more functionality can be added
1922 # here if needed.
1927 # here if needed.
1923
1928
1924 # The input cache shouldn't be updated
1929 # The input cache shouldn't be updated
1925
1930
1926 return line
1931 return line
1927
1932
1928 def write(self,data):
1933 def write(self,data):
1929 """Write a string to the default output"""
1934 """Write a string to the default output"""
1930 Term.cout.write(data)
1935 Term.cout.write(data)
1931
1936
1932 def write_err(self,data):
1937 def write_err(self,data):
1933 """Write a string to the default error output"""
1938 """Write a string to the default error output"""
1934 Term.cerr.write(data)
1939 Term.cerr.write(data)
1935
1940
1936 def exit(self):
1941 def exit(self):
1937 """Handle interactive exit.
1942 """Handle interactive exit.
1938
1943
1939 This method sets the exit_now attribute."""
1944 This method sets the exit_now attribute."""
1940
1945
1941 if self.rc.confirm_exit:
1946 if self.rc.confirm_exit:
1942 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1947 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1943 self.exit_now = True
1948 self.exit_now = True
1944 else:
1949 else:
1945 self.exit_now = True
1950 self.exit_now = True
1946 return self.exit_now
1951 return self.exit_now
1947
1952
1948 def safe_execfile(self,fname,*where,**kw):
1953 def safe_execfile(self,fname,*where,**kw):
1949 fname = os.path.expanduser(fname)
1954 fname = os.path.expanduser(fname)
1950
1955
1951 # find things also in current directory
1956 # find things also in current directory
1952 dname = os.path.dirname(fname)
1957 dname = os.path.dirname(fname)
1953 if not sys.path.count(dname):
1958 if not sys.path.count(dname):
1954 sys.path.append(dname)
1959 sys.path.append(dname)
1955
1960
1956 try:
1961 try:
1957 xfile = open(fname)
1962 xfile = open(fname)
1958 except:
1963 except:
1959 print >> Term.cerr, \
1964 print >> Term.cerr, \
1960 'Could not open file <%s> for safe execution.' % fname
1965 'Could not open file <%s> for safe execution.' % fname
1961 return None
1966 return None
1962
1967
1963 kw.setdefault('islog',0)
1968 kw.setdefault('islog',0)
1964 kw.setdefault('quiet',1)
1969 kw.setdefault('quiet',1)
1965 kw.setdefault('exit_ignore',0)
1970 kw.setdefault('exit_ignore',0)
1966 first = xfile.readline()
1971 first = xfile.readline()
1967 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
1972 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
1968 xfile.close()
1973 xfile.close()
1969 # line by line execution
1974 # line by line execution
1970 if first.startswith(loghead) or kw['islog']:
1975 if first.startswith(loghead) or kw['islog']:
1971 print 'Loading log file <%s> one line at a time...' % fname
1976 print 'Loading log file <%s> one line at a time...' % fname
1972 if kw['quiet']:
1977 if kw['quiet']:
1973 stdout_save = sys.stdout
1978 stdout_save = sys.stdout
1974 sys.stdout = StringIO.StringIO()
1979 sys.stdout = StringIO.StringIO()
1975 try:
1980 try:
1976 globs,locs = where[0:2]
1981 globs,locs = where[0:2]
1977 except:
1982 except:
1978 try:
1983 try:
1979 globs = locs = where[0]
1984 globs = locs = where[0]
1980 except:
1985 except:
1981 globs = locs = globals()
1986 globs = locs = globals()
1982 badblocks = []
1987 badblocks = []
1983
1988
1984 # we also need to identify indented blocks of code when replaying
1989 # we also need to identify indented blocks of code when replaying
1985 # logs and put them together before passing them to an exec
1990 # logs and put them together before passing them to an exec
1986 # statement. This takes a bit of regexp and look-ahead work in the
1991 # statement. This takes a bit of regexp and look-ahead work in the
1987 # file. It's easiest if we swallow the whole thing in memory
1992 # file. It's easiest if we swallow the whole thing in memory
1988 # first, and manually walk through the lines list moving the
1993 # first, and manually walk through the lines list moving the
1989 # counter ourselves.
1994 # counter ourselves.
1990 indent_re = re.compile('\s+\S')
1995 indent_re = re.compile('\s+\S')
1991 xfile = open(fname)
1996 xfile = open(fname)
1992 filelines = xfile.readlines()
1997 filelines = xfile.readlines()
1993 xfile.close()
1998 xfile.close()
1994 nlines = len(filelines)
1999 nlines = len(filelines)
1995 lnum = 0
2000 lnum = 0
1996 while lnum < nlines:
2001 while lnum < nlines:
1997 line = filelines[lnum]
2002 line = filelines[lnum]
1998 lnum += 1
2003 lnum += 1
1999 # don't re-insert logger status info into cache
2004 # don't re-insert logger status info into cache
2000 if line.startswith('#log#'):
2005 if line.startswith('#log#'):
2001 continue
2006 continue
2002 elif line.startswith('#!'):
2007 elif line.startswith('#!'):
2003 self.update_cache(line[1:])
2008 self.update_cache(line[1:])
2004 else:
2009 else:
2005 # build a block of code (maybe a single line) for execution
2010 # build a block of code (maybe a single line) for execution
2006 block = line
2011 block = line
2007 try:
2012 try:
2008 next = filelines[lnum] # lnum has already incremented
2013 next = filelines[lnum] # lnum has already incremented
2009 except:
2014 except:
2010 next = None
2015 next = None
2011 while next and indent_re.match(next):
2016 while next and indent_re.match(next):
2012 block += next
2017 block += next
2013 lnum += 1
2018 lnum += 1
2014 try:
2019 try:
2015 next = filelines[lnum]
2020 next = filelines[lnum]
2016 except:
2021 except:
2017 next = None
2022 next = None
2018 # now execute the block of one or more lines
2023 # now execute the block of one or more lines
2019 try:
2024 try:
2020 exec block in globs,locs
2025 exec block in globs,locs
2021 self.update_cache(block.rstrip())
2026 self.update_cache(block.rstrip())
2022 except SystemExit:
2027 except SystemExit:
2023 pass
2028 pass
2024 except:
2029 except:
2025 badblocks.append(block.rstrip())
2030 badblocks.append(block.rstrip())
2026 if kw['quiet']: # restore stdout
2031 if kw['quiet']: # restore stdout
2027 sys.stdout.close()
2032 sys.stdout.close()
2028 sys.stdout = stdout_save
2033 sys.stdout = stdout_save
2029 print 'Finished replaying log file <%s>' % fname
2034 print 'Finished replaying log file <%s>' % fname
2030 if badblocks:
2035 if badblocks:
2031 print >> sys.stderr, ('\nThe following lines/blocks in file '
2036 print >> sys.stderr, ('\nThe following lines/blocks in file '
2032 '<%s> reported errors:' % fname)
2037 '<%s> reported errors:' % fname)
2033
2038
2034 for badline in badblocks:
2039 for badline in badblocks:
2035 print >> sys.stderr, badline
2040 print >> sys.stderr, badline
2036 else: # regular file execution
2041 else: # regular file execution
2037 try:
2042 try:
2038 execfile(fname,*where)
2043 execfile(fname,*where)
2039 except SyntaxError:
2044 except SyntaxError:
2040 etype,evalue = sys.exc_info()[:2]
2045 etype,evalue = sys.exc_info()[:2]
2041 self.SyntaxTB(etype,evalue,[])
2046 self.SyntaxTB(etype,evalue,[])
2042 warn('Failure executing file: <%s>' % fname)
2047 warn('Failure executing file: <%s>' % fname)
2043 except SystemExit,status:
2048 except SystemExit,status:
2044 if not kw['exit_ignore']:
2049 if not kw['exit_ignore']:
2045 self.InteractiveTB()
2050 self.InteractiveTB()
2046 warn('Failure executing file: <%s>' % fname)
2051 warn('Failure executing file: <%s>' % fname)
2047 except:
2052 except:
2048 self.InteractiveTB()
2053 self.InteractiveTB()
2049 warn('Failure executing file: <%s>' % fname)
2054 warn('Failure executing file: <%s>' % fname)
2050
2055
2051 #************************* end of file <iplib.py> *****************************
2056 #************************* end of file <iplib.py> *****************************
@@ -1,796 +1,796 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 ultraTB.py -- Spice up your tracebacks!
3 ultraTB.py -- Spice up your tracebacks!
4
4
5 * ColorTB
5 * ColorTB
6 I've always found it a bit hard to visually parse tracebacks in Python. The
6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 ColorTB class is a solution to that problem. It colors the different parts of a
7 ColorTB class is a solution to that problem. It colors the different parts of a
8 traceback in a manner similar to what you would expect from a syntax-highlighting
8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 text editor.
9 text editor.
10
10
11 Installation instructions for ColorTB:
11 Installation instructions for ColorTB:
12 import sys,ultraTB
12 import sys,ultraTB
13 sys.excepthook = ultraTB.ColorTB()
13 sys.excepthook = ultraTB.ColorTB()
14
14
15 * VerboseTB
15 * VerboseTB
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 and intended it for CGI programmers, but why should they have all the fun? I
18 and intended it for CGI programmers, but why should they have all the fun? I
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 but kind of neat, and maybe useful for long-running programs that you believe
20 but kind of neat, and maybe useful for long-running programs that you believe
21 are bug-free. If a crash *does* occur in that type of program you want details.
21 are bug-free. If a crash *does* occur in that type of program you want details.
22 Give it a shot--you'll love it or you'll hate it.
22 Give it a shot--you'll love it or you'll hate it.
23
23
24 Note:
24 Note:
25
25
26 The Verbose mode prints the variables currently visible where the exception
26 The Verbose mode prints the variables currently visible where the exception
27 happened (shortening their strings if too long). This can potentially be
27 happened (shortening their strings if too long). This can potentially be
28 very slow, if you happen to have a huge data structure whose string
28 very slow, if you happen to have a huge data structure whose string
29 representation is complex to compute. Your computer may appear to freeze for
29 representation is complex to compute. Your computer may appear to freeze for
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 with Ctrl-C (maybe hitting it more than once).
31 with Ctrl-C (maybe hitting it more than once).
32
32
33 If you encounter this kind of situation often, you may want to use the
33 If you encounter this kind of situation often, you may want to use the
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 variables (but otherwise includes the information and context given by
35 variables (but otherwise includes the information and context given by
36 Verbose).
36 Verbose).
37
37
38
38
39 Installation instructions for ColorTB:
39 Installation instructions for ColorTB:
40 import sys,ultraTB
40 import sys,ultraTB
41 sys.excepthook = ultraTB.VerboseTB()
41 sys.excepthook = ultraTB.VerboseTB()
42
42
43 Note: Much of the code in this module was lifted verbatim from the standard
43 Note: Much of the code in this module was lifted verbatim from the standard
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45
45
46 * Color schemes
46 * Color schemes
47 The colors are defined in the class TBTools through the use of the
47 The colors are defined in the class TBTools through the use of the
48 ColorSchemeTable class. Currently the following exist:
48 ColorSchemeTable class. Currently the following exist:
49
49
50 - NoColor: allows all of this module to be used in any terminal (the color
50 - NoColor: allows all of this module to be used in any terminal (the color
51 escapes are just dummy blank strings).
51 escapes are just dummy blank strings).
52
52
53 - Linux: is meant to look good in a terminal like the Linux console (black
53 - Linux: is meant to look good in a terminal like the Linux console (black
54 or very dark background).
54 or very dark background).
55
55
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 in light background terminals.
57 in light background terminals.
58
58
59 You can implement other color schemes easily, the syntax is fairly
59 You can implement other color schemes easily, the syntax is fairly
60 self-explanatory. Please send back new schemes you develop to the author for
60 self-explanatory. Please send back new schemes you develop to the author for
61 possible inclusion in future releases.
61 possible inclusion in future releases.
62
62
63 $Id: ultraTB.py 965 2005-12-28 23:23:09Z fperez $"""
63 $Id: ultraTB.py 975 2005-12-29 23:50:22Z fperez $"""
64
64
65 #*****************************************************************************
65 #*****************************************************************************
66 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
66 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
67 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
67 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
68 #
68 #
69 # Distributed under the terms of the BSD License. The full license is in
69 # Distributed under the terms of the BSD License. The full license is in
70 # the file COPYING, distributed as part of this software.
70 # the file COPYING, distributed as part of this software.
71 #*****************************************************************************
71 #*****************************************************************************
72
72
73 from IPython import Release
73 from IPython import Release
74 __author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
74 __author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
75 Release.authors['Fernando'])
75 Release.authors['Fernando'])
76 __license__ = Release.license
76 __license__ = Release.license
77
77
78 # Required modules
78 # Required modules
79 import inspect
79 import inspect
80 import keyword
80 import keyword
81 import linecache
81 import linecache
82 import os
82 import os
83 import pydoc
83 import pydoc
84 import string
84 import string
85 import sys
85 import sys
86 import time
86 import time
87 import tokenize
87 import tokenize
88 import traceback
88 import traceback
89 import types
89 import types
90
90
91 # IPython's own modules
91 # IPython's own modules
92 # Modified pdb which doesn't damage IPython's readline handling
92 # Modified pdb which doesn't damage IPython's readline handling
93 from IPython import Debugger
93 from IPython import Debugger
94 from IPython.Struct import Struct
94 from IPython.Struct import Struct
95 from IPython.excolors import ExceptionColors
95 from IPython.excolors import ExceptionColors
96 from IPython.genutils import Term,uniq_stable,error,info
96 from IPython.genutils import Term,uniq_stable,error,info
97
97
98 #---------------------------------------------------------------------------
98 #---------------------------------------------------------------------------
99 # Code begins
99 # Code begins
100
100
101 def inspect_error():
101 def inspect_error():
102 """Print a message about internal inspect errors.
102 """Print a message about internal inspect errors.
103
103
104 These are unfortunately quite common."""
104 These are unfortunately quite common."""
105
105
106 error('Internal Python error in the inspect module.\n'
106 error('Internal Python error in the inspect module.\n'
107 'Below is the traceback from this internal error.\n')
107 'Below is the traceback from this internal error.\n')
108
108
109 class TBTools:
109 class TBTools:
110 """Basic tools used by all traceback printer classes."""
110 """Basic tools used by all traceback printer classes."""
111
111
112 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
112 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
113 # Whether to call the interactive pdb debugger after printing
113 # Whether to call the interactive pdb debugger after printing
114 # tracebacks or not
114 # tracebacks or not
115 self.call_pdb = call_pdb
115 self.call_pdb = call_pdb
116
116
117 # Create color table
117 # Create color table
118 self.color_scheme_table = ExceptionColors
118 self.color_scheme_table = ExceptionColors
119
119
120 self.set_colors(color_scheme)
120 self.set_colors(color_scheme)
121 self.old_scheme = color_scheme # save initial value for toggles
121 self.old_scheme = color_scheme # save initial value for toggles
122
122
123 if call_pdb:
123 if call_pdb:
124 self.pdb = Debugger.Pdb(self.color_scheme_table.active_scheme_name)
124 self.pdb = Debugger.Pdb(self.color_scheme_table.active_scheme_name)
125 else:
125 else:
126 self.pdb = None
126 self.pdb = None
127
127
128 def set_colors(self,*args,**kw):
128 def set_colors(self,*args,**kw):
129 """Shorthand access to the color table scheme selector method."""
129 """Shorthand access to the color table scheme selector method."""
130
130
131 self.color_scheme_table.set_active_scheme(*args,**kw)
131 self.color_scheme_table.set_active_scheme(*args,**kw)
132 # for convenience, set Colors to the active scheme
132 # for convenience, set Colors to the active scheme
133 self.Colors = self.color_scheme_table.active_colors
133 self.Colors = self.color_scheme_table.active_colors
134
134
135 def color_toggle(self):
135 def color_toggle(self):
136 """Toggle between the currently active color scheme and NoColor."""
136 """Toggle between the currently active color scheme and NoColor."""
137
137
138 if self.color_scheme_table.active_scheme_name == 'NoColor':
138 if self.color_scheme_table.active_scheme_name == 'NoColor':
139 self.color_scheme_table.set_active_scheme(self.old_scheme)
139 self.color_scheme_table.set_active_scheme(self.old_scheme)
140 self.Colors = self.color_scheme_table.active_colors
140 self.Colors = self.color_scheme_table.active_colors
141 else:
141 else:
142 self.old_scheme = self.color_scheme_table.active_scheme_name
142 self.old_scheme = self.color_scheme_table.active_scheme_name
143 self.color_scheme_table.set_active_scheme('NoColor')
143 self.color_scheme_table.set_active_scheme('NoColor')
144 self.Colors = self.color_scheme_table.active_colors
144 self.Colors = self.color_scheme_table.active_colors
145
145
146 #---------------------------------------------------------------------------
146 #---------------------------------------------------------------------------
147 class ListTB(TBTools):
147 class ListTB(TBTools):
148 """Print traceback information from a traceback list, with optional color.
148 """Print traceback information from a traceback list, with optional color.
149
149
150 Calling: requires 3 arguments:
150 Calling: requires 3 arguments:
151 (etype, evalue, elist)
151 (etype, evalue, elist)
152 as would be obtained by:
152 as would be obtained by:
153 etype, evalue, tb = sys.exc_info()
153 etype, evalue, tb = sys.exc_info()
154 if tb:
154 if tb:
155 elist = traceback.extract_tb(tb)
155 elist = traceback.extract_tb(tb)
156 else:
156 else:
157 elist = None
157 elist = None
158
158
159 It can thus be used by programs which need to process the traceback before
159 It can thus be used by programs which need to process the traceback before
160 printing (such as console replacements based on the code module from the
160 printing (such as console replacements based on the code module from the
161 standard library).
161 standard library).
162
162
163 Because they are meant to be called without a full traceback (only a
163 Because they are meant to be called without a full traceback (only a
164 list), instances of this class can't call the interactive pdb debugger."""
164 list), instances of this class can't call the interactive pdb debugger."""
165
165
166 def __init__(self,color_scheme = 'NoColor'):
166 def __init__(self,color_scheme = 'NoColor'):
167 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
167 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
168
168
169 def __call__(self, etype, value, elist):
169 def __call__(self, etype, value, elist):
170 print >> Term.cerr, self.text(etype,value,elist)
170 print >> Term.cerr, self.text(etype,value,elist)
171
171
172 def text(self,etype, value, elist,context=5):
172 def text(self,etype, value, elist,context=5):
173 """Return a color formatted string with the traceback info."""
173 """Return a color formatted string with the traceback info."""
174
174
175 Colors = self.Colors
175 Colors = self.Colors
176 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
176 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
177 if elist:
177 if elist:
178 out_string.append('Traceback %s(most recent call last)%s:' % \
178 out_string.append('Traceback %s(most recent call last)%s:' % \
179 (Colors.normalEm, Colors.Normal) + '\n')
179 (Colors.normalEm, Colors.Normal) + '\n')
180 out_string.extend(self._format_list(elist))
180 out_string.extend(self._format_list(elist))
181 lines = self._format_exception_only(etype, value)
181 lines = self._format_exception_only(etype, value)
182 for line in lines[:-1]:
182 for line in lines[:-1]:
183 out_string.append(" "+line)
183 out_string.append(" "+line)
184 out_string.append(lines[-1])
184 out_string.append(lines[-1])
185 return ''.join(out_string)
185 return ''.join(out_string)
186
186
187 def _format_list(self, extracted_list):
187 def _format_list(self, extracted_list):
188 """Format a list of traceback entry tuples for printing.
188 """Format a list of traceback entry tuples for printing.
189
189
190 Given a list of tuples as returned by extract_tb() or
190 Given a list of tuples as returned by extract_tb() or
191 extract_stack(), return a list of strings ready for printing.
191 extract_stack(), return a list of strings ready for printing.
192 Each string in the resulting list corresponds to the item with the
192 Each string in the resulting list corresponds to the item with the
193 same index in the argument list. Each string ends in a newline;
193 same index in the argument list. Each string ends in a newline;
194 the strings may contain internal newlines as well, for those items
194 the strings may contain internal newlines as well, for those items
195 whose source text line is not None.
195 whose source text line is not None.
196
196
197 Lifted almost verbatim from traceback.py
197 Lifted almost verbatim from traceback.py
198 """
198 """
199
199
200 Colors = self.Colors
200 Colors = self.Colors
201 list = []
201 list = []
202 for filename, lineno, name, line in extracted_list[:-1]:
202 for filename, lineno, name, line in extracted_list[:-1]:
203 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
203 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
204 (Colors.filename, filename, Colors.Normal,
204 (Colors.filename, filename, Colors.Normal,
205 Colors.lineno, lineno, Colors.Normal,
205 Colors.lineno, lineno, Colors.Normal,
206 Colors.name, name, Colors.Normal)
206 Colors.name, name, Colors.Normal)
207 if line:
207 if line:
208 item = item + ' %s\n' % line.strip()
208 item = item + ' %s\n' % line.strip()
209 list.append(item)
209 list.append(item)
210 # Emphasize the last entry
210 # Emphasize the last entry
211 filename, lineno, name, line = extracted_list[-1]
211 filename, lineno, name, line = extracted_list[-1]
212 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
212 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
213 (Colors.normalEm,
213 (Colors.normalEm,
214 Colors.filenameEm, filename, Colors.normalEm,
214 Colors.filenameEm, filename, Colors.normalEm,
215 Colors.linenoEm, lineno, Colors.normalEm,
215 Colors.linenoEm, lineno, Colors.normalEm,
216 Colors.nameEm, name, Colors.normalEm,
216 Colors.nameEm, name, Colors.normalEm,
217 Colors.Normal)
217 Colors.Normal)
218 if line:
218 if line:
219 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
219 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
220 Colors.Normal)
220 Colors.Normal)
221 list.append(item)
221 list.append(item)
222 return list
222 return list
223
223
224 def _format_exception_only(self, etype, value):
224 def _format_exception_only(self, etype, value):
225 """Format the exception part of a traceback.
225 """Format the exception part of a traceback.
226
226
227 The arguments are the exception type and value such as given by
227 The arguments are the exception type and value such as given by
228 sys.last_type and sys.last_value. The return value is a list of
228 sys.exc_info()[:2]. The return value is a list of strings, each ending
229 strings, each ending in a newline. Normally, the list contains a
229 in a newline. Normally, the list contains a single string; however,
230 single string; however, for SyntaxError exceptions, it contains
230 for SyntaxError exceptions, it contains several lines that (when
231 several lines that (when printed) display detailed information
231 printed) display detailed information about where the syntax error
232 about where the syntax error occurred. The message indicating
232 occurred. The message indicating which exception occurred is the
233 which exception occurred is the always last string in the list.
233 always last string in the list.
234
234
235 Also lifted nearly verbatim from traceback.py
235 Also lifted nearly verbatim from traceback.py
236 """
236 """
237
237
238 Colors = self.Colors
238 Colors = self.Colors
239 list = []
239 list = []
240 if type(etype) == types.ClassType:
240 if type(etype) == types.ClassType:
241 stype = Colors.excName + etype.__name__ + Colors.Normal
241 stype = Colors.excName + etype.__name__ + Colors.Normal
242 else:
242 else:
243 stype = etype # String exceptions don't get special coloring
243 stype = etype # String exceptions don't get special coloring
244 if value is None:
244 if value is None:
245 list.append( str(stype) + '\n')
245 list.append( str(stype) + '\n')
246 else:
246 else:
247 if etype is SyntaxError:
247 if etype is SyntaxError:
248 try:
248 try:
249 msg, (filename, lineno, offset, line) = value
249 msg, (filename, lineno, offset, line) = value
250 except:
250 except:
251 pass
251 pass
252 else:
252 else:
253 #print 'filename is',filename # dbg
253 #print 'filename is',filename # dbg
254 if not filename: filename = "<string>"
254 if not filename: filename = "<string>"
255 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
255 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
256 (Colors.normalEm,
256 (Colors.normalEm,
257 Colors.filenameEm, filename, Colors.normalEm,
257 Colors.filenameEm, filename, Colors.normalEm,
258 Colors.linenoEm, lineno, Colors.Normal ))
258 Colors.linenoEm, lineno, Colors.Normal ))
259 if line is not None:
259 if line is not None:
260 i = 0
260 i = 0
261 while i < len(line) and line[i].isspace():
261 while i < len(line) and line[i].isspace():
262 i = i+1
262 i = i+1
263 list.append('%s %s%s\n' % (Colors.line,
263 list.append('%s %s%s\n' % (Colors.line,
264 line.strip(),
264 line.strip(),
265 Colors.Normal))
265 Colors.Normal))
266 if offset is not None:
266 if offset is not None:
267 s = ' '
267 s = ' '
268 for c in line[i:offset-1]:
268 for c in line[i:offset-1]:
269 if c.isspace():
269 if c.isspace():
270 s = s + c
270 s = s + c
271 else:
271 else:
272 s = s + ' '
272 s = s + ' '
273 list.append('%s%s^%s\n' % (Colors.caret, s,
273 list.append('%s%s^%s\n' % (Colors.caret, s,
274 Colors.Normal) )
274 Colors.Normal) )
275 value = msg
275 value = msg
276 s = self._some_str(value)
276 s = self._some_str(value)
277 if s:
277 if s:
278 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
278 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
279 Colors.Normal, s))
279 Colors.Normal, s))
280 else:
280 else:
281 list.append('%s\n' % str(stype))
281 list.append('%s\n' % str(stype))
282 return list
282 return list
283
283
284 def _some_str(self, value):
284 def _some_str(self, value):
285 # Lifted from traceback.py
285 # Lifted from traceback.py
286 try:
286 try:
287 return str(value)
287 return str(value)
288 except:
288 except:
289 return '<unprintable %s object>' % type(value).__name__
289 return '<unprintable %s object>' % type(value).__name__
290
290
291 #----------------------------------------------------------------------------
291 #----------------------------------------------------------------------------
292 class VerboseTB(TBTools):
292 class VerboseTB(TBTools):
293 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
293 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
294 of HTML. Requires inspect and pydoc. Crazy, man.
294 of HTML. Requires inspect and pydoc. Crazy, man.
295
295
296 Modified version which optionally strips the topmost entries from the
296 Modified version which optionally strips the topmost entries from the
297 traceback, to be used with alternate interpreters (because their own code
297 traceback, to be used with alternate interpreters (because their own code
298 would appear in the traceback)."""
298 would appear in the traceback)."""
299
299
300 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
300 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
301 call_pdb = 0, include_vars=1):
301 call_pdb = 0, include_vars=1):
302 """Specify traceback offset, headers and color scheme.
302 """Specify traceback offset, headers and color scheme.
303
303
304 Define how many frames to drop from the tracebacks. Calling it with
304 Define how many frames to drop from the tracebacks. Calling it with
305 tb_offset=1 allows use of this handler in interpreters which will have
305 tb_offset=1 allows use of this handler in interpreters which will have
306 their own code at the top of the traceback (VerboseTB will first
306 their own code at the top of the traceback (VerboseTB will first
307 remove that frame before printing the traceback info)."""
307 remove that frame before printing the traceback info)."""
308 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
308 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
309 self.tb_offset = tb_offset
309 self.tb_offset = tb_offset
310 self.long_header = long_header
310 self.long_header = long_header
311 self.include_vars = include_vars
311 self.include_vars = include_vars
312
312
313 def text(self, etype, evalue, etb, context=5):
313 def text(self, etype, evalue, etb, context=5):
314 """Return a nice text document describing the traceback."""
314 """Return a nice text document describing the traceback."""
315
315
316 # some locals
316 # some locals
317 Colors = self.Colors # just a shorthand + quicker name lookup
317 Colors = self.Colors # just a shorthand + quicker name lookup
318 ColorsNormal = Colors.Normal # used a lot
318 ColorsNormal = Colors.Normal # used a lot
319 indent_size = 8 # we need some space to put line numbers before
319 indent_size = 8 # we need some space to put line numbers before
320 indent = ' '*indent_size
320 indent = ' '*indent_size
321 numbers_width = indent_size - 1 # leave space between numbers & code
321 numbers_width = indent_size - 1 # leave space between numbers & code
322 text_repr = pydoc.text.repr
322 text_repr = pydoc.text.repr
323 exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
323 exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
324 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
324 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
325 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
325 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
326
326
327 # some internal-use functions
327 # some internal-use functions
328 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
328 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
329 def nullrepr(value, repr=text_repr): return ''
329 def nullrepr(value, repr=text_repr): return ''
330
330
331 # meat of the code begins
331 # meat of the code begins
332 if type(etype) is types.ClassType:
332 if type(etype) is types.ClassType:
333 etype = etype.__name__
333 etype = etype.__name__
334
334
335 if self.long_header:
335 if self.long_header:
336 # Header with the exception type, python version, and date
336 # Header with the exception type, python version, and date
337 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
337 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
338 date = time.ctime(time.time())
338 date = time.ctime(time.time())
339
339
340 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
340 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
341 exc, ' '*(75-len(str(etype))-len(pyver)),
341 exc, ' '*(75-len(str(etype))-len(pyver)),
342 pyver, string.rjust(date, 75) )
342 pyver, string.rjust(date, 75) )
343 head += "\nA problem occured executing Python code. Here is the sequence of function"\
343 head += "\nA problem occured executing Python code. Here is the sequence of function"\
344 "\ncalls leading up to the error, with the most recent (innermost) call last."
344 "\ncalls leading up to the error, with the most recent (innermost) call last."
345 else:
345 else:
346 # Simplified header
346 # Simplified header
347 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
347 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
348 string.rjust('Traceback (most recent call last)',
348 string.rjust('Traceback (most recent call last)',
349 75 - len(str(etype)) ) )
349 75 - len(str(etype)) ) )
350 frames = []
350 frames = []
351 # Flush cache before calling inspect. This helps alleviate some of the
351 # Flush cache before calling inspect. This helps alleviate some of the
352 # problems with python 2.3's inspect.py.
352 # problems with python 2.3's inspect.py.
353 linecache.checkcache()
353 linecache.checkcache()
354 # Drop topmost frames if requested
354 # Drop topmost frames if requested
355 try:
355 try:
356 records = inspect.getinnerframes(etb, context)[self.tb_offset:]
356 records = inspect.getinnerframes(etb, context)[self.tb_offset:]
357 except:
357 except:
358
358
359 # FIXME: I've been getting many crash reports from python 2.3
359 # FIXME: I've been getting many crash reports from python 2.3
360 # users, traceable to inspect.py. If I can find a small test-case
360 # users, traceable to inspect.py. If I can find a small test-case
361 # to reproduce this, I should either write a better workaround or
361 # to reproduce this, I should either write a better workaround or
362 # file a bug report against inspect (if that's the real problem).
362 # file a bug report against inspect (if that's the real problem).
363 # So far, I haven't been able to find an isolated example to
363 # So far, I haven't been able to find an isolated example to
364 # reproduce the problem.
364 # reproduce the problem.
365 inspect_error()
365 inspect_error()
366 traceback.print_exc(file=Term.cerr)
366 traceback.print_exc(file=Term.cerr)
367 info('\nUnfortunately, your original traceback can not be constructed.\n')
367 info('\nUnfortunately, your original traceback can not be constructed.\n')
368 return ''
368 return ''
369
369
370 # build some color string templates outside these nested loops
370 # build some color string templates outside these nested loops
371 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
371 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
372 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
372 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
373 ColorsNormal)
373 ColorsNormal)
374 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
374 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
375 (Colors.vName, Colors.valEm, ColorsNormal)
375 (Colors.vName, Colors.valEm, ColorsNormal)
376 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
376 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
377 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
377 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
378 Colors.vName, ColorsNormal)
378 Colors.vName, ColorsNormal)
379 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
379 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
380 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
380 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
381 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
381 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
382 ColorsNormal)
382 ColorsNormal)
383
383
384 # now, loop over all records printing context and info
384 # now, loop over all records printing context and info
385 abspath = os.path.abspath
385 abspath = os.path.abspath
386 for frame, file, lnum, func, lines, index in records:
386 for frame, file, lnum, func, lines, index in records:
387 #print '*** record:',file,lnum,func,lines,index # dbg
387 #print '*** record:',file,lnum,func,lines,index # dbg
388 try:
388 try:
389 file = file and abspath(file) or '?'
389 file = file and abspath(file) or '?'
390 except OSError:
390 except OSError:
391 # if file is '<console>' or something not in the filesystem,
391 # if file is '<console>' or something not in the filesystem,
392 # the abspath call will throw an OSError. Just ignore it and
392 # the abspath call will throw an OSError. Just ignore it and
393 # keep the original file string.
393 # keep the original file string.
394 pass
394 pass
395 link = tpl_link % file
395 link = tpl_link % file
396 try:
396 try:
397 args, varargs, varkw, locals = inspect.getargvalues(frame)
397 args, varargs, varkw, locals = inspect.getargvalues(frame)
398 except:
398 except:
399 # This can happen due to a bug in python2.3. We should be
399 # This can happen due to a bug in python2.3. We should be
400 # able to remove this try/except when 2.4 becomes a
400 # able to remove this try/except when 2.4 becomes a
401 # requirement. Bug details at http://python.org/sf/1005466
401 # requirement. Bug details at http://python.org/sf/1005466
402 inspect_error()
402 inspect_error()
403 traceback.print_exc(file=Term.cerr)
403 traceback.print_exc(file=Term.cerr)
404 info("\nIPython's exception reporting continues...\n")
404 info("\nIPython's exception reporting continues...\n")
405
405
406 if func == '?':
406 if func == '?':
407 call = ''
407 call = ''
408 else:
408 else:
409 # Decide whether to include variable details or not
409 # Decide whether to include variable details or not
410 var_repr = self.include_vars and eqrepr or nullrepr
410 var_repr = self.include_vars and eqrepr or nullrepr
411 try:
411 try:
412 call = tpl_call % (func,inspect.formatargvalues(args,
412 call = tpl_call % (func,inspect.formatargvalues(args,
413 varargs, varkw,
413 varargs, varkw,
414 locals,formatvalue=var_repr))
414 locals,formatvalue=var_repr))
415 except KeyError:
415 except KeyError:
416 # Very odd crash from inspect.formatargvalues(). The
416 # Very odd crash from inspect.formatargvalues(). The
417 # scenario under which it appeared was a call to
417 # scenario under which it appeared was a call to
418 # view(array,scale) in NumTut.view.view(), where scale had
418 # view(array,scale) in NumTut.view.view(), where scale had
419 # been defined as a scalar (it should be a tuple). Somehow
419 # been defined as a scalar (it should be a tuple). Somehow
420 # inspect messes up resolving the argument list of view()
420 # inspect messes up resolving the argument list of view()
421 # and barfs out. At some point I should dig into this one
421 # and barfs out. At some point I should dig into this one
422 # and file a bug report about it.
422 # and file a bug report about it.
423 inspect_error()
423 inspect_error()
424 traceback.print_exc(file=Term.cerr)
424 traceback.print_exc(file=Term.cerr)
425 info("\nIPython's exception reporting continues...\n")
425 info("\nIPython's exception reporting continues...\n")
426 call = tpl_call_fail % func
426 call = tpl_call_fail % func
427
427
428 # Initialize a list of names on the current line, which the
428 # Initialize a list of names on the current line, which the
429 # tokenizer below will populate.
429 # tokenizer below will populate.
430 names = []
430 names = []
431
431
432 def tokeneater(token_type, token, start, end, line):
432 def tokeneater(token_type, token, start, end, line):
433 """Stateful tokeneater which builds dotted names.
433 """Stateful tokeneater which builds dotted names.
434
434
435 The list of names it appends to (from the enclosing scope) can
435 The list of names it appends to (from the enclosing scope) can
436 contain repeated composite names. This is unavoidable, since
436 contain repeated composite names. This is unavoidable, since
437 there is no way to disambguate partial dotted structures until
437 there is no way to disambguate partial dotted structures until
438 the full list is known. The caller is responsible for pruning
438 the full list is known. The caller is responsible for pruning
439 the final list of duplicates before using it."""
439 the final list of duplicates before using it."""
440
440
441 # build composite names
441 # build composite names
442 if token == '.':
442 if token == '.':
443 try:
443 try:
444 names[-1] += '.'
444 names[-1] += '.'
445 # store state so the next token is added for x.y.z names
445 # store state so the next token is added for x.y.z names
446 tokeneater.name_cont = True
446 tokeneater.name_cont = True
447 return
447 return
448 except IndexError:
448 except IndexError:
449 pass
449 pass
450 if token_type == tokenize.NAME and token not in keyword.kwlist:
450 if token_type == tokenize.NAME and token not in keyword.kwlist:
451 if tokeneater.name_cont:
451 if tokeneater.name_cont:
452 # Dotted names
452 # Dotted names
453 names[-1] += token
453 names[-1] += token
454 tokeneater.name_cont = False
454 tokeneater.name_cont = False
455 else:
455 else:
456 # Regular new names. We append everything, the caller
456 # Regular new names. We append everything, the caller
457 # will be responsible for pruning the list later. It's
457 # will be responsible for pruning the list later. It's
458 # very tricky to try to prune as we go, b/c composite
458 # very tricky to try to prune as we go, b/c composite
459 # names can fool us. The pruning at the end is easy
459 # names can fool us. The pruning at the end is easy
460 # to do (or the caller can print a list with repeated
460 # to do (or the caller can print a list with repeated
461 # names if so desired.
461 # names if so desired.
462 names.append(token)
462 names.append(token)
463 elif token_type == tokenize.NEWLINE:
463 elif token_type == tokenize.NEWLINE:
464 raise IndexError
464 raise IndexError
465 # we need to store a bit of state in the tokenizer to build
465 # we need to store a bit of state in the tokenizer to build
466 # dotted names
466 # dotted names
467 tokeneater.name_cont = False
467 tokeneater.name_cont = False
468
468
469 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
469 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
470 line = getline(file, lnum[0])
470 line = getline(file, lnum[0])
471 lnum[0] += 1
471 lnum[0] += 1
472 return line
472 return line
473
473
474 # Build the list of names on this line of code where the exception
474 # Build the list of names on this line of code where the exception
475 # occurred.
475 # occurred.
476 try:
476 try:
477 # This builds the names list in-place by capturing it from the
477 # This builds the names list in-place by capturing it from the
478 # enclosing scope.
478 # enclosing scope.
479 tokenize.tokenize(linereader, tokeneater)
479 tokenize.tokenize(linereader, tokeneater)
480 except IndexError:
480 except IndexError:
481 # signals exit of tokenizer
481 # signals exit of tokenizer
482 pass
482 pass
483 except tokenize.TokenError,msg:
483 except tokenize.TokenError,msg:
484 _m = ("An unexpected error occurred while tokenizing input\n"
484 _m = ("An unexpected error occurred while tokenizing input\n"
485 "The following traceback may be corrupted or invalid\n"
485 "The following traceback may be corrupted or invalid\n"
486 "The error message is: %s\n" % msg)
486 "The error message is: %s\n" % msg)
487 error(_m)
487 error(_m)
488
488
489 # prune names list of duplicates, but keep the right order
489 # prune names list of duplicates, but keep the right order
490 unique_names = uniq_stable(names)
490 unique_names = uniq_stable(names)
491
491
492 # Start loop over vars
492 # Start loop over vars
493 lvals = []
493 lvals = []
494 if self.include_vars:
494 if self.include_vars:
495 for name_full in unique_names:
495 for name_full in unique_names:
496 name_base = name_full.split('.',1)[0]
496 name_base = name_full.split('.',1)[0]
497 if name_base in frame.f_code.co_varnames:
497 if name_base in frame.f_code.co_varnames:
498 if locals.has_key(name_base):
498 if locals.has_key(name_base):
499 try:
499 try:
500 value = repr(eval(name_full,locals))
500 value = repr(eval(name_full,locals))
501 except:
501 except:
502 value = undefined
502 value = undefined
503 else:
503 else:
504 value = undefined
504 value = undefined
505 name = tpl_local_var % name_full
505 name = tpl_local_var % name_full
506 else:
506 else:
507 if frame.f_globals.has_key(name_base):
507 if frame.f_globals.has_key(name_base):
508 try:
508 try:
509 value = repr(eval(name_full,frame.f_globals))
509 value = repr(eval(name_full,frame.f_globals))
510 except:
510 except:
511 value = undefined
511 value = undefined
512 else:
512 else:
513 value = undefined
513 value = undefined
514 name = tpl_global_var % name_full
514 name = tpl_global_var % name_full
515 lvals.append(tpl_name_val % (name,value))
515 lvals.append(tpl_name_val % (name,value))
516 if lvals:
516 if lvals:
517 lvals = '%s%s' % (indent,em_normal.join(lvals))
517 lvals = '%s%s' % (indent,em_normal.join(lvals))
518 else:
518 else:
519 lvals = ''
519 lvals = ''
520
520
521 level = '%s %s\n' % (link,call)
521 level = '%s %s\n' % (link,call)
522 excerpt = []
522 excerpt = []
523 if index is not None:
523 if index is not None:
524 i = lnum - index
524 i = lnum - index
525 for line in lines:
525 for line in lines:
526 if i == lnum:
526 if i == lnum:
527 # This is the line with the error
527 # This is the line with the error
528 pad = numbers_width - len(str(i))
528 pad = numbers_width - len(str(i))
529 if pad >= 3:
529 if pad >= 3:
530 marker = '-'*(pad-3) + '-> '
530 marker = '-'*(pad-3) + '-> '
531 elif pad == 2:
531 elif pad == 2:
532 marker = '> '
532 marker = '> '
533 elif pad == 1:
533 elif pad == 1:
534 marker = '>'
534 marker = '>'
535 else:
535 else:
536 marker = ''
536 marker = ''
537 num = '%s%s' % (marker,i)
537 num = '%s%s' % (marker,i)
538 line = tpl_line_em % (num,line)
538 line = tpl_line_em % (num,line)
539 else:
539 else:
540 num = '%*s' % (numbers_width,i)
540 num = '%*s' % (numbers_width,i)
541 line = tpl_line % (num,line)
541 line = tpl_line % (num,line)
542
542
543 excerpt.append(line)
543 excerpt.append(line)
544 if self.include_vars and i == lnum:
544 if self.include_vars and i == lnum:
545 excerpt.append('%s\n' % lvals)
545 excerpt.append('%s\n' % lvals)
546 i += 1
546 i += 1
547 frames.append('%s%s' % (level,''.join(excerpt)) )
547 frames.append('%s%s' % (level,''.join(excerpt)) )
548
548
549 # Get (safely) a string form of the exception info
549 # Get (safely) a string form of the exception info
550 try:
550 try:
551 etype_str,evalue_str = map(str,(etype,evalue))
551 etype_str,evalue_str = map(str,(etype,evalue))
552 except:
552 except:
553 # User exception is improperly defined.
553 # User exception is improperly defined.
554 etype,evalue = str,sys.exc_info()[:2]
554 etype,evalue = str,sys.exc_info()[:2]
555 etype_str,evalue_str = map(str,(etype,evalue))
555 etype_str,evalue_str = map(str,(etype,evalue))
556 # ... and format it
556 # ... and format it
557 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
557 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
558 ColorsNormal, evalue_str)]
558 ColorsNormal, evalue_str)]
559 if type(evalue) is types.InstanceType:
559 if type(evalue) is types.InstanceType:
560 try:
560 try:
561 names = [w for w in dir(evalue) if isinstance(w, basestring)]
561 names = [w for w in dir(evalue) if isinstance(w, basestring)]
562 except:
562 except:
563 # Every now and then, an object with funny inernals blows up
563 # Every now and then, an object with funny inernals blows up
564 # when dir() is called on it. We do the best we can to report
564 # when dir() is called on it. We do the best we can to report
565 # the problem and continue
565 # the problem and continue
566 _m = '%sException reporting error (object with broken dir())%s:'
566 _m = '%sException reporting error (object with broken dir())%s:'
567 exception.append(_m % (Colors.excName,ColorsNormal))
567 exception.append(_m % (Colors.excName,ColorsNormal))
568 etype_str,evalue_str = map(str,sys.exc_info()[:2])
568 etype_str,evalue_str = map(str,sys.exc_info()[:2])
569 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
569 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
570 ColorsNormal, evalue_str))
570 ColorsNormal, evalue_str))
571 names = []
571 names = []
572 for name in names:
572 for name in names:
573 value = text_repr(getattr(evalue, name))
573 value = text_repr(getattr(evalue, name))
574 exception.append('\n%s%s = %s' % (indent, name, value))
574 exception.append('\n%s%s = %s' % (indent, name, value))
575 # return all our info assembled as a single string
575 # return all our info assembled as a single string
576 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
576 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
577
577
578 def debugger(self):
578 def debugger(self):
579 """Call up the pdb debugger if desired, always clean up the tb reference.
579 """Call up the pdb debugger if desired, always clean up the tb reference.
580
580
581 If the call_pdb flag is set, the pdb interactive debugger is
581 If the call_pdb flag is set, the pdb interactive debugger is
582 invoked. In all cases, the self.tb reference to the current traceback
582 invoked. In all cases, the self.tb reference to the current traceback
583 is deleted to prevent lingering references which hamper memory
583 is deleted to prevent lingering references which hamper memory
584 management.
584 management.
585
585
586 Note that each call to pdb() does an 'import readline', so if your app
586 Note that each call to pdb() does an 'import readline', so if your app
587 requires a special setup for the readline completers, you'll have to
587 requires a special setup for the readline completers, you'll have to
588 fix that by hand after invoking the exception handler."""
588 fix that by hand after invoking the exception handler."""
589
589
590 if self.call_pdb:
590 if self.call_pdb:
591 if self.pdb is None:
591 if self.pdb is None:
592 self.pdb = Debugger.Pdb(
592 self.pdb = Debugger.Pdb(
593 self.color_scheme_table.active_scheme_name)
593 self.color_scheme_table.active_scheme_name)
594 # the system displayhook may have changed, restore the original
594 # the system displayhook may have changed, restore the original
595 # for pdb
595 # for pdb
596 dhook = sys.displayhook
596 dhook = sys.displayhook
597 sys.displayhook = sys.__displayhook__
597 sys.displayhook = sys.__displayhook__
598 self.pdb.reset()
598 self.pdb.reset()
599 # Find the right frame so we don't pop up inside ipython itself
599 # Find the right frame so we don't pop up inside ipython itself
600 etb = self.tb
600 etb = self.tb
601 while self.tb.tb_next is not None:
601 while self.tb.tb_next is not None:
602 self.tb = self.tb.tb_next
602 self.tb = self.tb.tb_next
603 try:
603 try:
604 if etb and etb.tb_next:
604 if etb and etb.tb_next:
605 etb = etb.tb_next
605 etb = etb.tb_next
606 self.pdb.botframe = etb.tb_frame
606 self.pdb.botframe = etb.tb_frame
607 self.pdb.interaction(self.tb.tb_frame, self.tb)
607 self.pdb.interaction(self.tb.tb_frame, self.tb)
608 except:
608 except:
609 print '*** ERROR ***'
609 print '*** ERROR ***'
610 print 'This version of pdb has a bug and crashed.'
610 print 'This version of pdb has a bug and crashed.'
611 print 'Returning to IPython...'
611 print 'Returning to IPython...'
612 sys.displayhook = dhook
612 sys.displayhook = dhook
613 del self.tb
613 del self.tb
614
614
615 def handler(self, info=None):
615 def handler(self, info=None):
616 (etype, evalue, etb) = info or sys.exc_info()
616 (etype, evalue, etb) = info or sys.exc_info()
617 self.tb = etb
617 self.tb = etb
618 print >> Term.cerr, self.text(etype, evalue, etb)
618 print >> Term.cerr, self.text(etype, evalue, etb)
619
619
620 # Changed so an instance can just be called as VerboseTB_inst() and print
620 # Changed so an instance can just be called as VerboseTB_inst() and print
621 # out the right info on its own.
621 # out the right info on its own.
622 def __call__(self, etype=None, evalue=None, etb=None):
622 def __call__(self, etype=None, evalue=None, etb=None):
623 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
623 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
624 if etb is None:
624 if etb is None:
625 self.handler()
625 self.handler()
626 else:
626 else:
627 self.handler((etype, evalue, etb))
627 self.handler((etype, evalue, etb))
628 self.debugger()
628 self.debugger()
629
629
630 #----------------------------------------------------------------------------
630 #----------------------------------------------------------------------------
631 class FormattedTB(VerboseTB,ListTB):
631 class FormattedTB(VerboseTB,ListTB):
632 """Subclass ListTB but allow calling with a traceback.
632 """Subclass ListTB but allow calling with a traceback.
633
633
634 It can thus be used as a sys.excepthook for Python > 2.1.
634 It can thus be used as a sys.excepthook for Python > 2.1.
635
635
636 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
636 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
637
637
638 Allows a tb_offset to be specified. This is useful for situations where
638 Allows a tb_offset to be specified. This is useful for situations where
639 one needs to remove a number of topmost frames from the traceback (such as
639 one needs to remove a number of topmost frames from the traceback (such as
640 occurs with python programs that themselves execute other python code,
640 occurs with python programs that themselves execute other python code,
641 like Python shells). """
641 like Python shells). """
642
642
643 def __init__(self, mode = 'Plain', color_scheme='Linux',
643 def __init__(self, mode = 'Plain', color_scheme='Linux',
644 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
644 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
645
645
646 # NEVER change the order of this list. Put new modes at the end:
646 # NEVER change the order of this list. Put new modes at the end:
647 self.valid_modes = ['Plain','Context','Verbose']
647 self.valid_modes = ['Plain','Context','Verbose']
648 self.verbose_modes = self.valid_modes[1:3]
648 self.verbose_modes = self.valid_modes[1:3]
649
649
650 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
650 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
651 call_pdb=call_pdb,include_vars=include_vars)
651 call_pdb=call_pdb,include_vars=include_vars)
652 self.set_mode(mode)
652 self.set_mode(mode)
653
653
654 def _extract_tb(self,tb):
654 def _extract_tb(self,tb):
655 if tb:
655 if tb:
656 return traceback.extract_tb(tb)
656 return traceback.extract_tb(tb)
657 else:
657 else:
658 return None
658 return None
659
659
660 def text(self, etype, value, tb,context=5,mode=None):
660 def text(self, etype, value, tb,context=5,mode=None):
661 """Return formatted traceback.
661 """Return formatted traceback.
662
662
663 If the optional mode parameter is given, it overrides the current
663 If the optional mode parameter is given, it overrides the current
664 mode."""
664 mode."""
665
665
666 if mode is None:
666 if mode is None:
667 mode = self.mode
667 mode = self.mode
668 if mode in self.verbose_modes:
668 if mode in self.verbose_modes:
669 # verbose modes need a full traceback
669 # verbose modes need a full traceback
670 return VerboseTB.text(self,etype, value, tb,context=5)
670 return VerboseTB.text(self,etype, value, tb,context=5)
671 else:
671 else:
672 # We must check the source cache because otherwise we can print
672 # We must check the source cache because otherwise we can print
673 # out-of-date source code.
673 # out-of-date source code.
674 linecache.checkcache()
674 linecache.checkcache()
675 # Now we can extract and format the exception
675 # Now we can extract and format the exception
676 elist = self._extract_tb(tb)
676 elist = self._extract_tb(tb)
677 if len(elist) > self.tb_offset:
677 if len(elist) > self.tb_offset:
678 del elist[:self.tb_offset]
678 del elist[:self.tb_offset]
679 return ListTB.text(self,etype,value,elist)
679 return ListTB.text(self,etype,value,elist)
680
680
681 def set_mode(self,mode=None):
681 def set_mode(self,mode=None):
682 """Switch to the desired mode.
682 """Switch to the desired mode.
683
683
684 If mode is not specified, cycles through the available modes."""
684 If mode is not specified, cycles through the available modes."""
685
685
686 if not mode:
686 if not mode:
687 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
687 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
688 len(self.valid_modes)
688 len(self.valid_modes)
689 self.mode = self.valid_modes[new_idx]
689 self.mode = self.valid_modes[new_idx]
690 elif mode not in self.valid_modes:
690 elif mode not in self.valid_modes:
691 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
691 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
692 'Valid modes: '+str(self.valid_modes)
692 'Valid modes: '+str(self.valid_modes)
693 else:
693 else:
694 self.mode = mode
694 self.mode = mode
695 # include variable details only in 'Verbose' mode
695 # include variable details only in 'Verbose' mode
696 self.include_vars = (self.mode == self.valid_modes[2])
696 self.include_vars = (self.mode == self.valid_modes[2])
697
697
698 # some convenient shorcuts
698 # some convenient shorcuts
699 def plain(self):
699 def plain(self):
700 self.set_mode(self.valid_modes[0])
700 self.set_mode(self.valid_modes[0])
701
701
702 def context(self):
702 def context(self):
703 self.set_mode(self.valid_modes[1])
703 self.set_mode(self.valid_modes[1])
704
704
705 def verbose(self):
705 def verbose(self):
706 self.set_mode(self.valid_modes[2])
706 self.set_mode(self.valid_modes[2])
707
707
708 #----------------------------------------------------------------------------
708 #----------------------------------------------------------------------------
709 class AutoFormattedTB(FormattedTB):
709 class AutoFormattedTB(FormattedTB):
710 """A traceback printer which can be called on the fly.
710 """A traceback printer which can be called on the fly.
711
711
712 It will find out about exceptions by itself.
712 It will find out about exceptions by itself.
713
713
714 A brief example:
714 A brief example:
715
715
716 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
716 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
717 try:
717 try:
718 ...
718 ...
719 except:
719 except:
720 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
720 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
721 """
721 """
722 def __call__(self,etype=None,evalue=None,etb=None,
722 def __call__(self,etype=None,evalue=None,etb=None,
723 out=None,tb_offset=None):
723 out=None,tb_offset=None):
724 """Print out a formatted exception traceback.
724 """Print out a formatted exception traceback.
725
725
726 Optional arguments:
726 Optional arguments:
727 - out: an open file-like object to direct output to.
727 - out: an open file-like object to direct output to.
728
728
729 - tb_offset: the number of frames to skip over in the stack, on a
729 - tb_offset: the number of frames to skip over in the stack, on a
730 per-call basis (this overrides temporarily the instance's tb_offset
730 per-call basis (this overrides temporarily the instance's tb_offset
731 given at initialization time. """
731 given at initialization time. """
732
732
733 if out is None:
733 if out is None:
734 out = Term.cerr
734 out = Term.cerr
735 if tb_offset is not None:
735 if tb_offset is not None:
736 tb_offset, self.tb_offset = self.tb_offset, tb_offset
736 tb_offset, self.tb_offset = self.tb_offset, tb_offset
737 print >> out, self.text(etype, evalue, etb)
737 print >> out, self.text(etype, evalue, etb)
738 self.tb_offset = tb_offset
738 self.tb_offset = tb_offset
739 else:
739 else:
740 print >> out, self.text(etype, evalue, etb)
740 print >> out, self.text(etype, evalue, etb)
741 self.debugger()
741 self.debugger()
742
742
743 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
743 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
744 if etype is None:
744 if etype is None:
745 etype,value,tb = sys.exc_info()
745 etype,value,tb = sys.exc_info()
746 self.tb = tb
746 self.tb = tb
747 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
747 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
748
748
749 #---------------------------------------------------------------------------
749 #---------------------------------------------------------------------------
750 # A simple class to preserve Nathan's original functionality.
750 # A simple class to preserve Nathan's original functionality.
751 class ColorTB(FormattedTB):
751 class ColorTB(FormattedTB):
752 """Shorthand to initialize a FormattedTB in Linux colors mode."""
752 """Shorthand to initialize a FormattedTB in Linux colors mode."""
753 def __init__(self,color_scheme='Linux',call_pdb=0):
753 def __init__(self,color_scheme='Linux',call_pdb=0):
754 FormattedTB.__init__(self,color_scheme=color_scheme,
754 FormattedTB.__init__(self,color_scheme=color_scheme,
755 call_pdb=call_pdb)
755 call_pdb=call_pdb)
756
756
757 #----------------------------------------------------------------------------
757 #----------------------------------------------------------------------------
758 # module testing (minimal)
758 # module testing (minimal)
759 if __name__ == "__main__":
759 if __name__ == "__main__":
760 def spam(c, (d, e)):
760 def spam(c, (d, e)):
761 x = c + d
761 x = c + d
762 y = c * d
762 y = c * d
763 foo(x, y)
763 foo(x, y)
764
764
765 def foo(a, b, bar=1):
765 def foo(a, b, bar=1):
766 eggs(a, b + bar)
766 eggs(a, b + bar)
767
767
768 def eggs(f, g, z=globals()):
768 def eggs(f, g, z=globals()):
769 h = f + g
769 h = f + g
770 i = f - g
770 i = f - g
771 return h / i
771 return h / i
772
772
773 print ''
773 print ''
774 print '*** Before ***'
774 print '*** Before ***'
775 try:
775 try:
776 print spam(1, (2, 3))
776 print spam(1, (2, 3))
777 except:
777 except:
778 traceback.print_exc()
778 traceback.print_exc()
779 print ''
779 print ''
780
780
781 handler = ColorTB()
781 handler = ColorTB()
782 print '*** ColorTB ***'
782 print '*** ColorTB ***'
783 try:
783 try:
784 print spam(1, (2, 3))
784 print spam(1, (2, 3))
785 except:
785 except:
786 apply(handler, sys.exc_info() )
786 apply(handler, sys.exc_info() )
787 print ''
787 print ''
788
788
789 handler = VerboseTB()
789 handler = VerboseTB()
790 print '*** VerboseTB ***'
790 print '*** VerboseTB ***'
791 try:
791 try:
792 print spam(1, (2, 3))
792 print spam(1, (2, 3))
793 except:
793 except:
794 apply(handler, sys.exc_info() )
794 apply(handler, sys.exc_info() )
795 print ''
795 print ''
796
796
@@ -1,4642 +1,4660 b''
1 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
1 2005-12-29 Fernando Perez <Fernando.Perez@colorado.edu>
2
2
3 * IPython/iplib.py (showtraceback): remove use of the
4 sys.last_{type/value/traceback} structures, which are non
5 thread-safe.
6
7 * IPython/macro.py (Macro.__init__): moved macros to a standalone
8 file. Now that they'll be more likely to be used with the
9 persistance system (%store), I want to make sure their module path
10 doesn't change in the future, so that we don't break things for
11 users' persisted data.
12
13 * IPython/iplib.py (autoindent_update): move indentation
14 management into the _text_ processing loop, not the keyboard
15 interactive one. This is necessary to correctly process non-typed
16 multiline input (such as macros).
17
3 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
18 * IPython/Magic.py (Magic.format_latex): patch by Stefan van der
4 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
19 Walt <stefan-AT-sun.ac.za> to fix latex formatting of docstrings,
5 which was producing problems in the resulting manual.
20 which was producing problems in the resulting manual.
21 (magic_whos): improve reporting of instances (show their class,
22 instead of simply printing 'instance' which isn't terribly
23 informative).
6
24
7 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
25 * IPython/genutils.py (shell): commit Jorgen Stenarson's patch
8 (minor mods) to support network shares under win32.
26 (minor mods) to support network shares under win32.
9
27
10 * IPython/winconsole.py (get_console_size): add new winconsole
28 * IPython/winconsole.py (get_console_size): add new winconsole
11 module and fixes to page_dumb() to improve its behavior under
29 module and fixes to page_dumb() to improve its behavior under
12 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
30 win32. Contributed by Alexander Belchenko <bialix-AT-ukr.net>.
13
31
14 * IPython/Magic.py (Macro): simplified Macro class to just
32 * IPython/Magic.py (Macro): simplified Macro class to just
15 subclass list. We've had only 2.2 compatibility for a very long
33 subclass list. We've had only 2.2 compatibility for a very long
16 time, yet I was still avoiding subclassing the builtin types. No
34 time, yet I was still avoiding subclassing the builtin types. No
17 more (I'm also starting to use properties, though I won't shift to
35 more (I'm also starting to use properties, though I won't shift to
18 2.3-specific features quite yet).
36 2.3-specific features quite yet).
19 (magic_store): added Ville's patch for lightweight variable
37 (magic_store): added Ville's patch for lightweight variable
20 persistence, after a request on the user list by Matt Wilkie
38 persistence, after a request on the user list by Matt Wilkie
21 <maphew-AT-gmail.com>. The new %store magic's docstring has full
39 <maphew-AT-gmail.com>. The new %store magic's docstring has full
22 details.
40 details.
23
41
24 * IPython/iplib.py (InteractiveShell.post_config_initialization):
42 * IPython/iplib.py (InteractiveShell.post_config_initialization):
25 changed the default logfile name from 'ipython.log' to
43 changed the default logfile name from 'ipython.log' to
26 'ipython_log.py'. These logs are real python files, and now that
44 'ipython_log.py'. These logs are real python files, and now that
27 we have much better multiline support, people are more likely to
45 we have much better multiline support, people are more likely to
28 want to use them as such. Might as well name them correctly.
46 want to use them as such. Might as well name them correctly.
29
47
30 * IPython/Magic.py: substantial cleanup. While we can't stop
48 * IPython/Magic.py: substantial cleanup. While we can't stop
31 using magics as mixins, due to the existing customizations 'out
49 using magics as mixins, due to the existing customizations 'out
32 there' which rely on the mixin naming conventions, at least I
50 there' which rely on the mixin naming conventions, at least I
33 cleaned out all cross-class name usage. So once we are OK with
51 cleaned out all cross-class name usage. So once we are OK with
34 breaking compatibility, the two systems can be separated.
52 breaking compatibility, the two systems can be separated.
35
53
36 * IPython/Logger.py: major cleanup. This one is NOT a mixin
54 * IPython/Logger.py: major cleanup. This one is NOT a mixin
37 anymore, and the class is a fair bit less hideous as well. New
55 anymore, and the class is a fair bit less hideous as well. New
38 features were also introduced: timestamping of input, and logging
56 features were also introduced: timestamping of input, and logging
39 of output results. These are user-visible with the -t and -o
57 of output results. These are user-visible with the -t and -o
40 options to %logstart. Closes
58 options to %logstart. Closes
41 http://www.scipy.net/roundup/ipython/issue11 and a request by
59 http://www.scipy.net/roundup/ipython/issue11 and a request by
42 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
60 William Stein (SAGE developer - http://modular.ucsd.edu/sage).
43
61
44 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
62 2005-12-28 Fernando Perez <Fernando.Perez@colorado.edu>
45
63
46 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
64 * IPython/iplib.py (handle_shell_escape): add Ville's patch to
47 better hadnle backslashes in paths. See the thread 'More Windows
65 better hadnle backslashes in paths. See the thread 'More Windows
48 questions part 2 - \/ characters revisited' on the iypthon user
66 questions part 2 - \/ characters revisited' on the iypthon user
49 list:
67 list:
50 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
68 http://scipy.net/pipermail/ipython-user/2005-June/000907.html
51
69
52 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
70 (InteractiveShell.__init__): fix tab-completion bug in threaded shells.
53
71
54 (InteractiveShell.__init__): change threaded shells to not use the
72 (InteractiveShell.__init__): change threaded shells to not use the
55 ipython crash handler. This was causing more problems than not,
73 ipython crash handler. This was causing more problems than not,
56 as exceptions in the main thread (GUI code, typically) would
74 as exceptions in the main thread (GUI code, typically) would
57 always show up as a 'crash', when they really weren't.
75 always show up as a 'crash', when they really weren't.
58
76
59 The colors and exception mode commands (%colors/%xmode) have been
77 The colors and exception mode commands (%colors/%xmode) have been
60 synchronized to also take this into account, so users can get
78 synchronized to also take this into account, so users can get
61 verbose exceptions for their threaded code as well. I also added
79 verbose exceptions for their threaded code as well. I also added
62 support for activating pdb inside this exception handler as well,
80 support for activating pdb inside this exception handler as well,
63 so now GUI authors can use IPython's enhanced pdb at runtime.
81 so now GUI authors can use IPython's enhanced pdb at runtime.
64
82
65 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
83 * IPython/ipmaker.py (make_IPython): make the autoedit_syntax flag
66 true by default, and add it to the shipped ipythonrc file. Since
84 true by default, and add it to the shipped ipythonrc file. Since
67 this asks the user before proceeding, I think it's OK to make it
85 this asks the user before proceeding, I think it's OK to make it
68 true by default.
86 true by default.
69
87
70 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
88 * IPython/Magic.py (magic_exit): make new exit/quit magics instead
71 of the previous special-casing of input in the eval loop. I think
89 of the previous special-casing of input in the eval loop. I think
72 this is cleaner, as they really are commands and shouldn't have
90 this is cleaner, as they really are commands and shouldn't have
73 a special role in the middle of the core code.
91 a special role in the middle of the core code.
74
92
75 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
93 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu>
76
94
77 * IPython/iplib.py (edit_syntax_error): added support for
95 * IPython/iplib.py (edit_syntax_error): added support for
78 automatically reopening the editor if the file had a syntax error
96 automatically reopening the editor if the file had a syntax error
79 in it. Thanks to scottt who provided the patch at:
97 in it. Thanks to scottt who provided the patch at:
80 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
98 http://www.scipy.net/roundup/ipython/issue36 (slightly modified
81 version committed).
99 version committed).
82
100
83 * IPython/iplib.py (handle_normal): add suport for multi-line
101 * IPython/iplib.py (handle_normal): add suport for multi-line
84 input with emtpy lines. This fixes
102 input with emtpy lines. This fixes
85 http://www.scipy.net/roundup/ipython/issue43 and a similar
103 http://www.scipy.net/roundup/ipython/issue43 and a similar
86 discussion on the user list.
104 discussion on the user list.
87
105
88 WARNING: a behavior change is necessarily introduced to support
106 WARNING: a behavior change is necessarily introduced to support
89 blank lines: now a single blank line with whitespace does NOT
107 blank lines: now a single blank line with whitespace does NOT
90 break the input loop, which means that when autoindent is on, by
108 break the input loop, which means that when autoindent is on, by
91 default hitting return on the next (indented) line does NOT exit.
109 default hitting return on the next (indented) line does NOT exit.
92
110
93 Instead, to exit a multiline input you can either have:
111 Instead, to exit a multiline input you can either have:
94
112
95 - TWO whitespace lines (just hit return again), or
113 - TWO whitespace lines (just hit return again), or
96 - a single whitespace line of a different length than provided
114 - a single whitespace line of a different length than provided
97 by the autoindent (add or remove a space).
115 by the autoindent (add or remove a space).
98
116
99 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
117 * IPython/completer.py (MagicCompleter.__init__): new 'completer'
100 module to better organize all readline-related functionality.
118 module to better organize all readline-related functionality.
101 I've deleted FlexCompleter and put all completion clases here.
119 I've deleted FlexCompleter and put all completion clases here.
102
120
103 * IPython/iplib.py (raw_input): improve indentation management.
121 * IPython/iplib.py (raw_input): improve indentation management.
104 It is now possible to paste indented code with autoindent on, and
122 It is now possible to paste indented code with autoindent on, and
105 the code is interpreted correctly (though it still looks bad on
123 the code is interpreted correctly (though it still looks bad on
106 screen, due to the line-oriented nature of ipython).
124 screen, due to the line-oriented nature of ipython).
107 (MagicCompleter.complete): change behavior so that a TAB key on an
125 (MagicCompleter.complete): change behavior so that a TAB key on an
108 otherwise empty line actually inserts a tab, instead of completing
126 otherwise empty line actually inserts a tab, instead of completing
109 on the entire global namespace. This makes it easier to use the
127 on the entire global namespace. This makes it easier to use the
110 TAB key for indentation. After a request by Hans Meine
128 TAB key for indentation. After a request by Hans Meine
111 <hans_meine-AT-gmx.net>
129 <hans_meine-AT-gmx.net>
112 (_prefilter): add support so that typing plain 'exit' or 'quit'
130 (_prefilter): add support so that typing plain 'exit' or 'quit'
113 does a sensible thing. Originally I tried to deviate as little as
131 does a sensible thing. Originally I tried to deviate as little as
114 possible from the default python behavior, but even that one may
132 possible from the default python behavior, but even that one may
115 change in this direction (thread on python-dev to that effect).
133 change in this direction (thread on python-dev to that effect).
116 Regardless, ipython should do the right thing even if CPython's
134 Regardless, ipython should do the right thing even if CPython's
117 '>>>' prompt doesn't.
135 '>>>' prompt doesn't.
118 (InteractiveShell): removed subclassing code.InteractiveConsole
136 (InteractiveShell): removed subclassing code.InteractiveConsole
119 class. By now we'd overridden just about all of its methods: I've
137 class. By now we'd overridden just about all of its methods: I've
120 copied the remaining two over, and now ipython is a standalone
138 copied the remaining two over, and now ipython is a standalone
121 class. This will provide a clearer picture for the chainsaw
139 class. This will provide a clearer picture for the chainsaw
122 branch refactoring.
140 branch refactoring.
123
141
124 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
142 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu>
125
143
126 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
144 * IPython/ultraTB.py (VerboseTB.text): harden reporting against
127 failures for objects which break when dir() is called on them.
145 failures for objects which break when dir() is called on them.
128
146
129 * IPython/FlexCompleter.py (Completer.__init__): Added support for
147 * IPython/FlexCompleter.py (Completer.__init__): Added support for
130 distinct local and global namespaces in the completer API. This
148 distinct local and global namespaces in the completer API. This
131 change allows us top properly handle completion with distinct
149 change allows us top properly handle completion with distinct
132 scopes, including in embedded instances (this had never really
150 scopes, including in embedded instances (this had never really
133 worked correctly).
151 worked correctly).
134
152
135 Note: this introduces a change in the constructor for
153 Note: this introduces a change in the constructor for
136 MagicCompleter, as a new global_namespace parameter is now the
154 MagicCompleter, as a new global_namespace parameter is now the
137 second argument (the others were bumped one position).
155 second argument (the others were bumped one position).
138
156
139 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
157 2005-12-25 Fernando Perez <Fernando.Perez@colorado.edu>
140
158
141 * IPython/iplib.py (embed_mainloop): fix tab-completion in
159 * IPython/iplib.py (embed_mainloop): fix tab-completion in
142 embedded instances (which can be done now thanks to Vivian's
160 embedded instances (which can be done now thanks to Vivian's
143 frame-handling fixes for pdb).
161 frame-handling fixes for pdb).
144 (InteractiveShell.__init__): Fix namespace handling problem in
162 (InteractiveShell.__init__): Fix namespace handling problem in
145 embedded instances. We were overwriting __main__ unconditionally,
163 embedded instances. We were overwriting __main__ unconditionally,
146 and this should only be done for 'full' (non-embedded) IPython;
164 and this should only be done for 'full' (non-embedded) IPython;
147 embedded instances must respect the caller's __main__. Thanks to
165 embedded instances must respect the caller's __main__. Thanks to
148 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
166 a bug report by Yaroslav Bulatov <yaroslavvb-AT-gmail.com>
149
167
150 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
168 2005-12-24 Fernando Perez <Fernando.Perez@colorado.edu>
151
169
152 * setup.py: added download_url to setup(). This registers the
170 * setup.py: added download_url to setup(). This registers the
153 download address at PyPI, which is not only useful to humans
171 download address at PyPI, which is not only useful to humans
154 browsing the site, but is also picked up by setuptools (the Eggs
172 browsing the site, but is also picked up by setuptools (the Eggs
155 machinery). Thanks to Ville and R. Kern for the info/discussion
173 machinery). Thanks to Ville and R. Kern for the info/discussion
156 on this.
174 on this.
157
175
158 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
176 2005-12-23 Fernando Perez <Fernando.Perez@colorado.edu>
159
177
160 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
178 * IPython/Debugger.py (Pdb.__init__): Major pdb mode enhancements.
161 This brings a lot of nice functionality to the pdb mode, which now
179 This brings a lot of nice functionality to the pdb mode, which now
162 has tab-completion, syntax highlighting, and better stack handling
180 has tab-completion, syntax highlighting, and better stack handling
163 than before. Many thanks to Vivian De Smedt
181 than before. Many thanks to Vivian De Smedt
164 <vivian-AT-vdesmedt.com> for the original patches.
182 <vivian-AT-vdesmedt.com> for the original patches.
165
183
166 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
184 2005-12-08 Fernando Perez <Fernando.Perez@colorado.edu>
167
185
168 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
186 * IPython/Shell.py (IPShellGTK.mainloop): fix mainloop() calling
169 sequence to consistently accept the banner argument. The
187 sequence to consistently accept the banner argument. The
170 inconsistency was tripping SAGE, thanks to Gary Zablackis
188 inconsistency was tripping SAGE, thanks to Gary Zablackis
171 <gzabl-AT-yahoo.com> for the report.
189 <gzabl-AT-yahoo.com> for the report.
172
190
173 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
191 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
174
192
175 * IPython/iplib.py (InteractiveShell.post_config_initialization):
193 * IPython/iplib.py (InteractiveShell.post_config_initialization):
176 Fix bug where a naked 'alias' call in the ipythonrc file would
194 Fix bug where a naked 'alias' call in the ipythonrc file would
177 cause a crash. Bug reported by Jorgen Stenarson.
195 cause a crash. Bug reported by Jorgen Stenarson.
178
196
179 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
197 2005-11-15 Fernando Perez <Fernando.Perez@colorado.edu>
180
198
181 * IPython/ipmaker.py (make_IPython): cleanups which should improve
199 * IPython/ipmaker.py (make_IPython): cleanups which should improve
182 startup time.
200 startup time.
183
201
184 * IPython/iplib.py (runcode): my globals 'fix' for embedded
202 * IPython/iplib.py (runcode): my globals 'fix' for embedded
185 instances had introduced a bug with globals in normal code. Now
203 instances had introduced a bug with globals in normal code. Now
186 it's working in all cases.
204 it's working in all cases.
187
205
188 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
206 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
189 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
207 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
190 has been introduced to set the default case sensitivity of the
208 has been introduced to set the default case sensitivity of the
191 searches. Users can still select either mode at runtime on a
209 searches. Users can still select either mode at runtime on a
192 per-search basis.
210 per-search basis.
193
211
194 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
212 2005-11-13 Fernando Perez <Fernando.Perez@colorado.edu>
195
213
196 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
214 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
197 attributes in wildcard searches for subclasses. Modified version
215 attributes in wildcard searches for subclasses. Modified version
198 of a patch by Jorgen.
216 of a patch by Jorgen.
199
217
200 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
218 2005-11-12 Fernando Perez <Fernando.Perez@colorado.edu>
201
219
202 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
220 * IPython/iplib.py (embed_mainloop): Fix handling of globals for
203 embedded instances. I added a user_global_ns attribute to the
221 embedded instances. I added a user_global_ns attribute to the
204 InteractiveShell class to handle this.
222 InteractiveShell class to handle this.
205
223
206 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
224 2005-10-31 Fernando Perez <Fernando.Perez@colorado.edu>
207
225
208 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
226 * IPython/Shell.py (IPShellGTK.mainloop): Change timeout_add to
209 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
227 idle_add, which fixes horrible keyboard lag problems under gtk 2.6
210 (reported under win32, but may happen also in other platforms).
228 (reported under win32, but may happen also in other platforms).
211 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
229 Bug report and fix courtesy of Sean Moore <smm-AT-logic.bm>
212
230
213 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
231 2005-10-15 Fernando Perez <Fernando.Perez@colorado.edu>
214
232
215 * IPython/Magic.py (magic_psearch): new support for wildcard
233 * IPython/Magic.py (magic_psearch): new support for wildcard
216 patterns. Now, typing ?a*b will list all names which begin with a
234 patterns. Now, typing ?a*b will list all names which begin with a
217 and end in b, for example. The %psearch magic has full
235 and end in b, for example. The %psearch magic has full
218 docstrings. Many thanks to JΓΆrgen Stenarson
236 docstrings. Many thanks to JΓΆrgen Stenarson
219 <jorgen.stenarson-AT-bostream.nu>, author of the patches
237 <jorgen.stenarson-AT-bostream.nu>, author of the patches
220 implementing this functionality.
238 implementing this functionality.
221
239
222 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
240 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
223
241
224 * Manual: fixed long-standing annoyance of double-dashes (as in
242 * Manual: fixed long-standing annoyance of double-dashes (as in
225 --prefix=~, for example) being stripped in the HTML version. This
243 --prefix=~, for example) being stripped in the HTML version. This
226 is a latex2html bug, but a workaround was provided. Many thanks
244 is a latex2html bug, but a workaround was provided. Many thanks
227 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
245 to George K. Thiruvathukal <gthiruv-AT-luc.edu> for the detailed
228 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
246 help, and Michael Tobis <mtobis-AT-gmail.com> for getting the ball
229 rolling. This seemingly small issue had tripped a number of users
247 rolling. This seemingly small issue had tripped a number of users
230 when first installing, so I'm glad to see it gone.
248 when first installing, so I'm glad to see it gone.
231
249
232 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
250 2005-09-27 Fernando Perez <Fernando.Perez@colorado.edu>
233
251
234 * IPython/Extensions/numeric_formats.py: fix missing import,
252 * IPython/Extensions/numeric_formats.py: fix missing import,
235 reported by Stephen Walton.
253 reported by Stephen Walton.
236
254
237 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
255 2005-09-24 Fernando Perez <Fernando.Perez@colorado.edu>
238
256
239 * IPython/demo.py: finish demo module, fully documented now.
257 * IPython/demo.py: finish demo module, fully documented now.
240
258
241 * IPython/genutils.py (file_read): simple little utility to read a
259 * IPython/genutils.py (file_read): simple little utility to read a
242 file and ensure it's closed afterwards.
260 file and ensure it's closed afterwards.
243
261
244 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
262 2005-09-23 Fernando Perez <Fernando.Perez@colorado.edu>
245
263
246 * IPython/demo.py (Demo.__init__): added support for individually
264 * IPython/demo.py (Demo.__init__): added support for individually
247 tagging blocks for automatic execution.
265 tagging blocks for automatic execution.
248
266
249 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
267 * IPython/Magic.py (magic_pycat): new %pycat magic for showing
250 syntax-highlighted python sources, requested by John.
268 syntax-highlighted python sources, requested by John.
251
269
252 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
270 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
253
271
254 * IPython/demo.py (Demo.again): fix bug where again() blocks after
272 * IPython/demo.py (Demo.again): fix bug where again() blocks after
255 finishing.
273 finishing.
256
274
257 * IPython/genutils.py (shlex_split): moved from Magic to here,
275 * IPython/genutils.py (shlex_split): moved from Magic to here,
258 where all 2.2 compatibility stuff lives. I needed it for demo.py.
276 where all 2.2 compatibility stuff lives. I needed it for demo.py.
259
277
260 * IPython/demo.py (Demo.__init__): added support for silent
278 * IPython/demo.py (Demo.__init__): added support for silent
261 blocks, improved marks as regexps, docstrings written.
279 blocks, improved marks as regexps, docstrings written.
262 (Demo.__init__): better docstring, added support for sys.argv.
280 (Demo.__init__): better docstring, added support for sys.argv.
263
281
264 * IPython/genutils.py (marquee): little utility used by the demo
282 * IPython/genutils.py (marquee): little utility used by the demo
265 code, handy in general.
283 code, handy in general.
266
284
267 * IPython/demo.py (Demo.__init__): new class for interactive
285 * IPython/demo.py (Demo.__init__): new class for interactive
268 demos. Not documented yet, I just wrote it in a hurry for
286 demos. Not documented yet, I just wrote it in a hurry for
269 scipy'05. Will docstring later.
287 scipy'05. Will docstring later.
270
288
271 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
289 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
272
290
273 * IPython/Shell.py (sigint_handler): Drastic simplification which
291 * IPython/Shell.py (sigint_handler): Drastic simplification which
274 also seems to make Ctrl-C work correctly across threads! This is
292 also seems to make Ctrl-C work correctly across threads! This is
275 so simple, that I can't beleive I'd missed it before. Needs more
293 so simple, that I can't beleive I'd missed it before. Needs more
276 testing, though.
294 testing, though.
277 (KBINT): Never mind, revert changes. I'm sure I'd tried something
295 (KBINT): Never mind, revert changes. I'm sure I'd tried something
278 like this before...
296 like this before...
279
297
280 * IPython/genutils.py (get_home_dir): add protection against
298 * IPython/genutils.py (get_home_dir): add protection against
281 non-dirs in win32 registry.
299 non-dirs in win32 registry.
282
300
283 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
301 * IPython/iplib.py (InteractiveShell.alias_table_validate): fix
284 bug where dict was mutated while iterating (pysh crash).
302 bug where dict was mutated while iterating (pysh crash).
285
303
286 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
304 2005-09-06 Fernando Perez <Fernando.Perez@colorado.edu>
287
305
288 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
306 * IPython/iplib.py (handle_auto): Fix inconsistency arising from
289 spurious newlines added by this routine. After a report by
307 spurious newlines added by this routine. After a report by
290 F. Mantegazza.
308 F. Mantegazza.
291
309
292 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
310 2005-09-05 Fernando Perez <Fernando.Perez@colorado.edu>
293
311
294 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
312 * IPython/Shell.py (hijack_gtk): remove pygtk.require("2.0")
295 calls. These were a leftover from the GTK 1.x days, and can cause
313 calls. These were a leftover from the GTK 1.x days, and can cause
296 problems in certain cases (after a report by John Hunter).
314 problems in certain cases (after a report by John Hunter).
297
315
298 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
316 * IPython/iplib.py (InteractiveShell.__init__): Trap exception if
299 os.getcwd() fails at init time. Thanks to patch from David Remahl
317 os.getcwd() fails at init time. Thanks to patch from David Remahl
300 <chmod007-AT-mac.com>.
318 <chmod007-AT-mac.com>.
301 (InteractiveShell.__init__): prevent certain special magics from
319 (InteractiveShell.__init__): prevent certain special magics from
302 being shadowed by aliases. Closes
320 being shadowed by aliases. Closes
303 http://www.scipy.net/roundup/ipython/issue41.
321 http://www.scipy.net/roundup/ipython/issue41.
304
322
305 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
323 2005-08-31 Fernando Perez <Fernando.Perez@colorado.edu>
306
324
307 * IPython/iplib.py (InteractiveShell.complete): Added new
325 * IPython/iplib.py (InteractiveShell.complete): Added new
308 top-level completion method to expose the completion mechanism
326 top-level completion method to expose the completion mechanism
309 beyond readline-based environments.
327 beyond readline-based environments.
310
328
311 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
329 2005-08-19 Fernando Perez <Fernando.Perez@colorado.edu>
312
330
313 * tools/ipsvnc (svnversion): fix svnversion capture.
331 * tools/ipsvnc (svnversion): fix svnversion capture.
314
332
315 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
333 * IPython/iplib.py (InteractiveShell.__init__): Add has_readline
316 attribute to self, which was missing. Before, it was set by a
334 attribute to self, which was missing. Before, it was set by a
317 routine which in certain cases wasn't being called, so the
335 routine which in certain cases wasn't being called, so the
318 instance could end up missing the attribute. This caused a crash.
336 instance could end up missing the attribute. This caused a crash.
319 Closes http://www.scipy.net/roundup/ipython/issue40.
337 Closes http://www.scipy.net/roundup/ipython/issue40.
320
338
321 2005-08-16 Fernando Perez <fperez@colorado.edu>
339 2005-08-16 Fernando Perez <fperez@colorado.edu>
322
340
323 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
341 * IPython/ultraTB.py (VerboseTB.text): don't crash if object
324 contains non-string attribute. Closes
342 contains non-string attribute. Closes
325 http://www.scipy.net/roundup/ipython/issue38.
343 http://www.scipy.net/roundup/ipython/issue38.
326
344
327 2005-08-14 Fernando Perez <fperez@colorado.edu>
345 2005-08-14 Fernando Perez <fperez@colorado.edu>
328
346
329 * tools/ipsvnc: Minor improvements, to add changeset info.
347 * tools/ipsvnc: Minor improvements, to add changeset info.
330
348
331 2005-08-12 Fernando Perez <fperez@colorado.edu>
349 2005-08-12 Fernando Perez <fperez@colorado.edu>
332
350
333 * IPython/iplib.py (runsource): remove self.code_to_run_src
351 * IPython/iplib.py (runsource): remove self.code_to_run_src
334 attribute. I realized this is nothing more than
352 attribute. I realized this is nothing more than
335 '\n'.join(self.buffer), and having the same data in two different
353 '\n'.join(self.buffer), and having the same data in two different
336 places is just asking for synchronization bugs. This may impact
354 places is just asking for synchronization bugs. This may impact
337 people who have custom exception handlers, so I need to warn
355 people who have custom exception handlers, so I need to warn
338 ipython-dev about it (F. Mantegazza may use them).
356 ipython-dev about it (F. Mantegazza may use them).
339
357
340 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
358 2005-07-29 Fernando Perez <Fernando.Perez@colorado.edu>
341
359
342 * IPython/genutils.py: fix 2.2 compatibility (generators)
360 * IPython/genutils.py: fix 2.2 compatibility (generators)
343
361
344 2005-07-18 Fernando Perez <fperez@colorado.edu>
362 2005-07-18 Fernando Perez <fperez@colorado.edu>
345
363
346 * IPython/genutils.py (get_home_dir): fix to help users with
364 * IPython/genutils.py (get_home_dir): fix to help users with
347 invalid $HOME under win32.
365 invalid $HOME under win32.
348
366
349 2005-07-17 Fernando Perez <fperez@colorado.edu>
367 2005-07-17 Fernando Perez <fperez@colorado.edu>
350
368
351 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
369 * IPython/Prompts.py (str_safe): Make unicode-safe. Also remove
352 some old hacks and clean up a bit other routines; code should be
370 some old hacks and clean up a bit other routines; code should be
353 simpler and a bit faster.
371 simpler and a bit faster.
354
372
355 * IPython/iplib.py (interact): removed some last-resort attempts
373 * IPython/iplib.py (interact): removed some last-resort attempts
356 to survive broken stdout/stderr. That code was only making it
374 to survive broken stdout/stderr. That code was only making it
357 harder to abstract out the i/o (necessary for gui integration),
375 harder to abstract out the i/o (necessary for gui integration),
358 and the crashes it could prevent were extremely rare in practice
376 and the crashes it could prevent were extremely rare in practice
359 (besides being fully user-induced in a pretty violent manner).
377 (besides being fully user-induced in a pretty violent manner).
360
378
361 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
379 * IPython/genutils.py (IOStream.__init__): Simplify the i/o stuff.
362 Nothing major yet, but the code is simpler to read; this should
380 Nothing major yet, but the code is simpler to read; this should
363 make it easier to do more serious modifications in the future.
381 make it easier to do more serious modifications in the future.
364
382
365 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
383 * IPython/Extensions/InterpreterExec.py: Fix auto-quoting in pysh,
366 which broke in .15 (thanks to a report by Ville).
384 which broke in .15 (thanks to a report by Ville).
367
385
368 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
386 * IPython/Itpl.py (Itpl.__init__): add unicode support (it may not
369 be quite correct, I know next to nothing about unicode). This
387 be quite correct, I know next to nothing about unicode). This
370 will allow unicode strings to be used in prompts, amongst other
388 will allow unicode strings to be used in prompts, amongst other
371 cases. It also will prevent ipython from crashing when unicode
389 cases. It also will prevent ipython from crashing when unicode
372 shows up unexpectedly in many places. If ascii encoding fails, we
390 shows up unexpectedly in many places. If ascii encoding fails, we
373 assume utf_8. Currently the encoding is not a user-visible
391 assume utf_8. Currently the encoding is not a user-visible
374 setting, though it could be made so if there is demand for it.
392 setting, though it could be made so if there is demand for it.
375
393
376 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
394 * IPython/ipmaker.py (make_IPython): remove old 2.1-specific hack.
377
395
378 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
396 * IPython/Struct.py (Struct.merge): switch keys() to iterator.
379
397
380 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
398 * IPython/background_jobs.py: moved 2.2 compatibility to genutils.
381
399
382 * IPython/genutils.py: Add 2.2 compatibility here, so all other
400 * IPython/genutils.py: Add 2.2 compatibility here, so all other
383 code can work transparently for 2.2/2.3.
401 code can work transparently for 2.2/2.3.
384
402
385 2005-07-16 Fernando Perez <fperez@colorado.edu>
403 2005-07-16 Fernando Perez <fperez@colorado.edu>
386
404
387 * IPython/ultraTB.py (ExceptionColors): Make a global variable
405 * IPython/ultraTB.py (ExceptionColors): Make a global variable
388 out of the color scheme table used for coloring exception
406 out of the color scheme table used for coloring exception
389 tracebacks. This allows user code to add new schemes at runtime.
407 tracebacks. This allows user code to add new schemes at runtime.
390 This is a minimally modified version of the patch at
408 This is a minimally modified version of the patch at
391 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
409 http://www.scipy.net/roundup/ipython/issue35, many thanks to pabw
392 for the contribution.
410 for the contribution.
393
411
394 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
412 * IPython/FlexCompleter.py (Completer.attr_matches): Add a
395 slightly modified version of the patch in
413 slightly modified version of the patch in
396 http://www.scipy.net/roundup/ipython/issue34, which also allows me
414 http://www.scipy.net/roundup/ipython/issue34, which also allows me
397 to remove the previous try/except solution (which was costlier).
415 to remove the previous try/except solution (which was costlier).
398 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
416 Thanks to Gaetan Lehmann <gaetan.lehmann-AT-jouy.inra.fr> for the fix.
399
417
400 2005-06-08 Fernando Perez <fperez@colorado.edu>
418 2005-06-08 Fernando Perez <fperez@colorado.edu>
401
419
402 * IPython/iplib.py (write/write_err): Add methods to abstract all
420 * IPython/iplib.py (write/write_err): Add methods to abstract all
403 I/O a bit more.
421 I/O a bit more.
404
422
405 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
423 * IPython/Shell.py (IPShellGTK.mainloop): Fix GTK deprecation
406 warning, reported by Aric Hagberg, fix by JD Hunter.
424 warning, reported by Aric Hagberg, fix by JD Hunter.
407
425
408 2005-06-02 *** Released version 0.6.15
426 2005-06-02 *** Released version 0.6.15
409
427
410 2005-06-01 Fernando Perez <fperez@colorado.edu>
428 2005-06-01 Fernando Perez <fperez@colorado.edu>
411
429
412 * IPython/iplib.py (MagicCompleter.file_matches): Fix
430 * IPython/iplib.py (MagicCompleter.file_matches): Fix
413 tab-completion of filenames within open-quoted strings. Note that
431 tab-completion of filenames within open-quoted strings. Note that
414 this requires that in ~/.ipython/ipythonrc, users change the
432 this requires that in ~/.ipython/ipythonrc, users change the
415 readline delimiters configuration to read:
433 readline delimiters configuration to read:
416
434
417 readline_remove_delims -/~
435 readline_remove_delims -/~
418
436
419
437
420 2005-05-31 *** Released version 0.6.14
438 2005-05-31 *** Released version 0.6.14
421
439
422 2005-05-29 Fernando Perez <fperez@colorado.edu>
440 2005-05-29 Fernando Perez <fperez@colorado.edu>
423
441
424 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
442 * IPython/ultraTB.py (VerboseTB.text): Fix crash for tracebacks
425 with files not on the filesystem. Reported by Eliyahu Sandler
443 with files not on the filesystem. Reported by Eliyahu Sandler
426 <eli@gondolin.net>
444 <eli@gondolin.net>
427
445
428 2005-05-22 Fernando Perez <fperez@colorado.edu>
446 2005-05-22 Fernando Perez <fperez@colorado.edu>
429
447
430 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
448 * IPython/iplib.py: Fix a few crashes in the --upgrade option.
431 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
449 After an initial report by LUK ShunTim <shuntim.luk@polyu.edu.hk>.
432
450
433 2005-05-19 Fernando Perez <fperez@colorado.edu>
451 2005-05-19 Fernando Perez <fperez@colorado.edu>
434
452
435 * IPython/iplib.py (safe_execfile): close a file which could be
453 * IPython/iplib.py (safe_execfile): close a file which could be
436 left open (causing problems in win32, which locks open files).
454 left open (causing problems in win32, which locks open files).
437 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
455 Thanks to a bug report by D Brown <dbrown2@yahoo.com>.
438
456
439 2005-05-18 Fernando Perez <fperez@colorado.edu>
457 2005-05-18 Fernando Perez <fperez@colorado.edu>
440
458
441 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
459 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): pass all
442 keyword arguments correctly to safe_execfile().
460 keyword arguments correctly to safe_execfile().
443
461
444 2005-05-13 Fernando Perez <fperez@colorado.edu>
462 2005-05-13 Fernando Perez <fperez@colorado.edu>
445
463
446 * ipython.1: Added info about Qt to manpage, and threads warning
464 * ipython.1: Added info about Qt to manpage, and threads warning
447 to usage page (invoked with --help).
465 to usage page (invoked with --help).
448
466
449 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
467 * IPython/iplib.py (MagicCompleter.python_func_kw_matches): Added
450 new matcher (it goes at the end of the priority list) to do
468 new matcher (it goes at the end of the priority list) to do
451 tab-completion on named function arguments. Submitted by George
469 tab-completion on named function arguments. Submitted by George
452 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
470 Sakkis <gsakkis-AT-eden.rutgers.edu>. See the thread at
453 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
471 http://www.scipy.net/pipermail/ipython-dev/2005-April/000436.html
454 for more details.
472 for more details.
455
473
456 * IPython/Magic.py (magic_run): Added new -e flag to ignore
474 * IPython/Magic.py (magic_run): Added new -e flag to ignore
457 SystemExit exceptions in the script being run. Thanks to a report
475 SystemExit exceptions in the script being run. Thanks to a report
458 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
476 by danny shevitz <danny_shevitz-AT-yahoo.com>, about this
459 producing very annoying behavior when running unit tests.
477 producing very annoying behavior when running unit tests.
460
478
461 2005-05-12 Fernando Perez <fperez@colorado.edu>
479 2005-05-12 Fernando Perez <fperez@colorado.edu>
462
480
463 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
481 * IPython/iplib.py (handle_auto): fixed auto-quoting and parens,
464 which I'd broken (again) due to a changed regexp. In the process,
482 which I'd broken (again) due to a changed regexp. In the process,
465 added ';' as an escape to auto-quote the whole line without
483 added ';' as an escape to auto-quote the whole line without
466 splitting its arguments. Thanks to a report by Jerry McRae
484 splitting its arguments. Thanks to a report by Jerry McRae
467 <qrs0xyc02-AT-sneakemail.com>.
485 <qrs0xyc02-AT-sneakemail.com>.
468
486
469 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
487 * IPython/ultraTB.py (VerboseTB.text): protect against rare but
470 possible crashes caused by a TokenError. Reported by Ed Schofield
488 possible crashes caused by a TokenError. Reported by Ed Schofield
471 <schofield-AT-ftw.at>.
489 <schofield-AT-ftw.at>.
472
490
473 2005-05-06 Fernando Perez <fperez@colorado.edu>
491 2005-05-06 Fernando Perez <fperez@colorado.edu>
474
492
475 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
493 * IPython/Shell.py (hijack_wx): Fix to work with WX v.2.6.
476
494
477 2005-04-29 Fernando Perez <fperez@colorado.edu>
495 2005-04-29 Fernando Perez <fperez@colorado.edu>
478
496
479 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
497 * IPython/Shell.py (IPShellQt): Thanks to Denis Rivière
480 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
498 <nudz-AT-free.fr>, Yann Cointepas <yann-AT-sapetnioc.org> and Benjamin
481 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
499 Thyreau <Benji2-AT-decideur.info>, we now have a -qthread option
482 which provides support for Qt interactive usage (similar to the
500 which provides support for Qt interactive usage (similar to the
483 existing one for WX and GTK). This had been often requested.
501 existing one for WX and GTK). This had been often requested.
484
502
485 2005-04-14 *** Released version 0.6.13
503 2005-04-14 *** Released version 0.6.13
486
504
487 2005-04-08 Fernando Perez <fperez@colorado.edu>
505 2005-04-08 Fernando Perez <fperez@colorado.edu>
488
506
489 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
507 * IPython/Magic.py (Magic._ofind): remove docstring evaluation
490 from _ofind, which gets called on almost every input line. Now,
508 from _ofind, which gets called on almost every input line. Now,
491 we only try to get docstrings if they are actually going to be
509 we only try to get docstrings if they are actually going to be
492 used (the overhead of fetching unnecessary docstrings can be
510 used (the overhead of fetching unnecessary docstrings can be
493 noticeable for certain objects, such as Pyro proxies).
511 noticeable for certain objects, such as Pyro proxies).
494
512
495 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
513 * IPython/iplib.py (MagicCompleter.python_matches): Change the API
496 for completers. For some reason I had been passing them the state
514 for completers. For some reason I had been passing them the state
497 variable, which completers never actually need, and was in
515 variable, which completers never actually need, and was in
498 conflict with the rlcompleter API. Custom completers ONLY need to
516 conflict with the rlcompleter API. Custom completers ONLY need to
499 take the text parameter.
517 take the text parameter.
500
518
501 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
519 * IPython/Extensions/InterpreterExec.py: Fix regexp so that magics
502 work correctly in pysh. I've also moved all the logic which used
520 work correctly in pysh. I've also moved all the logic which used
503 to be in pysh.py here, which will prevent problems with future
521 to be in pysh.py here, which will prevent problems with future
504 upgrades. However, this time I must warn users to update their
522 upgrades. However, this time I must warn users to update their
505 pysh profile to include the line
523 pysh profile to include the line
506
524
507 import_all IPython.Extensions.InterpreterExec
525 import_all IPython.Extensions.InterpreterExec
508
526
509 because otherwise things won't work for them. They MUST also
527 because otherwise things won't work for them. They MUST also
510 delete pysh.py and the line
528 delete pysh.py and the line
511
529
512 execfile pysh.py
530 execfile pysh.py
513
531
514 from their ipythonrc-pysh.
532 from their ipythonrc-pysh.
515
533
516 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
534 * IPython/FlexCompleter.py (Completer.attr_matches): Make more
517 robust in the face of objects whose dir() returns non-strings
535 robust in the face of objects whose dir() returns non-strings
518 (which it shouldn't, but some broken libs like ITK do). Thanks to
536 (which it shouldn't, but some broken libs like ITK do). Thanks to
519 a patch by John Hunter (implemented differently, though). Also
537 a patch by John Hunter (implemented differently, though). Also
520 minor improvements by using .extend instead of + on lists.
538 minor improvements by using .extend instead of + on lists.
521
539
522 * pysh.py:
540 * pysh.py:
523
541
524 2005-04-06 Fernando Perez <fperez@colorado.edu>
542 2005-04-06 Fernando Perez <fperez@colorado.edu>
525
543
526 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
544 * IPython/ipmaker.py (make_IPython): Make multi_line_specials on
527 by default, so that all users benefit from it. Those who don't
545 by default, so that all users benefit from it. Those who don't
528 want it can still turn it off.
546 want it can still turn it off.
529
547
530 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
548 * IPython/UserConfig/ipythonrc: Add multi_line_specials to the
531 config file, I'd forgotten about this, so users were getting it
549 config file, I'd forgotten about this, so users were getting it
532 off by default.
550 off by default.
533
551
534 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
552 * IPython/iplib.py (ipmagic): big overhaul of the magic system for
535 consistency. Now magics can be called in multiline statements,
553 consistency. Now magics can be called in multiline statements,
536 and python variables can be expanded in magic calls via $var.
554 and python variables can be expanded in magic calls via $var.
537 This makes the magic system behave just like aliases or !system
555 This makes the magic system behave just like aliases or !system
538 calls.
556 calls.
539
557
540 2005-03-28 Fernando Perez <fperez@colorado.edu>
558 2005-03-28 Fernando Perez <fperez@colorado.edu>
541
559
542 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
560 * IPython/iplib.py (handle_auto): cleanup to use %s instead of
543 expensive string additions for building command. Add support for
561 expensive string additions for building command. Add support for
544 trailing ';' when autocall is used.
562 trailing ';' when autocall is used.
545
563
546 2005-03-26 Fernando Perez <fperez@colorado.edu>
564 2005-03-26 Fernando Perez <fperez@colorado.edu>
547
565
548 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
566 * ipython.el: Fix http://www.scipy.net/roundup/ipython/issue31.
549 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
567 Bugfix by A. Schmolck, the ipython.el maintainer. Also make
550 ipython.el robust against prompts with any number of spaces
568 ipython.el robust against prompts with any number of spaces
551 (including 0) after the ':' character.
569 (including 0) after the ':' character.
552
570
553 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
571 * IPython/Prompts.py (Prompt2.set_p_str): Fix spurious space in
554 continuation prompt, which misled users to think the line was
572 continuation prompt, which misled users to think the line was
555 already indented. Closes debian Bug#300847, reported to me by
573 already indented. Closes debian Bug#300847, reported to me by
556 Norbert Tretkowski <tretkowski-AT-inittab.de>.
574 Norbert Tretkowski <tretkowski-AT-inittab.de>.
557
575
558 2005-03-23 Fernando Perez <fperez@colorado.edu>
576 2005-03-23 Fernando Perez <fperez@colorado.edu>
559
577
560 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
578 * IPython/Prompts.py (Prompt1.__str__): Make sure that prompts are
561 properly aligned if they have embedded newlines.
579 properly aligned if they have embedded newlines.
562
580
563 * IPython/iplib.py (runlines): Add a public method to expose
581 * IPython/iplib.py (runlines): Add a public method to expose
564 IPython's code execution machinery, so that users can run strings
582 IPython's code execution machinery, so that users can run strings
565 as if they had been typed at the prompt interactively.
583 as if they had been typed at the prompt interactively.
566 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
584 (InteractiveShell.__init__): Added getoutput() to the __IPYTHON__
567 methods which can call the system shell, but with python variable
585 methods which can call the system shell, but with python variable
568 expansion. The three such methods are: __IPYTHON__.system,
586 expansion. The three such methods are: __IPYTHON__.system,
569 .getoutput and .getoutputerror. These need to be documented in a
587 .getoutput and .getoutputerror. These need to be documented in a
570 'public API' section (to be written) of the manual.
588 'public API' section (to be written) of the manual.
571
589
572 2005-03-20 Fernando Perez <fperez@colorado.edu>
590 2005-03-20 Fernando Perez <fperez@colorado.edu>
573
591
574 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
592 * IPython/iplib.py (InteractiveShell.set_custom_exc): new system
575 for custom exception handling. This is quite powerful, and it
593 for custom exception handling. This is quite powerful, and it
576 allows for user-installable exception handlers which can trap
594 allows for user-installable exception handlers which can trap
577 custom exceptions at runtime and treat them separately from
595 custom exceptions at runtime and treat them separately from
578 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
596 IPython's default mechanisms. At the request of FrΓ©dΓ©ric
579 Mantegazza <mantegazza-AT-ill.fr>.
597 Mantegazza <mantegazza-AT-ill.fr>.
580 (InteractiveShell.set_custom_completer): public API function to
598 (InteractiveShell.set_custom_completer): public API function to
581 add new completers at runtime.
599 add new completers at runtime.
582
600
583 2005-03-19 Fernando Perez <fperez@colorado.edu>
601 2005-03-19 Fernando Perez <fperez@colorado.edu>
584
602
585 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
603 * IPython/OInspect.py (getdoc): Add a call to obj.getdoc(), to
586 allow objects which provide their docstrings via non-standard
604 allow objects which provide their docstrings via non-standard
587 mechanisms (like Pyro proxies) to still be inspected by ipython's
605 mechanisms (like Pyro proxies) to still be inspected by ipython's
588 ? system.
606 ? system.
589
607
590 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
608 * IPython/iplib.py (InteractiveShell.__init__): back off the _o/_e
591 automatic capture system. I tried quite hard to make it work
609 automatic capture system. I tried quite hard to make it work
592 reliably, and simply failed. I tried many combinations with the
610 reliably, and simply failed. I tried many combinations with the
593 subprocess module, but eventually nothing worked in all needed
611 subprocess module, but eventually nothing worked in all needed
594 cases (not blocking stdin for the child, duplicating stdout
612 cases (not blocking stdin for the child, duplicating stdout
595 without blocking, etc). The new %sc/%sx still do capture to these
613 without blocking, etc). The new %sc/%sx still do capture to these
596 magical list/string objects which make shell use much more
614 magical list/string objects which make shell use much more
597 conveninent, so not all is lost.
615 conveninent, so not all is lost.
598
616
599 XXX - FIX MANUAL for the change above!
617 XXX - FIX MANUAL for the change above!
600
618
601 (runsource): I copied code.py's runsource() into ipython to modify
619 (runsource): I copied code.py's runsource() into ipython to modify
602 it a bit. Now the code object and source to be executed are
620 it a bit. Now the code object and source to be executed are
603 stored in ipython. This makes this info accessible to third-party
621 stored in ipython. This makes this info accessible to third-party
604 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
622 tools, like custom exception handlers. After a request by FrΓ©dΓ©ric
605 Mantegazza <mantegazza-AT-ill.fr>.
623 Mantegazza <mantegazza-AT-ill.fr>.
606
624
607 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
625 * IPython/UserConfig/ipythonrc: Add up/down arrow keys to
608 history-search via readline (like C-p/C-n). I'd wanted this for a
626 history-search via readline (like C-p/C-n). I'd wanted this for a
609 long time, but only recently found out how to do it. For users
627 long time, but only recently found out how to do it. For users
610 who already have their ipythonrc files made and want this, just
628 who already have their ipythonrc files made and want this, just
611 add:
629 add:
612
630
613 readline_parse_and_bind "\e[A": history-search-backward
631 readline_parse_and_bind "\e[A": history-search-backward
614 readline_parse_and_bind "\e[B": history-search-forward
632 readline_parse_and_bind "\e[B": history-search-forward
615
633
616 2005-03-18 Fernando Perez <fperez@colorado.edu>
634 2005-03-18 Fernando Perez <fperez@colorado.edu>
617
635
618 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
636 * IPython/Magic.py (magic_sc): %sc and %sx now use the fancy
619 LSString and SList classes which allow transparent conversions
637 LSString and SList classes which allow transparent conversions
620 between list mode and whitespace-separated string.
638 between list mode and whitespace-separated string.
621 (magic_r): Fix recursion problem in %r.
639 (magic_r): Fix recursion problem in %r.
622
640
623 * IPython/genutils.py (LSString): New class to be used for
641 * IPython/genutils.py (LSString): New class to be used for
624 automatic storage of the results of all alias/system calls in _o
642 automatic storage of the results of all alias/system calls in _o
625 and _e (stdout/err). These provide a .l/.list attribute which
643 and _e (stdout/err). These provide a .l/.list attribute which
626 does automatic splitting on newlines. This means that for most
644 does automatic splitting on newlines. This means that for most
627 uses, you'll never need to do capturing of output with %sc/%sx
645 uses, you'll never need to do capturing of output with %sc/%sx
628 anymore, since ipython keeps this always done for you. Note that
646 anymore, since ipython keeps this always done for you. Note that
629 only the LAST results are stored, the _o/e variables are
647 only the LAST results are stored, the _o/e variables are
630 overwritten on each call. If you need to save their contents
648 overwritten on each call. If you need to save their contents
631 further, simply bind them to any other name.
649 further, simply bind them to any other name.
632
650
633 2005-03-17 Fernando Perez <fperez@colorado.edu>
651 2005-03-17 Fernando Perez <fperez@colorado.edu>
634
652
635 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
653 * IPython/Prompts.py (BasePrompt.cwd_filt): a few more fixes for
636 prompt namespace handling.
654 prompt namespace handling.
637
655
638 2005-03-16 Fernando Perez <fperez@colorado.edu>
656 2005-03-16 Fernando Perez <fperez@colorado.edu>
639
657
640 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
658 * IPython/Prompts.py (CachedOutput.__init__): Fix default and
641 classic prompts to be '>>> ' (final space was missing, and it
659 classic prompts to be '>>> ' (final space was missing, and it
642 trips the emacs python mode).
660 trips the emacs python mode).
643 (BasePrompt.__str__): Added safe support for dynamic prompt
661 (BasePrompt.__str__): Added safe support for dynamic prompt
644 strings. Now you can set your prompt string to be '$x', and the
662 strings. Now you can set your prompt string to be '$x', and the
645 value of x will be printed from your interactive namespace. The
663 value of x will be printed from your interactive namespace. The
646 interpolation syntax includes the full Itpl support, so
664 interpolation syntax includes the full Itpl support, so
647 ${foo()+x+bar()} is a valid prompt string now, and the function
665 ${foo()+x+bar()} is a valid prompt string now, and the function
648 calls will be made at runtime.
666 calls will be made at runtime.
649
667
650 2005-03-15 Fernando Perez <fperez@colorado.edu>
668 2005-03-15 Fernando Perez <fperez@colorado.edu>
651
669
652 * IPython/Magic.py (magic_history): renamed %hist to %history, to
670 * IPython/Magic.py (magic_history): renamed %hist to %history, to
653 avoid name clashes in pylab. %hist still works, it just forwards
671 avoid name clashes in pylab. %hist still works, it just forwards
654 the call to %history.
672 the call to %history.
655
673
656 2005-03-02 *** Released version 0.6.12
674 2005-03-02 *** Released version 0.6.12
657
675
658 2005-03-02 Fernando Perez <fperez@colorado.edu>
676 2005-03-02 Fernando Perez <fperez@colorado.edu>
659
677
660 * IPython/iplib.py (handle_magic): log magic calls properly as
678 * IPython/iplib.py (handle_magic): log magic calls properly as
661 ipmagic() function calls.
679 ipmagic() function calls.
662
680
663 * IPython/Magic.py (magic_time): Improved %time to support
681 * IPython/Magic.py (magic_time): Improved %time to support
664 statements and provide wall-clock as well as CPU time.
682 statements and provide wall-clock as well as CPU time.
665
683
666 2005-02-27 Fernando Perez <fperez@colorado.edu>
684 2005-02-27 Fernando Perez <fperez@colorado.edu>
667
685
668 * IPython/hooks.py: New hooks module, to expose user-modifiable
686 * IPython/hooks.py: New hooks module, to expose user-modifiable
669 IPython functionality in a clean manner. For now only the editor
687 IPython functionality in a clean manner. For now only the editor
670 hook is actually written, and other thigns which I intend to turn
688 hook is actually written, and other thigns which I intend to turn
671 into proper hooks aren't yet there. The display and prefilter
689 into proper hooks aren't yet there. The display and prefilter
672 stuff, for example, should be hooks. But at least now the
690 stuff, for example, should be hooks. But at least now the
673 framework is in place, and the rest can be moved here with more
691 framework is in place, and the rest can be moved here with more
674 time later. IPython had had a .hooks variable for a long time for
692 time later. IPython had had a .hooks variable for a long time for
675 this purpose, but I'd never actually used it for anything.
693 this purpose, but I'd never actually used it for anything.
676
694
677 2005-02-26 Fernando Perez <fperez@colorado.edu>
695 2005-02-26 Fernando Perez <fperez@colorado.edu>
678
696
679 * IPython/ipmaker.py (make_IPython): make the default ipython
697 * IPython/ipmaker.py (make_IPython): make the default ipython
680 directory be called _ipython under win32, to follow more the
698 directory be called _ipython under win32, to follow more the
681 naming peculiarities of that platform (where buggy software like
699 naming peculiarities of that platform (where buggy software like
682 Visual Sourcesafe breaks with .named directories). Reported by
700 Visual Sourcesafe breaks with .named directories). Reported by
683 Ville Vainio.
701 Ville Vainio.
684
702
685 2005-02-23 Fernando Perez <fperez@colorado.edu>
703 2005-02-23 Fernando Perez <fperez@colorado.edu>
686
704
687 * IPython/iplib.py (InteractiveShell.__init__): removed a few
705 * IPython/iplib.py (InteractiveShell.__init__): removed a few
688 auto_aliases for win32 which were causing problems. Users can
706 auto_aliases for win32 which were causing problems. Users can
689 define the ones they personally like.
707 define the ones they personally like.
690
708
691 2005-02-21 Fernando Perez <fperez@colorado.edu>
709 2005-02-21 Fernando Perez <fperez@colorado.edu>
692
710
693 * IPython/Magic.py (magic_time): new magic to time execution of
711 * IPython/Magic.py (magic_time): new magic to time execution of
694 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
712 expressions. After a request by Charles Moad <cmoad-AT-indiana.edu>.
695
713
696 2005-02-19 Fernando Perez <fperez@colorado.edu>
714 2005-02-19 Fernando Perez <fperez@colorado.edu>
697
715
698 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
716 * IPython/ConfigLoader.py (ConfigLoader.load): Allow empty strings
699 into keys (for prompts, for example).
717 into keys (for prompts, for example).
700
718
701 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
719 * IPython/Prompts.py (BasePrompt.set_p_str): Fix to allow empty
702 prompts in case users want them. This introduces a small behavior
720 prompts in case users want them. This introduces a small behavior
703 change: ipython does not automatically add a space to all prompts
721 change: ipython does not automatically add a space to all prompts
704 anymore. To get the old prompts with a space, users should add it
722 anymore. To get the old prompts with a space, users should add it
705 manually to their ipythonrc file, so for example prompt_in1 should
723 manually to their ipythonrc file, so for example prompt_in1 should
706 now read 'In [\#]: ' instead of 'In [\#]:'.
724 now read 'In [\#]: ' instead of 'In [\#]:'.
707 (BasePrompt.__init__): New option prompts_pad_left (only in rc
725 (BasePrompt.__init__): New option prompts_pad_left (only in rc
708 file) to control left-padding of secondary prompts.
726 file) to control left-padding of secondary prompts.
709
727
710 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
728 * IPython/Magic.py (Magic.profile_missing_notice): Don't crash if
711 the profiler can't be imported. Fix for Debian, which removed
729 the profiler can't be imported. Fix for Debian, which removed
712 profile.py because of License issues. I applied a slightly
730 profile.py because of License issues. I applied a slightly
713 modified version of the original Debian patch at
731 modified version of the original Debian patch at
714 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
732 http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=294500.
715
733
716 2005-02-17 Fernando Perez <fperez@colorado.edu>
734 2005-02-17 Fernando Perez <fperez@colorado.edu>
717
735
718 * IPython/genutils.py (native_line_ends): Fix bug which would
736 * IPython/genutils.py (native_line_ends): Fix bug which would
719 cause improper line-ends under win32 b/c I was not opening files
737 cause improper line-ends under win32 b/c I was not opening files
720 in binary mode. Bug report and fix thanks to Ville.
738 in binary mode. Bug report and fix thanks to Ville.
721
739
722 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
740 * IPython/iplib.py (handle_auto): Fix bug which I introduced when
723 trying to catch spurious foo[1] autocalls. My fix actually broke
741 trying to catch spurious foo[1] autocalls. My fix actually broke
724 ',/' autoquote/call with explicit escape (bad regexp).
742 ',/' autoquote/call with explicit escape (bad regexp).
725
743
726 2005-02-15 *** Released version 0.6.11
744 2005-02-15 *** Released version 0.6.11
727
745
728 2005-02-14 Fernando Perez <fperez@colorado.edu>
746 2005-02-14 Fernando Perez <fperez@colorado.edu>
729
747
730 * IPython/background_jobs.py: New background job management
748 * IPython/background_jobs.py: New background job management
731 subsystem. This is implemented via a new set of classes, and
749 subsystem. This is implemented via a new set of classes, and
732 IPython now provides a builtin 'jobs' object for background job
750 IPython now provides a builtin 'jobs' object for background job
733 execution. A convenience %bg magic serves as a lightweight
751 execution. A convenience %bg magic serves as a lightweight
734 frontend for starting the more common type of calls. This was
752 frontend for starting the more common type of calls. This was
735 inspired by discussions with B. Granger and the BackgroundCommand
753 inspired by discussions with B. Granger and the BackgroundCommand
736 class described in the book Python Scripting for Computational
754 class described in the book Python Scripting for Computational
737 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
755 Science, by H. P. Langtangen: http://folk.uio.no/hpl/scripting
738 (although ultimately no code from this text was used, as IPython's
756 (although ultimately no code from this text was used, as IPython's
739 system is a separate implementation).
757 system is a separate implementation).
740
758
741 * IPython/iplib.py (MagicCompleter.python_matches): add new option
759 * IPython/iplib.py (MagicCompleter.python_matches): add new option
742 to control the completion of single/double underscore names
760 to control the completion of single/double underscore names
743 separately. As documented in the example ipytonrc file, the
761 separately. As documented in the example ipytonrc file, the
744 readline_omit__names variable can now be set to 2, to omit even
762 readline_omit__names variable can now be set to 2, to omit even
745 single underscore names. Thanks to a patch by Brian Wong
763 single underscore names. Thanks to a patch by Brian Wong
746 <BrianWong-AT-AirgoNetworks.Com>.
764 <BrianWong-AT-AirgoNetworks.Com>.
747 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
765 (InteractiveShell.__init__): Fix bug which would cause foo[1] to
748 be autocalled as foo([1]) if foo were callable. A problem for
766 be autocalled as foo([1]) if foo were callable. A problem for
749 things which are both callable and implement __getitem__.
767 things which are both callable and implement __getitem__.
750 (init_readline): Fix autoindentation for win32. Thanks to a patch
768 (init_readline): Fix autoindentation for win32. Thanks to a patch
751 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
769 by Vivian De Smedt <vivian-AT-vdesmedt.com>.
752
770
753 2005-02-12 Fernando Perez <fperez@colorado.edu>
771 2005-02-12 Fernando Perez <fperez@colorado.edu>
754
772
755 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
773 * IPython/ipmaker.py (make_IPython): Disabled the stout traps
756 which I had written long ago to sort out user error messages which
774 which I had written long ago to sort out user error messages which
757 may occur during startup. This seemed like a good idea initially,
775 may occur during startup. This seemed like a good idea initially,
758 but it has proven a disaster in retrospect. I don't want to
776 but it has proven a disaster in retrospect. I don't want to
759 change much code for now, so my fix is to set the internal 'debug'
777 change much code for now, so my fix is to set the internal 'debug'
760 flag to true everywhere, whose only job was precisely to control
778 flag to true everywhere, whose only job was precisely to control
761 this subsystem. This closes issue 28 (as well as avoiding all
779 this subsystem. This closes issue 28 (as well as avoiding all
762 sorts of strange hangups which occur from time to time).
780 sorts of strange hangups which occur from time to time).
763
781
764 2005-02-07 Fernando Perez <fperez@colorado.edu>
782 2005-02-07 Fernando Perez <fperez@colorado.edu>
765
783
766 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
784 * IPython/Magic.py (magic_edit): Fix 'ed -p' not working when the
767 previous call produced a syntax error.
785 previous call produced a syntax error.
768
786
769 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
787 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
770 classes without constructor.
788 classes without constructor.
771
789
772 2005-02-06 Fernando Perez <fperez@colorado.edu>
790 2005-02-06 Fernando Perez <fperez@colorado.edu>
773
791
774 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
792 * IPython/iplib.py (MagicCompleter.complete): Extend the list of
775 completions with the results of each matcher, so we return results
793 completions with the results of each matcher, so we return results
776 to the user from all namespaces. This breaks with ipython
794 to the user from all namespaces. This breaks with ipython
777 tradition, but I think it's a nicer behavior. Now you get all
795 tradition, but I think it's a nicer behavior. Now you get all
778 possible completions listed, from all possible namespaces (python,
796 possible completions listed, from all possible namespaces (python,
779 filesystem, magics...) After a request by John Hunter
797 filesystem, magics...) After a request by John Hunter
780 <jdhunter-AT-nitace.bsd.uchicago.edu>.
798 <jdhunter-AT-nitace.bsd.uchicago.edu>.
781
799
782 2005-02-05 Fernando Perez <fperez@colorado.edu>
800 2005-02-05 Fernando Perez <fperez@colorado.edu>
783
801
784 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
802 * IPython/Magic.py (magic_prun): Fix bug where prun would fail if
785 the call had quote characters in it (the quotes were stripped).
803 the call had quote characters in it (the quotes were stripped).
786
804
787 2005-01-31 Fernando Perez <fperez@colorado.edu>
805 2005-01-31 Fernando Perez <fperez@colorado.edu>
788
806
789 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
807 * IPython/iplib.py (InteractiveShell.__init__): reduce reliance on
790 Itpl.itpl() to make the code more robust against psyco
808 Itpl.itpl() to make the code more robust against psyco
791 optimizations.
809 optimizations.
792
810
793 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
811 * IPython/Itpl.py (Itpl.__str__): Use a _getframe() call instead
794 of causing an exception. Quicker, cleaner.
812 of causing an exception. Quicker, cleaner.
795
813
796 2005-01-28 Fernando Perez <fperez@colorado.edu>
814 2005-01-28 Fernando Perez <fperez@colorado.edu>
797
815
798 * scripts/ipython_win_post_install.py (install): hardcode
816 * scripts/ipython_win_post_install.py (install): hardcode
799 sys.prefix+'python.exe' as the executable path. It turns out that
817 sys.prefix+'python.exe' as the executable path. It turns out that
800 during the post-installation run, sys.executable resolves to the
818 during the post-installation run, sys.executable resolves to the
801 name of the binary installer! I should report this as a distutils
819 name of the binary installer! I should report this as a distutils
802 bug, I think. I updated the .10 release with this tiny fix, to
820 bug, I think. I updated the .10 release with this tiny fix, to
803 avoid annoying the lists further.
821 avoid annoying the lists further.
804
822
805 2005-01-27 *** Released version 0.6.10
823 2005-01-27 *** Released version 0.6.10
806
824
807 2005-01-27 Fernando Perez <fperez@colorado.edu>
825 2005-01-27 Fernando Perez <fperez@colorado.edu>
808
826
809 * IPython/numutils.py (norm): Added 'inf' as optional name for
827 * IPython/numutils.py (norm): Added 'inf' as optional name for
810 L-infinity norm, included references to mathworld.com for vector
828 L-infinity norm, included references to mathworld.com for vector
811 norm definitions.
829 norm definitions.
812 (amin/amax): added amin/amax for array min/max. Similar to what
830 (amin/amax): added amin/amax for array min/max. Similar to what
813 pylab ships with after the recent reorganization of names.
831 pylab ships with after the recent reorganization of names.
814 (spike/spike_odd): removed deprecated spike/spike_odd functions.
832 (spike/spike_odd): removed deprecated spike/spike_odd functions.
815
833
816 * ipython.el: committed Alex's recent fixes and improvements.
834 * ipython.el: committed Alex's recent fixes and improvements.
817 Tested with python-mode from CVS, and it looks excellent. Since
835 Tested with python-mode from CVS, and it looks excellent. Since
818 python-mode hasn't released anything in a while, I'm temporarily
836 python-mode hasn't released anything in a while, I'm temporarily
819 putting a copy of today's CVS (v 4.70) of python-mode in:
837 putting a copy of today's CVS (v 4.70) of python-mode in:
820 http://ipython.scipy.org/tmp/python-mode.el
838 http://ipython.scipy.org/tmp/python-mode.el
821
839
822 * scripts/ipython_win_post_install.py (install): Win32 fix to use
840 * scripts/ipython_win_post_install.py (install): Win32 fix to use
823 sys.executable for the executable name, instead of assuming it's
841 sys.executable for the executable name, instead of assuming it's
824 called 'python.exe' (the post-installer would have produced broken
842 called 'python.exe' (the post-installer would have produced broken
825 setups on systems with a differently named python binary).
843 setups on systems with a differently named python binary).
826
844
827 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
845 * IPython/PyColorize.py (Parser.__call__): change explicit '\n'
828 references to os.linesep, to make the code more
846 references to os.linesep, to make the code more
829 platform-independent. This is also part of the win32 coloring
847 platform-independent. This is also part of the win32 coloring
830 fixes.
848 fixes.
831
849
832 * IPython/genutils.py (page_dumb): Remove attempts to chop long
850 * IPython/genutils.py (page_dumb): Remove attempts to chop long
833 lines, which actually cause coloring bugs because the length of
851 lines, which actually cause coloring bugs because the length of
834 the line is very difficult to correctly compute with embedded
852 the line is very difficult to correctly compute with embedded
835 escapes. This was the source of all the coloring problems under
853 escapes. This was the source of all the coloring problems under
836 Win32. I think that _finally_, Win32 users have a properly
854 Win32. I think that _finally_, Win32 users have a properly
837 working ipython in all respects. This would never have happened
855 working ipython in all respects. This would never have happened
838 if not for Gary Bishop and Viktor Ransmayr's great help and work.
856 if not for Gary Bishop and Viktor Ransmayr's great help and work.
839
857
840 2005-01-26 *** Released version 0.6.9
858 2005-01-26 *** Released version 0.6.9
841
859
842 2005-01-25 Fernando Perez <fperez@colorado.edu>
860 2005-01-25 Fernando Perez <fperez@colorado.edu>
843
861
844 * setup.py: finally, we have a true Windows installer, thanks to
862 * setup.py: finally, we have a true Windows installer, thanks to
845 the excellent work of Viktor Ransmayr
863 the excellent work of Viktor Ransmayr
846 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
864 <viktor.ransmayr-AT-t-online.de>. The docs have been updated for
847 Windows users. The setup routine is quite a bit cleaner thanks to
865 Windows users. The setup routine is quite a bit cleaner thanks to
848 this, and the post-install script uses the proper functions to
866 this, and the post-install script uses the proper functions to
849 allow a clean de-installation using the standard Windows Control
867 allow a clean de-installation using the standard Windows Control
850 Panel.
868 Panel.
851
869
852 * IPython/genutils.py (get_home_dir): changed to use the $HOME
870 * IPython/genutils.py (get_home_dir): changed to use the $HOME
853 environment variable under all OSes (including win32) if
871 environment variable under all OSes (including win32) if
854 available. This will give consistency to win32 users who have set
872 available. This will give consistency to win32 users who have set
855 this variable for any reason. If os.environ['HOME'] fails, the
873 this variable for any reason. If os.environ['HOME'] fails, the
856 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
874 previous policy of using HOMEDRIVE\HOMEPATH kicks in.
857
875
858 2005-01-24 Fernando Perez <fperez@colorado.edu>
876 2005-01-24 Fernando Perez <fperez@colorado.edu>
859
877
860 * IPython/numutils.py (empty_like): add empty_like(), similar to
878 * IPython/numutils.py (empty_like): add empty_like(), similar to
861 zeros_like() but taking advantage of the new empty() Numeric routine.
879 zeros_like() but taking advantage of the new empty() Numeric routine.
862
880
863 2005-01-23 *** Released version 0.6.8
881 2005-01-23 *** Released version 0.6.8
864
882
865 2005-01-22 Fernando Perez <fperez@colorado.edu>
883 2005-01-22 Fernando Perez <fperez@colorado.edu>
866
884
867 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
885 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): I removed the
868 automatic show() calls. After discussing things with JDH, it
886 automatic show() calls. After discussing things with JDH, it
869 turns out there are too many corner cases where this can go wrong.
887 turns out there are too many corner cases where this can go wrong.
870 It's best not to try to be 'too smart', and simply have ipython
888 It's best not to try to be 'too smart', and simply have ipython
871 reproduce as much as possible the default behavior of a normal
889 reproduce as much as possible the default behavior of a normal
872 python shell.
890 python shell.
873
891
874 * IPython/iplib.py (InteractiveShell.__init__): Modified the
892 * IPython/iplib.py (InteractiveShell.__init__): Modified the
875 line-splitting regexp and _prefilter() to avoid calling getattr()
893 line-splitting regexp and _prefilter() to avoid calling getattr()
876 on assignments. This closes
894 on assignments. This closes
877 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
895 http://www.scipy.net/roundup/ipython/issue24. Note that Python's
878 readline uses getattr(), so a simple <TAB> keypress is still
896 readline uses getattr(), so a simple <TAB> keypress is still
879 enough to trigger getattr() calls on an object.
897 enough to trigger getattr() calls on an object.
880
898
881 2005-01-21 Fernando Perez <fperez@colorado.edu>
899 2005-01-21 Fernando Perez <fperez@colorado.edu>
882
900
883 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
901 * IPython/Shell.py (MatplotlibShellBase.magic_run): Fix the %run
884 docstring under pylab so it doesn't mask the original.
902 docstring under pylab so it doesn't mask the original.
885
903
886 2005-01-21 *** Released version 0.6.7
904 2005-01-21 *** Released version 0.6.7
887
905
888 2005-01-21 Fernando Perez <fperez@colorado.edu>
906 2005-01-21 Fernando Perez <fperez@colorado.edu>
889
907
890 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
908 * IPython/Shell.py (MTInteractiveShell.runcode): Trap a crash with
891 signal handling for win32 users in multithreaded mode.
909 signal handling for win32 users in multithreaded mode.
892
910
893 2005-01-17 Fernando Perez <fperez@colorado.edu>
911 2005-01-17 Fernando Perez <fperez@colorado.edu>
894
912
895 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
913 * IPython/OInspect.py (Inspector.pinfo): Fix crash when inspecting
896 instances with no __init__. After a crash report by Norbert Nemec
914 instances with no __init__. After a crash report by Norbert Nemec
897 <Norbert-AT-nemec-online.de>.
915 <Norbert-AT-nemec-online.de>.
898
916
899 2005-01-14 Fernando Perez <fperez@colorado.edu>
917 2005-01-14 Fernando Perez <fperez@colorado.edu>
900
918
901 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
919 * IPython/ultraTB.py (VerboseTB.text): Fix bug in reporting of
902 names for verbose exceptions, when multiple dotted names and the
920 names for verbose exceptions, when multiple dotted names and the
903 'parent' object were present on the same line.
921 'parent' object were present on the same line.
904
922
905 2005-01-11 Fernando Perez <fperez@colorado.edu>
923 2005-01-11 Fernando Perez <fperez@colorado.edu>
906
924
907 * IPython/genutils.py (flag_calls): new utility to trap and flag
925 * IPython/genutils.py (flag_calls): new utility to trap and flag
908 calls in functions. I need it to clean up matplotlib support.
926 calls in functions. I need it to clean up matplotlib support.
909 Also removed some deprecated code in genutils.
927 Also removed some deprecated code in genutils.
910
928
911 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
929 * IPython/Shell.py (MatplotlibShellBase.mplot_exec): small fix so
912 that matplotlib scripts called with %run, which don't call show()
930 that matplotlib scripts called with %run, which don't call show()
913 themselves, still have their plotting windows open.
931 themselves, still have their plotting windows open.
914
932
915 2005-01-05 Fernando Perez <fperez@colorado.edu>
933 2005-01-05 Fernando Perez <fperez@colorado.edu>
916
934
917 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
935 * IPython/Shell.py (IPShellGTK.__init__): Patch by Andrew Straw
918 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
936 <astraw-AT-caltech.edu>, to fix gtk deprecation warnings.
919
937
920 2004-12-19 Fernando Perez <fperez@colorado.edu>
938 2004-12-19 Fernando Perez <fperez@colorado.edu>
921
939
922 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
940 * IPython/Shell.py (MTInteractiveShell.runcode): Get rid of
923 parent_runcode, which was an eyesore. The same result can be
941 parent_runcode, which was an eyesore. The same result can be
924 obtained with Python's regular superclass mechanisms.
942 obtained with Python's regular superclass mechanisms.
925
943
926 2004-12-17 Fernando Perez <fperez@colorado.edu>
944 2004-12-17 Fernando Perez <fperez@colorado.edu>
927
945
928 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
946 * IPython/Magic.py (Magic.magic_sc): Fix quote stripping problem
929 reported by Prabhu.
947 reported by Prabhu.
930 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
948 (Magic.magic_sx): direct all errors to Term.cerr (defaults to
931 sys.stderr) instead of explicitly calling sys.stderr. This helps
949 sys.stderr) instead of explicitly calling sys.stderr. This helps
932 maintain our I/O abstractions clean, for future GUI embeddings.
950 maintain our I/O abstractions clean, for future GUI embeddings.
933
951
934 * IPython/genutils.py (info): added new utility for sys.stderr
952 * IPython/genutils.py (info): added new utility for sys.stderr
935 unified info message handling (thin wrapper around warn()).
953 unified info message handling (thin wrapper around warn()).
936
954
937 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
955 * IPython/ultraTB.py (VerboseTB.text): Fix misreported global
938 composite (dotted) names on verbose exceptions.
956 composite (dotted) names on verbose exceptions.
939 (VerboseTB.nullrepr): harden against another kind of errors which
957 (VerboseTB.nullrepr): harden against another kind of errors which
940 Python's inspect module can trigger, and which were crashing
958 Python's inspect module can trigger, and which were crashing
941 IPython. Thanks to a report by Marco Lombardi
959 IPython. Thanks to a report by Marco Lombardi
942 <mlombard-AT-ma010192.hq.eso.org>.
960 <mlombard-AT-ma010192.hq.eso.org>.
943
961
944 2004-12-13 *** Released version 0.6.6
962 2004-12-13 *** Released version 0.6.6
945
963
946 2004-12-12 Fernando Perez <fperez@colorado.edu>
964 2004-12-12 Fernando Perez <fperez@colorado.edu>
947
965
948 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
966 * IPython/Shell.py (IPShellGTK.mainloop): catch RuntimeErrors
949 generated by pygtk upon initialization if it was built without
967 generated by pygtk upon initialization if it was built without
950 threads (for matplotlib users). After a crash reported by
968 threads (for matplotlib users). After a crash reported by
951 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
969 Leguijt, Jaap J SIEP-EPT-RES <Jaap.Leguijt-AT-shell.com>.
952
970
953 * IPython/ipmaker.py (make_IPython): fix small bug in the
971 * IPython/ipmaker.py (make_IPython): fix small bug in the
954 import_some parameter for multiple imports.
972 import_some parameter for multiple imports.
955
973
956 * IPython/iplib.py (ipmagic): simplified the interface of
974 * IPython/iplib.py (ipmagic): simplified the interface of
957 ipmagic() to take a single string argument, just as it would be
975 ipmagic() to take a single string argument, just as it would be
958 typed at the IPython cmd line.
976 typed at the IPython cmd line.
959 (ipalias): Added new ipalias() with an interface identical to
977 (ipalias): Added new ipalias() with an interface identical to
960 ipmagic(). This completes exposing a pure python interface to the
978 ipmagic(). This completes exposing a pure python interface to the
961 alias and magic system, which can be used in loops or more complex
979 alias and magic system, which can be used in loops or more complex
962 code where IPython's automatic line mangling is not active.
980 code where IPython's automatic line mangling is not active.
963
981
964 * IPython/genutils.py (timing): changed interface of timing to
982 * IPython/genutils.py (timing): changed interface of timing to
965 simply run code once, which is the most common case. timings()
983 simply run code once, which is the most common case. timings()
966 remains unchanged, for the cases where you want multiple runs.
984 remains unchanged, for the cases where you want multiple runs.
967
985
968 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
986 * IPython/Shell.py (MatplotlibShellBase._matplotlib_config): Fix a
969 bug where Python2.2 crashes with exec'ing code which does not end
987 bug where Python2.2 crashes with exec'ing code which does not end
970 in a single newline. Python 2.3 is OK, so I hadn't noticed this
988 in a single newline. Python 2.3 is OK, so I hadn't noticed this
971 before.
989 before.
972
990
973 2004-12-10 Fernando Perez <fperez@colorado.edu>
991 2004-12-10 Fernando Perez <fperez@colorado.edu>
974
992
975 * IPython/Magic.py (Magic.magic_prun): changed name of option from
993 * IPython/Magic.py (Magic.magic_prun): changed name of option from
976 -t to -T, to accomodate the new -t flag in %run (the %run and
994 -t to -T, to accomodate the new -t flag in %run (the %run and
977 %prun options are kind of intermixed, and it's not easy to change
995 %prun options are kind of intermixed, and it's not easy to change
978 this with the limitations of python's getopt).
996 this with the limitations of python's getopt).
979
997
980 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
998 * IPython/Magic.py (Magic.magic_run): Added new -t option to time
981 the execution of scripts. It's not as fine-tuned as timeit.py,
999 the execution of scripts. It's not as fine-tuned as timeit.py,
982 but it works from inside ipython (and under 2.2, which lacks
1000 but it works from inside ipython (and under 2.2, which lacks
983 timeit.py). Optionally a number of runs > 1 can be given for
1001 timeit.py). Optionally a number of runs > 1 can be given for
984 timing very short-running code.
1002 timing very short-running code.
985
1003
986 * IPython/genutils.py (uniq_stable): new routine which returns a
1004 * IPython/genutils.py (uniq_stable): new routine which returns a
987 list of unique elements in any iterable, but in stable order of
1005 list of unique elements in any iterable, but in stable order of
988 appearance. I needed this for the ultraTB fixes, and it's a handy
1006 appearance. I needed this for the ultraTB fixes, and it's a handy
989 utility.
1007 utility.
990
1008
991 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
1009 * IPython/ultraTB.py (VerboseTB.text): Fix proper reporting of
992 dotted names in Verbose exceptions. This had been broken since
1010 dotted names in Verbose exceptions. This had been broken since
993 the very start, now x.y will properly be printed in a Verbose
1011 the very start, now x.y will properly be printed in a Verbose
994 traceback, instead of x being shown and y appearing always as an
1012 traceback, instead of x being shown and y appearing always as an
995 'undefined global'. Getting this to work was a bit tricky,
1013 'undefined global'. Getting this to work was a bit tricky,
996 because by default python tokenizers are stateless. Saved by
1014 because by default python tokenizers are stateless. Saved by
997 python's ability to easily add a bit of state to an arbitrary
1015 python's ability to easily add a bit of state to an arbitrary
998 function (without needing to build a full-blown callable object).
1016 function (without needing to build a full-blown callable object).
999
1017
1000 Also big cleanup of this code, which had horrendous runtime
1018 Also big cleanup of this code, which had horrendous runtime
1001 lookups of zillions of attributes for colorization. Moved all
1019 lookups of zillions of attributes for colorization. Moved all
1002 this code into a few templates, which make it cleaner and quicker.
1020 this code into a few templates, which make it cleaner and quicker.
1003
1021
1004 Printout quality was also improved for Verbose exceptions: one
1022 Printout quality was also improved for Verbose exceptions: one
1005 variable per line, and memory addresses are printed (this can be
1023 variable per line, and memory addresses are printed (this can be
1006 quite handy in nasty debugging situations, which is what Verbose
1024 quite handy in nasty debugging situations, which is what Verbose
1007 is for).
1025 is for).
1008
1026
1009 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1027 * IPython/ipmaker.py (make_IPython): Do NOT execute files named in
1010 the command line as scripts to be loaded by embedded instances.
1028 the command line as scripts to be loaded by embedded instances.
1011 Doing so has the potential for an infinite recursion if there are
1029 Doing so has the potential for an infinite recursion if there are
1012 exceptions thrown in the process. This fixes a strange crash
1030 exceptions thrown in the process. This fixes a strange crash
1013 reported by Philippe MULLER <muller-AT-irit.fr>.
1031 reported by Philippe MULLER <muller-AT-irit.fr>.
1014
1032
1015 2004-12-09 Fernando Perez <fperez@colorado.edu>
1033 2004-12-09 Fernando Perez <fperez@colorado.edu>
1016
1034
1017 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1035 * IPython/Shell.py (MatplotlibShellBase.use): Change pylab support
1018 to reflect new names in matplotlib, which now expose the
1036 to reflect new names in matplotlib, which now expose the
1019 matlab-compatible interface via a pylab module instead of the
1037 matlab-compatible interface via a pylab module instead of the
1020 'matlab' name. The new code is backwards compatible, so users of
1038 'matlab' name. The new code is backwards compatible, so users of
1021 all matplotlib versions are OK. Patch by J. Hunter.
1039 all matplotlib versions are OK. Patch by J. Hunter.
1022
1040
1023 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1041 * IPython/OInspect.py (Inspector.pinfo): Add to object? printing
1024 of __init__ docstrings for instances (class docstrings are already
1042 of __init__ docstrings for instances (class docstrings are already
1025 automatically printed). Instances with customized docstrings
1043 automatically printed). Instances with customized docstrings
1026 (indep. of the class) are also recognized and all 3 separate
1044 (indep. of the class) are also recognized and all 3 separate
1027 docstrings are printed (instance, class, constructor). After some
1045 docstrings are printed (instance, class, constructor). After some
1028 comments/suggestions by J. Hunter.
1046 comments/suggestions by J. Hunter.
1029
1047
1030 2004-12-05 Fernando Perez <fperez@colorado.edu>
1048 2004-12-05 Fernando Perez <fperez@colorado.edu>
1031
1049
1032 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1050 * IPython/iplib.py (MagicCompleter.complete): Remove annoying
1033 warnings when tab-completion fails and triggers an exception.
1051 warnings when tab-completion fails and triggers an exception.
1034
1052
1035 2004-12-03 Fernando Perez <fperez@colorado.edu>
1053 2004-12-03 Fernando Perez <fperez@colorado.edu>
1036
1054
1037 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1055 * IPython/Magic.py (magic_prun): Fix bug where an exception would
1038 be triggered when using 'run -p'. An incorrect option flag was
1056 be triggered when using 'run -p'. An incorrect option flag was
1039 being set ('d' instead of 'D').
1057 being set ('d' instead of 'D').
1040 (manpage): fix missing escaped \- sign.
1058 (manpage): fix missing escaped \- sign.
1041
1059
1042 2004-11-30 *** Released version 0.6.5
1060 2004-11-30 *** Released version 0.6.5
1043
1061
1044 2004-11-30 Fernando Perez <fperez@colorado.edu>
1062 2004-11-30 Fernando Perez <fperez@colorado.edu>
1045
1063
1046 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1064 * IPython/Magic.py (Magic.magic_run): Fix bug in breakpoint
1047 setting with -d option.
1065 setting with -d option.
1048
1066
1049 * setup.py (docfiles): Fix problem where the doc glob I was using
1067 * setup.py (docfiles): Fix problem where the doc glob I was using
1050 was COMPLETELY BROKEN. It was giving the right files by pure
1068 was COMPLETELY BROKEN. It was giving the right files by pure
1051 accident, but failed once I tried to include ipython.el. Note:
1069 accident, but failed once I tried to include ipython.el. Note:
1052 glob() does NOT allow you to do exclusion on multiple endings!
1070 glob() does NOT allow you to do exclusion on multiple endings!
1053
1071
1054 2004-11-29 Fernando Perez <fperez@colorado.edu>
1072 2004-11-29 Fernando Perez <fperez@colorado.edu>
1055
1073
1056 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1074 * IPython/usage.py (__doc__): cleaned up usage docstring, by using
1057 the manpage as the source. Better formatting & consistency.
1075 the manpage as the source. Better formatting & consistency.
1058
1076
1059 * IPython/Magic.py (magic_run): Added new -d option, to run
1077 * IPython/Magic.py (magic_run): Added new -d option, to run
1060 scripts under the control of the python pdb debugger. Note that
1078 scripts under the control of the python pdb debugger. Note that
1061 this required changing the %prun option -d to -D, to avoid a clash
1079 this required changing the %prun option -d to -D, to avoid a clash
1062 (since %run must pass options to %prun, and getopt is too dumb to
1080 (since %run must pass options to %prun, and getopt is too dumb to
1063 handle options with string values with embedded spaces). Thanks
1081 handle options with string values with embedded spaces). Thanks
1064 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1082 to a suggestion by Matthew Arnison <maffew-AT-cat.org.au>.
1065 (magic_who_ls): added type matching to %who and %whos, so that one
1083 (magic_who_ls): added type matching to %who and %whos, so that one
1066 can filter their output to only include variables of certain
1084 can filter their output to only include variables of certain
1067 types. Another suggestion by Matthew.
1085 types. Another suggestion by Matthew.
1068 (magic_whos): Added memory summaries in kb and Mb for arrays.
1086 (magic_whos): Added memory summaries in kb and Mb for arrays.
1069 (magic_who): Improve formatting (break lines every 9 vars).
1087 (magic_who): Improve formatting (break lines every 9 vars).
1070
1088
1071 2004-11-28 Fernando Perez <fperez@colorado.edu>
1089 2004-11-28 Fernando Perez <fperez@colorado.edu>
1072
1090
1073 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1091 * IPython/Logger.py (Logger.log): Fix bug in syncing the input
1074 cache when empty lines were present.
1092 cache when empty lines were present.
1075
1093
1076 2004-11-24 Fernando Perez <fperez@colorado.edu>
1094 2004-11-24 Fernando Perez <fperez@colorado.edu>
1077
1095
1078 * IPython/usage.py (__doc__): document the re-activated threading
1096 * IPython/usage.py (__doc__): document the re-activated threading
1079 options for WX and GTK.
1097 options for WX and GTK.
1080
1098
1081 2004-11-23 Fernando Perez <fperez@colorado.edu>
1099 2004-11-23 Fernando Perez <fperez@colorado.edu>
1082
1100
1083 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1101 * IPython/Shell.py (start): Added Prabhu's big patch to reactivate
1084 the -wthread and -gthread options, along with a new -tk one to try
1102 the -wthread and -gthread options, along with a new -tk one to try
1085 and coordinate Tk threading with wx/gtk. The tk support is very
1103 and coordinate Tk threading with wx/gtk. The tk support is very
1086 platform dependent, since it seems to require Tcl and Tk to be
1104 platform dependent, since it seems to require Tcl and Tk to be
1087 built with threads (Fedora1/2 appears NOT to have it, but in
1105 built with threads (Fedora1/2 appears NOT to have it, but in
1088 Prabhu's Debian boxes it works OK). But even with some Tk
1106 Prabhu's Debian boxes it works OK). But even with some Tk
1089 limitations, this is a great improvement.
1107 limitations, this is a great improvement.
1090
1108
1091 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1109 * IPython/Prompts.py (prompt_specials_color): Added \t for time
1092 info in user prompts. Patch by Prabhu.
1110 info in user prompts. Patch by Prabhu.
1093
1111
1094 2004-11-18 Fernando Perez <fperez@colorado.edu>
1112 2004-11-18 Fernando Perez <fperez@colorado.edu>
1095
1113
1096 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1114 * IPython/genutils.py (ask_yes_no): Add check for a max of 20
1097 EOFErrors and bail, to avoid infinite loops if a non-terminating
1115 EOFErrors and bail, to avoid infinite loops if a non-terminating
1098 file is fed into ipython. Patch submitted in issue 19 by user,
1116 file is fed into ipython. Patch submitted in issue 19 by user,
1099 many thanks.
1117 many thanks.
1100
1118
1101 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1119 * IPython/iplib.py (InteractiveShell.handle_auto): do NOT trigger
1102 autoquote/parens in continuation prompts, which can cause lots of
1120 autoquote/parens in continuation prompts, which can cause lots of
1103 problems. Closes roundup issue 20.
1121 problems. Closes roundup issue 20.
1104
1122
1105 2004-11-17 Fernando Perez <fperez@colorado.edu>
1123 2004-11-17 Fernando Perez <fperez@colorado.edu>
1106
1124
1107 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1125 * debian/control (Build-Depends-Indep): Fix dpatch dependency,
1108 reported as debian bug #280505. I'm not sure my local changelog
1126 reported as debian bug #280505. I'm not sure my local changelog
1109 entry has the proper debian format (Jack?).
1127 entry has the proper debian format (Jack?).
1110
1128
1111 2004-11-08 *** Released version 0.6.4
1129 2004-11-08 *** Released version 0.6.4
1112
1130
1113 2004-11-08 Fernando Perez <fperez@colorado.edu>
1131 2004-11-08 Fernando Perez <fperez@colorado.edu>
1114
1132
1115 * IPython/iplib.py (init_readline): Fix exit message for Windows
1133 * IPython/iplib.py (init_readline): Fix exit message for Windows
1116 when readline is active. Thanks to a report by Eric Jones
1134 when readline is active. Thanks to a report by Eric Jones
1117 <eric-AT-enthought.com>.
1135 <eric-AT-enthought.com>.
1118
1136
1119 2004-11-07 Fernando Perez <fperez@colorado.edu>
1137 2004-11-07 Fernando Perez <fperez@colorado.edu>
1120
1138
1121 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1139 * IPython/genutils.py (page): Add a trap for OSError exceptions,
1122 sometimes seen by win2k/cygwin users.
1140 sometimes seen by win2k/cygwin users.
1123
1141
1124 2004-11-06 Fernando Perez <fperez@colorado.edu>
1142 2004-11-06 Fernando Perez <fperez@colorado.edu>
1125
1143
1126 * IPython/iplib.py (interact): Change the handling of %Exit from
1144 * IPython/iplib.py (interact): Change the handling of %Exit from
1127 trying to propagate a SystemExit to an internal ipython flag.
1145 trying to propagate a SystemExit to an internal ipython flag.
1128 This is less elegant than using Python's exception mechanism, but
1146 This is less elegant than using Python's exception mechanism, but
1129 I can't get that to work reliably with threads, so under -pylab
1147 I can't get that to work reliably with threads, so under -pylab
1130 %Exit was hanging IPython. Cross-thread exception handling is
1148 %Exit was hanging IPython. Cross-thread exception handling is
1131 really a bitch. Thaks to a bug report by Stephen Walton
1149 really a bitch. Thaks to a bug report by Stephen Walton
1132 <stephen.walton-AT-csun.edu>.
1150 <stephen.walton-AT-csun.edu>.
1133
1151
1134 2004-11-04 Fernando Perez <fperez@colorado.edu>
1152 2004-11-04 Fernando Perez <fperez@colorado.edu>
1135
1153
1136 * IPython/iplib.py (raw_input_original): store a pointer to the
1154 * IPython/iplib.py (raw_input_original): store a pointer to the
1137 true raw_input to harden against code which can modify it
1155 true raw_input to harden against code which can modify it
1138 (wx.py.PyShell does this and would otherwise crash ipython).
1156 (wx.py.PyShell does this and would otherwise crash ipython).
1139 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1157 Thanks to a bug report by Jim Flowers <james.flowers-AT-lgx.com>.
1140
1158
1141 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1159 * IPython/Shell.py (MTInteractiveShell.runsource): Cleaner fix for
1142 Ctrl-C problem, which does not mess up the input line.
1160 Ctrl-C problem, which does not mess up the input line.
1143
1161
1144 2004-11-03 Fernando Perez <fperez@colorado.edu>
1162 2004-11-03 Fernando Perez <fperez@colorado.edu>
1145
1163
1146 * IPython/Release.py: Changed licensing to BSD, in all files.
1164 * IPython/Release.py: Changed licensing to BSD, in all files.
1147 (name): lowercase name for tarball/RPM release.
1165 (name): lowercase name for tarball/RPM release.
1148
1166
1149 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1167 * IPython/OInspect.py (getdoc): wrap inspect.getdoc() safely for
1150 use throughout ipython.
1168 use throughout ipython.
1151
1169
1152 * IPython/Magic.py (Magic._ofind): Switch to using the new
1170 * IPython/Magic.py (Magic._ofind): Switch to using the new
1153 OInspect.getdoc() function.
1171 OInspect.getdoc() function.
1154
1172
1155 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1173 * IPython/Shell.py (sigint_handler): Hack to ignore the execution
1156 of the line currently being canceled via Ctrl-C. It's extremely
1174 of the line currently being canceled via Ctrl-C. It's extremely
1157 ugly, but I don't know how to do it better (the problem is one of
1175 ugly, but I don't know how to do it better (the problem is one of
1158 handling cross-thread exceptions).
1176 handling cross-thread exceptions).
1159
1177
1160 2004-10-28 Fernando Perez <fperez@colorado.edu>
1178 2004-10-28 Fernando Perez <fperez@colorado.edu>
1161
1179
1162 * IPython/Shell.py (signal_handler): add signal handlers to trap
1180 * IPython/Shell.py (signal_handler): add signal handlers to trap
1163 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1181 SIGINT and SIGSEGV in threaded code properly. Thanks to a bug
1164 report by Francesc Alted.
1182 report by Francesc Alted.
1165
1183
1166 2004-10-21 Fernando Perez <fperez@colorado.edu>
1184 2004-10-21 Fernando Perez <fperez@colorado.edu>
1167
1185
1168 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1186 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Fix @
1169 to % for pysh syntax extensions.
1187 to % for pysh syntax extensions.
1170
1188
1171 2004-10-09 Fernando Perez <fperez@colorado.edu>
1189 2004-10-09 Fernando Perez <fperez@colorado.edu>
1172
1190
1173 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1191 * IPython/Magic.py (Magic.magic_whos): modify output of Numeric
1174 arrays to print a more useful summary, without calling str(arr).
1192 arrays to print a more useful summary, without calling str(arr).
1175 This avoids the problem of extremely lengthy computations which
1193 This avoids the problem of extremely lengthy computations which
1176 occur if arr is large, and appear to the user as a system lockup
1194 occur if arr is large, and appear to the user as a system lockup
1177 with 100% cpu activity. After a suggestion by Kristian Sandberg
1195 with 100% cpu activity. After a suggestion by Kristian Sandberg
1178 <Kristian.Sandberg@colorado.edu>.
1196 <Kristian.Sandberg@colorado.edu>.
1179 (Magic.__init__): fix bug in global magic escapes not being
1197 (Magic.__init__): fix bug in global magic escapes not being
1180 correctly set.
1198 correctly set.
1181
1199
1182 2004-10-08 Fernando Perez <fperez@colorado.edu>
1200 2004-10-08 Fernando Perez <fperez@colorado.edu>
1183
1201
1184 * IPython/Magic.py (__license__): change to absolute imports of
1202 * IPython/Magic.py (__license__): change to absolute imports of
1185 ipython's own internal packages, to start adapting to the absolute
1203 ipython's own internal packages, to start adapting to the absolute
1186 import requirement of PEP-328.
1204 import requirement of PEP-328.
1187
1205
1188 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1206 * IPython/genutils.py (__author__): Fix coding to utf-8 on all
1189 files, and standardize author/license marks through the Release
1207 files, and standardize author/license marks through the Release
1190 module instead of having per/file stuff (except for files with
1208 module instead of having per/file stuff (except for files with
1191 particular licenses, like the MIT/PSF-licensed codes).
1209 particular licenses, like the MIT/PSF-licensed codes).
1192
1210
1193 * IPython/Debugger.py: remove dead code for python 2.1
1211 * IPython/Debugger.py: remove dead code for python 2.1
1194
1212
1195 2004-10-04 Fernando Perez <fperez@colorado.edu>
1213 2004-10-04 Fernando Perez <fperez@colorado.edu>
1196
1214
1197 * IPython/iplib.py (ipmagic): New function for accessing magics
1215 * IPython/iplib.py (ipmagic): New function for accessing magics
1198 via a normal python function call.
1216 via a normal python function call.
1199
1217
1200 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1218 * IPython/Magic.py (Magic.magic_magic): Change the magic escape
1201 from '@' to '%', to accomodate the new @decorator syntax of python
1219 from '@' to '%', to accomodate the new @decorator syntax of python
1202 2.4.
1220 2.4.
1203
1221
1204 2004-09-29 Fernando Perez <fperez@colorado.edu>
1222 2004-09-29 Fernando Perez <fperez@colorado.edu>
1205
1223
1206 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1224 * IPython/Shell.py (MatplotlibShellBase.use): Added a wrapper to
1207 matplotlib.use to prevent running scripts which try to switch
1225 matplotlib.use to prevent running scripts which try to switch
1208 interactive backends from within ipython. This will just crash
1226 interactive backends from within ipython. This will just crash
1209 the python interpreter, so we can't allow it (but a detailed error
1227 the python interpreter, so we can't allow it (but a detailed error
1210 is given to the user).
1228 is given to the user).
1211
1229
1212 2004-09-28 Fernando Perez <fperez@colorado.edu>
1230 2004-09-28 Fernando Perez <fperez@colorado.edu>
1213
1231
1214 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1232 * IPython/Shell.py (MatplotlibShellBase.mplot_exec):
1215 matplotlib-related fixes so that using @run with non-matplotlib
1233 matplotlib-related fixes so that using @run with non-matplotlib
1216 scripts doesn't pop up spurious plot windows. This requires
1234 scripts doesn't pop up spurious plot windows. This requires
1217 matplotlib >= 0.63, where I had to make some changes as well.
1235 matplotlib >= 0.63, where I had to make some changes as well.
1218
1236
1219 * IPython/ipmaker.py (make_IPython): update version requirement to
1237 * IPython/ipmaker.py (make_IPython): update version requirement to
1220 python 2.2.
1238 python 2.2.
1221
1239
1222 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1240 * IPython/iplib.py (InteractiveShell.mainloop): Add an optional
1223 banner arg for embedded customization.
1241 banner arg for embedded customization.
1224
1242
1225 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1243 * IPython/Magic.py (Magic.__init__): big cleanup to remove all
1226 explicit uses of __IP as the IPython's instance name. Now things
1244 explicit uses of __IP as the IPython's instance name. Now things
1227 are properly handled via the shell.name value. The actual code
1245 are properly handled via the shell.name value. The actual code
1228 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1246 is a bit ugly b/c I'm doing it via a global in Magic.py, but this
1229 is much better than before. I'll clean things completely when the
1247 is much better than before. I'll clean things completely when the
1230 magic stuff gets a real overhaul.
1248 magic stuff gets a real overhaul.
1231
1249
1232 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1250 * ipython.1: small fixes, sent in by Jack Moffit. He also sent in
1233 minor changes to debian dir.
1251 minor changes to debian dir.
1234
1252
1235 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1253 * IPython/iplib.py (InteractiveShell.__init__): Fix adding a
1236 pointer to the shell itself in the interactive namespace even when
1254 pointer to the shell itself in the interactive namespace even when
1237 a user-supplied dict is provided. This is needed for embedding
1255 a user-supplied dict is provided. This is needed for embedding
1238 purposes (found by tests with Michel Sanner).
1256 purposes (found by tests with Michel Sanner).
1239
1257
1240 2004-09-27 Fernando Perez <fperez@colorado.edu>
1258 2004-09-27 Fernando Perez <fperez@colorado.edu>
1241
1259
1242 * IPython/UserConfig/ipythonrc: remove []{} from
1260 * IPython/UserConfig/ipythonrc: remove []{} from
1243 readline_remove_delims, so that things like [modname.<TAB> do
1261 readline_remove_delims, so that things like [modname.<TAB> do
1244 proper completion. This disables [].TAB, but that's a less common
1262 proper completion. This disables [].TAB, but that's a less common
1245 case than module names in list comprehensions, for example.
1263 case than module names in list comprehensions, for example.
1246 Thanks to a report by Andrea Riciputi.
1264 Thanks to a report by Andrea Riciputi.
1247
1265
1248 2004-09-09 Fernando Perez <fperez@colorado.edu>
1266 2004-09-09 Fernando Perez <fperez@colorado.edu>
1249
1267
1250 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1268 * IPython/Shell.py (IPShellGTK.mainloop): reorder to avoid
1251 blocking problems in win32 and osx. Fix by John.
1269 blocking problems in win32 and osx. Fix by John.
1252
1270
1253 2004-09-08 Fernando Perez <fperez@colorado.edu>
1271 2004-09-08 Fernando Perez <fperez@colorado.edu>
1254
1272
1255 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1273 * IPython/Shell.py (IPShellWX.OnInit): Fix output redirection bug
1256 for Win32 and OSX. Fix by John Hunter.
1274 for Win32 and OSX. Fix by John Hunter.
1257
1275
1258 2004-08-30 *** Released version 0.6.3
1276 2004-08-30 *** Released version 0.6.3
1259
1277
1260 2004-08-30 Fernando Perez <fperez@colorado.edu>
1278 2004-08-30 Fernando Perez <fperez@colorado.edu>
1261
1279
1262 * setup.py (isfile): Add manpages to list of dependent files to be
1280 * setup.py (isfile): Add manpages to list of dependent files to be
1263 updated.
1281 updated.
1264
1282
1265 2004-08-27 Fernando Perez <fperez@colorado.edu>
1283 2004-08-27 Fernando Perez <fperez@colorado.edu>
1266
1284
1267 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1285 * IPython/Shell.py (start): I've disabled -wthread and -gthread
1268 for now. They don't really work with standalone WX/GTK code
1286 for now. They don't really work with standalone WX/GTK code
1269 (though matplotlib IS working fine with both of those backends).
1287 (though matplotlib IS working fine with both of those backends).
1270 This will neeed much more testing. I disabled most things with
1288 This will neeed much more testing. I disabled most things with
1271 comments, so turning it back on later should be pretty easy.
1289 comments, so turning it back on later should be pretty easy.
1272
1290
1273 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1291 * IPython/iplib.py (InteractiveShell.__init__): Fix accidental
1274 autocalling of expressions like r'foo', by modifying the line
1292 autocalling of expressions like r'foo', by modifying the line
1275 split regexp. Closes
1293 split regexp. Closes
1276 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1294 http://www.scipy.net/roundup/ipython/issue18, reported by Nicholas
1277 Riley <ipythonbugs-AT-sabi.net>.
1295 Riley <ipythonbugs-AT-sabi.net>.
1278 (InteractiveShell.mainloop): honor --nobanner with banner
1296 (InteractiveShell.mainloop): honor --nobanner with banner
1279 extensions.
1297 extensions.
1280
1298
1281 * IPython/Shell.py: Significant refactoring of all classes, so
1299 * IPython/Shell.py: Significant refactoring of all classes, so
1282 that we can really support ALL matplotlib backends and threading
1300 that we can really support ALL matplotlib backends and threading
1283 models (John spotted a bug with Tk which required this). Now we
1301 models (John spotted a bug with Tk which required this). Now we
1284 should support single-threaded, WX-threads and GTK-threads, both
1302 should support single-threaded, WX-threads and GTK-threads, both
1285 for generic code and for matplotlib.
1303 for generic code and for matplotlib.
1286
1304
1287 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1305 * IPython/ipmaker.py (__call__): Changed -mpthread option to
1288 -pylab, to simplify things for users. Will also remove the pylab
1306 -pylab, to simplify things for users. Will also remove the pylab
1289 profile, since now all of matplotlib configuration is directly
1307 profile, since now all of matplotlib configuration is directly
1290 handled here. This also reduces startup time.
1308 handled here. This also reduces startup time.
1291
1309
1292 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1310 * IPython/Shell.py (IPShellGTK.run): Fixed bug where mainloop() of
1293 shell wasn't being correctly called. Also in IPShellWX.
1311 shell wasn't being correctly called. Also in IPShellWX.
1294
1312
1295 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1313 * IPython/iplib.py (InteractiveShell.__init__): Added option to
1296 fine-tune banner.
1314 fine-tune banner.
1297
1315
1298 * IPython/numutils.py (spike): Deprecate these spike functions,
1316 * IPython/numutils.py (spike): Deprecate these spike functions,
1299 delete (long deprecated) gnuplot_exec handler.
1317 delete (long deprecated) gnuplot_exec handler.
1300
1318
1301 2004-08-26 Fernando Perez <fperez@colorado.edu>
1319 2004-08-26 Fernando Perez <fperez@colorado.edu>
1302
1320
1303 * ipython.1: Update for threading options, plus some others which
1321 * ipython.1: Update for threading options, plus some others which
1304 were missing.
1322 were missing.
1305
1323
1306 * IPython/ipmaker.py (__call__): Added -wthread option for
1324 * IPython/ipmaker.py (__call__): Added -wthread option for
1307 wxpython thread handling. Make sure threading options are only
1325 wxpython thread handling. Make sure threading options are only
1308 valid at the command line.
1326 valid at the command line.
1309
1327
1310 * scripts/ipython: moved shell selection into a factory function
1328 * scripts/ipython: moved shell selection into a factory function
1311 in Shell.py, to keep the starter script to a minimum.
1329 in Shell.py, to keep the starter script to a minimum.
1312
1330
1313 2004-08-25 Fernando Perez <fperez@colorado.edu>
1331 2004-08-25 Fernando Perez <fperez@colorado.edu>
1314
1332
1315 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1333 * IPython/Shell.py (IPShellWX.wxexit): fixes to WX threading, by
1316 John. Along with some recent changes he made to matplotlib, the
1334 John. Along with some recent changes he made to matplotlib, the
1317 next versions of both systems should work very well together.
1335 next versions of both systems should work very well together.
1318
1336
1319 2004-08-24 Fernando Perez <fperez@colorado.edu>
1337 2004-08-24 Fernando Perez <fperez@colorado.edu>
1320
1338
1321 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1339 * IPython/Magic.py (Magic.magic_prun): cleanup some dead code. I
1322 tried to switch the profiling to using hotshot, but I'm getting
1340 tried to switch the profiling to using hotshot, but I'm getting
1323 strange errors from prof.runctx() there. I may be misreading the
1341 strange errors from prof.runctx() there. I may be misreading the
1324 docs, but it looks weird. For now the profiling code will
1342 docs, but it looks weird. For now the profiling code will
1325 continue to use the standard profiler.
1343 continue to use the standard profiler.
1326
1344
1327 2004-08-23 Fernando Perez <fperez@colorado.edu>
1345 2004-08-23 Fernando Perez <fperez@colorado.edu>
1328
1346
1329 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1347 * IPython/Shell.py (IPShellWX.__init__): Improvements to the WX
1330 threaded shell, by John Hunter. It's not quite ready yet, but
1348 threaded shell, by John Hunter. It's not quite ready yet, but
1331 close.
1349 close.
1332
1350
1333 2004-08-22 Fernando Perez <fperez@colorado.edu>
1351 2004-08-22 Fernando Perez <fperez@colorado.edu>
1334
1352
1335 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1353 * IPython/iplib.py (InteractiveShell.interact): tab cleanups, also
1336 in Magic and ultraTB.
1354 in Magic and ultraTB.
1337
1355
1338 * ipython.1: document threading options in manpage.
1356 * ipython.1: document threading options in manpage.
1339
1357
1340 * scripts/ipython: Changed name of -thread option to -gthread,
1358 * scripts/ipython: Changed name of -thread option to -gthread,
1341 since this is GTK specific. I want to leave the door open for a
1359 since this is GTK specific. I want to leave the door open for a
1342 -wthread option for WX, which will most likely be necessary. This
1360 -wthread option for WX, which will most likely be necessary. This
1343 change affects usage and ipmaker as well.
1361 change affects usage and ipmaker as well.
1344
1362
1345 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1363 * IPython/Shell.py (matplotlib_shell): Add a factory function to
1346 handle the matplotlib shell issues. Code by John Hunter
1364 handle the matplotlib shell issues. Code by John Hunter
1347 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1365 <jdhunter-AT-nitace.bsd.uchicago.edu>.
1348 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1366 (IPShellMatplotlibWX.__init__): Rudimentary WX support. It's
1349 broken (and disabled for end users) for now, but it puts the
1367 broken (and disabled for end users) for now, but it puts the
1350 infrastructure in place.
1368 infrastructure in place.
1351
1369
1352 2004-08-21 Fernando Perez <fperez@colorado.edu>
1370 2004-08-21 Fernando Perez <fperez@colorado.edu>
1353
1371
1354 * ipythonrc-pylab: Add matplotlib support.
1372 * ipythonrc-pylab: Add matplotlib support.
1355
1373
1356 * matplotlib_config.py: new files for matplotlib support, part of
1374 * matplotlib_config.py: new files for matplotlib support, part of
1357 the pylab profile.
1375 the pylab profile.
1358
1376
1359 * IPython/usage.py (__doc__): documented the threading options.
1377 * IPython/usage.py (__doc__): documented the threading options.
1360
1378
1361 2004-08-20 Fernando Perez <fperez@colorado.edu>
1379 2004-08-20 Fernando Perez <fperez@colorado.edu>
1362
1380
1363 * ipython: Modified the main calling routine to handle the -thread
1381 * ipython: Modified the main calling routine to handle the -thread
1364 and -mpthread options. This needs to be done as a top-level hack,
1382 and -mpthread options. This needs to be done as a top-level hack,
1365 because it determines which class to instantiate for IPython
1383 because it determines which class to instantiate for IPython
1366 itself.
1384 itself.
1367
1385
1368 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1386 * IPython/Shell.py (MTInteractiveShell.__init__): New set of
1369 classes to support multithreaded GTK operation without blocking,
1387 classes to support multithreaded GTK operation without blocking,
1370 and matplotlib with all backends. This is a lot of still very
1388 and matplotlib with all backends. This is a lot of still very
1371 experimental code, and threads are tricky. So it may still have a
1389 experimental code, and threads are tricky. So it may still have a
1372 few rough edges... This code owes a lot to
1390 few rough edges... This code owes a lot to
1373 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1391 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by
1374 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1392 Brian # McErlean and John Finlay, to Antoon Pardon for fixes, and
1375 to John Hunter for all the matplotlib work.
1393 to John Hunter for all the matplotlib work.
1376
1394
1377 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1395 * IPython/ipmaker.py (__call__): Added -thread and -mpthread
1378 options for gtk thread and matplotlib support.
1396 options for gtk thread and matplotlib support.
1379
1397
1380 2004-08-16 Fernando Perez <fperez@colorado.edu>
1398 2004-08-16 Fernando Perez <fperez@colorado.edu>
1381
1399
1382 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1400 * IPython/iplib.py (InteractiveShell.__init__): don't trigger
1383 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1401 autocall for things like p*q,p/q,p+q,p-q, when p is callable. Bug
1384 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1402 reported by Stephen Walton <stephen.walton-AT-csun.edu>.
1385
1403
1386 2004-08-11 Fernando Perez <fperez@colorado.edu>
1404 2004-08-11 Fernando Perez <fperez@colorado.edu>
1387
1405
1388 * setup.py (isfile): Fix build so documentation gets updated for
1406 * setup.py (isfile): Fix build so documentation gets updated for
1389 rpms (it was only done for .tgz builds).
1407 rpms (it was only done for .tgz builds).
1390
1408
1391 2004-08-10 Fernando Perez <fperez@colorado.edu>
1409 2004-08-10 Fernando Perez <fperez@colorado.edu>
1392
1410
1393 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1411 * genutils.py (Term): Fix misspell of stdin stream (sin->cin).
1394
1412
1395 * iplib.py : Silence syntax error exceptions in tab-completion.
1413 * iplib.py : Silence syntax error exceptions in tab-completion.
1396
1414
1397 2004-08-05 Fernando Perez <fperez@colorado.edu>
1415 2004-08-05 Fernando Perez <fperez@colorado.edu>
1398
1416
1399 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1417 * IPython/Prompts.py (Prompt2.set_colors): Fix incorrectly set
1400 'color off' mark for continuation prompts. This was causing long
1418 'color off' mark for continuation prompts. This was causing long
1401 continuation lines to mis-wrap.
1419 continuation lines to mis-wrap.
1402
1420
1403 2004-08-01 Fernando Perez <fperez@colorado.edu>
1421 2004-08-01 Fernando Perez <fperez@colorado.edu>
1404
1422
1405 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1423 * IPython/ipmaker.py (make_IPython): Allow the shell class used
1406 for building ipython to be a parameter. All this is necessary
1424 for building ipython to be a parameter. All this is necessary
1407 right now to have a multithreaded version, but this insane
1425 right now to have a multithreaded version, but this insane
1408 non-design will be cleaned up soon. For now, it's a hack that
1426 non-design will be cleaned up soon. For now, it's a hack that
1409 works.
1427 works.
1410
1428
1411 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1429 * IPython/Shell.py (IPShell.__init__): Stop using mutable default
1412 args in various places. No bugs so far, but it's a dangerous
1430 args in various places. No bugs so far, but it's a dangerous
1413 practice.
1431 practice.
1414
1432
1415 2004-07-31 Fernando Perez <fperez@colorado.edu>
1433 2004-07-31 Fernando Perez <fperez@colorado.edu>
1416
1434
1417 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1435 * IPython/iplib.py (complete): ignore SyntaxError exceptions to
1418 fix completion of files with dots in their names under most
1436 fix completion of files with dots in their names under most
1419 profiles (pysh was OK because the completion order is different).
1437 profiles (pysh was OK because the completion order is different).
1420
1438
1421 2004-07-27 Fernando Perez <fperez@colorado.edu>
1439 2004-07-27 Fernando Perez <fperez@colorado.edu>
1422
1440
1423 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1441 * IPython/iplib.py (InteractiveShell.__init__): build dict of
1424 keywords manually, b/c the one in keyword.py was removed in python
1442 keywords manually, b/c the one in keyword.py was removed in python
1425 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1443 2.4. Patch by Anakim Border <aborder-AT-users.sourceforge.net>.
1426 This is NOT a bug under python 2.3 and earlier.
1444 This is NOT a bug under python 2.3 and earlier.
1427
1445
1428 2004-07-26 Fernando Perez <fperez@colorado.edu>
1446 2004-07-26 Fernando Perez <fperez@colorado.edu>
1429
1447
1430 * IPython/ultraTB.py (VerboseTB.text): Add another
1448 * IPython/ultraTB.py (VerboseTB.text): Add another
1431 linecache.checkcache() call to try to prevent inspect.py from
1449 linecache.checkcache() call to try to prevent inspect.py from
1432 crashing under python 2.3. I think this fixes
1450 crashing under python 2.3. I think this fixes
1433 http://www.scipy.net/roundup/ipython/issue17.
1451 http://www.scipy.net/roundup/ipython/issue17.
1434
1452
1435 2004-07-26 *** Released version 0.6.2
1453 2004-07-26 *** Released version 0.6.2
1436
1454
1437 2004-07-26 Fernando Perez <fperez@colorado.edu>
1455 2004-07-26 Fernando Perez <fperez@colorado.edu>
1438
1456
1439 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1457 * IPython/Magic.py (Magic.magic_cd): Fix bug where 'cd -N' would
1440 fail for any number.
1458 fail for any number.
1441 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1459 (Magic.magic_bookmark): Fix bug where 'bookmark -l' would fail for
1442 empty bookmarks.
1460 empty bookmarks.
1443
1461
1444 2004-07-26 *** Released version 0.6.1
1462 2004-07-26 *** Released version 0.6.1
1445
1463
1446 2004-07-26 Fernando Perez <fperez@colorado.edu>
1464 2004-07-26 Fernando Perez <fperez@colorado.edu>
1447
1465
1448 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1466 * ipython_win_post_install.py (run): Added pysh shortcut for Windows.
1449
1467
1450 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1468 * IPython/iplib.py (protect_filename): Applied Ville's patch for
1451 escaping '()[]{}' in filenames.
1469 escaping '()[]{}' in filenames.
1452
1470
1453 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1471 * IPython/Magic.py (shlex_split): Fix handling of '*' and '?' for
1454 Python 2.2 users who lack a proper shlex.split.
1472 Python 2.2 users who lack a proper shlex.split.
1455
1473
1456 2004-07-19 Fernando Perez <fperez@colorado.edu>
1474 2004-07-19 Fernando Perez <fperez@colorado.edu>
1457
1475
1458 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1476 * IPython/iplib.py (InteractiveShell.init_readline): Add support
1459 for reading readline's init file. I follow the normal chain:
1477 for reading readline's init file. I follow the normal chain:
1460 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1478 $INPUTRC is honored, otherwise ~/.inputrc is used. Thanks to a
1461 report by Mike Heeter. This closes
1479 report by Mike Heeter. This closes
1462 http://www.scipy.net/roundup/ipython/issue16.
1480 http://www.scipy.net/roundup/ipython/issue16.
1463
1481
1464 2004-07-18 Fernando Perez <fperez@colorado.edu>
1482 2004-07-18 Fernando Perez <fperez@colorado.edu>
1465
1483
1466 * IPython/iplib.py (__init__): Add better handling of '\' under
1484 * IPython/iplib.py (__init__): Add better handling of '\' under
1467 Win32 for filenames. After a patch by Ville.
1485 Win32 for filenames. After a patch by Ville.
1468
1486
1469 2004-07-17 Fernando Perez <fperez@colorado.edu>
1487 2004-07-17 Fernando Perez <fperez@colorado.edu>
1470
1488
1471 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1489 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
1472 autocalling would be triggered for 'foo is bar' if foo is
1490 autocalling would be triggered for 'foo is bar' if foo is
1473 callable. I also cleaned up the autocall detection code to use a
1491 callable. I also cleaned up the autocall detection code to use a
1474 regexp, which is faster. Bug reported by Alexander Schmolck.
1492 regexp, which is faster. Bug reported by Alexander Schmolck.
1475
1493
1476 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1494 * IPython/Magic.py (Magic.magic_pinfo): Fix bug where strings with
1477 '?' in them would confuse the help system. Reported by Alex
1495 '?' in them would confuse the help system. Reported by Alex
1478 Schmolck.
1496 Schmolck.
1479
1497
1480 2004-07-16 Fernando Perez <fperez@colorado.edu>
1498 2004-07-16 Fernando Perez <fperez@colorado.edu>
1481
1499
1482 * IPython/GnuplotInteractive.py (__all__): added plot2.
1500 * IPython/GnuplotInteractive.py (__all__): added plot2.
1483
1501
1484 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1502 * IPython/Gnuplot2.py (Gnuplot.plot2): added new function for
1485 plotting dictionaries, lists or tuples of 1d arrays.
1503 plotting dictionaries, lists or tuples of 1d arrays.
1486
1504
1487 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1505 * IPython/Magic.py (Magic.magic_hist): small clenaups and
1488 optimizations.
1506 optimizations.
1489
1507
1490 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1508 * IPython/iplib.py:Remove old Changelog info for cleanup. This is
1491 the information which was there from Janko's original IPP code:
1509 the information which was there from Janko's original IPP code:
1492
1510
1493 03.05.99 20:53 porto.ifm.uni-kiel.de
1511 03.05.99 20:53 porto.ifm.uni-kiel.de
1494 --Started changelog.
1512 --Started changelog.
1495 --make clear do what it say it does
1513 --make clear do what it say it does
1496 --added pretty output of lines from inputcache
1514 --added pretty output of lines from inputcache
1497 --Made Logger a mixin class, simplifies handling of switches
1515 --Made Logger a mixin class, simplifies handling of switches
1498 --Added own completer class. .string<TAB> expands to last history
1516 --Added own completer class. .string<TAB> expands to last history
1499 line which starts with string. The new expansion is also present
1517 line which starts with string. The new expansion is also present
1500 with Ctrl-r from the readline library. But this shows, who this
1518 with Ctrl-r from the readline library. But this shows, who this
1501 can be done for other cases.
1519 can be done for other cases.
1502 --Added convention that all shell functions should accept a
1520 --Added convention that all shell functions should accept a
1503 parameter_string This opens the door for different behaviour for
1521 parameter_string This opens the door for different behaviour for
1504 each function. @cd is a good example of this.
1522 each function. @cd is a good example of this.
1505
1523
1506 04.05.99 12:12 porto.ifm.uni-kiel.de
1524 04.05.99 12:12 porto.ifm.uni-kiel.de
1507 --added logfile rotation
1525 --added logfile rotation
1508 --added new mainloop method which freezes first the namespace
1526 --added new mainloop method which freezes first the namespace
1509
1527
1510 07.05.99 21:24 porto.ifm.uni-kiel.de
1528 07.05.99 21:24 porto.ifm.uni-kiel.de
1511 --added the docreader classes. Now there is a help system.
1529 --added the docreader classes. Now there is a help system.
1512 -This is only a first try. Currently it's not easy to put new
1530 -This is only a first try. Currently it's not easy to put new
1513 stuff in the indices. But this is the way to go. Info would be
1531 stuff in the indices. But this is the way to go. Info would be
1514 better, but HTML is every where and not everybody has an info
1532 better, but HTML is every where and not everybody has an info
1515 system installed and it's not so easy to change html-docs to info.
1533 system installed and it's not so easy to change html-docs to info.
1516 --added global logfile option
1534 --added global logfile option
1517 --there is now a hook for object inspection method pinfo needs to
1535 --there is now a hook for object inspection method pinfo needs to
1518 be provided for this. Can be reached by two '??'.
1536 be provided for this. Can be reached by two '??'.
1519
1537
1520 08.05.99 20:51 porto.ifm.uni-kiel.de
1538 08.05.99 20:51 porto.ifm.uni-kiel.de
1521 --added a README
1539 --added a README
1522 --bug in rc file. Something has changed so functions in the rc
1540 --bug in rc file. Something has changed so functions in the rc
1523 file need to reference the shell and not self. Not clear if it's a
1541 file need to reference the shell and not self. Not clear if it's a
1524 bug or feature.
1542 bug or feature.
1525 --changed rc file for new behavior
1543 --changed rc file for new behavior
1526
1544
1527 2004-07-15 Fernando Perez <fperez@colorado.edu>
1545 2004-07-15 Fernando Perez <fperez@colorado.edu>
1528
1546
1529 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1547 * IPython/Logger.py (Logger.log): fixed recent bug where the input
1530 cache was falling out of sync in bizarre manners when multi-line
1548 cache was falling out of sync in bizarre manners when multi-line
1531 input was present. Minor optimizations and cleanup.
1549 input was present. Minor optimizations and cleanup.
1532
1550
1533 (Logger): Remove old Changelog info for cleanup. This is the
1551 (Logger): Remove old Changelog info for cleanup. This is the
1534 information which was there from Janko's original code:
1552 information which was there from Janko's original code:
1535
1553
1536 Changes to Logger: - made the default log filename a parameter
1554 Changes to Logger: - made the default log filename a parameter
1537
1555
1538 - put a check for lines beginning with !@? in log(). Needed
1556 - put a check for lines beginning with !@? in log(). Needed
1539 (even if the handlers properly log their lines) for mid-session
1557 (even if the handlers properly log their lines) for mid-session
1540 logging activation to work properly. Without this, lines logged
1558 logging activation to work properly. Without this, lines logged
1541 in mid session, which get read from the cache, would end up
1559 in mid session, which get read from the cache, would end up
1542 'bare' (with !@? in the open) in the log. Now they are caught
1560 'bare' (with !@? in the open) in the log. Now they are caught
1543 and prepended with a #.
1561 and prepended with a #.
1544
1562
1545 * IPython/iplib.py (InteractiveShell.init_readline): added check
1563 * IPython/iplib.py (InteractiveShell.init_readline): added check
1546 in case MagicCompleter fails to be defined, so we don't crash.
1564 in case MagicCompleter fails to be defined, so we don't crash.
1547
1565
1548 2004-07-13 Fernando Perez <fperez@colorado.edu>
1566 2004-07-13 Fernando Perez <fperez@colorado.edu>
1549
1567
1550 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1568 * IPython/Gnuplot2.py (Gnuplot.hardcopy): add automatic generation
1551 of EPS if the requested filename ends in '.eps'.
1569 of EPS if the requested filename ends in '.eps'.
1552
1570
1553 2004-07-04 Fernando Perez <fperez@colorado.edu>
1571 2004-07-04 Fernando Perez <fperez@colorado.edu>
1554
1572
1555 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1573 * IPython/iplib.py (InteractiveShell.handle_shell_escape): Fix
1556 escaping of quotes when calling the shell.
1574 escaping of quotes when calling the shell.
1557
1575
1558 2004-07-02 Fernando Perez <fperez@colorado.edu>
1576 2004-07-02 Fernando Perez <fperez@colorado.edu>
1559
1577
1560 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1578 * IPython/Prompts.py (CachedOutput.update): Fix problem with
1561 gettext not working because we were clobbering '_'. Fixes
1579 gettext not working because we were clobbering '_'. Fixes
1562 http://www.scipy.net/roundup/ipython/issue6.
1580 http://www.scipy.net/roundup/ipython/issue6.
1563
1581
1564 2004-07-01 Fernando Perez <fperez@colorado.edu>
1582 2004-07-01 Fernando Perez <fperez@colorado.edu>
1565
1583
1566 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1584 * IPython/Magic.py (Magic.magic_cd): integrated bookmark handling
1567 into @cd. Patch by Ville.
1585 into @cd. Patch by Ville.
1568
1586
1569 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1587 * IPython/iplib.py (InteractiveShell.post_config_initialization):
1570 new function to store things after ipmaker runs. Patch by Ville.
1588 new function to store things after ipmaker runs. Patch by Ville.
1571 Eventually this will go away once ipmaker is removed and the class
1589 Eventually this will go away once ipmaker is removed and the class
1572 gets cleaned up, but for now it's ok. Key functionality here is
1590 gets cleaned up, but for now it's ok. Key functionality here is
1573 the addition of the persistent storage mechanism, a dict for
1591 the addition of the persistent storage mechanism, a dict for
1574 keeping data across sessions (for now just bookmarks, but more can
1592 keeping data across sessions (for now just bookmarks, but more can
1575 be implemented later).
1593 be implemented later).
1576
1594
1577 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1595 * IPython/Magic.py (Magic.magic_bookmark): New bookmark system,
1578 persistent across sections. Patch by Ville, I modified it
1596 persistent across sections. Patch by Ville, I modified it
1579 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1597 soemwhat to allow bookmarking arbitrary dirs other than CWD. Also
1580 added a '-l' option to list all bookmarks.
1598 added a '-l' option to list all bookmarks.
1581
1599
1582 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1600 * IPython/iplib.py (InteractiveShell.atexit_operations): new
1583 center for cleanup. Registered with atexit.register(). I moved
1601 center for cleanup. Registered with atexit.register(). I moved
1584 here the old exit_cleanup(). After a patch by Ville.
1602 here the old exit_cleanup(). After a patch by Ville.
1585
1603
1586 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1604 * IPython/Magic.py (get_py_filename): added '~' to the accepted
1587 characters in the hacked shlex_split for python 2.2.
1605 characters in the hacked shlex_split for python 2.2.
1588
1606
1589 * IPython/iplib.py (file_matches): more fixes to filenames with
1607 * IPython/iplib.py (file_matches): more fixes to filenames with
1590 whitespace in them. It's not perfect, but limitations in python's
1608 whitespace in them. It's not perfect, but limitations in python's
1591 readline make it impossible to go further.
1609 readline make it impossible to go further.
1592
1610
1593 2004-06-29 Fernando Perez <fperez@colorado.edu>
1611 2004-06-29 Fernando Perez <fperez@colorado.edu>
1594
1612
1595 * IPython/iplib.py (file_matches): escape whitespace correctly in
1613 * IPython/iplib.py (file_matches): escape whitespace correctly in
1596 filename completions. Bug reported by Ville.
1614 filename completions. Bug reported by Ville.
1597
1615
1598 2004-06-28 Fernando Perez <fperez@colorado.edu>
1616 2004-06-28 Fernando Perez <fperez@colorado.edu>
1599
1617
1600 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1618 * IPython/ipmaker.py (__call__): Added per-profile histories. Now
1601 the history file will be called 'history-PROFNAME' (or just
1619 the history file will be called 'history-PROFNAME' (or just
1602 'history' if no profile is loaded). I was getting annoyed at
1620 'history' if no profile is loaded). I was getting annoyed at
1603 getting my Numerical work history clobbered by pysh sessions.
1621 getting my Numerical work history clobbered by pysh sessions.
1604
1622
1605 * IPython/iplib.py (InteractiveShell.__init__): Internal
1623 * IPython/iplib.py (InteractiveShell.__init__): Internal
1606 getoutputerror() function so that we can honor the system_verbose
1624 getoutputerror() function so that we can honor the system_verbose
1607 flag for _all_ system calls. I also added escaping of #
1625 flag for _all_ system calls. I also added escaping of #
1608 characters here to avoid confusing Itpl.
1626 characters here to avoid confusing Itpl.
1609
1627
1610 * IPython/Magic.py (shlex_split): removed call to shell in
1628 * IPython/Magic.py (shlex_split): removed call to shell in
1611 parse_options and replaced it with shlex.split(). The annoying
1629 parse_options and replaced it with shlex.split(). The annoying
1612 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1630 part was that in Python 2.2, shlex.split() doesn't exist, so I had
1613 to backport it from 2.3, with several frail hacks (the shlex
1631 to backport it from 2.3, with several frail hacks (the shlex
1614 module is rather limited in 2.2). Thanks to a suggestion by Ville
1632 module is rather limited in 2.2). Thanks to a suggestion by Ville
1615 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1633 Vainio <vivainio@kolumbus.fi>. For Python 2.3 there should be no
1616 problem.
1634 problem.
1617
1635
1618 (Magic.magic_system_verbose): new toggle to print the actual
1636 (Magic.magic_system_verbose): new toggle to print the actual
1619 system calls made by ipython. Mainly for debugging purposes.
1637 system calls made by ipython. Mainly for debugging purposes.
1620
1638
1621 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1639 * IPython/GnuplotRuntime.py (gnu_out): fix bug for cygwin, which
1622 doesn't support persistence. Reported (and fix suggested) by
1640 doesn't support persistence. Reported (and fix suggested) by
1623 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1641 Travis Caldwell <travis_caldwell2000@yahoo.com>.
1624
1642
1625 2004-06-26 Fernando Perez <fperez@colorado.edu>
1643 2004-06-26 Fernando Perez <fperez@colorado.edu>
1626
1644
1627 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1645 * IPython/Logger.py (Logger.log): fix to handle correctly empty
1628 continue prompts.
1646 continue prompts.
1629
1647
1630 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1648 * IPython/Extensions/InterpreterExec.py (pysh): moved the pysh()
1631 function (basically a big docstring) and a few more things here to
1649 function (basically a big docstring) and a few more things here to
1632 speedup startup. pysh.py is now very lightweight. We want because
1650 speedup startup. pysh.py is now very lightweight. We want because
1633 it gets execfile'd, while InterpreterExec gets imported, so
1651 it gets execfile'd, while InterpreterExec gets imported, so
1634 byte-compilation saves time.
1652 byte-compilation saves time.
1635
1653
1636 2004-06-25 Fernando Perez <fperez@colorado.edu>
1654 2004-06-25 Fernando Perez <fperez@colorado.edu>
1637
1655
1638 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1656 * IPython/Magic.py (Magic.magic_cd): Fixed to restore usage of 'cd
1639 -NUM', which was recently broken.
1657 -NUM', which was recently broken.
1640
1658
1641 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1659 * IPython/iplib.py (InteractiveShell.handle_shell_escape): allow !
1642 in multi-line input (but not !!, which doesn't make sense there).
1660 in multi-line input (but not !!, which doesn't make sense there).
1643
1661
1644 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1662 * IPython/UserConfig/ipythonrc: made autoindent on by default.
1645 It's just too useful, and people can turn it off in the less
1663 It's just too useful, and people can turn it off in the less
1646 common cases where it's a problem.
1664 common cases where it's a problem.
1647
1665
1648 2004-06-24 Fernando Perez <fperez@colorado.edu>
1666 2004-06-24 Fernando Perez <fperez@colorado.edu>
1649
1667
1650 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1668 * IPython/iplib.py (InteractiveShell._prefilter): big change -
1651 special syntaxes (like alias calling) is now allied in multi-line
1669 special syntaxes (like alias calling) is now allied in multi-line
1652 input. This is still _very_ experimental, but it's necessary for
1670 input. This is still _very_ experimental, but it's necessary for
1653 efficient shell usage combining python looping syntax with system
1671 efficient shell usage combining python looping syntax with system
1654 calls. For now it's restricted to aliases, I don't think it
1672 calls. For now it's restricted to aliases, I don't think it
1655 really even makes sense to have this for magics.
1673 really even makes sense to have this for magics.
1656
1674
1657 2004-06-23 Fernando Perez <fperez@colorado.edu>
1675 2004-06-23 Fernando Perez <fperez@colorado.edu>
1658
1676
1659 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1677 * IPython/Extensions/InterpreterExec.py (prefilter_shell): Added
1660 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1678 $var=cmd <=> @sc var=cmd and $$var=cmd <=> @sc -l var=cmd.
1661
1679
1662 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1680 * IPython/Magic.py (Magic.magic_rehashx): modified to handle
1663 extensions under Windows (after code sent by Gary Bishop). The
1681 extensions under Windows (after code sent by Gary Bishop). The
1664 extensions considered 'executable' are stored in IPython's rc
1682 extensions considered 'executable' are stored in IPython's rc
1665 structure as win_exec_ext.
1683 structure as win_exec_ext.
1666
1684
1667 * IPython/genutils.py (shell): new function, like system() but
1685 * IPython/genutils.py (shell): new function, like system() but
1668 without return value. Very useful for interactive shell work.
1686 without return value. Very useful for interactive shell work.
1669
1687
1670 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1688 * IPython/Magic.py (Magic.magic_unalias): New @unalias function to
1671 delete aliases.
1689 delete aliases.
1672
1690
1673 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1691 * IPython/iplib.py (InteractiveShell.alias_table_update): make
1674 sure that the alias table doesn't contain python keywords.
1692 sure that the alias table doesn't contain python keywords.
1675
1693
1676 2004-06-21 Fernando Perez <fperez@colorado.edu>
1694 2004-06-21 Fernando Perez <fperez@colorado.edu>
1677
1695
1678 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1696 * IPython/Magic.py (Magic.magic_rehash): Fix crash when
1679 non-existent items are found in $PATH. Reported by Thorsten.
1697 non-existent items are found in $PATH. Reported by Thorsten.
1680
1698
1681 2004-06-20 Fernando Perez <fperez@colorado.edu>
1699 2004-06-20 Fernando Perez <fperez@colorado.edu>
1682
1700
1683 * IPython/iplib.py (complete): modified the completer so that the
1701 * IPython/iplib.py (complete): modified the completer so that the
1684 order of priorities can be easily changed at runtime.
1702 order of priorities can be easily changed at runtime.
1685
1703
1686 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1704 * IPython/Extensions/InterpreterExec.py (prefilter_shell):
1687 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1705 Modified to auto-execute all lines beginning with '~', '/' or '.'.
1688
1706
1689 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1707 * IPython/Magic.py (Magic.magic_sx): modified @sc and @sx to
1690 expand Python variables prepended with $ in all system calls. The
1708 expand Python variables prepended with $ in all system calls. The
1691 same was done to InteractiveShell.handle_shell_escape. Now all
1709 same was done to InteractiveShell.handle_shell_escape. Now all
1692 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1710 system access mechanisms (!, !!, @sc, @sx and aliases) allow the
1693 expansion of python variables and expressions according to the
1711 expansion of python variables and expressions according to the
1694 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1712 syntax of PEP-215 - http://www.python.org/peps/pep-0215.html.
1695
1713
1696 Though PEP-215 has been rejected, a similar (but simpler) one
1714 Though PEP-215 has been rejected, a similar (but simpler) one
1697 seems like it will go into Python 2.4, PEP-292 -
1715 seems like it will go into Python 2.4, PEP-292 -
1698 http://www.python.org/peps/pep-0292.html.
1716 http://www.python.org/peps/pep-0292.html.
1699
1717
1700 I'll keep the full syntax of PEP-215, since IPython has since the
1718 I'll keep the full syntax of PEP-215, since IPython has since the
1701 start used Ka-Ping Yee's reference implementation discussed there
1719 start used Ka-Ping Yee's reference implementation discussed there
1702 (Itpl), and I actually like the powerful semantics it offers.
1720 (Itpl), and I actually like the powerful semantics it offers.
1703
1721
1704 In order to access normal shell variables, the $ has to be escaped
1722 In order to access normal shell variables, the $ has to be escaped
1705 via an extra $. For example:
1723 via an extra $. For example:
1706
1724
1707 In [7]: PATH='a python variable'
1725 In [7]: PATH='a python variable'
1708
1726
1709 In [8]: !echo $PATH
1727 In [8]: !echo $PATH
1710 a python variable
1728 a python variable
1711
1729
1712 In [9]: !echo $$PATH
1730 In [9]: !echo $$PATH
1713 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1731 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
1714
1732
1715 (Magic.parse_options): escape $ so the shell doesn't evaluate
1733 (Magic.parse_options): escape $ so the shell doesn't evaluate
1716 things prematurely.
1734 things prematurely.
1717
1735
1718 * IPython/iplib.py (InteractiveShell.call_alias): added the
1736 * IPython/iplib.py (InteractiveShell.call_alias): added the
1719 ability for aliases to expand python variables via $.
1737 ability for aliases to expand python variables via $.
1720
1738
1721 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1739 * IPython/Magic.py (Magic.magic_rehash): based on the new alias
1722 system, now there's a @rehash/@rehashx pair of magics. These work
1740 system, now there's a @rehash/@rehashx pair of magics. These work
1723 like the csh rehash command, and can be invoked at any time. They
1741 like the csh rehash command, and can be invoked at any time. They
1724 build a table of aliases to everything in the user's $PATH
1742 build a table of aliases to everything in the user's $PATH
1725 (@rehash uses everything, @rehashx is slower but only adds
1743 (@rehash uses everything, @rehashx is slower but only adds
1726 executable files). With this, the pysh.py-based shell profile can
1744 executable files). With this, the pysh.py-based shell profile can
1727 now simply call rehash upon startup, and full access to all
1745 now simply call rehash upon startup, and full access to all
1728 programs in the user's path is obtained.
1746 programs in the user's path is obtained.
1729
1747
1730 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1748 * IPython/iplib.py (InteractiveShell.call_alias): The new alias
1731 functionality is now fully in place. I removed the old dynamic
1749 functionality is now fully in place. I removed the old dynamic
1732 code generation based approach, in favor of a much lighter one
1750 code generation based approach, in favor of a much lighter one
1733 based on a simple dict. The advantage is that this allows me to
1751 based on a simple dict. The advantage is that this allows me to
1734 now have thousands of aliases with negligible cost (unthinkable
1752 now have thousands of aliases with negligible cost (unthinkable
1735 with the old system).
1753 with the old system).
1736
1754
1737 2004-06-19 Fernando Perez <fperez@colorado.edu>
1755 2004-06-19 Fernando Perez <fperez@colorado.edu>
1738
1756
1739 * IPython/iplib.py (__init__): extended MagicCompleter class to
1757 * IPython/iplib.py (__init__): extended MagicCompleter class to
1740 also complete (last in priority) on user aliases.
1758 also complete (last in priority) on user aliases.
1741
1759
1742 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1760 * IPython/Itpl.py (Itpl.__str__): fixed order of globals/locals in
1743 call to eval.
1761 call to eval.
1744 (ItplNS.__init__): Added a new class which functions like Itpl,
1762 (ItplNS.__init__): Added a new class which functions like Itpl,
1745 but allows configuring the namespace for the evaluation to occur
1763 but allows configuring the namespace for the evaluation to occur
1746 in.
1764 in.
1747
1765
1748 2004-06-18 Fernando Perez <fperez@colorado.edu>
1766 2004-06-18 Fernando Perez <fperez@colorado.edu>
1749
1767
1750 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1768 * IPython/iplib.py (InteractiveShell.runcode): modify to print a
1751 better message when 'exit' or 'quit' are typed (a common newbie
1769 better message when 'exit' or 'quit' are typed (a common newbie
1752 confusion).
1770 confusion).
1753
1771
1754 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1772 * IPython/Magic.py (Magic.magic_colors): Added the runtime color
1755 check for Windows users.
1773 check for Windows users.
1756
1774
1757 * IPython/iplib.py (InteractiveShell.user_setup): removed
1775 * IPython/iplib.py (InteractiveShell.user_setup): removed
1758 disabling of colors for Windows. I'll test at runtime and issue a
1776 disabling of colors for Windows. I'll test at runtime and issue a
1759 warning if Gary's readline isn't found, as to nudge users to
1777 warning if Gary's readline isn't found, as to nudge users to
1760 download it.
1778 download it.
1761
1779
1762 2004-06-16 Fernando Perez <fperez@colorado.edu>
1780 2004-06-16 Fernando Perez <fperez@colorado.edu>
1763
1781
1764 * IPython/genutils.py (Stream.__init__): changed to print errors
1782 * IPython/genutils.py (Stream.__init__): changed to print errors
1765 to sys.stderr. I had a circular dependency here. Now it's
1783 to sys.stderr. I had a circular dependency here. Now it's
1766 possible to run ipython as IDLE's shell (consider this pre-alpha,
1784 possible to run ipython as IDLE's shell (consider this pre-alpha,
1767 since true stdout things end up in the starting terminal instead
1785 since true stdout things end up in the starting terminal instead
1768 of IDLE's out).
1786 of IDLE's out).
1769
1787
1770 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1788 * IPython/Prompts.py (Prompt2.set_colors): prevent crashes for
1771 users who haven't # updated their prompt_in2 definitions. Remove
1789 users who haven't # updated their prompt_in2 definitions. Remove
1772 eventually.
1790 eventually.
1773 (multiple_replace): added credit to original ASPN recipe.
1791 (multiple_replace): added credit to original ASPN recipe.
1774
1792
1775 2004-06-15 Fernando Perez <fperez@colorado.edu>
1793 2004-06-15 Fernando Perez <fperez@colorado.edu>
1776
1794
1777 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1795 * IPython/iplib.py (InteractiveShell.__init__): add 'cp' to the
1778 list of auto-defined aliases.
1796 list of auto-defined aliases.
1779
1797
1780 2004-06-13 Fernando Perez <fperez@colorado.edu>
1798 2004-06-13 Fernando Perez <fperez@colorado.edu>
1781
1799
1782 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1800 * setup.py (scriptfiles): Don't trigger win_post_install unless an
1783 install was really requested (so setup.py can be used for other
1801 install was really requested (so setup.py can be used for other
1784 things under Windows).
1802 things under Windows).
1785
1803
1786 2004-06-10 Fernando Perez <fperez@colorado.edu>
1804 2004-06-10 Fernando Perez <fperez@colorado.edu>
1787
1805
1788 * IPython/Logger.py (Logger.create_log): Manually remove any old
1806 * IPython/Logger.py (Logger.create_log): Manually remove any old
1789 backup, since os.remove may fail under Windows. Fixes bug
1807 backup, since os.remove may fail under Windows. Fixes bug
1790 reported by Thorsten.
1808 reported by Thorsten.
1791
1809
1792 2004-06-09 Fernando Perez <fperez@colorado.edu>
1810 2004-06-09 Fernando Perez <fperez@colorado.edu>
1793
1811
1794 * examples/example-embed.py: fixed all references to %n (replaced
1812 * examples/example-embed.py: fixed all references to %n (replaced
1795 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1813 with \\# for ps1/out prompts and with \\D for ps2 prompts). Done
1796 for all examples and the manual as well.
1814 for all examples and the manual as well.
1797
1815
1798 2004-06-08 Fernando Perez <fperez@colorado.edu>
1816 2004-06-08 Fernando Perez <fperez@colorado.edu>
1799
1817
1800 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1818 * IPython/Prompts.py (Prompt2.set_p_str): fixed all prompt
1801 alignment and color management. All 3 prompt subsystems now
1819 alignment and color management. All 3 prompt subsystems now
1802 inherit from BasePrompt.
1820 inherit from BasePrompt.
1803
1821
1804 * tools/release: updates for windows installer build and tag rpms
1822 * tools/release: updates for windows installer build and tag rpms
1805 with python version (since paths are fixed).
1823 with python version (since paths are fixed).
1806
1824
1807 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1825 * IPython/UserConfig/ipythonrc: modified to use \# instead of %n,
1808 which will become eventually obsolete. Also fixed the default
1826 which will become eventually obsolete. Also fixed the default
1809 prompt_in2 to use \D, so at least new users start with the correct
1827 prompt_in2 to use \D, so at least new users start with the correct
1810 defaults.
1828 defaults.
1811 WARNING: Users with existing ipythonrc files will need to apply
1829 WARNING: Users with existing ipythonrc files will need to apply
1812 this fix manually!
1830 this fix manually!
1813
1831
1814 * setup.py: make windows installer (.exe). This is finally the
1832 * setup.py: make windows installer (.exe). This is finally the
1815 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1833 integration of an old patch by Cory Dodt <dodt-AT-fcoe.k12.ca.us>,
1816 which I hadn't included because it required Python 2.3 (or recent
1834 which I hadn't included because it required Python 2.3 (or recent
1817 distutils).
1835 distutils).
1818
1836
1819 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1837 * IPython/usage.py (__doc__): update docs (and manpage) to reflect
1820 usage of new '\D' escape.
1838 usage of new '\D' escape.
1821
1839
1822 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1840 * IPython/Prompts.py (ROOT_SYMBOL): Small fix for Windows (which
1823 lacks os.getuid())
1841 lacks os.getuid())
1824 (CachedOutput.set_colors): Added the ability to turn coloring
1842 (CachedOutput.set_colors): Added the ability to turn coloring
1825 on/off with @colors even for manually defined prompt colors. It
1843 on/off with @colors even for manually defined prompt colors. It
1826 uses a nasty global, but it works safely and via the generic color
1844 uses a nasty global, but it works safely and via the generic color
1827 handling mechanism.
1845 handling mechanism.
1828 (Prompt2.__init__): Introduced new escape '\D' for continuation
1846 (Prompt2.__init__): Introduced new escape '\D' for continuation
1829 prompts. It represents the counter ('\#') as dots.
1847 prompts. It represents the counter ('\#') as dots.
1830 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1848 *** NOTE *** THIS IS A BACKWARDS-INCOMPATIBLE CHANGE. Users will
1831 need to update their ipythonrc files and replace '%n' with '\D' in
1849 need to update their ipythonrc files and replace '%n' with '\D' in
1832 their prompt_in2 settings everywhere. Sorry, but there's
1850 their prompt_in2 settings everywhere. Sorry, but there's
1833 otherwise no clean way to get all prompts to properly align. The
1851 otherwise no clean way to get all prompts to properly align. The
1834 ipythonrc shipped with IPython has been updated.
1852 ipythonrc shipped with IPython has been updated.
1835
1853
1836 2004-06-07 Fernando Perez <fperez@colorado.edu>
1854 2004-06-07 Fernando Perez <fperez@colorado.edu>
1837
1855
1838 * setup.py (isfile): Pass local_icons option to latex2html, so the
1856 * setup.py (isfile): Pass local_icons option to latex2html, so the
1839 resulting HTML file is self-contained. Thanks to
1857 resulting HTML file is self-contained. Thanks to
1840 dryice-AT-liu.com.cn for the tip.
1858 dryice-AT-liu.com.cn for the tip.
1841
1859
1842 * pysh.py: I created a new profile 'shell', which implements a
1860 * pysh.py: I created a new profile 'shell', which implements a
1843 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1861 _rudimentary_ IPython-based shell. This is in NO WAY a realy
1844 system shell, nor will it become one anytime soon. It's mainly
1862 system shell, nor will it become one anytime soon. It's mainly
1845 meant to illustrate the use of the new flexible bash-like prompts.
1863 meant to illustrate the use of the new flexible bash-like prompts.
1846 I guess it could be used by hardy souls for true shell management,
1864 I guess it could be used by hardy souls for true shell management,
1847 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1865 but it's no tcsh/bash... pysh.py is loaded by the 'shell'
1848 profile. This uses the InterpreterExec extension provided by
1866 profile. This uses the InterpreterExec extension provided by
1849 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1867 W.J. van der Laan <gnufnork-AT-hetdigitalegat.nl>
1850
1868
1851 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1869 * IPython/Prompts.py (PromptOut.__str__): now it will correctly
1852 auto-align itself with the length of the previous input prompt
1870 auto-align itself with the length of the previous input prompt
1853 (taking into account the invisible color escapes).
1871 (taking into account the invisible color escapes).
1854 (CachedOutput.__init__): Large restructuring of this class. Now
1872 (CachedOutput.__init__): Large restructuring of this class. Now
1855 all three prompts (primary1, primary2, output) are proper objects,
1873 all three prompts (primary1, primary2, output) are proper objects,
1856 managed by the 'parent' CachedOutput class. The code is still a
1874 managed by the 'parent' CachedOutput class. The code is still a
1857 bit hackish (all prompts share state via a pointer to the cache),
1875 bit hackish (all prompts share state via a pointer to the cache),
1858 but it's overall far cleaner than before.
1876 but it's overall far cleaner than before.
1859
1877
1860 * IPython/genutils.py (getoutputerror): modified to add verbose,
1878 * IPython/genutils.py (getoutputerror): modified to add verbose,
1861 debug and header options. This makes the interface of all getout*
1879 debug and header options. This makes the interface of all getout*
1862 functions uniform.
1880 functions uniform.
1863 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1881 (SystemExec.getoutputerror): added getoutputerror to SystemExec.
1864
1882
1865 * IPython/Magic.py (Magic.default_option): added a function to
1883 * IPython/Magic.py (Magic.default_option): added a function to
1866 allow registering default options for any magic command. This
1884 allow registering default options for any magic command. This
1867 makes it easy to have profiles which customize the magics globally
1885 makes it easy to have profiles which customize the magics globally
1868 for a certain use. The values set through this function are
1886 for a certain use. The values set through this function are
1869 picked up by the parse_options() method, which all magics should
1887 picked up by the parse_options() method, which all magics should
1870 use to parse their options.
1888 use to parse their options.
1871
1889
1872 * IPython/genutils.py (warn): modified the warnings framework to
1890 * IPython/genutils.py (warn): modified the warnings framework to
1873 use the Term I/O class. I'm trying to slowly unify all of
1891 use the Term I/O class. I'm trying to slowly unify all of
1874 IPython's I/O operations to pass through Term.
1892 IPython's I/O operations to pass through Term.
1875
1893
1876 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1894 * IPython/Prompts.py (Prompt2._str_other): Added functionality in
1877 the secondary prompt to correctly match the length of the primary
1895 the secondary prompt to correctly match the length of the primary
1878 one for any prompt. Now multi-line code will properly line up
1896 one for any prompt. Now multi-line code will properly line up
1879 even for path dependent prompts, such as the new ones available
1897 even for path dependent prompts, such as the new ones available
1880 via the prompt_specials.
1898 via the prompt_specials.
1881
1899
1882 2004-06-06 Fernando Perez <fperez@colorado.edu>
1900 2004-06-06 Fernando Perez <fperez@colorado.edu>
1883
1901
1884 * IPython/Prompts.py (prompt_specials): Added the ability to have
1902 * IPython/Prompts.py (prompt_specials): Added the ability to have
1885 bash-like special sequences in the prompts, which get
1903 bash-like special sequences in the prompts, which get
1886 automatically expanded. Things like hostname, current working
1904 automatically expanded. Things like hostname, current working
1887 directory and username are implemented already, but it's easy to
1905 directory and username are implemented already, but it's easy to
1888 add more in the future. Thanks to a patch by W.J. van der Laan
1906 add more in the future. Thanks to a patch by W.J. van der Laan
1889 <gnufnork-AT-hetdigitalegat.nl>
1907 <gnufnork-AT-hetdigitalegat.nl>
1890 (prompt_specials): Added color support for prompt strings, so
1908 (prompt_specials): Added color support for prompt strings, so
1891 users can define arbitrary color setups for their prompts.
1909 users can define arbitrary color setups for their prompts.
1892
1910
1893 2004-06-05 Fernando Perez <fperez@colorado.edu>
1911 2004-06-05 Fernando Perez <fperez@colorado.edu>
1894
1912
1895 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
1913 * IPython/genutils.py (Term.reopen_all): Added Windows-specific
1896 code to load Gary Bishop's readline and configure it
1914 code to load Gary Bishop's readline and configure it
1897 automatically. Thanks to Gary for help on this.
1915 automatically. Thanks to Gary for help on this.
1898
1916
1899 2004-06-01 Fernando Perez <fperez@colorado.edu>
1917 2004-06-01 Fernando Perez <fperez@colorado.edu>
1900
1918
1901 * IPython/Logger.py (Logger.create_log): fix bug for logging
1919 * IPython/Logger.py (Logger.create_log): fix bug for logging
1902 with no filename (previous fix was incomplete).
1920 with no filename (previous fix was incomplete).
1903
1921
1904 2004-05-25 Fernando Perez <fperez@colorado.edu>
1922 2004-05-25 Fernando Perez <fperez@colorado.edu>
1905
1923
1906 * IPython/Magic.py (Magic.parse_options): fix bug where naked
1924 * IPython/Magic.py (Magic.parse_options): fix bug where naked
1907 parens would get passed to the shell.
1925 parens would get passed to the shell.
1908
1926
1909 2004-05-20 Fernando Perez <fperez@colorado.edu>
1927 2004-05-20 Fernando Perez <fperez@colorado.edu>
1910
1928
1911 * IPython/Magic.py (Magic.magic_prun): changed default profile
1929 * IPython/Magic.py (Magic.magic_prun): changed default profile
1912 sort order to 'time' (the more common profiling need).
1930 sort order to 'time' (the more common profiling need).
1913
1931
1914 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
1932 * IPython/OInspect.py (Inspector.pinfo): flush the inspect cache
1915 so that source code shown is guaranteed in sync with the file on
1933 so that source code shown is guaranteed in sync with the file on
1916 disk (also changed in psource). Similar fix to the one for
1934 disk (also changed in psource). Similar fix to the one for
1917 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
1935 ultraTB on 2004-05-06. Thanks to a bug report by Yann Le Du
1918 <yann.ledu-AT-noos.fr>.
1936 <yann.ledu-AT-noos.fr>.
1919
1937
1920 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
1938 * IPython/Magic.py (Magic.parse_options): Fixed bug where commands
1921 with a single option would not be correctly parsed. Closes
1939 with a single option would not be correctly parsed. Closes
1922 http://www.scipy.net/roundup/ipython/issue14. This bug had been
1940 http://www.scipy.net/roundup/ipython/issue14. This bug had been
1923 introduced in 0.6.0 (on 2004-05-06).
1941 introduced in 0.6.0 (on 2004-05-06).
1924
1942
1925 2004-05-13 *** Released version 0.6.0
1943 2004-05-13 *** Released version 0.6.0
1926
1944
1927 2004-05-13 Fernando Perez <fperez@colorado.edu>
1945 2004-05-13 Fernando Perez <fperez@colorado.edu>
1928
1946
1929 * debian/: Added debian/ directory to CVS, so that debian support
1947 * debian/: Added debian/ directory to CVS, so that debian support
1930 is publicly accessible. The debian package is maintained by Jack
1948 is publicly accessible. The debian package is maintained by Jack
1931 Moffit <jack-AT-xiph.org>.
1949 Moffit <jack-AT-xiph.org>.
1932
1950
1933 * Documentation: included the notes about an ipython-based system
1951 * Documentation: included the notes about an ipython-based system
1934 shell (the hypothetical 'pysh') into the new_design.pdf document,
1952 shell (the hypothetical 'pysh') into the new_design.pdf document,
1935 so that these ideas get distributed to users along with the
1953 so that these ideas get distributed to users along with the
1936 official documentation.
1954 official documentation.
1937
1955
1938 2004-05-10 Fernando Perez <fperez@colorado.edu>
1956 2004-05-10 Fernando Perez <fperez@colorado.edu>
1939
1957
1940 * IPython/Logger.py (Logger.create_log): fix recently introduced
1958 * IPython/Logger.py (Logger.create_log): fix recently introduced
1941 bug (misindented line) where logstart would fail when not given an
1959 bug (misindented line) where logstart would fail when not given an
1942 explicit filename.
1960 explicit filename.
1943
1961
1944 2004-05-09 Fernando Perez <fperez@colorado.edu>
1962 2004-05-09 Fernando Perez <fperez@colorado.edu>
1945
1963
1946 * IPython/Magic.py (Magic.parse_options): skip system call when
1964 * IPython/Magic.py (Magic.parse_options): skip system call when
1947 there are no options to look for. Faster, cleaner for the common
1965 there are no options to look for. Faster, cleaner for the common
1948 case.
1966 case.
1949
1967
1950 * Documentation: many updates to the manual: describing Windows
1968 * Documentation: many updates to the manual: describing Windows
1951 support better, Gnuplot updates, credits, misc small stuff. Also
1969 support better, Gnuplot updates, credits, misc small stuff. Also
1952 updated the new_design doc a bit.
1970 updated the new_design doc a bit.
1953
1971
1954 2004-05-06 *** Released version 0.6.0.rc1
1972 2004-05-06 *** Released version 0.6.0.rc1
1955
1973
1956 2004-05-06 Fernando Perez <fperez@colorado.edu>
1974 2004-05-06 Fernando Perez <fperez@colorado.edu>
1957
1975
1958 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
1976 * IPython/ultraTB.py (ListTB.text): modified a ton of string +=
1959 operations to use the vastly more efficient list/''.join() method.
1977 operations to use the vastly more efficient list/''.join() method.
1960 (FormattedTB.text): Fix
1978 (FormattedTB.text): Fix
1961 http://www.scipy.net/roundup/ipython/issue12 - exception source
1979 http://www.scipy.net/roundup/ipython/issue12 - exception source
1962 extract not updated after reload. Thanks to Mike Salib
1980 extract not updated after reload. Thanks to Mike Salib
1963 <msalib-AT-mit.edu> for pinning the source of the problem.
1981 <msalib-AT-mit.edu> for pinning the source of the problem.
1964 Fortunately, the solution works inside ipython and doesn't require
1982 Fortunately, the solution works inside ipython and doesn't require
1965 any changes to python proper.
1983 any changes to python proper.
1966
1984
1967 * IPython/Magic.py (Magic.parse_options): Improved to process the
1985 * IPython/Magic.py (Magic.parse_options): Improved to process the
1968 argument list as a true shell would (by actually using the
1986 argument list as a true shell would (by actually using the
1969 underlying system shell). This way, all @magics automatically get
1987 underlying system shell). This way, all @magics automatically get
1970 shell expansion for variables. Thanks to a comment by Alex
1988 shell expansion for variables. Thanks to a comment by Alex
1971 Schmolck.
1989 Schmolck.
1972
1990
1973 2004-04-04 Fernando Perez <fperez@colorado.edu>
1991 2004-04-04 Fernando Perez <fperez@colorado.edu>
1974
1992
1975 * IPython/iplib.py (InteractiveShell.interact): Added a special
1993 * IPython/iplib.py (InteractiveShell.interact): Added a special
1976 trap for a debugger quit exception, which is basically impossible
1994 trap for a debugger quit exception, which is basically impossible
1977 to handle by normal mechanisms, given what pdb does to the stack.
1995 to handle by normal mechanisms, given what pdb does to the stack.
1978 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
1996 This fixes a crash reported by <fgibbons-AT-llama.med.harvard.edu>.
1979
1997
1980 2004-04-03 Fernando Perez <fperez@colorado.edu>
1998 2004-04-03 Fernando Perez <fperez@colorado.edu>
1981
1999
1982 * IPython/genutils.py (Term): Standardized the names of the Term
2000 * IPython/genutils.py (Term): Standardized the names of the Term
1983 class streams to cin/cout/cerr, following C++ naming conventions
2001 class streams to cin/cout/cerr, following C++ naming conventions
1984 (I can't use in/out/err because 'in' is not a valid attribute
2002 (I can't use in/out/err because 'in' is not a valid attribute
1985 name).
2003 name).
1986
2004
1987 * IPython/iplib.py (InteractiveShell.interact): don't increment
2005 * IPython/iplib.py (InteractiveShell.interact): don't increment
1988 the prompt if there's no user input. By Daniel 'Dang' Griffith
2006 the prompt if there's no user input. By Daniel 'Dang' Griffith
1989 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
2007 <pythondev-dang-AT-lazytwinacres.net>, after a suggestion from
1990 Francois Pinard.
2008 Francois Pinard.
1991
2009
1992 2004-04-02 Fernando Perez <fperez@colorado.edu>
2010 2004-04-02 Fernando Perez <fperez@colorado.edu>
1993
2011
1994 * IPython/genutils.py (Stream.__init__): Modified to survive at
2012 * IPython/genutils.py (Stream.__init__): Modified to survive at
1995 least importing in contexts where stdin/out/err aren't true file
2013 least importing in contexts where stdin/out/err aren't true file
1996 objects, such as PyCrust (they lack fileno() and mode). However,
2014 objects, such as PyCrust (they lack fileno() and mode). However,
1997 the recovery facilities which rely on these things existing will
2015 the recovery facilities which rely on these things existing will
1998 not work.
2016 not work.
1999
2017
2000 2004-04-01 Fernando Perez <fperez@colorado.edu>
2018 2004-04-01 Fernando Perez <fperez@colorado.edu>
2001
2019
2002 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2020 * IPython/Magic.py (Magic.magic_sx): modified (as well as @sc) to
2003 use the new getoutputerror() function, so it properly
2021 use the new getoutputerror() function, so it properly
2004 distinguishes stdout/err.
2022 distinguishes stdout/err.
2005
2023
2006 * IPython/genutils.py (getoutputerror): added a function to
2024 * IPython/genutils.py (getoutputerror): added a function to
2007 capture separately the standard output and error of a command.
2025 capture separately the standard output and error of a command.
2008 After a comment from dang on the mailing lists. This code is
2026 After a comment from dang on the mailing lists. This code is
2009 basically a modified version of commands.getstatusoutput(), from
2027 basically a modified version of commands.getstatusoutput(), from
2010 the standard library.
2028 the standard library.
2011
2029
2012 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2030 * IPython/iplib.py (InteractiveShell.handle_shell_escape): added
2013 '!!' as a special syntax (shorthand) to access @sx.
2031 '!!' as a special syntax (shorthand) to access @sx.
2014
2032
2015 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2033 * IPython/Magic.py (Magic.magic_sx): new magic, to execute a shell
2016 command and return its output as a list split on '\n'.
2034 command and return its output as a list split on '\n'.
2017
2035
2018 2004-03-31 Fernando Perez <fperez@colorado.edu>
2036 2004-03-31 Fernando Perez <fperez@colorado.edu>
2019
2037
2020 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2038 * IPython/FakeModule.py (FakeModule.__init__): added __nonzero__
2021 method to dictionaries used as FakeModule instances if they lack
2039 method to dictionaries used as FakeModule instances if they lack
2022 it. At least pydoc in python2.3 breaks for runtime-defined
2040 it. At least pydoc in python2.3 breaks for runtime-defined
2023 functions without this hack. At some point I need to _really_
2041 functions without this hack. At some point I need to _really_
2024 understand what FakeModule is doing, because it's a gross hack.
2042 understand what FakeModule is doing, because it's a gross hack.
2025 But it solves Arnd's problem for now...
2043 But it solves Arnd's problem for now...
2026
2044
2027 2004-02-27 Fernando Perez <fperez@colorado.edu>
2045 2004-02-27 Fernando Perez <fperez@colorado.edu>
2028
2046
2029 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2047 * IPython/Logger.py (Logger.create_log): Fix bug where 'rotate'
2030 mode would behave erratically. Also increased the number of
2048 mode would behave erratically. Also increased the number of
2031 possible logs in rotate mod to 999. Thanks to Rod Holland
2049 possible logs in rotate mod to 999. Thanks to Rod Holland
2032 <rhh@StructureLABS.com> for the report and fixes.
2050 <rhh@StructureLABS.com> for the report and fixes.
2033
2051
2034 2004-02-26 Fernando Perez <fperez@colorado.edu>
2052 2004-02-26 Fernando Perez <fperez@colorado.edu>
2035
2053
2036 * IPython/genutils.py (page): Check that the curses module really
2054 * IPython/genutils.py (page): Check that the curses module really
2037 has the initscr attribute before trying to use it. For some
2055 has the initscr attribute before trying to use it. For some
2038 reason, the Solaris curses module is missing this. I think this
2056 reason, the Solaris curses module is missing this. I think this
2039 should be considered a Solaris python bug, but I'm not sure.
2057 should be considered a Solaris python bug, but I'm not sure.
2040
2058
2041 2004-01-17 Fernando Perez <fperez@colorado.edu>
2059 2004-01-17 Fernando Perez <fperez@colorado.edu>
2042
2060
2043 * IPython/genutils.py (Stream.__init__): Changes to try to make
2061 * IPython/genutils.py (Stream.__init__): Changes to try to make
2044 ipython robust against stdin/out/err being closed by the user.
2062 ipython robust against stdin/out/err being closed by the user.
2045 This is 'user error' (and blocks a normal python session, at least
2063 This is 'user error' (and blocks a normal python session, at least
2046 the stdout case). However, Ipython should be able to survive such
2064 the stdout case). However, Ipython should be able to survive such
2047 instances of abuse as gracefully as possible. To simplify the
2065 instances of abuse as gracefully as possible. To simplify the
2048 coding and maintain compatibility with Gary Bishop's Term
2066 coding and maintain compatibility with Gary Bishop's Term
2049 contributions, I've made use of classmethods for this. I think
2067 contributions, I've made use of classmethods for this. I think
2050 this introduces a dependency on python 2.2.
2068 this introduces a dependency on python 2.2.
2051
2069
2052 2004-01-13 Fernando Perez <fperez@colorado.edu>
2070 2004-01-13 Fernando Perez <fperez@colorado.edu>
2053
2071
2054 * IPython/numutils.py (exp_safe): simplified the code a bit and
2072 * IPython/numutils.py (exp_safe): simplified the code a bit and
2055 removed the need for importing the kinds module altogether.
2073 removed the need for importing the kinds module altogether.
2056
2074
2057 2004-01-06 Fernando Perez <fperez@colorado.edu>
2075 2004-01-06 Fernando Perez <fperez@colorado.edu>
2058
2076
2059 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2077 * IPython/Magic.py (Magic.magic_sc): Made the shell capture system
2060 a magic function instead, after some community feedback. No
2078 a magic function instead, after some community feedback. No
2061 special syntax will exist for it, but its name is deliberately
2079 special syntax will exist for it, but its name is deliberately
2062 very short.
2080 very short.
2063
2081
2064 2003-12-20 Fernando Perez <fperez@colorado.edu>
2082 2003-12-20 Fernando Perez <fperez@colorado.edu>
2065
2083
2066 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2084 * IPython/iplib.py (InteractiveShell.handle_shell_assign): Added
2067 new functionality, to automagically assign the result of a shell
2085 new functionality, to automagically assign the result of a shell
2068 command to a variable. I'll solicit some community feedback on
2086 command to a variable. I'll solicit some community feedback on
2069 this before making it permanent.
2087 this before making it permanent.
2070
2088
2071 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2089 * IPython/OInspect.py (Inspector.pinfo): Fix crash when info was
2072 requested about callables for which inspect couldn't obtain a
2090 requested about callables for which inspect couldn't obtain a
2073 proper argspec. Thanks to a crash report sent by Etienne
2091 proper argspec. Thanks to a crash report sent by Etienne
2074 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2092 Posthumus <etienne-AT-apple01.cs.vu.nl>.
2075
2093
2076 2003-12-09 Fernando Perez <fperez@colorado.edu>
2094 2003-12-09 Fernando Perez <fperez@colorado.edu>
2077
2095
2078 * IPython/genutils.py (page): patch for the pager to work across
2096 * IPython/genutils.py (page): patch for the pager to work across
2079 various versions of Windows. By Gary Bishop.
2097 various versions of Windows. By Gary Bishop.
2080
2098
2081 2003-12-04 Fernando Perez <fperez@colorado.edu>
2099 2003-12-04 Fernando Perez <fperez@colorado.edu>
2082
2100
2083 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2101 * IPython/Gnuplot2.py (PlotItems): Fixes for working with
2084 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2102 Gnuplot.py version 1.7, whose internal names changed quite a bit.
2085 While I tested this and it looks ok, there may still be corner
2103 While I tested this and it looks ok, there may still be corner
2086 cases I've missed.
2104 cases I've missed.
2087
2105
2088 2003-12-01 Fernando Perez <fperez@colorado.edu>
2106 2003-12-01 Fernando Perez <fperez@colorado.edu>
2089
2107
2090 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2108 * IPython/iplib.py (InteractiveShell._prefilter): Fixed a bug
2091 where a line like 'p,q=1,2' would fail because the automagic
2109 where a line like 'p,q=1,2' would fail because the automagic
2092 system would be triggered for @p.
2110 system would be triggered for @p.
2093
2111
2094 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2112 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): Tab-related
2095 cleanups, code unmodified.
2113 cleanups, code unmodified.
2096
2114
2097 * IPython/genutils.py (Term): added a class for IPython to handle
2115 * IPython/genutils.py (Term): added a class for IPython to handle
2098 output. In most cases it will just be a proxy for stdout/err, but
2116 output. In most cases it will just be a proxy for stdout/err, but
2099 having this allows modifications to be made for some platforms,
2117 having this allows modifications to be made for some platforms,
2100 such as handling color escapes under Windows. All of this code
2118 such as handling color escapes under Windows. All of this code
2101 was contributed by Gary Bishop, with minor modifications by me.
2119 was contributed by Gary Bishop, with minor modifications by me.
2102 The actual changes affect many files.
2120 The actual changes affect many files.
2103
2121
2104 2003-11-30 Fernando Perez <fperez@colorado.edu>
2122 2003-11-30 Fernando Perez <fperez@colorado.edu>
2105
2123
2106 * IPython/iplib.py (file_matches): new completion code, courtesy
2124 * IPython/iplib.py (file_matches): new completion code, courtesy
2107 of Jeff Collins. This enables filename completion again under
2125 of Jeff Collins. This enables filename completion again under
2108 python 2.3, which disabled it at the C level.
2126 python 2.3, which disabled it at the C level.
2109
2127
2110 2003-11-11 Fernando Perez <fperez@colorado.edu>
2128 2003-11-11 Fernando Perez <fperez@colorado.edu>
2111
2129
2112 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2130 * IPython/numutils.py (amap): Added amap() fn. Simple shorthand
2113 for Numeric.array(map(...)), but often convenient.
2131 for Numeric.array(map(...)), but often convenient.
2114
2132
2115 2003-11-05 Fernando Perez <fperez@colorado.edu>
2133 2003-11-05 Fernando Perez <fperez@colorado.edu>
2116
2134
2117 * IPython/numutils.py (frange): Changed a call from int() to
2135 * IPython/numutils.py (frange): Changed a call from int() to
2118 int(round()) to prevent a problem reported with arange() in the
2136 int(round()) to prevent a problem reported with arange() in the
2119 numpy list.
2137 numpy list.
2120
2138
2121 2003-10-06 Fernando Perez <fperez@colorado.edu>
2139 2003-10-06 Fernando Perez <fperez@colorado.edu>
2122
2140
2123 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2141 * IPython/DPyGetOpt.py (DPyGetOpt.processArguments): changed to
2124 prevent crashes if sys lacks an argv attribute (it happens with
2142 prevent crashes if sys lacks an argv attribute (it happens with
2125 embedded interpreters which build a bare-bones sys module).
2143 embedded interpreters which build a bare-bones sys module).
2126 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2144 Thanks to a report/bugfix by Adam Hupp <hupp-AT-cs.wisc.edu>.
2127
2145
2128 2003-09-24 Fernando Perez <fperez@colorado.edu>
2146 2003-09-24 Fernando Perez <fperez@colorado.edu>
2129
2147
2130 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2148 * IPython/Magic.py (Magic._ofind): blanket except around getattr()
2131 to protect against poorly written user objects where __getattr__
2149 to protect against poorly written user objects where __getattr__
2132 raises exceptions other than AttributeError. Thanks to a bug
2150 raises exceptions other than AttributeError. Thanks to a bug
2133 report by Oliver Sander <osander-AT-gmx.de>.
2151 report by Oliver Sander <osander-AT-gmx.de>.
2134
2152
2135 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2153 * IPython/FakeModule.py (FakeModule.__repr__): this method was
2136 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2154 missing. Thanks to bug report by Ralf Schmitt <ralf-AT-brainbot.com>.
2137
2155
2138 2003-09-09 Fernando Perez <fperez@colorado.edu>
2156 2003-09-09 Fernando Perez <fperez@colorado.edu>
2139
2157
2140 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2158 * IPython/iplib.py (InteractiveShell._prefilter): fix bug where
2141 unpacking a list whith a callable as first element would
2159 unpacking a list whith a callable as first element would
2142 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2160 mistakenly trigger autocalling. Thanks to a bug report by Jeffery
2143 Collins.
2161 Collins.
2144
2162
2145 2003-08-25 *** Released version 0.5.0
2163 2003-08-25 *** Released version 0.5.0
2146
2164
2147 2003-08-22 Fernando Perez <fperez@colorado.edu>
2165 2003-08-22 Fernando Perez <fperez@colorado.edu>
2148
2166
2149 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2167 * IPython/ultraTB.py (VerboseTB.linereader): Improved handling of
2150 improperly defined user exceptions. Thanks to feedback from Mark
2168 improperly defined user exceptions. Thanks to feedback from Mark
2151 Russell <mrussell-AT-verio.net>.
2169 Russell <mrussell-AT-verio.net>.
2152
2170
2153 2003-08-20 Fernando Perez <fperez@colorado.edu>
2171 2003-08-20 Fernando Perez <fperez@colorado.edu>
2154
2172
2155 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2173 * IPython/OInspect.py (Inspector.pinfo): changed String Form
2156 printing so that it would print multi-line string forms starting
2174 printing so that it would print multi-line string forms starting
2157 with a new line. This way the formatting is better respected for
2175 with a new line. This way the formatting is better respected for
2158 objects which work hard to make nice string forms.
2176 objects which work hard to make nice string forms.
2159
2177
2160 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2178 * IPython/iplib.py (InteractiveShell.handle_auto): Fix bug where
2161 autocall would overtake data access for objects with both
2179 autocall would overtake data access for objects with both
2162 __getitem__ and __call__.
2180 __getitem__ and __call__.
2163
2181
2164 2003-08-19 *** Released version 0.5.0-rc1
2182 2003-08-19 *** Released version 0.5.0-rc1
2165
2183
2166 2003-08-19 Fernando Perez <fperez@colorado.edu>
2184 2003-08-19 Fernando Perez <fperez@colorado.edu>
2167
2185
2168 * IPython/deep_reload.py (load_tail): single tiny change here
2186 * IPython/deep_reload.py (load_tail): single tiny change here
2169 seems to fix the long-standing bug of dreload() failing to work
2187 seems to fix the long-standing bug of dreload() failing to work
2170 for dotted names. But this module is pretty tricky, so I may have
2188 for dotted names. But this module is pretty tricky, so I may have
2171 missed some subtlety. Needs more testing!.
2189 missed some subtlety. Needs more testing!.
2172
2190
2173 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2191 * IPython/ultraTB.py (VerboseTB.linereader): harden against user
2174 exceptions which have badly implemented __str__ methods.
2192 exceptions which have badly implemented __str__ methods.
2175 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2193 (VerboseTB.text): harden against inspect.getinnerframes crashing,
2176 which I've been getting reports about from Python 2.3 users. I
2194 which I've been getting reports about from Python 2.3 users. I
2177 wish I had a simple test case to reproduce the problem, so I could
2195 wish I had a simple test case to reproduce the problem, so I could
2178 either write a cleaner workaround or file a bug report if
2196 either write a cleaner workaround or file a bug report if
2179 necessary.
2197 necessary.
2180
2198
2181 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2199 * IPython/Magic.py (Magic.magic_edit): fixed bug where after
2182 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2200 making a class 'foo', file 'foo.py' couldn't be edited. Thanks to
2183 a bug report by Tjabo Kloppenburg.
2201 a bug report by Tjabo Kloppenburg.
2184
2202
2185 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2203 * IPython/ultraTB.py (VerboseTB.debugger): hardened against pdb
2186 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2204 crashes. Wrapped the pdb call in a blanket try/except, since pdb
2187 seems rather unstable. Thanks to a bug report by Tjabo
2205 seems rather unstable. Thanks to a bug report by Tjabo
2188 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2206 Kloppenburg <tjabo.kloppenburg-AT-unix-ag.uni-siegen.de>.
2189
2207
2190 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2208 * IPython/Release.py (version): release 0.5.0-rc1. I want to put
2191 this out soon because of the critical fixes in the inner loop for
2209 this out soon because of the critical fixes in the inner loop for
2192 generators.
2210 generators.
2193
2211
2194 * IPython/Magic.py (Magic.getargspec): removed. This (and
2212 * IPython/Magic.py (Magic.getargspec): removed. This (and
2195 _get_def) have been obsoleted by OInspect for a long time, I
2213 _get_def) have been obsoleted by OInspect for a long time, I
2196 hadn't noticed that they were dead code.
2214 hadn't noticed that they were dead code.
2197 (Magic._ofind): restored _ofind functionality for a few literals
2215 (Magic._ofind): restored _ofind functionality for a few literals
2198 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2216 (those in ["''",'""','[]','{}','()']). But it won't work anymore
2199 for things like "hello".capitalize?, since that would require a
2217 for things like "hello".capitalize?, since that would require a
2200 potentially dangerous eval() again.
2218 potentially dangerous eval() again.
2201
2219
2202 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2220 * IPython/iplib.py (InteractiveShell._prefilter): reorganized the
2203 logic a bit more to clean up the escapes handling and minimize the
2221 logic a bit more to clean up the escapes handling and minimize the
2204 use of _ofind to only necessary cases. The interactive 'feel' of
2222 use of _ofind to only necessary cases. The interactive 'feel' of
2205 IPython should have improved quite a bit with the changes in
2223 IPython should have improved quite a bit with the changes in
2206 _prefilter and _ofind (besides being far safer than before).
2224 _prefilter and _ofind (besides being far safer than before).
2207
2225
2208 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2226 * IPython/Magic.py (Magic.magic_edit): Fixed old bug (but rather
2209 obscure, never reported). Edit would fail to find the object to
2227 obscure, never reported). Edit would fail to find the object to
2210 edit under some circumstances.
2228 edit under some circumstances.
2211 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2229 (Magic._ofind): CRITICAL FIX. Finally removed the eval() calls
2212 which were causing double-calling of generators. Those eval calls
2230 which were causing double-calling of generators. Those eval calls
2213 were _very_ dangerous, since code with side effects could be
2231 were _very_ dangerous, since code with side effects could be
2214 triggered. As they say, 'eval is evil'... These were the
2232 triggered. As they say, 'eval is evil'... These were the
2215 nastiest evals in IPython. Besides, _ofind is now far simpler,
2233 nastiest evals in IPython. Besides, _ofind is now far simpler,
2216 and it should also be quite a bit faster. Its use of inspect is
2234 and it should also be quite a bit faster. Its use of inspect is
2217 also safer, so perhaps some of the inspect-related crashes I've
2235 also safer, so perhaps some of the inspect-related crashes I've
2218 seen lately with Python 2.3 might be taken care of. That will
2236 seen lately with Python 2.3 might be taken care of. That will
2219 need more testing.
2237 need more testing.
2220
2238
2221 2003-08-17 Fernando Perez <fperez@colorado.edu>
2239 2003-08-17 Fernando Perez <fperez@colorado.edu>
2222
2240
2223 * IPython/iplib.py (InteractiveShell._prefilter): significant
2241 * IPython/iplib.py (InteractiveShell._prefilter): significant
2224 simplifications to the logic for handling user escapes. Faster
2242 simplifications to the logic for handling user escapes. Faster
2225 and simpler code.
2243 and simpler code.
2226
2244
2227 2003-08-14 Fernando Perez <fperez@colorado.edu>
2245 2003-08-14 Fernando Perez <fperez@colorado.edu>
2228
2246
2229 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2247 * IPython/numutils.py (sum_flat): rewrote to be non-recursive.
2230 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2248 Now it requires O(N) storage (N=size(a)) for non-contiguous input,
2231 but it should be quite a bit faster. And the recursive version
2249 but it should be quite a bit faster. And the recursive version
2232 generated O(log N) intermediate storage for all rank>1 arrays,
2250 generated O(log N) intermediate storage for all rank>1 arrays,
2233 even if they were contiguous.
2251 even if they were contiguous.
2234 (l1norm): Added this function.
2252 (l1norm): Added this function.
2235 (norm): Added this function for arbitrary norms (including
2253 (norm): Added this function for arbitrary norms (including
2236 l-infinity). l1 and l2 are still special cases for convenience
2254 l-infinity). l1 and l2 are still special cases for convenience
2237 and speed.
2255 and speed.
2238
2256
2239 2003-08-03 Fernando Perez <fperez@colorado.edu>
2257 2003-08-03 Fernando Perez <fperez@colorado.edu>
2240
2258
2241 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2259 * IPython/Magic.py (Magic.magic_edit): Removed all remaining string
2242 exceptions, which now raise PendingDeprecationWarnings in Python
2260 exceptions, which now raise PendingDeprecationWarnings in Python
2243 2.3. There were some in Magic and some in Gnuplot2.
2261 2.3. There were some in Magic and some in Gnuplot2.
2244
2262
2245 2003-06-30 Fernando Perez <fperez@colorado.edu>
2263 2003-06-30 Fernando Perez <fperez@colorado.edu>
2246
2264
2247 * IPython/genutils.py (page): modified to call curses only for
2265 * IPython/genutils.py (page): modified to call curses only for
2248 terminals where TERM=='xterm'. After problems under many other
2266 terminals where TERM=='xterm'. After problems under many other
2249 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2267 terminals were reported by Keith Beattie <KSBeattie-AT-lbl.gov>.
2250
2268
2251 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2269 * IPython/iplib.py (complete): removed spurious 'print "IE"' which
2252 would be triggered when readline was absent. This was just an old
2270 would be triggered when readline was absent. This was just an old
2253 debugging statement I'd forgotten to take out.
2271 debugging statement I'd forgotten to take out.
2254
2272
2255 2003-06-20 Fernando Perez <fperez@colorado.edu>
2273 2003-06-20 Fernando Perez <fperez@colorado.edu>
2256
2274
2257 * IPython/genutils.py (clock): modified to return only user time
2275 * IPython/genutils.py (clock): modified to return only user time
2258 (not counting system time), after a discussion on scipy. While
2276 (not counting system time), after a discussion on scipy. While
2259 system time may be a useful quantity occasionally, it may much
2277 system time may be a useful quantity occasionally, it may much
2260 more easily be skewed by occasional swapping or other similar
2278 more easily be skewed by occasional swapping or other similar
2261 activity.
2279 activity.
2262
2280
2263 2003-06-05 Fernando Perez <fperez@colorado.edu>
2281 2003-06-05 Fernando Perez <fperez@colorado.edu>
2264
2282
2265 * IPython/numutils.py (identity): new function, for building
2283 * IPython/numutils.py (identity): new function, for building
2266 arbitrary rank Kronecker deltas (mostly backwards compatible with
2284 arbitrary rank Kronecker deltas (mostly backwards compatible with
2267 Numeric.identity)
2285 Numeric.identity)
2268
2286
2269 2003-06-03 Fernando Perez <fperez@colorado.edu>
2287 2003-06-03 Fernando Perez <fperez@colorado.edu>
2270
2288
2271 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2289 * IPython/iplib.py (InteractiveShell.handle_magic): protect
2272 arguments passed to magics with spaces, to allow trailing '\' to
2290 arguments passed to magics with spaces, to allow trailing '\' to
2273 work normally (mainly for Windows users).
2291 work normally (mainly for Windows users).
2274
2292
2275 2003-05-29 Fernando Perez <fperez@colorado.edu>
2293 2003-05-29 Fernando Perez <fperez@colorado.edu>
2276
2294
2277 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2295 * IPython/ipmaker.py (make_IPython): Load site._Helper() as help
2278 instead of pydoc.help. This fixes a bizarre behavior where
2296 instead of pydoc.help. This fixes a bizarre behavior where
2279 printing '%s' % locals() would trigger the help system. Now
2297 printing '%s' % locals() would trigger the help system. Now
2280 ipython behaves like normal python does.
2298 ipython behaves like normal python does.
2281
2299
2282 Note that if one does 'from pydoc import help', the bizarre
2300 Note that if one does 'from pydoc import help', the bizarre
2283 behavior returns, but this will also happen in normal python, so
2301 behavior returns, but this will also happen in normal python, so
2284 it's not an ipython bug anymore (it has to do with how pydoc.help
2302 it's not an ipython bug anymore (it has to do with how pydoc.help
2285 is implemented).
2303 is implemented).
2286
2304
2287 2003-05-22 Fernando Perez <fperez@colorado.edu>
2305 2003-05-22 Fernando Perez <fperez@colorado.edu>
2288
2306
2289 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2307 * IPython/FlexCompleter.py (Completer.attr_matches): fixed to
2290 return [] instead of None when nothing matches, also match to end
2308 return [] instead of None when nothing matches, also match to end
2291 of line. Patch by Gary Bishop.
2309 of line. Patch by Gary Bishop.
2292
2310
2293 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2311 * IPython/ipmaker.py (make_IPython): Added same sys.excepthook
2294 protection as before, for files passed on the command line. This
2312 protection as before, for files passed on the command line. This
2295 prevents the CrashHandler from kicking in if user files call into
2313 prevents the CrashHandler from kicking in if user files call into
2296 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2314 sys.excepthook (such as PyQt and WxWindows have a nasty habit of
2297 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2315 doing). After a report by Kasper Souren <Kasper.Souren-AT-ircam.fr>
2298
2316
2299 2003-05-20 *** Released version 0.4.0
2317 2003-05-20 *** Released version 0.4.0
2300
2318
2301 2003-05-20 Fernando Perez <fperez@colorado.edu>
2319 2003-05-20 Fernando Perez <fperez@colorado.edu>
2302
2320
2303 * setup.py: added support for manpages. It's a bit hackish b/c of
2321 * setup.py: added support for manpages. It's a bit hackish b/c of
2304 a bug in the way the bdist_rpm distutils target handles gzipped
2322 a bug in the way the bdist_rpm distutils target handles gzipped
2305 manpages, but it works. After a patch by Jack.
2323 manpages, but it works. After a patch by Jack.
2306
2324
2307 2003-05-19 Fernando Perez <fperez@colorado.edu>
2325 2003-05-19 Fernando Perez <fperez@colorado.edu>
2308
2326
2309 * IPython/numutils.py: added a mockup of the kinds module, since
2327 * IPython/numutils.py: added a mockup of the kinds module, since
2310 it was recently removed from Numeric. This way, numutils will
2328 it was recently removed from Numeric. This way, numutils will
2311 work for all users even if they are missing kinds.
2329 work for all users even if they are missing kinds.
2312
2330
2313 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2331 * IPython/Magic.py (Magic._ofind): Harden against an inspect
2314 failure, which can occur with SWIG-wrapped extensions. After a
2332 failure, which can occur with SWIG-wrapped extensions. After a
2315 crash report from Prabhu.
2333 crash report from Prabhu.
2316
2334
2317 2003-05-16 Fernando Perez <fperez@colorado.edu>
2335 2003-05-16 Fernando Perez <fperez@colorado.edu>
2318
2336
2319 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2337 * IPython/iplib.py (InteractiveShell.excepthook): New method to
2320 protect ipython from user code which may call directly
2338 protect ipython from user code which may call directly
2321 sys.excepthook (this looks like an ipython crash to the user, even
2339 sys.excepthook (this looks like an ipython crash to the user, even
2322 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2340 when it isn't). After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2323 This is especially important to help users of WxWindows, but may
2341 This is especially important to help users of WxWindows, but may
2324 also be useful in other cases.
2342 also be useful in other cases.
2325
2343
2326 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2344 * IPython/ultraTB.py (AutoFormattedTB.__call__): Changed to allow
2327 an optional tb_offset to be specified, and to preserve exception
2345 an optional tb_offset to be specified, and to preserve exception
2328 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2346 info if given. After a patch by Gary Bishop <gb-AT-cs.unc.edu>.
2329
2347
2330 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2348 * ipython.1 (Default): Thanks to Jack's work, we now have manpages!
2331
2349
2332 2003-05-15 Fernando Perez <fperez@colorado.edu>
2350 2003-05-15 Fernando Perez <fperez@colorado.edu>
2333
2351
2334 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2352 * IPython/iplib.py (InteractiveShell.user_setup): Fix crash when
2335 installing for a new user under Windows.
2353 installing for a new user under Windows.
2336
2354
2337 2003-05-12 Fernando Perez <fperez@colorado.edu>
2355 2003-05-12 Fernando Perez <fperez@colorado.edu>
2338
2356
2339 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2357 * IPython/iplib.py (InteractiveShell.handle_emacs): New line
2340 handler for Emacs comint-based lines. Currently it doesn't do
2358 handler for Emacs comint-based lines. Currently it doesn't do
2341 much (but importantly, it doesn't update the history cache). In
2359 much (but importantly, it doesn't update the history cache). In
2342 the future it may be expanded if Alex needs more functionality
2360 the future it may be expanded if Alex needs more functionality
2343 there.
2361 there.
2344
2362
2345 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2363 * IPython/CrashHandler.py (CrashHandler.__call__): Added platform
2346 info to crash reports.
2364 info to crash reports.
2347
2365
2348 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2366 * IPython/iplib.py (InteractiveShell.mainloop): Added -c option,
2349 just like Python's -c. Also fixed crash with invalid -color
2367 just like Python's -c. Also fixed crash with invalid -color
2350 option value at startup. Thanks to Will French
2368 option value at startup. Thanks to Will French
2351 <wfrench-AT-bestweb.net> for the bug report.
2369 <wfrench-AT-bestweb.net> for the bug report.
2352
2370
2353 2003-05-09 Fernando Perez <fperez@colorado.edu>
2371 2003-05-09 Fernando Perez <fperez@colorado.edu>
2354
2372
2355 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2373 * IPython/genutils.py (EvalDict.__getitem__): Renamed EvalString
2356 to EvalDict (it's a mapping, after all) and simplified its code
2374 to EvalDict (it's a mapping, after all) and simplified its code
2357 quite a bit, after a nice discussion on c.l.py where Gustavo
2375 quite a bit, after a nice discussion on c.l.py where Gustavo
2358 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
2376 CΓ³rdova <gcordova-AT-sismex.com> suggested the new version.
2359
2377
2360 2003-04-30 Fernando Perez <fperez@colorado.edu>
2378 2003-04-30 Fernando Perez <fperez@colorado.edu>
2361
2379
2362 * IPython/genutils.py (timings_out): modified it to reduce its
2380 * IPython/genutils.py (timings_out): modified it to reduce its
2363 overhead in the common reps==1 case.
2381 overhead in the common reps==1 case.
2364
2382
2365 2003-04-29 Fernando Perez <fperez@colorado.edu>
2383 2003-04-29 Fernando Perez <fperez@colorado.edu>
2366
2384
2367 * IPython/genutils.py (timings_out): Modified to use the resource
2385 * IPython/genutils.py (timings_out): Modified to use the resource
2368 module, which avoids the wraparound problems of time.clock().
2386 module, which avoids the wraparound problems of time.clock().
2369
2387
2370 2003-04-17 *** Released version 0.2.15pre4
2388 2003-04-17 *** Released version 0.2.15pre4
2371
2389
2372 2003-04-17 Fernando Perez <fperez@colorado.edu>
2390 2003-04-17 Fernando Perez <fperez@colorado.edu>
2373
2391
2374 * setup.py (scriptfiles): Split windows-specific stuff over to a
2392 * setup.py (scriptfiles): Split windows-specific stuff over to a
2375 separate file, in an attempt to have a Windows GUI installer.
2393 separate file, in an attempt to have a Windows GUI installer.
2376 That didn't work, but part of the groundwork is done.
2394 That didn't work, but part of the groundwork is done.
2377
2395
2378 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2396 * IPython/UserConfig/ipythonrc: Added M-i, M-o and M-I for
2379 indent/unindent with 4 spaces. Particularly useful in combination
2397 indent/unindent with 4 spaces. Particularly useful in combination
2380 with the new auto-indent option.
2398 with the new auto-indent option.
2381
2399
2382 2003-04-16 Fernando Perez <fperez@colorado.edu>
2400 2003-04-16 Fernando Perez <fperez@colorado.edu>
2383
2401
2384 * IPython/Magic.py: various replacements of self.rc for
2402 * IPython/Magic.py: various replacements of self.rc for
2385 self.shell.rc. A lot more remains to be done to fully disentangle
2403 self.shell.rc. A lot more remains to be done to fully disentangle
2386 this class from the main Shell class.
2404 this class from the main Shell class.
2387
2405
2388 * IPython/GnuplotRuntime.py: added checks for mouse support so
2406 * IPython/GnuplotRuntime.py: added checks for mouse support so
2389 that we don't try to enable it if the current gnuplot doesn't
2407 that we don't try to enable it if the current gnuplot doesn't
2390 really support it. Also added checks so that we don't try to
2408 really support it. Also added checks so that we don't try to
2391 enable persist under Windows (where Gnuplot doesn't recognize the
2409 enable persist under Windows (where Gnuplot doesn't recognize the
2392 option).
2410 option).
2393
2411
2394 * IPython/iplib.py (InteractiveShell.interact): Added optional
2412 * IPython/iplib.py (InteractiveShell.interact): Added optional
2395 auto-indenting code, after a patch by King C. Shu
2413 auto-indenting code, after a patch by King C. Shu
2396 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2414 <kingshu-AT-myrealbox.com>. It's off by default because it doesn't
2397 get along well with pasting indented code. If I ever figure out
2415 get along well with pasting indented code. If I ever figure out
2398 how to make that part go well, it will become on by default.
2416 how to make that part go well, it will become on by default.
2399
2417
2400 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2418 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixed bug which would
2401 crash ipython if there was an unmatched '%' in the user's prompt
2419 crash ipython if there was an unmatched '%' in the user's prompt
2402 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2420 string. Reported by Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2403
2421
2404 * IPython/iplib.py (InteractiveShell.interact): removed the
2422 * IPython/iplib.py (InteractiveShell.interact): removed the
2405 ability to ask the user whether he wants to crash or not at the
2423 ability to ask the user whether he wants to crash or not at the
2406 'last line' exception handler. Calling functions at that point
2424 'last line' exception handler. Calling functions at that point
2407 changes the stack, and the error reports would have incorrect
2425 changes the stack, and the error reports would have incorrect
2408 tracebacks.
2426 tracebacks.
2409
2427
2410 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2428 * IPython/Magic.py (Magic.magic_page): Added new @page magic, to
2411 pass through a peger a pretty-printed form of any object. After a
2429 pass through a peger a pretty-printed form of any object. After a
2412 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2430 contribution by Olivier Aubert <oaubert-AT-bat710.univ-lyon1.fr>
2413
2431
2414 2003-04-14 Fernando Perez <fperez@colorado.edu>
2432 2003-04-14 Fernando Perez <fperez@colorado.edu>
2415
2433
2416 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2434 * IPython/iplib.py (InteractiveShell.user_setup): Fixed bug where
2417 all files in ~ would be modified at first install (instead of
2435 all files in ~ would be modified at first install (instead of
2418 ~/.ipython). This could be potentially disastrous, as the
2436 ~/.ipython). This could be potentially disastrous, as the
2419 modification (make line-endings native) could damage binary files.
2437 modification (make line-endings native) could damage binary files.
2420
2438
2421 2003-04-10 Fernando Perez <fperez@colorado.edu>
2439 2003-04-10 Fernando Perez <fperez@colorado.edu>
2422
2440
2423 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2441 * IPython/iplib.py (InteractiveShell.handle_help): Modified to
2424 handle only lines which are invalid python. This now means that
2442 handle only lines which are invalid python. This now means that
2425 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2443 lines like 'x=1 #?' execute properly. Thanks to Jeffery Collins
2426 for the bug report.
2444 for the bug report.
2427
2445
2428 2003-04-01 Fernando Perez <fperez@colorado.edu>
2446 2003-04-01 Fernando Perez <fperez@colorado.edu>
2429
2447
2430 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2448 * IPython/iplib.py (InteractiveShell.showtraceback): Fixed bug
2431 where failing to set sys.last_traceback would crash pdb.pm().
2449 where failing to set sys.last_traceback would crash pdb.pm().
2432 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2450 Thanks to Jeffery D. Collins <Jeff.Collins-AT-vexcel.com> for the bug
2433 report.
2451 report.
2434
2452
2435 2003-03-25 Fernando Perez <fperez@colorado.edu>
2453 2003-03-25 Fernando Perez <fperez@colorado.edu>
2436
2454
2437 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2455 * IPython/Magic.py (Magic.magic_prun): rstrip() output of profiler
2438 before printing it (it had a lot of spurious blank lines at the
2456 before printing it (it had a lot of spurious blank lines at the
2439 end).
2457 end).
2440
2458
2441 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2459 * IPython/Gnuplot2.py (Gnuplot.hardcopy): fixed bug where lpr
2442 output would be sent 21 times! Obviously people don't use this
2460 output would be sent 21 times! Obviously people don't use this
2443 too often, or I would have heard about it.
2461 too often, or I would have heard about it.
2444
2462
2445 2003-03-24 Fernando Perez <fperez@colorado.edu>
2463 2003-03-24 Fernando Perez <fperez@colorado.edu>
2446
2464
2447 * setup.py (scriptfiles): renamed the data_files parameter from
2465 * setup.py (scriptfiles): renamed the data_files parameter from
2448 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2466 'base' to 'data' to fix rpm build issues. Thanks to Ralf Ahlbrink
2449 for the patch.
2467 for the patch.
2450
2468
2451 2003-03-20 Fernando Perez <fperez@colorado.edu>
2469 2003-03-20 Fernando Perez <fperez@colorado.edu>
2452
2470
2453 * IPython/genutils.py (error): added error() and fatal()
2471 * IPython/genutils.py (error): added error() and fatal()
2454 functions.
2472 functions.
2455
2473
2456 2003-03-18 *** Released version 0.2.15pre3
2474 2003-03-18 *** Released version 0.2.15pre3
2457
2475
2458 2003-03-18 Fernando Perez <fperez@colorado.edu>
2476 2003-03-18 Fernando Perez <fperez@colorado.edu>
2459
2477
2460 * setupext/install_data_ext.py
2478 * setupext/install_data_ext.py
2461 (install_data_ext.initialize_options): Class contributed by Jack
2479 (install_data_ext.initialize_options): Class contributed by Jack
2462 Moffit for fixing the old distutils hack. He is sending this to
2480 Moffit for fixing the old distutils hack. He is sending this to
2463 the distutils folks so in the future we may not need it as a
2481 the distutils folks so in the future we may not need it as a
2464 private fix.
2482 private fix.
2465
2483
2466 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2484 * MANIFEST.in: Extensive reorganization, based on Jack Moffit's
2467 changes for Debian packaging. See his patch for full details.
2485 changes for Debian packaging. See his patch for full details.
2468 The old distutils hack of making the ipythonrc* files carry a
2486 The old distutils hack of making the ipythonrc* files carry a
2469 bogus .py extension is gone, at last. Examples were moved to a
2487 bogus .py extension is gone, at last. Examples were moved to a
2470 separate subdir under doc/, and the separate executable scripts
2488 separate subdir under doc/, and the separate executable scripts
2471 now live in their own directory. Overall a great cleanup. The
2489 now live in their own directory. Overall a great cleanup. The
2472 manual was updated to use the new files, and setup.py has been
2490 manual was updated to use the new files, and setup.py has been
2473 fixed for this setup.
2491 fixed for this setup.
2474
2492
2475 * IPython/PyColorize.py (Parser.usage): made non-executable and
2493 * IPython/PyColorize.py (Parser.usage): made non-executable and
2476 created a pycolor wrapper around it to be included as a script.
2494 created a pycolor wrapper around it to be included as a script.
2477
2495
2478 2003-03-12 *** Released version 0.2.15pre2
2496 2003-03-12 *** Released version 0.2.15pre2
2479
2497
2480 2003-03-12 Fernando Perez <fperez@colorado.edu>
2498 2003-03-12 Fernando Perez <fperez@colorado.edu>
2481
2499
2482 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2500 * IPython/ColorANSI.py (make_color_table): Finally fixed the
2483 long-standing problem with garbage characters in some terminals.
2501 long-standing problem with garbage characters in some terminals.
2484 The issue was really that the \001 and \002 escapes must _only_ be
2502 The issue was really that the \001 and \002 escapes must _only_ be
2485 passed to input prompts (which call readline), but _never_ to
2503 passed to input prompts (which call readline), but _never_ to
2486 normal text to be printed on screen. I changed ColorANSI to have
2504 normal text to be printed on screen. I changed ColorANSI to have
2487 two classes: TermColors and InputTermColors, each with the
2505 two classes: TermColors and InputTermColors, each with the
2488 appropriate escapes for input prompts or normal text. The code in
2506 appropriate escapes for input prompts or normal text. The code in
2489 Prompts.py got slightly more complicated, but this very old and
2507 Prompts.py got slightly more complicated, but this very old and
2490 annoying bug is finally fixed.
2508 annoying bug is finally fixed.
2491
2509
2492 All the credit for nailing down the real origin of this problem
2510 All the credit for nailing down the real origin of this problem
2493 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2511 and the correct solution goes to Jack Moffit <jack-AT-xiph.org>.
2494 *Many* thanks to him for spending quite a bit of effort on this.
2512 *Many* thanks to him for spending quite a bit of effort on this.
2495
2513
2496 2003-03-05 *** Released version 0.2.15pre1
2514 2003-03-05 *** Released version 0.2.15pre1
2497
2515
2498 2003-03-03 Fernando Perez <fperez@colorado.edu>
2516 2003-03-03 Fernando Perez <fperez@colorado.edu>
2499
2517
2500 * IPython/FakeModule.py: Moved the former _FakeModule to a
2518 * IPython/FakeModule.py: Moved the former _FakeModule to a
2501 separate file, because it's also needed by Magic (to fix a similar
2519 separate file, because it's also needed by Magic (to fix a similar
2502 pickle-related issue in @run).
2520 pickle-related issue in @run).
2503
2521
2504 2003-03-02 Fernando Perez <fperez@colorado.edu>
2522 2003-03-02 Fernando Perez <fperez@colorado.edu>
2505
2523
2506 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2524 * IPython/Magic.py (Magic.magic_autocall): new magic to control
2507 the autocall option at runtime.
2525 the autocall option at runtime.
2508 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2526 (Magic.magic_dhist): changed self.user_ns to self.shell.user_ns
2509 across Magic.py to start separating Magic from InteractiveShell.
2527 across Magic.py to start separating Magic from InteractiveShell.
2510 (Magic._ofind): Fixed to return proper namespace for dotted
2528 (Magic._ofind): Fixed to return proper namespace for dotted
2511 names. Before, a dotted name would always return 'not currently
2529 names. Before, a dotted name would always return 'not currently
2512 defined', because it would find the 'parent'. s.x would be found,
2530 defined', because it would find the 'parent'. s.x would be found,
2513 but since 'x' isn't defined by itself, it would get confused.
2531 but since 'x' isn't defined by itself, it would get confused.
2514 (Magic.magic_run): Fixed pickling problems reported by Ralf
2532 (Magic.magic_run): Fixed pickling problems reported by Ralf
2515 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2533 Ahlbrink <RAhlbrink-AT-RosenInspection.net>. The fix was similar to
2516 that I'd used when Mike Heeter reported similar issues at the
2534 that I'd used when Mike Heeter reported similar issues at the
2517 top-level, but now for @run. It boils down to injecting the
2535 top-level, but now for @run. It boils down to injecting the
2518 namespace where code is being executed with something that looks
2536 namespace where code is being executed with something that looks
2519 enough like a module to fool pickle.dump(). Since a pickle stores
2537 enough like a module to fool pickle.dump(). Since a pickle stores
2520 a named reference to the importing module, we need this for
2538 a named reference to the importing module, we need this for
2521 pickles to save something sensible.
2539 pickles to save something sensible.
2522
2540
2523 * IPython/ipmaker.py (make_IPython): added an autocall option.
2541 * IPython/ipmaker.py (make_IPython): added an autocall option.
2524
2542
2525 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2543 * IPython/iplib.py (InteractiveShell._prefilter): reordered all of
2526 the auto-eval code. Now autocalling is an option, and the code is
2544 the auto-eval code. Now autocalling is an option, and the code is
2527 also vastly safer. There is no more eval() involved at all.
2545 also vastly safer. There is no more eval() involved at all.
2528
2546
2529 2003-03-01 Fernando Perez <fperez@colorado.edu>
2547 2003-03-01 Fernando Perez <fperez@colorado.edu>
2530
2548
2531 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2549 * IPython/Magic.py (Magic._ofind): Changed interface to return a
2532 dict with named keys instead of a tuple.
2550 dict with named keys instead of a tuple.
2533
2551
2534 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2552 * IPython: Started using CVS for IPython as of 0.2.15pre1.
2535
2553
2536 * setup.py (make_shortcut): Fixed message about directories
2554 * setup.py (make_shortcut): Fixed message about directories
2537 created during Windows installation (the directories were ok, just
2555 created during Windows installation (the directories were ok, just
2538 the printed message was misleading). Thanks to Chris Liechti
2556 the printed message was misleading). Thanks to Chris Liechti
2539 <cliechti-AT-gmx.net> for the heads up.
2557 <cliechti-AT-gmx.net> for the heads up.
2540
2558
2541 2003-02-21 Fernando Perez <fperez@colorado.edu>
2559 2003-02-21 Fernando Perez <fperez@colorado.edu>
2542
2560
2543 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2561 * IPython/iplib.py (InteractiveShell._prefilter): Fixed catching
2544 of ValueError exception when checking for auto-execution. This
2562 of ValueError exception when checking for auto-execution. This
2545 one is raised by things like Numeric arrays arr.flat when the
2563 one is raised by things like Numeric arrays arr.flat when the
2546 array is non-contiguous.
2564 array is non-contiguous.
2547
2565
2548 2003-01-31 Fernando Perez <fperez@colorado.edu>
2566 2003-01-31 Fernando Perez <fperez@colorado.edu>
2549
2567
2550 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2568 * IPython/genutils.py (SystemExec.bq): Fixed bug where bq would
2551 not return any value at all (even though the command would get
2569 not return any value at all (even though the command would get
2552 executed).
2570 executed).
2553 (xsys): Flush stdout right after printing the command to ensure
2571 (xsys): Flush stdout right after printing the command to ensure
2554 proper ordering of commands and command output in the total
2572 proper ordering of commands and command output in the total
2555 output.
2573 output.
2556 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2574 (SystemExec/xsys/bq): Switched the names of xsys/bq and
2557 system/getoutput as defaults. The old ones are kept for
2575 system/getoutput as defaults. The old ones are kept for
2558 compatibility reasons, so no code which uses this library needs
2576 compatibility reasons, so no code which uses this library needs
2559 changing.
2577 changing.
2560
2578
2561 2003-01-27 *** Released version 0.2.14
2579 2003-01-27 *** Released version 0.2.14
2562
2580
2563 2003-01-25 Fernando Perez <fperez@colorado.edu>
2581 2003-01-25 Fernando Perez <fperez@colorado.edu>
2564
2582
2565 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2583 * IPython/Magic.py (Magic.magic_edit): Fixed problem where
2566 functions defined in previous edit sessions could not be re-edited
2584 functions defined in previous edit sessions could not be re-edited
2567 (because the temp files were immediately removed). Now temp files
2585 (because the temp files were immediately removed). Now temp files
2568 are removed only at IPython's exit.
2586 are removed only at IPython's exit.
2569 (Magic.magic_run): Improved @run to perform shell-like expansions
2587 (Magic.magic_run): Improved @run to perform shell-like expansions
2570 on its arguments (~users and $VARS). With this, @run becomes more
2588 on its arguments (~users and $VARS). With this, @run becomes more
2571 like a normal command-line.
2589 like a normal command-line.
2572
2590
2573 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2591 * IPython/Shell.py (IPShellEmbed.__call__): Fixed a bunch of small
2574 bugs related to embedding and cleaned up that code. A fairly
2592 bugs related to embedding and cleaned up that code. A fairly
2575 important one was the impossibility to access the global namespace
2593 important one was the impossibility to access the global namespace
2576 through the embedded IPython (only local variables were visible).
2594 through the embedded IPython (only local variables were visible).
2577
2595
2578 2003-01-14 Fernando Perez <fperez@colorado.edu>
2596 2003-01-14 Fernando Perez <fperez@colorado.edu>
2579
2597
2580 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2598 * IPython/iplib.py (InteractiveShell._prefilter): Fixed
2581 auto-calling to be a bit more conservative. Now it doesn't get
2599 auto-calling to be a bit more conservative. Now it doesn't get
2582 triggered if any of '!=()<>' are in the rest of the input line, to
2600 triggered if any of '!=()<>' are in the rest of the input line, to
2583 allow comparing callables. Thanks to Alex for the heads up.
2601 allow comparing callables. Thanks to Alex for the heads up.
2584
2602
2585 2003-01-07 Fernando Perez <fperez@colorado.edu>
2603 2003-01-07 Fernando Perez <fperez@colorado.edu>
2586
2604
2587 * IPython/genutils.py (page): fixed estimation of the number of
2605 * IPython/genutils.py (page): fixed estimation of the number of
2588 lines in a string to be paged to simply count newlines. This
2606 lines in a string to be paged to simply count newlines. This
2589 prevents over-guessing due to embedded escape sequences. A better
2607 prevents over-guessing due to embedded escape sequences. A better
2590 long-term solution would involve stripping out the control chars
2608 long-term solution would involve stripping out the control chars
2591 for the count, but it's potentially so expensive I just don't
2609 for the count, but it's potentially so expensive I just don't
2592 think it's worth doing.
2610 think it's worth doing.
2593
2611
2594 2002-12-19 *** Released version 0.2.14pre50
2612 2002-12-19 *** Released version 0.2.14pre50
2595
2613
2596 2002-12-19 Fernando Perez <fperez@colorado.edu>
2614 2002-12-19 Fernando Perez <fperez@colorado.edu>
2597
2615
2598 * tools/release (version): Changed release scripts to inform
2616 * tools/release (version): Changed release scripts to inform
2599 Andrea and build a NEWS file with a list of recent changes.
2617 Andrea and build a NEWS file with a list of recent changes.
2600
2618
2601 * IPython/ColorANSI.py (__all__): changed terminal detection
2619 * IPython/ColorANSI.py (__all__): changed terminal detection
2602 code. Seems to work better for xterms without breaking
2620 code. Seems to work better for xterms without breaking
2603 konsole. Will need more testing to determine if WinXP and Mac OSX
2621 konsole. Will need more testing to determine if WinXP and Mac OSX
2604 also work ok.
2622 also work ok.
2605
2623
2606 2002-12-18 *** Released version 0.2.14pre49
2624 2002-12-18 *** Released version 0.2.14pre49
2607
2625
2608 2002-12-18 Fernando Perez <fperez@colorado.edu>
2626 2002-12-18 Fernando Perez <fperez@colorado.edu>
2609
2627
2610 * Docs: added new info about Mac OSX, from Andrea.
2628 * Docs: added new info about Mac OSX, from Andrea.
2611
2629
2612 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2630 * IPython/Gnuplot2.py (String): Added a String PlotItem class to
2613 allow direct plotting of python strings whose format is the same
2631 allow direct plotting of python strings whose format is the same
2614 of gnuplot data files.
2632 of gnuplot data files.
2615
2633
2616 2002-12-16 Fernando Perez <fperez@colorado.edu>
2634 2002-12-16 Fernando Perez <fperez@colorado.edu>
2617
2635
2618 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2636 * IPython/iplib.py (InteractiveShell.interact): fixed default (y)
2619 value of exit question to be acknowledged.
2637 value of exit question to be acknowledged.
2620
2638
2621 2002-12-03 Fernando Perez <fperez@colorado.edu>
2639 2002-12-03 Fernando Perez <fperez@colorado.edu>
2622
2640
2623 * IPython/ipmaker.py: removed generators, which had been added
2641 * IPython/ipmaker.py: removed generators, which had been added
2624 by mistake in an earlier debugging run. This was causing trouble
2642 by mistake in an earlier debugging run. This was causing trouble
2625 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2643 to users of python 2.1.x. Thanks to Abel Daniel <abli-AT-freemail.hu>
2626 for pointing this out.
2644 for pointing this out.
2627
2645
2628 2002-11-17 Fernando Perez <fperez@colorado.edu>
2646 2002-11-17 Fernando Perez <fperez@colorado.edu>
2629
2647
2630 * Manual: updated the Gnuplot section.
2648 * Manual: updated the Gnuplot section.
2631
2649
2632 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2650 * IPython/GnuplotRuntime.py: refactored a lot all this code, with
2633 a much better split of what goes in Runtime and what goes in
2651 a much better split of what goes in Runtime and what goes in
2634 Interactive.
2652 Interactive.
2635
2653
2636 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2654 * IPython/ipmaker.py: fixed bug where import_fail_info wasn't
2637 being imported from iplib.
2655 being imported from iplib.
2638
2656
2639 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2657 * IPython/GnuplotInteractive.py (magic_gpc): renamed @gp to @gpc
2640 for command-passing. Now the global Gnuplot instance is called
2658 for command-passing. Now the global Gnuplot instance is called
2641 'gp' instead of 'g', which was really a far too fragile and
2659 'gp' instead of 'g', which was really a far too fragile and
2642 common name.
2660 common name.
2643
2661
2644 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2662 * IPython/Gnuplot2.py (eps_fix_bbox): added this to fix broken
2645 bounding boxes generated by Gnuplot for square plots.
2663 bounding boxes generated by Gnuplot for square plots.
2646
2664
2647 * IPython/genutils.py (popkey): new function added. I should
2665 * IPython/genutils.py (popkey): new function added. I should
2648 suggest this on c.l.py as a dict method, it seems useful.
2666 suggest this on c.l.py as a dict method, it seems useful.
2649
2667
2650 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2668 * IPython/Gnuplot2.py (Gnuplot.plot): Overhauled plot and replot
2651 to transparently handle PostScript generation. MUCH better than
2669 to transparently handle PostScript generation. MUCH better than
2652 the previous plot_eps/replot_eps (which I removed now). The code
2670 the previous plot_eps/replot_eps (which I removed now). The code
2653 is also fairly clean and well documented now (including
2671 is also fairly clean and well documented now (including
2654 docstrings).
2672 docstrings).
2655
2673
2656 2002-11-13 Fernando Perez <fperez@colorado.edu>
2674 2002-11-13 Fernando Perez <fperez@colorado.edu>
2657
2675
2658 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2676 * IPython/Magic.py (Magic.magic_edit): fixed docstring
2659 (inconsistent with options).
2677 (inconsistent with options).
2660
2678
2661 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2679 * IPython/Gnuplot2.py (Gnuplot.hardcopy): hardcopy had been
2662 manually disabled, I don't know why. Fixed it.
2680 manually disabled, I don't know why. Fixed it.
2663 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2681 (Gnuplot._plot_eps): added new plot_eps/replot_eps to get directly
2664 eps output.
2682 eps output.
2665
2683
2666 2002-11-12 Fernando Perez <fperez@colorado.edu>
2684 2002-11-12 Fernando Perez <fperez@colorado.edu>
2667
2685
2668 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2686 * IPython/genutils.py (ask_yes_no): trap EOF and ^C so that they
2669 don't propagate up to caller. Fixes crash reported by François
2687 don't propagate up to caller. Fixes crash reported by François
2670 Pinard.
2688 Pinard.
2671
2689
2672 2002-11-09 Fernando Perez <fperez@colorado.edu>
2690 2002-11-09 Fernando Perez <fperez@colorado.edu>
2673
2691
2674 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2692 * IPython/ipmaker.py (make_IPython): fixed problem with writing
2675 history file for new users.
2693 history file for new users.
2676 (make_IPython): fixed bug where initial install would leave the
2694 (make_IPython): fixed bug where initial install would leave the
2677 user running in the .ipython dir.
2695 user running in the .ipython dir.
2678 (make_IPython): fixed bug where config dir .ipython would be
2696 (make_IPython): fixed bug where config dir .ipython would be
2679 created regardless of the given -ipythondir option. Thanks to Cory
2697 created regardless of the given -ipythondir option. Thanks to Cory
2680 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2698 Dodt <cdodt-AT-fcoe.k12.ca.us> for the bug report.
2681
2699
2682 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2700 * IPython/genutils.py (ask_yes_no): new function for asking yes/no
2683 type confirmations. Will need to use it in all of IPython's code
2701 type confirmations. Will need to use it in all of IPython's code
2684 consistently.
2702 consistently.
2685
2703
2686 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2704 * IPython/CrashHandler.py (CrashHandler.__call__): changed the
2687 context to print 31 lines instead of the default 5. This will make
2705 context to print 31 lines instead of the default 5. This will make
2688 the crash reports extremely detailed in case the problem is in
2706 the crash reports extremely detailed in case the problem is in
2689 libraries I don't have access to.
2707 libraries I don't have access to.
2690
2708
2691 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2709 * IPython/iplib.py (InteractiveShell.interact): changed the 'last
2692 line of defense' code to still crash, but giving users fair
2710 line of defense' code to still crash, but giving users fair
2693 warning. I don't want internal errors to go unreported: if there's
2711 warning. I don't want internal errors to go unreported: if there's
2694 an internal problem, IPython should crash and generate a full
2712 an internal problem, IPython should crash and generate a full
2695 report.
2713 report.
2696
2714
2697 2002-11-08 Fernando Perez <fperez@colorado.edu>
2715 2002-11-08 Fernando Perez <fperez@colorado.edu>
2698
2716
2699 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2717 * IPython/iplib.py (InteractiveShell.interact): added code to trap
2700 otherwise uncaught exceptions which can appear if people set
2718 otherwise uncaught exceptions which can appear if people set
2701 sys.stdout to something badly broken. Thanks to a crash report
2719 sys.stdout to something badly broken. Thanks to a crash report
2702 from henni-AT-mail.brainbot.com.
2720 from henni-AT-mail.brainbot.com.
2703
2721
2704 2002-11-04 Fernando Perez <fperez@colorado.edu>
2722 2002-11-04 Fernando Perez <fperez@colorado.edu>
2705
2723
2706 * IPython/iplib.py (InteractiveShell.interact): added
2724 * IPython/iplib.py (InteractiveShell.interact): added
2707 __IPYTHON__active to the builtins. It's a flag which goes on when
2725 __IPYTHON__active to the builtins. It's a flag which goes on when
2708 the interaction starts and goes off again when it stops. This
2726 the interaction starts and goes off again when it stops. This
2709 allows embedding code to detect being inside IPython. Before this
2727 allows embedding code to detect being inside IPython. Before this
2710 was done via __IPYTHON__, but that only shows that an IPython
2728 was done via __IPYTHON__, but that only shows that an IPython
2711 instance has been created.
2729 instance has been created.
2712
2730
2713 * IPython/Magic.py (Magic.magic_env): I realized that in a
2731 * IPython/Magic.py (Magic.magic_env): I realized that in a
2714 UserDict, instance.data holds the data as a normal dict. So I
2732 UserDict, instance.data holds the data as a normal dict. So I
2715 modified @env to return os.environ.data instead of rebuilding a
2733 modified @env to return os.environ.data instead of rebuilding a
2716 dict by hand.
2734 dict by hand.
2717
2735
2718 2002-11-02 Fernando Perez <fperez@colorado.edu>
2736 2002-11-02 Fernando Perez <fperez@colorado.edu>
2719
2737
2720 * IPython/genutils.py (warn): changed so that level 1 prints no
2738 * IPython/genutils.py (warn): changed so that level 1 prints no
2721 header. Level 2 is now the default (with 'WARNING' header, as
2739 header. Level 2 is now the default (with 'WARNING' header, as
2722 before). I think I tracked all places where changes were needed in
2740 before). I think I tracked all places where changes were needed in
2723 IPython, but outside code using the old level numbering may have
2741 IPython, but outside code using the old level numbering may have
2724 broken.
2742 broken.
2725
2743
2726 * IPython/iplib.py (InteractiveShell.runcode): added this to
2744 * IPython/iplib.py (InteractiveShell.runcode): added this to
2727 handle the tracebacks in SystemExit traps correctly. The previous
2745 handle the tracebacks in SystemExit traps correctly. The previous
2728 code (through interact) was printing more of the stack than
2746 code (through interact) was printing more of the stack than
2729 necessary, showing IPython internal code to the user.
2747 necessary, showing IPython internal code to the user.
2730
2748
2731 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2749 * IPython/UserConfig/ipythonrc.py: Made confirm_exit 1 by
2732 default. Now that the default at the confirmation prompt is yes,
2750 default. Now that the default at the confirmation prompt is yes,
2733 it's not so intrusive. François' argument that ipython sessions
2751 it's not so intrusive. François' argument that ipython sessions
2734 tend to be complex enough not to lose them from an accidental C-d,
2752 tend to be complex enough not to lose them from an accidental C-d,
2735 is a valid one.
2753 is a valid one.
2736
2754
2737 * IPython/iplib.py (InteractiveShell.interact): added a
2755 * IPython/iplib.py (InteractiveShell.interact): added a
2738 showtraceback() call to the SystemExit trap, and modified the exit
2756 showtraceback() call to the SystemExit trap, and modified the exit
2739 confirmation to have yes as the default.
2757 confirmation to have yes as the default.
2740
2758
2741 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2759 * IPython/UserConfig/ipythonrc.py: removed 'session' option from
2742 this file. It's been gone from the code for a long time, this was
2760 this file. It's been gone from the code for a long time, this was
2743 simply leftover junk.
2761 simply leftover junk.
2744
2762
2745 2002-11-01 Fernando Perez <fperez@colorado.edu>
2763 2002-11-01 Fernando Perez <fperez@colorado.edu>
2746
2764
2747 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2765 * IPython/UserConfig/ipythonrc.py: new confirm_exit option
2748 added. If set, IPython now traps EOF and asks for
2766 added. If set, IPython now traps EOF and asks for
2749 confirmation. After a request by François Pinard.
2767 confirmation. After a request by François Pinard.
2750
2768
2751 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2769 * IPython/Magic.py (Magic.magic_Exit): New @Exit and @Quit instead
2752 of @abort, and with a new (better) mechanism for handling the
2770 of @abort, and with a new (better) mechanism for handling the
2753 exceptions.
2771 exceptions.
2754
2772
2755 2002-10-27 Fernando Perez <fperez@colorado.edu>
2773 2002-10-27 Fernando Perez <fperez@colorado.edu>
2756
2774
2757 * IPython/usage.py (__doc__): updated the --help information and
2775 * IPython/usage.py (__doc__): updated the --help information and
2758 the ipythonrc file to indicate that -log generates
2776 the ipythonrc file to indicate that -log generates
2759 ./ipython.log. Also fixed the corresponding info in @logstart.
2777 ./ipython.log. Also fixed the corresponding info in @logstart.
2760 This and several other fixes in the manuals thanks to reports by
2778 This and several other fixes in the manuals thanks to reports by
2761 François Pinard <pinard-AT-iro.umontreal.ca>.
2779 François Pinard <pinard-AT-iro.umontreal.ca>.
2762
2780
2763 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2781 * IPython/Logger.py (Logger.switch_log): Fixed error message to
2764 refer to @logstart (instead of @log, which doesn't exist).
2782 refer to @logstart (instead of @log, which doesn't exist).
2765
2783
2766 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2784 * IPython/iplib.py (InteractiveShell._prefilter): fixed
2767 AttributeError crash. Thanks to Christopher Armstrong
2785 AttributeError crash. Thanks to Christopher Armstrong
2768 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2786 <radix-AT-twistedmatrix.com> for the report/fix. This bug had been
2769 introduced recently (in 0.2.14pre37) with the fix to the eval
2787 introduced recently (in 0.2.14pre37) with the fix to the eval
2770 problem mentioned below.
2788 problem mentioned below.
2771
2789
2772 2002-10-17 Fernando Perez <fperez@colorado.edu>
2790 2002-10-17 Fernando Perez <fperez@colorado.edu>
2773
2791
2774 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2792 * IPython/ConfigLoader.py (ConfigLoader.load): Fixes for Windows
2775 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2793 installation. Thanks to Leonardo Santagada <retype-AT-terra.com.br>.
2776
2794
2777 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2795 * IPython/iplib.py (InteractiveShell._prefilter): Many changes to
2778 this function to fix a problem reported by Alex Schmolck. He saw
2796 this function to fix a problem reported by Alex Schmolck. He saw
2779 it with list comprehensions and generators, which were getting
2797 it with list comprehensions and generators, which were getting
2780 called twice. The real problem was an 'eval' call in testing for
2798 called twice. The real problem was an 'eval' call in testing for
2781 automagic which was evaluating the input line silently.
2799 automagic which was evaluating the input line silently.
2782
2800
2783 This is a potentially very nasty bug, if the input has side
2801 This is a potentially very nasty bug, if the input has side
2784 effects which must not be repeated. The code is much cleaner now,
2802 effects which must not be repeated. The code is much cleaner now,
2785 without any blanket 'except' left and with a regexp test for
2803 without any blanket 'except' left and with a regexp test for
2786 actual function names.
2804 actual function names.
2787
2805
2788 But an eval remains, which I'm not fully comfortable with. I just
2806 But an eval remains, which I'm not fully comfortable with. I just
2789 don't know how to find out if an expression could be a callable in
2807 don't know how to find out if an expression could be a callable in
2790 the user's namespace without doing an eval on the string. However
2808 the user's namespace without doing an eval on the string. However
2791 that string is now much more strictly checked so that no code
2809 that string is now much more strictly checked so that no code
2792 slips by, so the eval should only happen for things that can
2810 slips by, so the eval should only happen for things that can
2793 really be only function/method names.
2811 really be only function/method names.
2794
2812
2795 2002-10-15 Fernando Perez <fperez@colorado.edu>
2813 2002-10-15 Fernando Perez <fperez@colorado.edu>
2796
2814
2797 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2815 * Updated LyX to 1.2.1 so I can work on the docs again. Added Mac
2798 OSX information to main manual, removed README_Mac_OSX file from
2816 OSX information to main manual, removed README_Mac_OSX file from
2799 distribution. Also updated credits for recent additions.
2817 distribution. Also updated credits for recent additions.
2800
2818
2801 2002-10-10 Fernando Perez <fperez@colorado.edu>
2819 2002-10-10 Fernando Perez <fperez@colorado.edu>
2802
2820
2803 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2821 * README_Mac_OSX: Added a README for Mac OSX users for fixing
2804 terminal-related issues. Many thanks to Andrea Riciputi
2822 terminal-related issues. Many thanks to Andrea Riciputi
2805 <andrea.riciputi-AT-libero.it> for writing it.
2823 <andrea.riciputi-AT-libero.it> for writing it.
2806
2824
2807 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2825 * IPython/UserConfig/ipythonrc.py: Fixes to various small issues,
2808 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2826 thanks to Thorsten Kampe <thorsten-AT-thorstenkampe.de>.
2809
2827
2810 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2828 * setup.py (make_shortcut): Fixes for Windows installation. Thanks
2811 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2829 to Fredrik Kant <fredrik.kant-AT-front.com> and Syver Enstad
2812 <syver-en-AT-online.no> who both submitted patches for this problem.
2830 <syver-en-AT-online.no> who both submitted patches for this problem.
2813
2831
2814 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2832 * IPython/iplib.py (InteractiveShell.embed_mainloop): Patch for
2815 global embedding to make sure that things don't overwrite user
2833 global embedding to make sure that things don't overwrite user
2816 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2834 globals accidentally. Thanks to Richard <rxe-AT-renre-europe.com>
2817
2835
2818 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2836 * IPython/Gnuplot2.py (gp): Patch for Gnuplot.py 1.6
2819 compatibility. Thanks to Hayden Callow
2837 compatibility. Thanks to Hayden Callow
2820 <h.callow-AT-elec.canterbury.ac.nz>
2838 <h.callow-AT-elec.canterbury.ac.nz>
2821
2839
2822 2002-10-04 Fernando Perez <fperez@colorado.edu>
2840 2002-10-04 Fernando Perez <fperez@colorado.edu>
2823
2841
2824 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2842 * IPython/Gnuplot2.py (PlotItem): Added 'index' option for
2825 Gnuplot.File objects.
2843 Gnuplot.File objects.
2826
2844
2827 2002-07-23 Fernando Perez <fperez@colorado.edu>
2845 2002-07-23 Fernando Perez <fperez@colorado.edu>
2828
2846
2829 * IPython/genutils.py (timing): Added timings() and timing() for
2847 * IPython/genutils.py (timing): Added timings() and timing() for
2830 quick access to the most commonly needed data, the execution
2848 quick access to the most commonly needed data, the execution
2831 times. Old timing() renamed to timings_out().
2849 times. Old timing() renamed to timings_out().
2832
2850
2833 2002-07-18 Fernando Perez <fperez@colorado.edu>
2851 2002-07-18 Fernando Perez <fperez@colorado.edu>
2834
2852
2835 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2853 * IPython/Shell.py (IPShellEmbed.restore_system_completer): fixed
2836 bug with nested instances disrupting the parent's tab completion.
2854 bug with nested instances disrupting the parent's tab completion.
2837
2855
2838 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2856 * IPython/iplib.py (all_completions): Added Alex Schmolck's
2839 all_completions code to begin the emacs integration.
2857 all_completions code to begin the emacs integration.
2840
2858
2841 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2859 * IPython/Gnuplot2.py (zip_items): Added optional 'titles'
2842 argument to allow titling individual arrays when plotting.
2860 argument to allow titling individual arrays when plotting.
2843
2861
2844 2002-07-15 Fernando Perez <fperez@colorado.edu>
2862 2002-07-15 Fernando Perez <fperez@colorado.edu>
2845
2863
2846 * setup.py (make_shortcut): changed to retrieve the value of
2864 * setup.py (make_shortcut): changed to retrieve the value of
2847 'Program Files' directory from the registry (this value changes in
2865 'Program Files' directory from the registry (this value changes in
2848 non-english versions of Windows). Thanks to Thomas Fanslau
2866 non-english versions of Windows). Thanks to Thomas Fanslau
2849 <tfanslau-AT-gmx.de> for the report.
2867 <tfanslau-AT-gmx.de> for the report.
2850
2868
2851 2002-07-10 Fernando Perez <fperez@colorado.edu>
2869 2002-07-10 Fernando Perez <fperez@colorado.edu>
2852
2870
2853 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2871 * IPython/ultraTB.py (VerboseTB.debugger): enabled workaround for
2854 a bug in pdb, which crashes if a line with only whitespace is
2872 a bug in pdb, which crashes if a line with only whitespace is
2855 entered. Bug report submitted to sourceforge.
2873 entered. Bug report submitted to sourceforge.
2856
2874
2857 2002-07-09 Fernando Perez <fperez@colorado.edu>
2875 2002-07-09 Fernando Perez <fperez@colorado.edu>
2858
2876
2859 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2877 * IPython/ultraTB.py (VerboseTB.nullrepr): fixed rare crash when
2860 reporting exceptions (it's a bug in inspect.py, I just set a
2878 reporting exceptions (it's a bug in inspect.py, I just set a
2861 workaround).
2879 workaround).
2862
2880
2863 2002-07-08 Fernando Perez <fperez@colorado.edu>
2881 2002-07-08 Fernando Perez <fperez@colorado.edu>
2864
2882
2865 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2883 * IPython/iplib.py (InteractiveShell.__init__): fixed reference to
2866 __IPYTHON__ in __builtins__ to show up in user_ns.
2884 __IPYTHON__ in __builtins__ to show up in user_ns.
2867
2885
2868 2002-07-03 Fernando Perez <fperez@colorado.edu>
2886 2002-07-03 Fernando Perez <fperez@colorado.edu>
2869
2887
2870 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2888 * IPython/GnuplotInteractive.py (magic_gp_set_default): changed
2871 name from @gp_set_instance to @gp_set_default.
2889 name from @gp_set_instance to @gp_set_default.
2872
2890
2873 * IPython/ipmaker.py (make_IPython): default editor value set to
2891 * IPython/ipmaker.py (make_IPython): default editor value set to
2874 '0' (a string), to match the rc file. Otherwise will crash when
2892 '0' (a string), to match the rc file. Otherwise will crash when
2875 .strip() is called on it.
2893 .strip() is called on it.
2876
2894
2877
2895
2878 2002-06-28 Fernando Perez <fperez@colorado.edu>
2896 2002-06-28 Fernando Perez <fperez@colorado.edu>
2879
2897
2880 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2898 * IPython/iplib.py (InteractiveShell.safe_execfile): fix importing
2881 of files in current directory when a file is executed via
2899 of files in current directory when a file is executed via
2882 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2900 @run. Patch also by RA <ralf_ahlbrink-AT-web.de>.
2883
2901
2884 * setup.py (manfiles): fix for rpm builds, submitted by RA
2902 * setup.py (manfiles): fix for rpm builds, submitted by RA
2885 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2903 <ralf_ahlbrink-AT-web.de>. Now we have RPMs!
2886
2904
2887 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2905 * IPython/ipmaker.py (make_IPython): fixed lookup of default
2888 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2906 editor when set to '0'. Problem was, '0' evaluates to True (it's a
2889 string!). A. Schmolck caught this one.
2907 string!). A. Schmolck caught this one.
2890
2908
2891 2002-06-27 Fernando Perez <fperez@colorado.edu>
2909 2002-06-27 Fernando Perez <fperez@colorado.edu>
2892
2910
2893 * IPython/ipmaker.py (make_IPython): fixed bug when running user
2911 * IPython/ipmaker.py (make_IPython): fixed bug when running user
2894 defined files at the cmd line. __name__ wasn't being set to
2912 defined files at the cmd line. __name__ wasn't being set to
2895 __main__.
2913 __main__.
2896
2914
2897 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
2915 * IPython/Gnuplot2.py (zip_items): improved it so it can plot also
2898 regular lists and tuples besides Numeric arrays.
2916 regular lists and tuples besides Numeric arrays.
2899
2917
2900 * IPython/Prompts.py (CachedOutput.__call__): Added output
2918 * IPython/Prompts.py (CachedOutput.__call__): Added output
2901 supression for input ending with ';'. Similar to Mathematica and
2919 supression for input ending with ';'. Similar to Mathematica and
2902 Matlab. The _* vars and Out[] list are still updated, just like
2920 Matlab. The _* vars and Out[] list are still updated, just like
2903 Mathematica behaves.
2921 Mathematica behaves.
2904
2922
2905 2002-06-25 Fernando Perez <fperez@colorado.edu>
2923 2002-06-25 Fernando Perez <fperez@colorado.edu>
2906
2924
2907 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
2925 * IPython/ConfigLoader.py (ConfigLoader.load): fixed checking of
2908 .ini extensions for profiels under Windows.
2926 .ini extensions for profiels under Windows.
2909
2927
2910 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
2928 * IPython/OInspect.py (Inspector.pinfo): improved alignment of
2911 string form. Fix contributed by Alexander Schmolck
2929 string form. Fix contributed by Alexander Schmolck
2912 <a.schmolck-AT-gmx.net>
2930 <a.schmolck-AT-gmx.net>
2913
2931
2914 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
2932 * IPython/GnuplotRuntime.py (gp_new): new function. Returns a
2915 pre-configured Gnuplot instance.
2933 pre-configured Gnuplot instance.
2916
2934
2917 2002-06-21 Fernando Perez <fperez@colorado.edu>
2935 2002-06-21 Fernando Perez <fperez@colorado.edu>
2918
2936
2919 * IPython/numutils.py (exp_safe): new function, works around the
2937 * IPython/numutils.py (exp_safe): new function, works around the
2920 underflow problems in Numeric.
2938 underflow problems in Numeric.
2921 (log2): New fn. Safe log in base 2: returns exact integer answer
2939 (log2): New fn. Safe log in base 2: returns exact integer answer
2922 for exact integer powers of 2.
2940 for exact integer powers of 2.
2923
2941
2924 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
2942 * IPython/Magic.py (get_py_filename): fixed it not expanding '~'
2925 properly.
2943 properly.
2926
2944
2927 2002-06-20 Fernando Perez <fperez@colorado.edu>
2945 2002-06-20 Fernando Perez <fperez@colorado.edu>
2928
2946
2929 * IPython/genutils.py (timing): new function like
2947 * IPython/genutils.py (timing): new function like
2930 Mathematica's. Similar to time_test, but returns more info.
2948 Mathematica's. Similar to time_test, but returns more info.
2931
2949
2932 2002-06-18 Fernando Perez <fperez@colorado.edu>
2950 2002-06-18 Fernando Perez <fperez@colorado.edu>
2933
2951
2934 * IPython/Magic.py (Magic.magic_save): modified @save and @r
2952 * IPython/Magic.py (Magic.magic_save): modified @save and @r
2935 according to Mike Heeter's suggestions.
2953 according to Mike Heeter's suggestions.
2936
2954
2937 2002-06-16 Fernando Perez <fperez@colorado.edu>
2955 2002-06-16 Fernando Perez <fperez@colorado.edu>
2938
2956
2939 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
2957 * IPython/GnuplotRuntime.py: Massive overhaul to the Gnuplot
2940 system. GnuplotMagic is gone as a user-directory option. New files
2958 system. GnuplotMagic is gone as a user-directory option. New files
2941 make it easier to use all the gnuplot stuff both from external
2959 make it easier to use all the gnuplot stuff both from external
2942 programs as well as from IPython. Had to rewrite part of
2960 programs as well as from IPython. Had to rewrite part of
2943 hardcopy() b/c of a strange bug: often the ps files simply don't
2961 hardcopy() b/c of a strange bug: often the ps files simply don't
2944 get created, and require a repeat of the command (often several
2962 get created, and require a repeat of the command (often several
2945 times).
2963 times).
2946
2964
2947 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
2965 * IPython/ultraTB.py (AutoFormattedTB.__call__): changed to
2948 resolve output channel at call time, so that if sys.stderr has
2966 resolve output channel at call time, so that if sys.stderr has
2949 been redirected by user this gets honored.
2967 been redirected by user this gets honored.
2950
2968
2951 2002-06-13 Fernando Perez <fperez@colorado.edu>
2969 2002-06-13 Fernando Perez <fperez@colorado.edu>
2952
2970
2953 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
2971 * IPython/Shell.py (IPShell.__init__): Changed IPythonShell to
2954 IPShell. Kept a copy with the old names to avoid breaking people's
2972 IPShell. Kept a copy with the old names to avoid breaking people's
2955 embedded code.
2973 embedded code.
2956
2974
2957 * IPython/ipython: simplified it to the bare minimum after
2975 * IPython/ipython: simplified it to the bare minimum after
2958 Holger's suggestions. Added info about how to use it in
2976 Holger's suggestions. Added info about how to use it in
2959 PYTHONSTARTUP.
2977 PYTHONSTARTUP.
2960
2978
2961 * IPython/Shell.py (IPythonShell): changed the options passing
2979 * IPython/Shell.py (IPythonShell): changed the options passing
2962 from a string with funky %s replacements to a straight list. Maybe
2980 from a string with funky %s replacements to a straight list. Maybe
2963 a bit more typing, but it follows sys.argv conventions, so there's
2981 a bit more typing, but it follows sys.argv conventions, so there's
2964 less special-casing to remember.
2982 less special-casing to remember.
2965
2983
2966 2002-06-12 Fernando Perez <fperez@colorado.edu>
2984 2002-06-12 Fernando Perez <fperez@colorado.edu>
2967
2985
2968 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
2986 * IPython/Magic.py (Magic.magic_r): new magic auto-repeat
2969 command. Thanks to a suggestion by Mike Heeter.
2987 command. Thanks to a suggestion by Mike Heeter.
2970 (Magic.magic_pfile): added behavior to look at filenames if given
2988 (Magic.magic_pfile): added behavior to look at filenames if given
2971 arg is not a defined object.
2989 arg is not a defined object.
2972 (Magic.magic_save): New @save function to save code snippets. Also
2990 (Magic.magic_save): New @save function to save code snippets. Also
2973 a Mike Heeter idea.
2991 a Mike Heeter idea.
2974
2992
2975 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
2993 * IPython/UserConfig/GnuplotMagic.py (plot): Improvements to
2976 plot() and replot(). Much more convenient now, especially for
2994 plot() and replot(). Much more convenient now, especially for
2977 interactive use.
2995 interactive use.
2978
2996
2979 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
2997 * IPython/Magic.py (Magic.magic_run): Added .py automatically to
2980 filenames.
2998 filenames.
2981
2999
2982 2002-06-02 Fernando Perez <fperez@colorado.edu>
3000 2002-06-02 Fernando Perez <fperez@colorado.edu>
2983
3001
2984 * IPython/Struct.py (Struct.__init__): modified to admit
3002 * IPython/Struct.py (Struct.__init__): modified to admit
2985 initialization via another struct.
3003 initialization via another struct.
2986
3004
2987 * IPython/genutils.py (SystemExec.__init__): New stateful
3005 * IPython/genutils.py (SystemExec.__init__): New stateful
2988 interface to xsys and bq. Useful for writing system scripts.
3006 interface to xsys and bq. Useful for writing system scripts.
2989
3007
2990 2002-05-30 Fernando Perez <fperez@colorado.edu>
3008 2002-05-30 Fernando Perez <fperez@colorado.edu>
2991
3009
2992 * MANIFEST.in: Changed docfile selection to exclude all the lyx
3010 * MANIFEST.in: Changed docfile selection to exclude all the lyx
2993 documents. This will make the user download smaller (it's getting
3011 documents. This will make the user download smaller (it's getting
2994 too big).
3012 too big).
2995
3013
2996 2002-05-29 Fernando Perez <fperez@colorado.edu>
3014 2002-05-29 Fernando Perez <fperez@colorado.edu>
2997
3015
2998 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
3016 * IPython/iplib.py (_FakeModule.__init__): New class introduced to
2999 fix problems with shelve and pickle. Seems to work, but I don't
3017 fix problems with shelve and pickle. Seems to work, but I don't
3000 know if corner cases break it. Thanks to Mike Heeter
3018 know if corner cases break it. Thanks to Mike Heeter
3001 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3019 <korora-AT-SDF.LONESTAR.ORG> for the bug reports and test cases.
3002
3020
3003 2002-05-24 Fernando Perez <fperez@colorado.edu>
3021 2002-05-24 Fernando Perez <fperez@colorado.edu>
3004
3022
3005 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3023 * IPython/Magic.py (Macro.__init__): fixed magics embedded in
3006 macros having broken.
3024 macros having broken.
3007
3025
3008 2002-05-21 Fernando Perez <fperez@colorado.edu>
3026 2002-05-21 Fernando Perez <fperez@colorado.edu>
3009
3027
3010 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3028 * IPython/Magic.py (Magic.magic_logstart): fixed recently
3011 introduced logging bug: all history before logging started was
3029 introduced logging bug: all history before logging started was
3012 being written one character per line! This came from the redesign
3030 being written one character per line! This came from the redesign
3013 of the input history as a special list which slices to strings,
3031 of the input history as a special list which slices to strings,
3014 not to lists.
3032 not to lists.
3015
3033
3016 2002-05-20 Fernando Perez <fperez@colorado.edu>
3034 2002-05-20 Fernando Perez <fperez@colorado.edu>
3017
3035
3018 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3036 * IPython/Prompts.py (CachedOutput.__init__): made the color table
3019 be an attribute of all classes in this module. The design of these
3037 be an attribute of all classes in this module. The design of these
3020 classes needs some serious overhauling.
3038 classes needs some serious overhauling.
3021
3039
3022 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3040 * IPython/DPyGetOpt.py (DPyGetOpt.setPosixCompliance): fixed bug
3023 which was ignoring '_' in option names.
3041 which was ignoring '_' in option names.
3024
3042
3025 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3043 * IPython/ultraTB.py (FormattedTB.__init__): Changed
3026 'Verbose_novars' to 'Context' and made it the new default. It's a
3044 'Verbose_novars' to 'Context' and made it the new default. It's a
3027 bit more readable and also safer than verbose.
3045 bit more readable and also safer than verbose.
3028
3046
3029 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3047 * IPython/PyColorize.py (Parser.__call__): Fixed coloring of
3030 triple-quoted strings.
3048 triple-quoted strings.
3031
3049
3032 * IPython/OInspect.py (__all__): new module exposing the object
3050 * IPython/OInspect.py (__all__): new module exposing the object
3033 introspection facilities. Now the corresponding magics are dummy
3051 introspection facilities. Now the corresponding magics are dummy
3034 wrappers around this. Having this module will make it much easier
3052 wrappers around this. Having this module will make it much easier
3035 to put these functions into our modified pdb.
3053 to put these functions into our modified pdb.
3036 This new object inspector system uses the new colorizing module,
3054 This new object inspector system uses the new colorizing module,
3037 so source code and other things are nicely syntax highlighted.
3055 so source code and other things are nicely syntax highlighted.
3038
3056
3039 2002-05-18 Fernando Perez <fperez@colorado.edu>
3057 2002-05-18 Fernando Perez <fperez@colorado.edu>
3040
3058
3041 * IPython/ColorANSI.py: Split the coloring tools into a separate
3059 * IPython/ColorANSI.py: Split the coloring tools into a separate
3042 module so I can use them in other code easier (they were part of
3060 module so I can use them in other code easier (they were part of
3043 ultraTB).
3061 ultraTB).
3044
3062
3045 2002-05-17 Fernando Perez <fperez@colorado.edu>
3063 2002-05-17 Fernando Perez <fperez@colorado.edu>
3046
3064
3047 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3065 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3048 fixed it to set the global 'g' also to the called instance, as
3066 fixed it to set the global 'g' also to the called instance, as
3049 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3067 long as 'g' was still a gnuplot instance (so it doesn't overwrite
3050 user's 'g' variables).
3068 user's 'g' variables).
3051
3069
3052 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3070 * IPython/iplib.py (InteractiveShell.__init__): Added In/Out
3053 global variables (aliases to _ih,_oh) so that users which expect
3071 global variables (aliases to _ih,_oh) so that users which expect
3054 In[5] or Out[7] to work aren't unpleasantly surprised.
3072 In[5] or Out[7] to work aren't unpleasantly surprised.
3055 (InputList.__getslice__): new class to allow executing slices of
3073 (InputList.__getslice__): new class to allow executing slices of
3056 input history directly. Very simple class, complements the use of
3074 input history directly. Very simple class, complements the use of
3057 macros.
3075 macros.
3058
3076
3059 2002-05-16 Fernando Perez <fperez@colorado.edu>
3077 2002-05-16 Fernando Perez <fperez@colorado.edu>
3060
3078
3061 * setup.py (docdirbase): make doc directory be just doc/IPython
3079 * setup.py (docdirbase): make doc directory be just doc/IPython
3062 without version numbers, it will reduce clutter for users.
3080 without version numbers, it will reduce clutter for users.
3063
3081
3064 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3082 * IPython/Magic.py (Magic.magic_run): Add explicit local dict to
3065 execfile call to prevent possible memory leak. See for details:
3083 execfile call to prevent possible memory leak. See for details:
3066 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3084 http://mail.python.org/pipermail/python-list/2002-February/088476.html
3067
3085
3068 2002-05-15 Fernando Perez <fperez@colorado.edu>
3086 2002-05-15 Fernando Perez <fperez@colorado.edu>
3069
3087
3070 * IPython/Magic.py (Magic.magic_psource): made the object
3088 * IPython/Magic.py (Magic.magic_psource): made the object
3071 introspection names be more standard: pdoc, pdef, pfile and
3089 introspection names be more standard: pdoc, pdef, pfile and
3072 psource. They all print/page their output, and it makes
3090 psource. They all print/page their output, and it makes
3073 remembering them easier. Kept old names for compatibility as
3091 remembering them easier. Kept old names for compatibility as
3074 aliases.
3092 aliases.
3075
3093
3076 2002-05-14 Fernando Perez <fperez@colorado.edu>
3094 2002-05-14 Fernando Perez <fperez@colorado.edu>
3077
3095
3078 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3096 * IPython/UserConfig/GnuplotMagic.py: I think I finally understood
3079 what the mouse problem was. The trick is to use gnuplot with temp
3097 what the mouse problem was. The trick is to use gnuplot with temp
3080 files and NOT with pipes (for data communication), because having
3098 files and NOT with pipes (for data communication), because having
3081 both pipes and the mouse on is bad news.
3099 both pipes and the mouse on is bad news.
3082
3100
3083 2002-05-13 Fernando Perez <fperez@colorado.edu>
3101 2002-05-13 Fernando Perez <fperez@colorado.edu>
3084
3102
3085 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3103 * IPython/Magic.py (Magic._ofind): fixed namespace order search
3086 bug. Information would be reported about builtins even when
3104 bug. Information would be reported about builtins even when
3087 user-defined functions overrode them.
3105 user-defined functions overrode them.
3088
3106
3089 2002-05-11 Fernando Perez <fperez@colorado.edu>
3107 2002-05-11 Fernando Perez <fperez@colorado.edu>
3090
3108
3091 * IPython/__init__.py (__all__): removed FlexCompleter from
3109 * IPython/__init__.py (__all__): removed FlexCompleter from
3092 __all__ so that things don't fail in platforms without readline.
3110 __all__ so that things don't fail in platforms without readline.
3093
3111
3094 2002-05-10 Fernando Perez <fperez@colorado.edu>
3112 2002-05-10 Fernando Perez <fperez@colorado.edu>
3095
3113
3096 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3114 * IPython/__init__.py (__all__): removed numutils from __all__ b/c
3097 it requires Numeric, effectively making Numeric a dependency for
3115 it requires Numeric, effectively making Numeric a dependency for
3098 IPython.
3116 IPython.
3099
3117
3100 * Released 0.2.13
3118 * Released 0.2.13
3101
3119
3102 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3120 * IPython/Magic.py (Magic.magic_prun): big overhaul to the
3103 profiler interface. Now all the major options from the profiler
3121 profiler interface. Now all the major options from the profiler
3104 module are directly supported in IPython, both for single
3122 module are directly supported in IPython, both for single
3105 expressions (@prun) and for full programs (@run -p).
3123 expressions (@prun) and for full programs (@run -p).
3106
3124
3107 2002-05-09 Fernando Perez <fperez@colorado.edu>
3125 2002-05-09 Fernando Perez <fperez@colorado.edu>
3108
3126
3109 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3127 * IPython/Magic.py (Magic.magic_doc): fixed to show docstrings of
3110 magic properly formatted for screen.
3128 magic properly formatted for screen.
3111
3129
3112 * setup.py (make_shortcut): Changed things to put pdf version in
3130 * setup.py (make_shortcut): Changed things to put pdf version in
3113 doc/ instead of doc/manual (had to change lyxport a bit).
3131 doc/ instead of doc/manual (had to change lyxport a bit).
3114
3132
3115 * IPython/Magic.py (Profile.string_stats): made profile runs go
3133 * IPython/Magic.py (Profile.string_stats): made profile runs go
3116 through pager (they are long and a pager allows searching, saving,
3134 through pager (they are long and a pager allows searching, saving,
3117 etc.)
3135 etc.)
3118
3136
3119 2002-05-08 Fernando Perez <fperez@colorado.edu>
3137 2002-05-08 Fernando Perez <fperez@colorado.edu>
3120
3138
3121 * Released 0.2.12
3139 * Released 0.2.12
3122
3140
3123 2002-05-06 Fernando Perez <fperez@colorado.edu>
3141 2002-05-06 Fernando Perez <fperez@colorado.edu>
3124
3142
3125 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3143 * IPython/Magic.py (Magic.magic_hist): small bug fixed (recently
3126 introduced); 'hist n1 n2' was broken.
3144 introduced); 'hist n1 n2' was broken.
3127 (Magic.magic_pdb): added optional on/off arguments to @pdb
3145 (Magic.magic_pdb): added optional on/off arguments to @pdb
3128 (Magic.magic_run): added option -i to @run, which executes code in
3146 (Magic.magic_run): added option -i to @run, which executes code in
3129 the IPython namespace instead of a clean one. Also added @irun as
3147 the IPython namespace instead of a clean one. Also added @irun as
3130 an alias to @run -i.
3148 an alias to @run -i.
3131
3149
3132 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3150 * IPython/UserConfig/GnuplotMagic.py (magic_gp_set_instance):
3133 fixed (it didn't really do anything, the namespaces were wrong).
3151 fixed (it didn't really do anything, the namespaces were wrong).
3134
3152
3135 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3153 * IPython/Debugger.py (__init__): Added workaround for python 2.1
3136
3154
3137 * IPython/__init__.py (__all__): Fixed package namespace, now
3155 * IPython/__init__.py (__all__): Fixed package namespace, now
3138 'import IPython' does give access to IPython.<all> as
3156 'import IPython' does give access to IPython.<all> as
3139 expected. Also renamed __release__ to Release.
3157 expected. Also renamed __release__ to Release.
3140
3158
3141 * IPython/Debugger.py (__license__): created new Pdb class which
3159 * IPython/Debugger.py (__license__): created new Pdb class which
3142 functions like a drop-in for the normal pdb.Pdb but does NOT
3160 functions like a drop-in for the normal pdb.Pdb but does NOT
3143 import readline by default. This way it doesn't muck up IPython's
3161 import readline by default. This way it doesn't muck up IPython's
3144 readline handling, and now tab-completion finally works in the
3162 readline handling, and now tab-completion finally works in the
3145 debugger -- sort of. It completes things globally visible, but the
3163 debugger -- sort of. It completes things globally visible, but the
3146 completer doesn't track the stack as pdb walks it. That's a bit
3164 completer doesn't track the stack as pdb walks it. That's a bit
3147 tricky, and I'll have to implement it later.
3165 tricky, and I'll have to implement it later.
3148
3166
3149 2002-05-05 Fernando Perez <fperez@colorado.edu>
3167 2002-05-05 Fernando Perez <fperez@colorado.edu>
3150
3168
3151 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3169 * IPython/Magic.py (Magic.magic_oinfo): fixed formatting bug for
3152 magic docstrings when printed via ? (explicit \'s were being
3170 magic docstrings when printed via ? (explicit \'s were being
3153 printed).
3171 printed).
3154
3172
3155 * IPython/ipmaker.py (make_IPython): fixed namespace
3173 * IPython/ipmaker.py (make_IPython): fixed namespace
3156 identification bug. Now variables loaded via logs or command-line
3174 identification bug. Now variables loaded via logs or command-line
3157 files are recognized in the interactive namespace by @who.
3175 files are recognized in the interactive namespace by @who.
3158
3176
3159 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3177 * IPython/iplib.py (InteractiveShell.safe_execfile): Fixed bug in
3160 log replay system stemming from the string form of Structs.
3178 log replay system stemming from the string form of Structs.
3161
3179
3162 * IPython/Magic.py (Macro.__init__): improved macros to properly
3180 * IPython/Magic.py (Macro.__init__): improved macros to properly
3163 handle magic commands in them.
3181 handle magic commands in them.
3164 (Magic.magic_logstart): usernames are now expanded so 'logstart
3182 (Magic.magic_logstart): usernames are now expanded so 'logstart
3165 ~/mylog' now works.
3183 ~/mylog' now works.
3166
3184
3167 * IPython/iplib.py (complete): fixed bug where paths starting with
3185 * IPython/iplib.py (complete): fixed bug where paths starting with
3168 '/' would be completed as magic names.
3186 '/' would be completed as magic names.
3169
3187
3170 2002-05-04 Fernando Perez <fperez@colorado.edu>
3188 2002-05-04 Fernando Perez <fperez@colorado.edu>
3171
3189
3172 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3190 * IPython/Magic.py (Magic.magic_run): added options -p and -f to
3173 allow running full programs under the profiler's control.
3191 allow running full programs under the profiler's control.
3174
3192
3175 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3193 * IPython/ultraTB.py (FormattedTB.__init__): Added Verbose_novars
3176 mode to report exceptions verbosely but without formatting
3194 mode to report exceptions verbosely but without formatting
3177 variables. This addresses the issue of ipython 'freezing' (it's
3195 variables. This addresses the issue of ipython 'freezing' (it's
3178 not frozen, but caught in an expensive formatting loop) when huge
3196 not frozen, but caught in an expensive formatting loop) when huge
3179 variables are in the context of an exception.
3197 variables are in the context of an exception.
3180 (VerboseTB.text): Added '--->' markers at line where exception was
3198 (VerboseTB.text): Added '--->' markers at line where exception was
3181 triggered. Much clearer to read, especially in NoColor modes.
3199 triggered. Much clearer to read, especially in NoColor modes.
3182
3200
3183 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3201 * IPython/Magic.py (Magic.magic_run): bugfix: -n option had been
3184 implemented in reverse when changing to the new parse_options().
3202 implemented in reverse when changing to the new parse_options().
3185
3203
3186 2002-05-03 Fernando Perez <fperez@colorado.edu>
3204 2002-05-03 Fernando Perez <fperez@colorado.edu>
3187
3205
3188 * IPython/Magic.py (Magic.parse_options): new function so that
3206 * IPython/Magic.py (Magic.parse_options): new function so that
3189 magics can parse options easier.
3207 magics can parse options easier.
3190 (Magic.magic_prun): new function similar to profile.run(),
3208 (Magic.magic_prun): new function similar to profile.run(),
3191 suggested by Chris Hart.
3209 suggested by Chris Hart.
3192 (Magic.magic_cd): fixed behavior so that it only changes if
3210 (Magic.magic_cd): fixed behavior so that it only changes if
3193 directory actually is in history.
3211 directory actually is in history.
3194
3212
3195 * IPython/usage.py (__doc__): added information about potential
3213 * IPython/usage.py (__doc__): added information about potential
3196 slowness of Verbose exception mode when there are huge data
3214 slowness of Verbose exception mode when there are huge data
3197 structures to be formatted (thanks to Archie Paulson).
3215 structures to be formatted (thanks to Archie Paulson).
3198
3216
3199 * IPython/ipmaker.py (make_IPython): Changed default logging
3217 * IPython/ipmaker.py (make_IPython): Changed default logging
3200 (when simply called with -log) to use curr_dir/ipython.log in
3218 (when simply called with -log) to use curr_dir/ipython.log in
3201 rotate mode. Fixed crash which was occuring with -log before
3219 rotate mode. Fixed crash which was occuring with -log before
3202 (thanks to Jim Boyle).
3220 (thanks to Jim Boyle).
3203
3221
3204 2002-05-01 Fernando Perez <fperez@colorado.edu>
3222 2002-05-01 Fernando Perez <fperez@colorado.edu>
3205
3223
3206 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3224 * Released 0.2.11 for these fixes (mainly the ultraTB one which
3207 was nasty -- though somewhat of a corner case).
3225 was nasty -- though somewhat of a corner case).
3208
3226
3209 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3227 * IPython/ultraTB.py (AutoFormattedTB.text): renamed __text to
3210 text (was a bug).
3228 text (was a bug).
3211
3229
3212 2002-04-30 Fernando Perez <fperez@colorado.edu>
3230 2002-04-30 Fernando Perez <fperez@colorado.edu>
3213
3231
3214 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3232 * IPython/UserConfig/GnuplotMagic.py (magic_gp): Minor fix to add
3215 a print after ^D or ^C from the user so that the In[] prompt
3233 a print after ^D or ^C from the user so that the In[] prompt
3216 doesn't over-run the gnuplot one.
3234 doesn't over-run the gnuplot one.
3217
3235
3218 2002-04-29 Fernando Perez <fperez@colorado.edu>
3236 2002-04-29 Fernando Perez <fperez@colorado.edu>
3219
3237
3220 * Released 0.2.10
3238 * Released 0.2.10
3221
3239
3222 * IPython/__release__.py (version): get date dynamically.
3240 * IPython/__release__.py (version): get date dynamically.
3223
3241
3224 * Misc. documentation updates thanks to Arnd's comments. Also ran
3242 * Misc. documentation updates thanks to Arnd's comments. Also ran
3225 a full spellcheck on the manual (hadn't been done in a while).
3243 a full spellcheck on the manual (hadn't been done in a while).
3226
3244
3227 2002-04-27 Fernando Perez <fperez@colorado.edu>
3245 2002-04-27 Fernando Perez <fperez@colorado.edu>
3228
3246
3229 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3247 * IPython/Magic.py (Magic.magic_logstart): Fixed bug where
3230 starting a log in mid-session would reset the input history list.
3248 starting a log in mid-session would reset the input history list.
3231
3249
3232 2002-04-26 Fernando Perez <fperez@colorado.edu>
3250 2002-04-26 Fernando Perez <fperez@colorado.edu>
3233
3251
3234 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3252 * IPython/iplib.py (InteractiveShell.wait): Fixed bug where not
3235 all files were being included in an update. Now anything in
3253 all files were being included in an update. Now anything in
3236 UserConfig that matches [A-Za-z]*.py will go (this excludes
3254 UserConfig that matches [A-Za-z]*.py will go (this excludes
3237 __init__.py)
3255 __init__.py)
3238
3256
3239 2002-04-25 Fernando Perez <fperez@colorado.edu>
3257 2002-04-25 Fernando Perez <fperez@colorado.edu>
3240
3258
3241 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3259 * IPython/iplib.py (InteractiveShell.__init__): Added __IPYTHON__
3242 to __builtins__ so that any form of embedded or imported code can
3260 to __builtins__ so that any form of embedded or imported code can
3243 test for being inside IPython.
3261 test for being inside IPython.
3244
3262
3245 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3263 * IPython/UserConfig/GnuplotMagic.py: (magic_gp_set_instance):
3246 changed to GnuplotMagic because it's now an importable module,
3264 changed to GnuplotMagic because it's now an importable module,
3247 this makes the name follow that of the standard Gnuplot module.
3265 this makes the name follow that of the standard Gnuplot module.
3248 GnuplotMagic can now be loaded at any time in mid-session.
3266 GnuplotMagic can now be loaded at any time in mid-session.
3249
3267
3250 2002-04-24 Fernando Perez <fperez@colorado.edu>
3268 2002-04-24 Fernando Perez <fperez@colorado.edu>
3251
3269
3252 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3270 * IPython/numutils.py: removed SIUnits. It doesn't properly set
3253 the globals (IPython has its own namespace) and the
3271 the globals (IPython has its own namespace) and the
3254 PhysicalQuantity stuff is much better anyway.
3272 PhysicalQuantity stuff is much better anyway.
3255
3273
3256 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3274 * IPython/UserConfig/example-gnuplot.py (g2): Added gnuplot
3257 embedding example to standard user directory for
3275 embedding example to standard user directory for
3258 distribution. Also put it in the manual.
3276 distribution. Also put it in the manual.
3259
3277
3260 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3278 * IPython/numutils.py (gnuplot_exec): Changed to take a gnuplot
3261 instance as first argument (so it doesn't rely on some obscure
3279 instance as first argument (so it doesn't rely on some obscure
3262 hidden global).
3280 hidden global).
3263
3281
3264 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3282 * IPython/UserConfig/ipythonrc.py: put () back in accepted
3265 delimiters. While it prevents ().TAB from working, it allows
3283 delimiters. While it prevents ().TAB from working, it allows
3266 completions in open (... expressions. This is by far a more common
3284 completions in open (... expressions. This is by far a more common
3267 case.
3285 case.
3268
3286
3269 2002-04-23 Fernando Perez <fperez@colorado.edu>
3287 2002-04-23 Fernando Perez <fperez@colorado.edu>
3270
3288
3271 * IPython/Extensions/InterpreterPasteInput.py: new
3289 * IPython/Extensions/InterpreterPasteInput.py: new
3272 syntax-processing module for pasting lines with >>> or ... at the
3290 syntax-processing module for pasting lines with >>> or ... at the
3273 start.
3291 start.
3274
3292
3275 * IPython/Extensions/PhysicalQ_Interactive.py
3293 * IPython/Extensions/PhysicalQ_Interactive.py
3276 (PhysicalQuantityInteractive.__int__): fixed to work with either
3294 (PhysicalQuantityInteractive.__int__): fixed to work with either
3277 Numeric or math.
3295 Numeric or math.
3278
3296
3279 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3297 * IPython/UserConfig/ipythonrc-numeric.py: reorganized the
3280 provided profiles. Now we have:
3298 provided profiles. Now we have:
3281 -math -> math module as * and cmath with its own namespace.
3299 -math -> math module as * and cmath with its own namespace.
3282 -numeric -> Numeric as *, plus gnuplot & grace
3300 -numeric -> Numeric as *, plus gnuplot & grace
3283 -physics -> same as before
3301 -physics -> same as before
3284
3302
3285 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3303 * IPython/Magic.py (Magic.magic_magic): Fixed bug where
3286 user-defined magics wouldn't be found by @magic if they were
3304 user-defined magics wouldn't be found by @magic if they were
3287 defined as class methods. Also cleaned up the namespace search
3305 defined as class methods. Also cleaned up the namespace search
3288 logic and the string building (to use %s instead of many repeated
3306 logic and the string building (to use %s instead of many repeated
3289 string adds).
3307 string adds).
3290
3308
3291 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3309 * IPython/UserConfig/example-magic.py (magic_foo): updated example
3292 of user-defined magics to operate with class methods (cleaner, in
3310 of user-defined magics to operate with class methods (cleaner, in
3293 line with the gnuplot code).
3311 line with the gnuplot code).
3294
3312
3295 2002-04-22 Fernando Perez <fperez@colorado.edu>
3313 2002-04-22 Fernando Perez <fperez@colorado.edu>
3296
3314
3297 * setup.py: updated dependency list so that manual is updated when
3315 * setup.py: updated dependency list so that manual is updated when
3298 all included files change.
3316 all included files change.
3299
3317
3300 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3318 * IPython/ipmaker.py (make_IPython): Fixed bug which was ignoring
3301 the delimiter removal option (the fix is ugly right now).
3319 the delimiter removal option (the fix is ugly right now).
3302
3320
3303 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3321 * IPython/UserConfig/ipythonrc-physics.py: simplified not to load
3304 all of the math profile (quicker loading, no conflict between
3322 all of the math profile (quicker loading, no conflict between
3305 g-9.8 and g-gnuplot).
3323 g-9.8 and g-gnuplot).
3306
3324
3307 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3325 * IPython/CrashHandler.py (CrashHandler.__call__): changed default
3308 name of post-mortem files to IPython_crash_report.txt.
3326 name of post-mortem files to IPython_crash_report.txt.
3309
3327
3310 * Cleanup/update of the docs. Added all the new readline info and
3328 * Cleanup/update of the docs. Added all the new readline info and
3311 formatted all lists as 'real lists'.
3329 formatted all lists as 'real lists'.
3312
3330
3313 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3331 * IPython/ipmaker.py (make_IPython): removed now-obsolete
3314 tab-completion options, since the full readline parse_and_bind is
3332 tab-completion options, since the full readline parse_and_bind is
3315 now accessible.
3333 now accessible.
3316
3334
3317 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3335 * IPython/iplib.py (InteractiveShell.init_readline): Changed
3318 handling of readline options. Now users can specify any string to
3336 handling of readline options. Now users can specify any string to
3319 be passed to parse_and_bind(), as well as the delimiters to be
3337 be passed to parse_and_bind(), as well as the delimiters to be
3320 removed.
3338 removed.
3321 (InteractiveShell.__init__): Added __name__ to the global
3339 (InteractiveShell.__init__): Added __name__ to the global
3322 namespace so that things like Itpl which rely on its existence
3340 namespace so that things like Itpl which rely on its existence
3323 don't crash.
3341 don't crash.
3324 (InteractiveShell._prefilter): Defined the default with a _ so
3342 (InteractiveShell._prefilter): Defined the default with a _ so
3325 that prefilter() is easier to override, while the default one
3343 that prefilter() is easier to override, while the default one
3326 remains available.
3344 remains available.
3327
3345
3328 2002-04-18 Fernando Perez <fperez@colorado.edu>
3346 2002-04-18 Fernando Perez <fperez@colorado.edu>
3329
3347
3330 * Added information about pdb in the docs.
3348 * Added information about pdb in the docs.
3331
3349
3332 2002-04-17 Fernando Perez <fperez@colorado.edu>
3350 2002-04-17 Fernando Perez <fperez@colorado.edu>
3333
3351
3334 * IPython/ipmaker.py (make_IPython): added rc_override option to
3352 * IPython/ipmaker.py (make_IPython): added rc_override option to
3335 allow passing config options at creation time which may override
3353 allow passing config options at creation time which may override
3336 anything set in the config files or command line. This is
3354 anything set in the config files or command line. This is
3337 particularly useful for configuring embedded instances.
3355 particularly useful for configuring embedded instances.
3338
3356
3339 2002-04-15 Fernando Perez <fperez@colorado.edu>
3357 2002-04-15 Fernando Perez <fperez@colorado.edu>
3340
3358
3341 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3359 * IPython/Logger.py (Logger.log): Fixed a nasty bug which could
3342 crash embedded instances because of the input cache falling out of
3360 crash embedded instances because of the input cache falling out of
3343 sync with the output counter.
3361 sync with the output counter.
3344
3362
3345 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3363 * IPython/Shell.py (IPythonShellEmbed.__init__): added a debug
3346 mode which calls pdb after an uncaught exception in IPython itself.
3364 mode which calls pdb after an uncaught exception in IPython itself.
3347
3365
3348 2002-04-14 Fernando Perez <fperez@colorado.edu>
3366 2002-04-14 Fernando Perez <fperez@colorado.edu>
3349
3367
3350 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3368 * IPython/iplib.py (InteractiveShell.showtraceback): pdb mucks up
3351 readline, fix it back after each call.
3369 readline, fix it back after each call.
3352
3370
3353 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3371 * IPython/ultraTB.py (AutoFormattedTB.__text): made text a private
3354 method to force all access via __call__(), which guarantees that
3372 method to force all access via __call__(), which guarantees that
3355 traceback references are properly deleted.
3373 traceback references are properly deleted.
3356
3374
3357 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3375 * IPython/Prompts.py (CachedOutput._display): minor fixes to
3358 improve printing when pprint is in use.
3376 improve printing when pprint is in use.
3359
3377
3360 2002-04-13 Fernando Perez <fperez@colorado.edu>
3378 2002-04-13 Fernando Perez <fperez@colorado.edu>
3361
3379
3362 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3380 * IPython/Shell.py (IPythonShellEmbed.__call__): SystemExit
3363 exceptions aren't caught anymore. If the user triggers one, he
3381 exceptions aren't caught anymore. If the user triggers one, he
3364 should know why he's doing it and it should go all the way up,
3382 should know why he's doing it and it should go all the way up,
3365 just like any other exception. So now @abort will fully kill the
3383 just like any other exception. So now @abort will fully kill the
3366 embedded interpreter and the embedding code (unless that happens
3384 embedded interpreter and the embedding code (unless that happens
3367 to catch SystemExit).
3385 to catch SystemExit).
3368
3386
3369 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3387 * IPython/ultraTB.py (VerboseTB.__init__): added a call_pdb flag
3370 and a debugger() method to invoke the interactive pdb debugger
3388 and a debugger() method to invoke the interactive pdb debugger
3371 after printing exception information. Also added the corresponding
3389 after printing exception information. Also added the corresponding
3372 -pdb option and @pdb magic to control this feature, and updated
3390 -pdb option and @pdb magic to control this feature, and updated
3373 the docs. After a suggestion from Christopher Hart
3391 the docs. After a suggestion from Christopher Hart
3374 (hart-AT-caltech.edu).
3392 (hart-AT-caltech.edu).
3375
3393
3376 2002-04-12 Fernando Perez <fperez@colorado.edu>
3394 2002-04-12 Fernando Perez <fperez@colorado.edu>
3377
3395
3378 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3396 * IPython/Shell.py (IPythonShellEmbed.__init__): modified to use
3379 the exception handlers defined by the user (not the CrashHandler)
3397 the exception handlers defined by the user (not the CrashHandler)
3380 so that user exceptions don't trigger an ipython bug report.
3398 so that user exceptions don't trigger an ipython bug report.
3381
3399
3382 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3400 * IPython/ultraTB.py (ColorTB.__init__): made the color scheme
3383 configurable (it should have always been so).
3401 configurable (it should have always been so).
3384
3402
3385 2002-03-26 Fernando Perez <fperez@colorado.edu>
3403 2002-03-26 Fernando Perez <fperez@colorado.edu>
3386
3404
3387 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3405 * IPython/Shell.py (IPythonShellEmbed.__call__): many changes here
3388 and there to fix embedding namespace issues. This should all be
3406 and there to fix embedding namespace issues. This should all be
3389 done in a more elegant way.
3407 done in a more elegant way.
3390
3408
3391 2002-03-25 Fernando Perez <fperez@colorado.edu>
3409 2002-03-25 Fernando Perez <fperez@colorado.edu>
3392
3410
3393 * IPython/genutils.py (get_home_dir): Try to make it work under
3411 * IPython/genutils.py (get_home_dir): Try to make it work under
3394 win9x also.
3412 win9x also.
3395
3413
3396 2002-03-20 Fernando Perez <fperez@colorado.edu>
3414 2002-03-20 Fernando Perez <fperez@colorado.edu>
3397
3415
3398 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3416 * IPython/Shell.py (IPythonShellEmbed.__init__): leave
3399 sys.displayhook untouched upon __init__.
3417 sys.displayhook untouched upon __init__.
3400
3418
3401 2002-03-19 Fernando Perez <fperez@colorado.edu>
3419 2002-03-19 Fernando Perez <fperez@colorado.edu>
3402
3420
3403 * Released 0.2.9 (for embedding bug, basically).
3421 * Released 0.2.9 (for embedding bug, basically).
3404
3422
3405 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3423 * IPython/Shell.py (IPythonShellEmbed.__call__): Trap SystemExit
3406 exceptions so that enclosing shell's state can be restored.
3424 exceptions so that enclosing shell's state can be restored.
3407
3425
3408 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3426 * Changed magic_gnuplot.py to magic-gnuplot.py to standardize
3409 naming conventions in the .ipython/ dir.
3427 naming conventions in the .ipython/ dir.
3410
3428
3411 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3429 * IPython/iplib.py (InteractiveShell.init_readline): removed '-'
3412 from delimiters list so filenames with - in them get expanded.
3430 from delimiters list so filenames with - in them get expanded.
3413
3431
3414 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3432 * IPython/Shell.py (IPythonShellEmbed.__call__): fixed bug with
3415 sys.displayhook not being properly restored after an embedded call.
3433 sys.displayhook not being properly restored after an embedded call.
3416
3434
3417 2002-03-18 Fernando Perez <fperez@colorado.edu>
3435 2002-03-18 Fernando Perez <fperez@colorado.edu>
3418
3436
3419 * Released 0.2.8
3437 * Released 0.2.8
3420
3438
3421 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3439 * IPython/iplib.py (InteractiveShell.user_setup): fixed bug where
3422 some files weren't being included in a -upgrade.
3440 some files weren't being included in a -upgrade.
3423 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3441 (InteractiveShell.init_readline): Added 'set show-all-if-ambiguous
3424 on' so that the first tab completes.
3442 on' so that the first tab completes.
3425 (InteractiveShell.handle_magic): fixed bug with spaces around
3443 (InteractiveShell.handle_magic): fixed bug with spaces around
3426 quotes breaking many magic commands.
3444 quotes breaking many magic commands.
3427
3445
3428 * setup.py: added note about ignoring the syntax error messages at
3446 * setup.py: added note about ignoring the syntax error messages at
3429 installation.
3447 installation.
3430
3448
3431 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3449 * IPython/UserConfig/magic_gnuplot.py (magic_gp): finished
3432 streamlining the gnuplot interface, now there's only one magic @gp.
3450 streamlining the gnuplot interface, now there's only one magic @gp.
3433
3451
3434 2002-03-17 Fernando Perez <fperez@colorado.edu>
3452 2002-03-17 Fernando Perez <fperez@colorado.edu>
3435
3453
3436 * IPython/UserConfig/magic_gnuplot.py: new name for the
3454 * IPython/UserConfig/magic_gnuplot.py: new name for the
3437 example-magic_pm.py file. Much enhanced system, now with a shell
3455 example-magic_pm.py file. Much enhanced system, now with a shell
3438 for communicating directly with gnuplot, one command at a time.
3456 for communicating directly with gnuplot, one command at a time.
3439
3457
3440 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3458 * IPython/Magic.py (Magic.magic_run): added option -n to prevent
3441 setting __name__=='__main__'.
3459 setting __name__=='__main__'.
3442
3460
3443 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3461 * IPython/UserConfig/example-magic_pm.py (magic_pm): Added
3444 mini-shell for accessing gnuplot from inside ipython. Should
3462 mini-shell for accessing gnuplot from inside ipython. Should
3445 extend it later for grace access too. Inspired by Arnd's
3463 extend it later for grace access too. Inspired by Arnd's
3446 suggestion.
3464 suggestion.
3447
3465
3448 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3466 * IPython/iplib.py (InteractiveShell.handle_magic): fixed bug when
3449 calling magic functions with () in their arguments. Thanks to Arnd
3467 calling magic functions with () in their arguments. Thanks to Arnd
3450 Baecker for pointing this to me.
3468 Baecker for pointing this to me.
3451
3469
3452 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3470 * IPython/numutils.py (sum_flat): fixed bug. Would recurse
3453 infinitely for integer or complex arrays (only worked with floats).
3471 infinitely for integer or complex arrays (only worked with floats).
3454
3472
3455 2002-03-16 Fernando Perez <fperez@colorado.edu>
3473 2002-03-16 Fernando Perez <fperez@colorado.edu>
3456
3474
3457 * setup.py: Merged setup and setup_windows into a single script
3475 * setup.py: Merged setup and setup_windows into a single script
3458 which properly handles things for windows users.
3476 which properly handles things for windows users.
3459
3477
3460 2002-03-15 Fernando Perez <fperez@colorado.edu>
3478 2002-03-15 Fernando Perez <fperez@colorado.edu>
3461
3479
3462 * Big change to the manual: now the magics are all automatically
3480 * Big change to the manual: now the magics are all automatically
3463 documented. This information is generated from their docstrings
3481 documented. This information is generated from their docstrings
3464 and put in a latex file included by the manual lyx file. This way
3482 and put in a latex file included by the manual lyx file. This way
3465 we get always up to date information for the magics. The manual
3483 we get always up to date information for the magics. The manual
3466 now also has proper version information, also auto-synced.
3484 now also has proper version information, also auto-synced.
3467
3485
3468 For this to work, an undocumented --magic_docstrings option was added.
3486 For this to work, an undocumented --magic_docstrings option was added.
3469
3487
3470 2002-03-13 Fernando Perez <fperez@colorado.edu>
3488 2002-03-13 Fernando Perez <fperez@colorado.edu>
3471
3489
3472 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3490 * IPython/ultraTB.py (TermColors): fixed problem with dark colors
3473 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3491 under CDE terminals. An explicit ;2 color reset is needed in the escapes.
3474
3492
3475 2002-03-12 Fernando Perez <fperez@colorado.edu>
3493 2002-03-12 Fernando Perez <fperez@colorado.edu>
3476
3494
3477 * IPython/ultraTB.py (TermColors): changed color escapes again to
3495 * IPython/ultraTB.py (TermColors): changed color escapes again to
3478 fix the (old, reintroduced) line-wrapping bug. Basically, if
3496 fix the (old, reintroduced) line-wrapping bug. Basically, if
3479 \001..\002 aren't given in the color escapes, lines get wrapped
3497 \001..\002 aren't given in the color escapes, lines get wrapped
3480 weirdly. But giving those screws up old xterms and emacs terms. So
3498 weirdly. But giving those screws up old xterms and emacs terms. So
3481 I added some logic for emacs terms to be ok, but I can't identify old
3499 I added some logic for emacs terms to be ok, but I can't identify old
3482 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3500 xterms separately ($TERM=='xterm' for many terminals, like konsole).
3483
3501
3484 2002-03-10 Fernando Perez <fperez@colorado.edu>
3502 2002-03-10 Fernando Perez <fperez@colorado.edu>
3485
3503
3486 * IPython/usage.py (__doc__): Various documentation cleanups and
3504 * IPython/usage.py (__doc__): Various documentation cleanups and
3487 updates, both in usage docstrings and in the manual.
3505 updates, both in usage docstrings and in the manual.
3488
3506
3489 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3507 * IPython/Prompts.py (CachedOutput.set_colors): cleanups for
3490 handling of caching. Set minimum acceptabe value for having a
3508 handling of caching. Set minimum acceptabe value for having a
3491 cache at 20 values.
3509 cache at 20 values.
3492
3510
3493 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3511 * IPython/iplib.py (InteractiveShell.user_setup): moved the
3494 install_first_time function to a method, renamed it and added an
3512 install_first_time function to a method, renamed it and added an
3495 'upgrade' mode. Now people can update their config directory with
3513 'upgrade' mode. Now people can update their config directory with
3496 a simple command line switch (-upgrade, also new).
3514 a simple command line switch (-upgrade, also new).
3497
3515
3498 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3516 * IPython/Magic.py (Magic.magic_pfile): Made @pfile an alias to
3499 @file (convenient for automagic users under Python >= 2.2).
3517 @file (convenient for automagic users under Python >= 2.2).
3500 Removed @files (it seemed more like a plural than an abbrev. of
3518 Removed @files (it seemed more like a plural than an abbrev. of
3501 'file show').
3519 'file show').
3502
3520
3503 * IPython/iplib.py (install_first_time): Fixed crash if there were
3521 * IPython/iplib.py (install_first_time): Fixed crash if there were
3504 backup files ('~') in .ipython/ install directory.
3522 backup files ('~') in .ipython/ install directory.
3505
3523
3506 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3524 * IPython/ipmaker.py (make_IPython): fixes for new prompt
3507 system. Things look fine, but these changes are fairly
3525 system. Things look fine, but these changes are fairly
3508 intrusive. Test them for a few days.
3526 intrusive. Test them for a few days.
3509
3527
3510 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3528 * IPython/Prompts.py (CachedOutput.__init__): Massive rewrite of
3511 the prompts system. Now all in/out prompt strings are user
3529 the prompts system. Now all in/out prompt strings are user
3512 controllable. This is particularly useful for embedding, as one
3530 controllable. This is particularly useful for embedding, as one
3513 can tag embedded instances with particular prompts.
3531 can tag embedded instances with particular prompts.
3514
3532
3515 Also removed global use of sys.ps1/2, which now allows nested
3533 Also removed global use of sys.ps1/2, which now allows nested
3516 embeddings without any problems. Added command-line options for
3534 embeddings without any problems. Added command-line options for
3517 the prompt strings.
3535 the prompt strings.
3518
3536
3519 2002-03-08 Fernando Perez <fperez@colorado.edu>
3537 2002-03-08 Fernando Perez <fperez@colorado.edu>
3520
3538
3521 * IPython/UserConfig/example-embed-short.py (ipshell): added
3539 * IPython/UserConfig/example-embed-short.py (ipshell): added
3522 example file with the bare minimum code for embedding.
3540 example file with the bare minimum code for embedding.
3523
3541
3524 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3542 * IPython/Shell.py (IPythonShellEmbed.set_dummy_mode): added
3525 functionality for the embeddable shell to be activated/deactivated
3543 functionality for the embeddable shell to be activated/deactivated
3526 either globally or at each call.
3544 either globally or at each call.
3527
3545
3528 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3546 * IPython/Prompts.py (Prompt1.auto_rewrite): Fixes the problem of
3529 rewriting the prompt with '--->' for auto-inputs with proper
3547 rewriting the prompt with '--->' for auto-inputs with proper
3530 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3548 coloring. Now the previous UGLY hack in handle_auto() is gone, and
3531 this is handled by the prompts class itself, as it should.
3549 this is handled by the prompts class itself, as it should.
3532
3550
3533 2002-03-05 Fernando Perez <fperez@colorado.edu>
3551 2002-03-05 Fernando Perez <fperez@colorado.edu>
3534
3552
3535 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3553 * IPython/Magic.py (Magic.magic_logstart): Changed @log to
3536 @logstart to avoid name clashes with the math log function.
3554 @logstart to avoid name clashes with the math log function.
3537
3555
3538 * Big updates to X/Emacs section of the manual.
3556 * Big updates to X/Emacs section of the manual.
3539
3557
3540 * Removed ipython_emacs. Milan explained to me how to pass
3558 * Removed ipython_emacs. Milan explained to me how to pass
3541 arguments to ipython through Emacs. Some day I'm going to end up
3559 arguments to ipython through Emacs. Some day I'm going to end up
3542 learning some lisp...
3560 learning some lisp...
3543
3561
3544 2002-03-04 Fernando Perez <fperez@colorado.edu>
3562 2002-03-04 Fernando Perez <fperez@colorado.edu>
3545
3563
3546 * IPython/ipython_emacs: Created script to be used as the
3564 * IPython/ipython_emacs: Created script to be used as the
3547 py-python-command Emacs variable so we can pass IPython
3565 py-python-command Emacs variable so we can pass IPython
3548 parameters. I can't figure out how to tell Emacs directly to pass
3566 parameters. I can't figure out how to tell Emacs directly to pass
3549 parameters to IPython, so a dummy shell script will do it.
3567 parameters to IPython, so a dummy shell script will do it.
3550
3568
3551 Other enhancements made for things to work better under Emacs'
3569 Other enhancements made for things to work better under Emacs'
3552 various types of terminals. Many thanks to Milan Zamazal
3570 various types of terminals. Many thanks to Milan Zamazal
3553 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3571 <pdm-AT-zamazal.org> for all the suggestions and pointers.
3554
3572
3555 2002-03-01 Fernando Perez <fperez@colorado.edu>
3573 2002-03-01 Fernando Perez <fperez@colorado.edu>
3556
3574
3557 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3575 * IPython/ipmaker.py (make_IPython): added a --readline! option so
3558 that loading of readline is now optional. This gives better
3576 that loading of readline is now optional. This gives better
3559 control to emacs users.
3577 control to emacs users.
3560
3578
3561 * IPython/ultraTB.py (__date__): Modified color escape sequences
3579 * IPython/ultraTB.py (__date__): Modified color escape sequences
3562 and now things work fine under xterm and in Emacs' term buffers
3580 and now things work fine under xterm and in Emacs' term buffers
3563 (though not shell ones). Well, in emacs you get colors, but all
3581 (though not shell ones). Well, in emacs you get colors, but all
3564 seem to be 'light' colors (no difference between dark and light
3582 seem to be 'light' colors (no difference between dark and light
3565 ones). But the garbage chars are gone, and also in xterms. It
3583 ones). But the garbage chars are gone, and also in xterms. It
3566 seems that now I'm using 'cleaner' ansi sequences.
3584 seems that now I'm using 'cleaner' ansi sequences.
3567
3585
3568 2002-02-21 Fernando Perez <fperez@colorado.edu>
3586 2002-02-21 Fernando Perez <fperez@colorado.edu>
3569
3587
3570 * Released 0.2.7 (mainly to publish the scoping fix).
3588 * Released 0.2.7 (mainly to publish the scoping fix).
3571
3589
3572 * IPython/Logger.py (Logger.logstate): added. A corresponding
3590 * IPython/Logger.py (Logger.logstate): added. A corresponding
3573 @logstate magic was created.
3591 @logstate magic was created.
3574
3592
3575 * IPython/Magic.py: fixed nested scoping problem under Python
3593 * IPython/Magic.py: fixed nested scoping problem under Python
3576 2.1.x (automagic wasn't working).
3594 2.1.x (automagic wasn't working).
3577
3595
3578 2002-02-20 Fernando Perez <fperez@colorado.edu>
3596 2002-02-20 Fernando Perez <fperez@colorado.edu>
3579
3597
3580 * Released 0.2.6.
3598 * Released 0.2.6.
3581
3599
3582 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3600 * IPython/OutputTrap.py (OutputTrap.__init__): added a 'quiet'
3583 option so that logs can come out without any headers at all.
3601 option so that logs can come out without any headers at all.
3584
3602
3585 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3603 * IPython/UserConfig/ipythonrc-scipy.py: created a profile for
3586 SciPy.
3604 SciPy.
3587
3605
3588 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3606 * IPython/iplib.py (InteractiveShell.embed_mainloop): Changed so
3589 that embedded IPython calls don't require vars() to be explicitly
3607 that embedded IPython calls don't require vars() to be explicitly
3590 passed. Now they are extracted from the caller's frame (code
3608 passed. Now they are extracted from the caller's frame (code
3591 snatched from Eric Jones' weave). Added better documentation to
3609 snatched from Eric Jones' weave). Added better documentation to
3592 the section on embedding and the example file.
3610 the section on embedding and the example file.
3593
3611
3594 * IPython/genutils.py (page): Changed so that under emacs, it just
3612 * IPython/genutils.py (page): Changed so that under emacs, it just
3595 prints the string. You can then page up and down in the emacs
3613 prints the string. You can then page up and down in the emacs
3596 buffer itself. This is how the builtin help() works.
3614 buffer itself. This is how the builtin help() works.
3597
3615
3598 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3616 * IPython/Prompts.py (CachedOutput.__call__): Fixed issue with
3599 macro scoping: macros need to be executed in the user's namespace
3617 macro scoping: macros need to be executed in the user's namespace
3600 to work as if they had been typed by the user.
3618 to work as if they had been typed by the user.
3601
3619
3602 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3620 * IPython/Magic.py (Magic.magic_macro): Changed macros so they
3603 execute automatically (no need to type 'exec...'). They then
3621 execute automatically (no need to type 'exec...'). They then
3604 behave like 'true macros'. The printing system was also modified
3622 behave like 'true macros'. The printing system was also modified
3605 for this to work.
3623 for this to work.
3606
3624
3607 2002-02-19 Fernando Perez <fperez@colorado.edu>
3625 2002-02-19 Fernando Perez <fperez@colorado.edu>
3608
3626
3609 * IPython/genutils.py (page_file): new function for paging files
3627 * IPython/genutils.py (page_file): new function for paging files
3610 in an OS-independent way. Also necessary for file viewing to work
3628 in an OS-independent way. Also necessary for file viewing to work
3611 well inside Emacs buffers.
3629 well inside Emacs buffers.
3612 (page): Added checks for being in an emacs buffer.
3630 (page): Added checks for being in an emacs buffer.
3613 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3631 (page): fixed bug for Windows ($TERM isn't set in Windows). Fixed
3614 same bug in iplib.
3632 same bug in iplib.
3615
3633
3616 2002-02-18 Fernando Perez <fperez@colorado.edu>
3634 2002-02-18 Fernando Perez <fperez@colorado.edu>
3617
3635
3618 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3636 * IPython/iplib.py (InteractiveShell.init_readline): modified use
3619 of readline so that IPython can work inside an Emacs buffer.
3637 of readline so that IPython can work inside an Emacs buffer.
3620
3638
3621 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3639 * IPython/ultraTB.py (AutoFormattedTB.__call__): some fixes to
3622 method signatures (they weren't really bugs, but it looks cleaner
3640 method signatures (they weren't really bugs, but it looks cleaner
3623 and keeps PyChecker happy).
3641 and keeps PyChecker happy).
3624
3642
3625 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3643 * IPython/ipmaker.py (make_IPython): added hooks Struct to __IP
3626 for implementing various user-defined hooks. Currently only
3644 for implementing various user-defined hooks. Currently only
3627 display is done.
3645 display is done.
3628
3646
3629 * IPython/Prompts.py (CachedOutput._display): changed display
3647 * IPython/Prompts.py (CachedOutput._display): changed display
3630 functions so that they can be dynamically changed by users easily.
3648 functions so that they can be dynamically changed by users easily.
3631
3649
3632 * IPython/Extensions/numeric_formats.py (num_display): added an
3650 * IPython/Extensions/numeric_formats.py (num_display): added an
3633 extension for printing NumPy arrays in flexible manners. It
3651 extension for printing NumPy arrays in flexible manners. It
3634 doesn't do anything yet, but all the structure is in
3652 doesn't do anything yet, but all the structure is in
3635 place. Ultimately the plan is to implement output format control
3653 place. Ultimately the plan is to implement output format control
3636 like in Octave.
3654 like in Octave.
3637
3655
3638 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3656 * IPython/Magic.py (Magic.lsmagic): changed so that bound magic
3639 methods are found at run-time by all the automatic machinery.
3657 methods are found at run-time by all the automatic machinery.
3640
3658
3641 2002-02-17 Fernando Perez <fperez@colorado.edu>
3659 2002-02-17 Fernando Perez <fperez@colorado.edu>
3642
3660
3643 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3661 * setup_Windows.py (make_shortcut): documented. Cleaned up the
3644 whole file a little.
3662 whole file a little.
3645
3663
3646 * ToDo: closed this document. Now there's a new_design.lyx
3664 * ToDo: closed this document. Now there's a new_design.lyx
3647 document for all new ideas. Added making a pdf of it for the
3665 document for all new ideas. Added making a pdf of it for the
3648 end-user distro.
3666 end-user distro.
3649
3667
3650 * IPython/Logger.py (Logger.switch_log): Created this to replace
3668 * IPython/Logger.py (Logger.switch_log): Created this to replace
3651 logon() and logoff(). It also fixes a nasty crash reported by
3669 logon() and logoff(). It also fixes a nasty crash reported by
3652 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3670 Philip Hisley <compsys-AT-starpower.net>. Many thanks to him.
3653
3671
3654 * IPython/iplib.py (complete): got auto-completion to work with
3672 * IPython/iplib.py (complete): got auto-completion to work with
3655 automagic (I had wanted this for a long time).
3673 automagic (I had wanted this for a long time).
3656
3674
3657 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3675 * IPython/Magic.py (Magic.magic_files): Added @files as an alias
3658 to @file, since file() is now a builtin and clashes with automagic
3676 to @file, since file() is now a builtin and clashes with automagic
3659 for @file.
3677 for @file.
3660
3678
3661 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3679 * Made some new files: Prompts, CrashHandler, Magic, Logger. All
3662 of this was previously in iplib, which had grown to more than 2000
3680 of this was previously in iplib, which had grown to more than 2000
3663 lines, way too long. No new functionality, but it makes managing
3681 lines, way too long. No new functionality, but it makes managing
3664 the code a bit easier.
3682 the code a bit easier.
3665
3683
3666 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3684 * IPython/iplib.py (IPythonCrashHandler.__call__): Added version
3667 information to crash reports.
3685 information to crash reports.
3668
3686
3669 2002-02-12 Fernando Perez <fperez@colorado.edu>
3687 2002-02-12 Fernando Perez <fperez@colorado.edu>
3670
3688
3671 * Released 0.2.5.
3689 * Released 0.2.5.
3672
3690
3673 2002-02-11 Fernando Perez <fperez@colorado.edu>
3691 2002-02-11 Fernando Perez <fperez@colorado.edu>
3674
3692
3675 * Wrote a relatively complete Windows installer. It puts
3693 * Wrote a relatively complete Windows installer. It puts
3676 everything in place, creates Start Menu entries and fixes the
3694 everything in place, creates Start Menu entries and fixes the
3677 color issues. Nothing fancy, but it works.
3695 color issues. Nothing fancy, but it works.
3678
3696
3679 2002-02-10 Fernando Perez <fperez@colorado.edu>
3697 2002-02-10 Fernando Perez <fperez@colorado.edu>
3680
3698
3681 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3699 * IPython/iplib.py (InteractiveShell.safe_execfile): added an
3682 os.path.expanduser() call so that we can type @run ~/myfile.py and
3700 os.path.expanduser() call so that we can type @run ~/myfile.py and
3683 have thigs work as expected.
3701 have thigs work as expected.
3684
3702
3685 * IPython/genutils.py (page): fixed exception handling so things
3703 * IPython/genutils.py (page): fixed exception handling so things
3686 work both in Unix and Windows correctly. Quitting a pager triggers
3704 work both in Unix and Windows correctly. Quitting a pager triggers
3687 an IOError/broken pipe in Unix, and in windows not finding a pager
3705 an IOError/broken pipe in Unix, and in windows not finding a pager
3688 is also an IOError, so I had to actually look at the return value
3706 is also an IOError, so I had to actually look at the return value
3689 of the exception, not just the exception itself. Should be ok now.
3707 of the exception, not just the exception itself. Should be ok now.
3690
3708
3691 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3709 * IPython/ultraTB.py (ColorSchemeTable.set_active_scheme):
3692 modified to allow case-insensitive color scheme changes.
3710 modified to allow case-insensitive color scheme changes.
3693
3711
3694 2002-02-09 Fernando Perez <fperez@colorado.edu>
3712 2002-02-09 Fernando Perez <fperez@colorado.edu>
3695
3713
3696 * IPython/genutils.py (native_line_ends): new function to leave
3714 * IPython/genutils.py (native_line_ends): new function to leave
3697 user config files with os-native line-endings.
3715 user config files with os-native line-endings.
3698
3716
3699 * README and manual updates.
3717 * README and manual updates.
3700
3718
3701 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3719 * IPython/genutils.py: fixed unicode bug: use types.StringTypes
3702 instead of StringType to catch Unicode strings.
3720 instead of StringType to catch Unicode strings.
3703
3721
3704 * IPython/genutils.py (filefind): fixed bug for paths with
3722 * IPython/genutils.py (filefind): fixed bug for paths with
3705 embedded spaces (very common in Windows).
3723 embedded spaces (very common in Windows).
3706
3724
3707 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3725 * IPython/ipmaker.py (make_IPython): added a '.ini' to the rc
3708 files under Windows, so that they get automatically associated
3726 files under Windows, so that they get automatically associated
3709 with a text editor. Windows makes it a pain to handle
3727 with a text editor. Windows makes it a pain to handle
3710 extension-less files.
3728 extension-less files.
3711
3729
3712 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3730 * IPython/iplib.py (InteractiveShell.init_readline): Made the
3713 warning about readline only occur for Posix. In Windows there's no
3731 warning about readline only occur for Posix. In Windows there's no
3714 way to get readline, so why bother with the warning.
3732 way to get readline, so why bother with the warning.
3715
3733
3716 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3734 * IPython/Struct.py (Struct.__str__): fixed to use self.__dict__
3717 for __str__ instead of dir(self), since dir() changed in 2.2.
3735 for __str__ instead of dir(self), since dir() changed in 2.2.
3718
3736
3719 * Ported to Windows! Tested on XP, I suspect it should work fine
3737 * Ported to Windows! Tested on XP, I suspect it should work fine
3720 on NT/2000, but I don't think it will work on 98 et al. That
3738 on NT/2000, but I don't think it will work on 98 et al. That
3721 series of Windows is such a piece of junk anyway that I won't try
3739 series of Windows is such a piece of junk anyway that I won't try
3722 porting it there. The XP port was straightforward, showed a few
3740 porting it there. The XP port was straightforward, showed a few
3723 bugs here and there (fixed all), in particular some string
3741 bugs here and there (fixed all), in particular some string
3724 handling stuff which required considering Unicode strings (which
3742 handling stuff which required considering Unicode strings (which
3725 Windows uses). This is good, but hasn't been too tested :) No
3743 Windows uses). This is good, but hasn't been too tested :) No
3726 fancy installer yet, I'll put a note in the manual so people at
3744 fancy installer yet, I'll put a note in the manual so people at
3727 least make manually a shortcut.
3745 least make manually a shortcut.
3728
3746
3729 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3747 * IPython/iplib.py (Magic.magic_colors): Unified the color options
3730 into a single one, "colors". This now controls both prompt and
3748 into a single one, "colors". This now controls both prompt and
3731 exception color schemes, and can be changed both at startup
3749 exception color schemes, and can be changed both at startup
3732 (either via command-line switches or via ipythonrc files) and at
3750 (either via command-line switches or via ipythonrc files) and at
3733 runtime, with @colors.
3751 runtime, with @colors.
3734 (Magic.magic_run): renamed @prun to @run and removed the old
3752 (Magic.magic_run): renamed @prun to @run and removed the old
3735 @run. The two were too similar to warrant keeping both.
3753 @run. The two were too similar to warrant keeping both.
3736
3754
3737 2002-02-03 Fernando Perez <fperez@colorado.edu>
3755 2002-02-03 Fernando Perez <fperez@colorado.edu>
3738
3756
3739 * IPython/iplib.py (install_first_time): Added comment on how to
3757 * IPython/iplib.py (install_first_time): Added comment on how to
3740 configure the color options for first-time users. Put a <return>
3758 configure the color options for first-time users. Put a <return>
3741 request at the end so that small-terminal users get a chance to
3759 request at the end so that small-terminal users get a chance to
3742 read the startup info.
3760 read the startup info.
3743
3761
3744 2002-01-23 Fernando Perez <fperez@colorado.edu>
3762 2002-01-23 Fernando Perez <fperez@colorado.edu>
3745
3763
3746 * IPython/iplib.py (CachedOutput.update): Changed output memory
3764 * IPython/iplib.py (CachedOutput.update): Changed output memory
3747 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3765 variable names from _o,_oo,_ooo,_o<n> to simply _,__,___,_<n>. For
3748 input history we still use _i. Did this b/c these variable are
3766 input history we still use _i. Did this b/c these variable are
3749 very commonly used in interactive work, so the less we need to
3767 very commonly used in interactive work, so the less we need to
3750 type the better off we are.
3768 type the better off we are.
3751 (Magic.magic_prun): updated @prun to better handle the namespaces
3769 (Magic.magic_prun): updated @prun to better handle the namespaces
3752 the file will run in, including a fix for __name__ not being set
3770 the file will run in, including a fix for __name__ not being set
3753 before.
3771 before.
3754
3772
3755 2002-01-20 Fernando Perez <fperez@colorado.edu>
3773 2002-01-20 Fernando Perez <fperez@colorado.edu>
3756
3774
3757 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3775 * IPython/ultraTB.py (VerboseTB.linereader): Fixed printing of
3758 extra garbage for Python 2.2. Need to look more carefully into
3776 extra garbage for Python 2.2. Need to look more carefully into
3759 this later.
3777 this later.
3760
3778
3761 2002-01-19 Fernando Perez <fperez@colorado.edu>
3779 2002-01-19 Fernando Perez <fperez@colorado.edu>
3762
3780
3763 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3781 * IPython/iplib.py (InteractiveShell.showtraceback): fixed to
3764 display SyntaxError exceptions properly formatted when they occur
3782 display SyntaxError exceptions properly formatted when they occur
3765 (they can be triggered by imported code).
3783 (they can be triggered by imported code).
3766
3784
3767 2002-01-18 Fernando Perez <fperez@colorado.edu>
3785 2002-01-18 Fernando Perez <fperez@colorado.edu>
3768
3786
3769 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3787 * IPython/iplib.py (InteractiveShell.safe_execfile): now
3770 SyntaxError exceptions are reported nicely formatted, instead of
3788 SyntaxError exceptions are reported nicely formatted, instead of
3771 spitting out only offset information as before.
3789 spitting out only offset information as before.
3772 (Magic.magic_prun): Added the @prun function for executing
3790 (Magic.magic_prun): Added the @prun function for executing
3773 programs with command line args inside IPython.
3791 programs with command line args inside IPython.
3774
3792
3775 2002-01-16 Fernando Perez <fperez@colorado.edu>
3793 2002-01-16 Fernando Perez <fperez@colorado.edu>
3776
3794
3777 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3795 * IPython/iplib.py (Magic.magic_hist): Changed @hist and @dhist
3778 to *not* include the last item given in a range. This brings their
3796 to *not* include the last item given in a range. This brings their
3779 behavior in line with Python's slicing:
3797 behavior in line with Python's slicing:
3780 a[n1:n2] -> a[n1]...a[n2-1]
3798 a[n1:n2] -> a[n1]...a[n2-1]
3781 It may be a bit less convenient, but I prefer to stick to Python's
3799 It may be a bit less convenient, but I prefer to stick to Python's
3782 conventions *everywhere*, so users never have to wonder.
3800 conventions *everywhere*, so users never have to wonder.
3783 (Magic.magic_macro): Added @macro function to ease the creation of
3801 (Magic.magic_macro): Added @macro function to ease the creation of
3784 macros.
3802 macros.
3785
3803
3786 2002-01-05 Fernando Perez <fperez@colorado.edu>
3804 2002-01-05 Fernando Perez <fperez@colorado.edu>
3787
3805
3788 * Released 0.2.4.
3806 * Released 0.2.4.
3789
3807
3790 * IPython/iplib.py (Magic.magic_pdef):
3808 * IPython/iplib.py (Magic.magic_pdef):
3791 (InteractiveShell.safe_execfile): report magic lines and error
3809 (InteractiveShell.safe_execfile): report magic lines and error
3792 lines without line numbers so one can easily copy/paste them for
3810 lines without line numbers so one can easily copy/paste them for
3793 re-execution.
3811 re-execution.
3794
3812
3795 * Updated manual with recent changes.
3813 * Updated manual with recent changes.
3796
3814
3797 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3815 * IPython/iplib.py (Magic.magic_oinfo): added constructor
3798 docstring printing when class? is called. Very handy for knowing
3816 docstring printing when class? is called. Very handy for knowing
3799 how to create class instances (as long as __init__ is well
3817 how to create class instances (as long as __init__ is well
3800 documented, of course :)
3818 documented, of course :)
3801 (Magic.magic_doc): print both class and constructor docstrings.
3819 (Magic.magic_doc): print both class and constructor docstrings.
3802 (Magic.magic_pdef): give constructor info if passed a class and
3820 (Magic.magic_pdef): give constructor info if passed a class and
3803 __call__ info for callable object instances.
3821 __call__ info for callable object instances.
3804
3822
3805 2002-01-04 Fernando Perez <fperez@colorado.edu>
3823 2002-01-04 Fernando Perez <fperez@colorado.edu>
3806
3824
3807 * Made deep_reload() off by default. It doesn't always work
3825 * Made deep_reload() off by default. It doesn't always work
3808 exactly as intended, so it's probably safer to have it off. It's
3826 exactly as intended, so it's probably safer to have it off. It's
3809 still available as dreload() anyway, so nothing is lost.
3827 still available as dreload() anyway, so nothing is lost.
3810
3828
3811 2002-01-02 Fernando Perez <fperez@colorado.edu>
3829 2002-01-02 Fernando Perez <fperez@colorado.edu>
3812
3830
3813 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3831 * Released 0.2.3 (contacted R.Singh at CU about biopython course,
3814 so I wanted an updated release).
3832 so I wanted an updated release).
3815
3833
3816 2001-12-27 Fernando Perez <fperez@colorado.edu>
3834 2001-12-27 Fernando Perez <fperez@colorado.edu>
3817
3835
3818 * IPython/iplib.py (InteractiveShell.interact): Added the original
3836 * IPython/iplib.py (InteractiveShell.interact): Added the original
3819 code from 'code.py' for this module in order to change the
3837 code from 'code.py' for this module in order to change the
3820 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3838 handling of a KeyboardInterrupt. This was necessary b/c otherwise
3821 the history cache would break when the user hit Ctrl-C, and
3839 the history cache would break when the user hit Ctrl-C, and
3822 interact() offers no way to add any hooks to it.
3840 interact() offers no way to add any hooks to it.
3823
3841
3824 2001-12-23 Fernando Perez <fperez@colorado.edu>
3842 2001-12-23 Fernando Perez <fperez@colorado.edu>
3825
3843
3826 * setup.py: added check for 'MANIFEST' before trying to remove
3844 * setup.py: added check for 'MANIFEST' before trying to remove
3827 it. Thanks to Sean Reifschneider.
3845 it. Thanks to Sean Reifschneider.
3828
3846
3829 2001-12-22 Fernando Perez <fperez@colorado.edu>
3847 2001-12-22 Fernando Perez <fperez@colorado.edu>
3830
3848
3831 * Released 0.2.2.
3849 * Released 0.2.2.
3832
3850
3833 * Finished (reasonably) writing the manual. Later will add the
3851 * Finished (reasonably) writing the manual. Later will add the
3834 python-standard navigation stylesheets, but for the time being
3852 python-standard navigation stylesheets, but for the time being
3835 it's fairly complete. Distribution will include html and pdf
3853 it's fairly complete. Distribution will include html and pdf
3836 versions.
3854 versions.
3837
3855
3838 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3856 * Bugfix: '.' wasn't being added to sys.path. Thanks to Prabhu
3839 (MayaVi author).
3857 (MayaVi author).
3840
3858
3841 2001-12-21 Fernando Perez <fperez@colorado.edu>
3859 2001-12-21 Fernando Perez <fperez@colorado.edu>
3842
3860
3843 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3861 * Released 0.2.1. Barring any nasty bugs, this is it as far as a
3844 good public release, I think (with the manual and the distutils
3862 good public release, I think (with the manual and the distutils
3845 installer). The manual can use some work, but that can go
3863 installer). The manual can use some work, but that can go
3846 slowly. Otherwise I think it's quite nice for end users. Next
3864 slowly. Otherwise I think it's quite nice for end users. Next
3847 summer, rewrite the guts of it...
3865 summer, rewrite the guts of it...
3848
3866
3849 * Changed format of ipythonrc files to use whitespace as the
3867 * Changed format of ipythonrc files to use whitespace as the
3850 separator instead of an explicit '='. Cleaner.
3868 separator instead of an explicit '='. Cleaner.
3851
3869
3852 2001-12-20 Fernando Perez <fperez@colorado.edu>
3870 2001-12-20 Fernando Perez <fperez@colorado.edu>
3853
3871
3854 * Started a manual in LyX. For now it's just a quick merge of the
3872 * Started a manual in LyX. For now it's just a quick merge of the
3855 various internal docstrings and READMEs. Later it may grow into a
3873 various internal docstrings and READMEs. Later it may grow into a
3856 nice, full-blown manual.
3874 nice, full-blown manual.
3857
3875
3858 * Set up a distutils based installer. Installation should now be
3876 * Set up a distutils based installer. Installation should now be
3859 trivially simple for end-users.
3877 trivially simple for end-users.
3860
3878
3861 2001-12-11 Fernando Perez <fperez@colorado.edu>
3879 2001-12-11 Fernando Perez <fperez@colorado.edu>
3862
3880
3863 * Released 0.2.0. First public release, announced it at
3881 * Released 0.2.0. First public release, announced it at
3864 comp.lang.python. From now on, just bugfixes...
3882 comp.lang.python. From now on, just bugfixes...
3865
3883
3866 * Went through all the files, set copyright/license notices and
3884 * Went through all the files, set copyright/license notices and
3867 cleaned up things. Ready for release.
3885 cleaned up things. Ready for release.
3868
3886
3869 2001-12-10 Fernando Perez <fperez@colorado.edu>
3887 2001-12-10 Fernando Perez <fperez@colorado.edu>
3870
3888
3871 * Changed the first-time installer not to use tarfiles. It's more
3889 * Changed the first-time installer not to use tarfiles. It's more
3872 robust now and less unix-dependent. Also makes it easier for
3890 robust now and less unix-dependent. Also makes it easier for
3873 people to later upgrade versions.
3891 people to later upgrade versions.
3874
3892
3875 * Changed @exit to @abort to reflect the fact that it's pretty
3893 * Changed @exit to @abort to reflect the fact that it's pretty
3876 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3894 brutal (a sys.exit()). The difference between @abort and Ctrl-D
3877 becomes significant only when IPyhton is embedded: in that case,
3895 becomes significant only when IPyhton is embedded: in that case,
3878 C-D closes IPython only, but @abort kills the enclosing program
3896 C-D closes IPython only, but @abort kills the enclosing program
3879 too (unless it had called IPython inside a try catching
3897 too (unless it had called IPython inside a try catching
3880 SystemExit).
3898 SystemExit).
3881
3899
3882 * Created Shell module which exposes the actuall IPython Shell
3900 * Created Shell module which exposes the actuall IPython Shell
3883 classes, currently the normal and the embeddable one. This at
3901 classes, currently the normal and the embeddable one. This at
3884 least offers a stable interface we won't need to change when
3902 least offers a stable interface we won't need to change when
3885 (later) the internals are rewritten. That rewrite will be confined
3903 (later) the internals are rewritten. That rewrite will be confined
3886 to iplib and ipmaker, but the Shell interface should remain as is.
3904 to iplib and ipmaker, but the Shell interface should remain as is.
3887
3905
3888 * Added embed module which offers an embeddable IPShell object,
3906 * Added embed module which offers an embeddable IPShell object,
3889 useful to fire up IPython *inside* a running program. Great for
3907 useful to fire up IPython *inside* a running program. Great for
3890 debugging or dynamical data analysis.
3908 debugging or dynamical data analysis.
3891
3909
3892 2001-12-08 Fernando Perez <fperez@colorado.edu>
3910 2001-12-08 Fernando Perez <fperez@colorado.edu>
3893
3911
3894 * Fixed small bug preventing seeing info from methods of defined
3912 * Fixed small bug preventing seeing info from methods of defined
3895 objects (incorrect namespace in _ofind()).
3913 objects (incorrect namespace in _ofind()).
3896
3914
3897 * Documentation cleanup. Moved the main usage docstrings to a
3915 * Documentation cleanup. Moved the main usage docstrings to a
3898 separate file, usage.py (cleaner to maintain, and hopefully in the
3916 separate file, usage.py (cleaner to maintain, and hopefully in the
3899 future some perlpod-like way of producing interactive, man and
3917 future some perlpod-like way of producing interactive, man and
3900 html docs out of it will be found).
3918 html docs out of it will be found).
3901
3919
3902 * Added @profile to see your profile at any time.
3920 * Added @profile to see your profile at any time.
3903
3921
3904 * Added @p as an alias for 'print'. It's especially convenient if
3922 * Added @p as an alias for 'print'. It's especially convenient if
3905 using automagic ('p x' prints x).
3923 using automagic ('p x' prints x).
3906
3924
3907 * Small cleanups and fixes after a pychecker run.
3925 * Small cleanups and fixes after a pychecker run.
3908
3926
3909 * Changed the @cd command to handle @cd - and @cd -<n> for
3927 * Changed the @cd command to handle @cd - and @cd -<n> for
3910 visiting any directory in _dh.
3928 visiting any directory in _dh.
3911
3929
3912 * Introduced _dh, a history of visited directories. @dhist prints
3930 * Introduced _dh, a history of visited directories. @dhist prints
3913 it out with numbers.
3931 it out with numbers.
3914
3932
3915 2001-12-07 Fernando Perez <fperez@colorado.edu>
3933 2001-12-07 Fernando Perez <fperez@colorado.edu>
3916
3934
3917 * Released 0.1.22
3935 * Released 0.1.22
3918
3936
3919 * Made initialization a bit more robust against invalid color
3937 * Made initialization a bit more robust against invalid color
3920 options in user input (exit, not traceback-crash).
3938 options in user input (exit, not traceback-crash).
3921
3939
3922 * Changed the bug crash reporter to write the report only in the
3940 * Changed the bug crash reporter to write the report only in the
3923 user's .ipython directory. That way IPython won't litter people's
3941 user's .ipython directory. That way IPython won't litter people's
3924 hard disks with crash files all over the place. Also print on
3942 hard disks with crash files all over the place. Also print on
3925 screen the necessary mail command.
3943 screen the necessary mail command.
3926
3944
3927 * With the new ultraTB, implemented LightBG color scheme for light
3945 * With the new ultraTB, implemented LightBG color scheme for light
3928 background terminals. A lot of people like white backgrounds, so I
3946 background terminals. A lot of people like white backgrounds, so I
3929 guess we should at least give them something readable.
3947 guess we should at least give them something readable.
3930
3948
3931 2001-12-06 Fernando Perez <fperez@colorado.edu>
3949 2001-12-06 Fernando Perez <fperez@colorado.edu>
3932
3950
3933 * Modified the structure of ultraTB. Now there's a proper class
3951 * Modified the structure of ultraTB. Now there's a proper class
3934 for tables of color schemes which allow adding schemes easily and
3952 for tables of color schemes which allow adding schemes easily and
3935 switching the active scheme without creating a new instance every
3953 switching the active scheme without creating a new instance every
3936 time (which was ridiculous). The syntax for creating new schemes
3954 time (which was ridiculous). The syntax for creating new schemes
3937 is also cleaner. I think ultraTB is finally done, with a clean
3955 is also cleaner. I think ultraTB is finally done, with a clean
3938 class structure. Names are also much cleaner (now there's proper
3956 class structure. Names are also much cleaner (now there's proper
3939 color tables, no need for every variable to also have 'color' in
3957 color tables, no need for every variable to also have 'color' in
3940 its name).
3958 its name).
3941
3959
3942 * Broke down genutils into separate files. Now genutils only
3960 * Broke down genutils into separate files. Now genutils only
3943 contains utility functions, and classes have been moved to their
3961 contains utility functions, and classes have been moved to their
3944 own files (they had enough independent functionality to warrant
3962 own files (they had enough independent functionality to warrant
3945 it): ConfigLoader, OutputTrap, Struct.
3963 it): ConfigLoader, OutputTrap, Struct.
3946
3964
3947 2001-12-05 Fernando Perez <fperez@colorado.edu>
3965 2001-12-05 Fernando Perez <fperez@colorado.edu>
3948
3966
3949 * IPython turns 21! Released version 0.1.21, as a candidate for
3967 * IPython turns 21! Released version 0.1.21, as a candidate for
3950 public consumption. If all goes well, release in a few days.
3968 public consumption. If all goes well, release in a few days.
3951
3969
3952 * Fixed path bug (files in Extensions/ directory wouldn't be found
3970 * Fixed path bug (files in Extensions/ directory wouldn't be found
3953 unless IPython/ was explicitly in sys.path).
3971 unless IPython/ was explicitly in sys.path).
3954
3972
3955 * Extended the FlexCompleter class as MagicCompleter to allow
3973 * Extended the FlexCompleter class as MagicCompleter to allow
3956 completion of @-starting lines.
3974 completion of @-starting lines.
3957
3975
3958 * Created __release__.py file as a central repository for release
3976 * Created __release__.py file as a central repository for release
3959 info that other files can read from.
3977 info that other files can read from.
3960
3978
3961 * Fixed small bug in logging: when logging was turned on in
3979 * Fixed small bug in logging: when logging was turned on in
3962 mid-session, old lines with special meanings (!@?) were being
3980 mid-session, old lines with special meanings (!@?) were being
3963 logged without the prepended comment, which is necessary since
3981 logged without the prepended comment, which is necessary since
3964 they are not truly valid python syntax. This should make session
3982 they are not truly valid python syntax. This should make session
3965 restores produce less errors.
3983 restores produce less errors.
3966
3984
3967 * The namespace cleanup forced me to make a FlexCompleter class
3985 * The namespace cleanup forced me to make a FlexCompleter class
3968 which is nothing but a ripoff of rlcompleter, but with selectable
3986 which is nothing but a ripoff of rlcompleter, but with selectable
3969 namespace (rlcompleter only works in __main__.__dict__). I'll try
3987 namespace (rlcompleter only works in __main__.__dict__). I'll try
3970 to submit a note to the authors to see if this change can be
3988 to submit a note to the authors to see if this change can be
3971 incorporated in future rlcompleter releases (Dec.6: done)
3989 incorporated in future rlcompleter releases (Dec.6: done)
3972
3990
3973 * More fixes to namespace handling. It was a mess! Now all
3991 * More fixes to namespace handling. It was a mess! Now all
3974 explicit references to __main__.__dict__ are gone (except when
3992 explicit references to __main__.__dict__ are gone (except when
3975 really needed) and everything is handled through the namespace
3993 really needed) and everything is handled through the namespace
3976 dicts in the IPython instance. We seem to be getting somewhere
3994 dicts in the IPython instance. We seem to be getting somewhere
3977 with this, finally...
3995 with this, finally...
3978
3996
3979 * Small documentation updates.
3997 * Small documentation updates.
3980
3998
3981 * Created the Extensions directory under IPython (with an
3999 * Created the Extensions directory under IPython (with an
3982 __init__.py). Put the PhysicalQ stuff there. This directory should
4000 __init__.py). Put the PhysicalQ stuff there. This directory should
3983 be used for all special-purpose extensions.
4001 be used for all special-purpose extensions.
3984
4002
3985 * File renaming:
4003 * File renaming:
3986 ipythonlib --> ipmaker
4004 ipythonlib --> ipmaker
3987 ipplib --> iplib
4005 ipplib --> iplib
3988 This makes a bit more sense in terms of what these files actually do.
4006 This makes a bit more sense in terms of what these files actually do.
3989
4007
3990 * Moved all the classes and functions in ipythonlib to ipplib, so
4008 * Moved all the classes and functions in ipythonlib to ipplib, so
3991 now ipythonlib only has make_IPython(). This will ease up its
4009 now ipythonlib only has make_IPython(). This will ease up its
3992 splitting in smaller functional chunks later.
4010 splitting in smaller functional chunks later.
3993
4011
3994 * Cleaned up (done, I think) output of @whos. Better column
4012 * Cleaned up (done, I think) output of @whos. Better column
3995 formatting, and now shows str(var) for as much as it can, which is
4013 formatting, and now shows str(var) for as much as it can, which is
3996 typically what one gets with a 'print var'.
4014 typically what one gets with a 'print var'.
3997
4015
3998 2001-12-04 Fernando Perez <fperez@colorado.edu>
4016 2001-12-04 Fernando Perez <fperez@colorado.edu>
3999
4017
4000 * Fixed namespace problems. Now builtin/IPyhton/user names get
4018 * Fixed namespace problems. Now builtin/IPyhton/user names get
4001 properly reported in their namespace. Internal namespace handling
4019 properly reported in their namespace. Internal namespace handling
4002 is finally getting decent (not perfect yet, but much better than
4020 is finally getting decent (not perfect yet, but much better than
4003 the ad-hoc mess we had).
4021 the ad-hoc mess we had).
4004
4022
4005 * Removed -exit option. If people just want to run a python
4023 * Removed -exit option. If people just want to run a python
4006 script, that's what the normal interpreter is for. Less
4024 script, that's what the normal interpreter is for. Less
4007 unnecessary options, less chances for bugs.
4025 unnecessary options, less chances for bugs.
4008
4026
4009 * Added a crash handler which generates a complete post-mortem if
4027 * Added a crash handler which generates a complete post-mortem if
4010 IPython crashes. This will help a lot in tracking bugs down the
4028 IPython crashes. This will help a lot in tracking bugs down the
4011 road.
4029 road.
4012
4030
4013 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4031 * Fixed nasty bug in auto-evaluation part of prefilter(). Names
4014 which were boud to functions being reassigned would bypass the
4032 which were boud to functions being reassigned would bypass the
4015 logger, breaking the sync of _il with the prompt counter. This
4033 logger, breaking the sync of _il with the prompt counter. This
4016 would then crash IPython later when a new line was logged.
4034 would then crash IPython later when a new line was logged.
4017
4035
4018 2001-12-02 Fernando Perez <fperez@colorado.edu>
4036 2001-12-02 Fernando Perez <fperez@colorado.edu>
4019
4037
4020 * Made IPython a package. This means people don't have to clutter
4038 * Made IPython a package. This means people don't have to clutter
4021 their sys.path with yet another directory. Changed the INSTALL
4039 their sys.path with yet another directory. Changed the INSTALL
4022 file accordingly.
4040 file accordingly.
4023
4041
4024 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4042 * Cleaned up the output of @who_ls, @who and @whos. @who_ls now
4025 sorts its output (so @who shows it sorted) and @whos formats the
4043 sorts its output (so @who shows it sorted) and @whos formats the
4026 table according to the width of the first column. Nicer, easier to
4044 table according to the width of the first column. Nicer, easier to
4027 read. Todo: write a generic table_format() which takes a list of
4045 read. Todo: write a generic table_format() which takes a list of
4028 lists and prints it nicely formatted, with optional row/column
4046 lists and prints it nicely formatted, with optional row/column
4029 separators and proper padding and justification.
4047 separators and proper padding and justification.
4030
4048
4031 * Released 0.1.20
4049 * Released 0.1.20
4032
4050
4033 * Fixed bug in @log which would reverse the inputcache list (a
4051 * Fixed bug in @log which would reverse the inputcache list (a
4034 copy operation was missing).
4052 copy operation was missing).
4035
4053
4036 * Code cleanup. @config was changed to use page(). Better, since
4054 * Code cleanup. @config was changed to use page(). Better, since
4037 its output is always quite long.
4055 its output is always quite long.
4038
4056
4039 * Itpl is back as a dependency. I was having too many problems
4057 * Itpl is back as a dependency. I was having too many problems
4040 getting the parametric aliases to work reliably, and it's just
4058 getting the parametric aliases to work reliably, and it's just
4041 easier to code weird string operations with it than playing %()s
4059 easier to code weird string operations with it than playing %()s
4042 games. It's only ~6k, so I don't think it's too big a deal.
4060 games. It's only ~6k, so I don't think it's too big a deal.
4043
4061
4044 * Found (and fixed) a very nasty bug with history. !lines weren't
4062 * Found (and fixed) a very nasty bug with history. !lines weren't
4045 getting cached, and the out of sync caches would crash
4063 getting cached, and the out of sync caches would crash
4046 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4064 IPython. Fixed it by reorganizing the prefilter/handlers/logger
4047 division of labor a bit better. Bug fixed, cleaner structure.
4065 division of labor a bit better. Bug fixed, cleaner structure.
4048
4066
4049 2001-12-01 Fernando Perez <fperez@colorado.edu>
4067 2001-12-01 Fernando Perez <fperez@colorado.edu>
4050
4068
4051 * Released 0.1.19
4069 * Released 0.1.19
4052
4070
4053 * Added option -n to @hist to prevent line number printing. Much
4071 * Added option -n to @hist to prevent line number printing. Much
4054 easier to copy/paste code this way.
4072 easier to copy/paste code this way.
4055
4073
4056 * Created global _il to hold the input list. Allows easy
4074 * Created global _il to hold the input list. Allows easy
4057 re-execution of blocks of code by slicing it (inspired by Janko's
4075 re-execution of blocks of code by slicing it (inspired by Janko's
4058 comment on 'macros').
4076 comment on 'macros').
4059
4077
4060 * Small fixes and doc updates.
4078 * Small fixes and doc updates.
4061
4079
4062 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4080 * Rewrote @history function (was @h). Renamed it to @hist, @h is
4063 much too fragile with automagic. Handles properly multi-line
4081 much too fragile with automagic. Handles properly multi-line
4064 statements and takes parameters.
4082 statements and takes parameters.
4065
4083
4066 2001-11-30 Fernando Perez <fperez@colorado.edu>
4084 2001-11-30 Fernando Perez <fperez@colorado.edu>
4067
4085
4068 * Version 0.1.18 released.
4086 * Version 0.1.18 released.
4069
4087
4070 * Fixed nasty namespace bug in initial module imports.
4088 * Fixed nasty namespace bug in initial module imports.
4071
4089
4072 * Added copyright/license notes to all code files (except
4090 * Added copyright/license notes to all code files (except
4073 DPyGetOpt). For the time being, LGPL. That could change.
4091 DPyGetOpt). For the time being, LGPL. That could change.
4074
4092
4075 * Rewrote a much nicer README, updated INSTALL, cleaned up
4093 * Rewrote a much nicer README, updated INSTALL, cleaned up
4076 ipythonrc-* samples.
4094 ipythonrc-* samples.
4077
4095
4078 * Overall code/documentation cleanup. Basically ready for
4096 * Overall code/documentation cleanup. Basically ready for
4079 release. Only remaining thing: licence decision (LGPL?).
4097 release. Only remaining thing: licence decision (LGPL?).
4080
4098
4081 * Converted load_config to a class, ConfigLoader. Now recursion
4099 * Converted load_config to a class, ConfigLoader. Now recursion
4082 control is better organized. Doesn't include the same file twice.
4100 control is better organized. Doesn't include the same file twice.
4083
4101
4084 2001-11-29 Fernando Perez <fperez@colorado.edu>
4102 2001-11-29 Fernando Perez <fperez@colorado.edu>
4085
4103
4086 * Got input history working. Changed output history variables from
4104 * Got input history working. Changed output history variables from
4087 _p to _o so that _i is for input and _o for output. Just cleaner
4105 _p to _o so that _i is for input and _o for output. Just cleaner
4088 convention.
4106 convention.
4089
4107
4090 * Implemented parametric aliases. This pretty much allows the
4108 * Implemented parametric aliases. This pretty much allows the
4091 alias system to offer full-blown shell convenience, I think.
4109 alias system to offer full-blown shell convenience, I think.
4092
4110
4093 * Version 0.1.17 released, 0.1.18 opened.
4111 * Version 0.1.17 released, 0.1.18 opened.
4094
4112
4095 * dot_ipython/ipythonrc (alias): added documentation.
4113 * dot_ipython/ipythonrc (alias): added documentation.
4096 (xcolor): Fixed small bug (xcolors -> xcolor)
4114 (xcolor): Fixed small bug (xcolors -> xcolor)
4097
4115
4098 * Changed the alias system. Now alias is a magic command to define
4116 * Changed the alias system. Now alias is a magic command to define
4099 aliases just like the shell. Rationale: the builtin magics should
4117 aliases just like the shell. Rationale: the builtin magics should
4100 be there for things deeply connected to IPython's
4118 be there for things deeply connected to IPython's
4101 architecture. And this is a much lighter system for what I think
4119 architecture. And this is a much lighter system for what I think
4102 is the really important feature: allowing users to define quickly
4120 is the really important feature: allowing users to define quickly
4103 magics that will do shell things for them, so they can customize
4121 magics that will do shell things for them, so they can customize
4104 IPython easily to match their work habits. If someone is really
4122 IPython easily to match their work habits. If someone is really
4105 desperate to have another name for a builtin alias, they can
4123 desperate to have another name for a builtin alias, they can
4106 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4124 always use __IP.magic_newname = __IP.magic_oldname. Hackish but
4107 works.
4125 works.
4108
4126
4109 2001-11-28 Fernando Perez <fperez@colorado.edu>
4127 2001-11-28 Fernando Perez <fperez@colorado.edu>
4110
4128
4111 * Changed @file so that it opens the source file at the proper
4129 * Changed @file so that it opens the source file at the proper
4112 line. Since it uses less, if your EDITOR environment is
4130 line. Since it uses less, if your EDITOR environment is
4113 configured, typing v will immediately open your editor of choice
4131 configured, typing v will immediately open your editor of choice
4114 right at the line where the object is defined. Not as quick as
4132 right at the line where the object is defined. Not as quick as
4115 having a direct @edit command, but for all intents and purposes it
4133 having a direct @edit command, but for all intents and purposes it
4116 works. And I don't have to worry about writing @edit to deal with
4134 works. And I don't have to worry about writing @edit to deal with
4117 all the editors, less does that.
4135 all the editors, less does that.
4118
4136
4119 * Version 0.1.16 released, 0.1.17 opened.
4137 * Version 0.1.16 released, 0.1.17 opened.
4120
4138
4121 * Fixed some nasty bugs in the page/page_dumb combo that could
4139 * Fixed some nasty bugs in the page/page_dumb combo that could
4122 crash IPython.
4140 crash IPython.
4123
4141
4124 2001-11-27 Fernando Perez <fperez@colorado.edu>
4142 2001-11-27 Fernando Perez <fperez@colorado.edu>
4125
4143
4126 * Version 0.1.15 released, 0.1.16 opened.
4144 * Version 0.1.15 released, 0.1.16 opened.
4127
4145
4128 * Finally got ? and ?? to work for undefined things: now it's
4146 * Finally got ? and ?? to work for undefined things: now it's
4129 possible to type {}.get? and get information about the get method
4147 possible to type {}.get? and get information about the get method
4130 of dicts, or os.path? even if only os is defined (so technically
4148 of dicts, or os.path? even if only os is defined (so technically
4131 os.path isn't). Works at any level. For example, after import os,
4149 os.path isn't). Works at any level. For example, after import os,
4132 os?, os.path?, os.path.abspath? all work. This is great, took some
4150 os?, os.path?, os.path.abspath? all work. This is great, took some
4133 work in _ofind.
4151 work in _ofind.
4134
4152
4135 * Fixed more bugs with logging. The sanest way to do it was to add
4153 * Fixed more bugs with logging. The sanest way to do it was to add
4136 to @log a 'mode' parameter. Killed two in one shot (this mode
4154 to @log a 'mode' parameter. Killed two in one shot (this mode
4137 option was a request of Janko's). I think it's finally clean
4155 option was a request of Janko's). I think it's finally clean
4138 (famous last words).
4156 (famous last words).
4139
4157
4140 * Added a page_dumb() pager which does a decent job of paging on
4158 * Added a page_dumb() pager which does a decent job of paging on
4141 screen, if better things (like less) aren't available. One less
4159 screen, if better things (like less) aren't available. One less
4142 unix dependency (someday maybe somebody will port this to
4160 unix dependency (someday maybe somebody will port this to
4143 windows).
4161 windows).
4144
4162
4145 * Fixed problem in magic_log: would lock of logging out if log
4163 * Fixed problem in magic_log: would lock of logging out if log
4146 creation failed (because it would still think it had succeeded).
4164 creation failed (because it would still think it had succeeded).
4147
4165
4148 * Improved the page() function using curses to auto-detect screen
4166 * Improved the page() function using curses to auto-detect screen
4149 size. Now it can make a much better decision on whether to print
4167 size. Now it can make a much better decision on whether to print
4150 or page a string. Option screen_length was modified: a value 0
4168 or page a string. Option screen_length was modified: a value 0
4151 means auto-detect, and that's the default now.
4169 means auto-detect, and that's the default now.
4152
4170
4153 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4171 * Version 0.1.14 released, 0.1.15 opened. I think this is ready to
4154 go out. I'll test it for a few days, then talk to Janko about
4172 go out. I'll test it for a few days, then talk to Janko about
4155 licences and announce it.
4173 licences and announce it.
4156
4174
4157 * Fixed the length of the auto-generated ---> prompt which appears
4175 * Fixed the length of the auto-generated ---> prompt which appears
4158 for auto-parens and auto-quotes. Getting this right isn't trivial,
4176 for auto-parens and auto-quotes. Getting this right isn't trivial,
4159 with all the color escapes, different prompt types and optional
4177 with all the color escapes, different prompt types and optional
4160 separators. But it seems to be working in all the combinations.
4178 separators. But it seems to be working in all the combinations.
4161
4179
4162 2001-11-26 Fernando Perez <fperez@colorado.edu>
4180 2001-11-26 Fernando Perez <fperez@colorado.edu>
4163
4181
4164 * Wrote a regexp filter to get option types from the option names
4182 * Wrote a regexp filter to get option types from the option names
4165 string. This eliminates the need to manually keep two duplicate
4183 string. This eliminates the need to manually keep two duplicate
4166 lists.
4184 lists.
4167
4185
4168 * Removed the unneeded check_option_names. Now options are handled
4186 * Removed the unneeded check_option_names. Now options are handled
4169 in a much saner manner and it's easy to visually check that things
4187 in a much saner manner and it's easy to visually check that things
4170 are ok.
4188 are ok.
4171
4189
4172 * Updated version numbers on all files I modified to carry a
4190 * Updated version numbers on all files I modified to carry a
4173 notice so Janko and Nathan have clear version markers.
4191 notice so Janko and Nathan have clear version markers.
4174
4192
4175 * Updated docstring for ultraTB with my changes. I should send
4193 * Updated docstring for ultraTB with my changes. I should send
4176 this to Nathan.
4194 this to Nathan.
4177
4195
4178 * Lots of small fixes. Ran everything through pychecker again.
4196 * Lots of small fixes. Ran everything through pychecker again.
4179
4197
4180 * Made loading of deep_reload an cmd line option. If it's not too
4198 * Made loading of deep_reload an cmd line option. If it's not too
4181 kosher, now people can just disable it. With -nodeep_reload it's
4199 kosher, now people can just disable it. With -nodeep_reload it's
4182 still available as dreload(), it just won't overwrite reload().
4200 still available as dreload(), it just won't overwrite reload().
4183
4201
4184 * Moved many options to the no| form (-opt and -noopt
4202 * Moved many options to the no| form (-opt and -noopt
4185 accepted). Cleaner.
4203 accepted). Cleaner.
4186
4204
4187 * Changed magic_log so that if called with no parameters, it uses
4205 * Changed magic_log so that if called with no parameters, it uses
4188 'rotate' mode. That way auto-generated logs aren't automatically
4206 'rotate' mode. That way auto-generated logs aren't automatically
4189 over-written. For normal logs, now a backup is made if it exists
4207 over-written. For normal logs, now a backup is made if it exists
4190 (only 1 level of backups). A new 'backup' mode was added to the
4208 (only 1 level of backups). A new 'backup' mode was added to the
4191 Logger class to support this. This was a request by Janko.
4209 Logger class to support this. This was a request by Janko.
4192
4210
4193 * Added @logoff/@logon to stop/restart an active log.
4211 * Added @logoff/@logon to stop/restart an active log.
4194
4212
4195 * Fixed a lot of bugs in log saving/replay. It was pretty
4213 * Fixed a lot of bugs in log saving/replay. It was pretty
4196 broken. Now special lines (!@,/) appear properly in the command
4214 broken. Now special lines (!@,/) appear properly in the command
4197 history after a log replay.
4215 history after a log replay.
4198
4216
4199 * Tried and failed to implement full session saving via pickle. My
4217 * Tried and failed to implement full session saving via pickle. My
4200 idea was to pickle __main__.__dict__, but modules can't be
4218 idea was to pickle __main__.__dict__, but modules can't be
4201 pickled. This would be a better alternative to replaying logs, but
4219 pickled. This would be a better alternative to replaying logs, but
4202 seems quite tricky to get to work. Changed -session to be called
4220 seems quite tricky to get to work. Changed -session to be called
4203 -logplay, which more accurately reflects what it does. And if we
4221 -logplay, which more accurately reflects what it does. And if we
4204 ever get real session saving working, -session is now available.
4222 ever get real session saving working, -session is now available.
4205
4223
4206 * Implemented color schemes for prompts also. As for tracebacks,
4224 * Implemented color schemes for prompts also. As for tracebacks,
4207 currently only NoColor and Linux are supported. But now the
4225 currently only NoColor and Linux are supported. But now the
4208 infrastructure is in place, based on a generic ColorScheme
4226 infrastructure is in place, based on a generic ColorScheme
4209 class. So writing and activating new schemes both for the prompts
4227 class. So writing and activating new schemes both for the prompts
4210 and the tracebacks should be straightforward.
4228 and the tracebacks should be straightforward.
4211
4229
4212 * Version 0.1.13 released, 0.1.14 opened.
4230 * Version 0.1.13 released, 0.1.14 opened.
4213
4231
4214 * Changed handling of options for output cache. Now counter is
4232 * Changed handling of options for output cache. Now counter is
4215 hardwired starting at 1 and one specifies the maximum number of
4233 hardwired starting at 1 and one specifies the maximum number of
4216 entries *in the outcache* (not the max prompt counter). This is
4234 entries *in the outcache* (not the max prompt counter). This is
4217 much better, since many statements won't increase the cache
4235 much better, since many statements won't increase the cache
4218 count. It also eliminated some confusing options, now there's only
4236 count. It also eliminated some confusing options, now there's only
4219 one: cache_size.
4237 one: cache_size.
4220
4238
4221 * Added 'alias' magic function and magic_alias option in the
4239 * Added 'alias' magic function and magic_alias option in the
4222 ipythonrc file. Now the user can easily define whatever names he
4240 ipythonrc file. Now the user can easily define whatever names he
4223 wants for the magic functions without having to play weird
4241 wants for the magic functions without having to play weird
4224 namespace games. This gives IPython a real shell-like feel.
4242 namespace games. This gives IPython a real shell-like feel.
4225
4243
4226 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4244 * Fixed doc/?/?? for magics. Now all work, in all forms (explicit
4227 @ or not).
4245 @ or not).
4228
4246
4229 This was one of the last remaining 'visible' bugs (that I know
4247 This was one of the last remaining 'visible' bugs (that I know
4230 of). I think if I can clean up the session loading so it works
4248 of). I think if I can clean up the session loading so it works
4231 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4249 100% I'll release a 0.2.0 version on c.p.l (talk to Janko first
4232 about licensing).
4250 about licensing).
4233
4251
4234 2001-11-25 Fernando Perez <fperez@colorado.edu>
4252 2001-11-25 Fernando Perez <fperez@colorado.edu>
4235
4253
4236 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4254 * Rewrote somewhat oinfo (?/??). Nicer, now uses page() and
4237 there's a cleaner distinction between what ? and ?? show.
4255 there's a cleaner distinction between what ? and ?? show.
4238
4256
4239 * Added screen_length option. Now the user can define his own
4257 * Added screen_length option. Now the user can define his own
4240 screen size for page() operations.
4258 screen size for page() operations.
4241
4259
4242 * Implemented magic shell-like functions with automatic code
4260 * Implemented magic shell-like functions with automatic code
4243 generation. Now adding another function is just a matter of adding
4261 generation. Now adding another function is just a matter of adding
4244 an entry to a dict, and the function is dynamically generated at
4262 an entry to a dict, and the function is dynamically generated at
4245 run-time. Python has some really cool features!
4263 run-time. Python has some really cool features!
4246
4264
4247 * Renamed many options to cleanup conventions a little. Now all
4265 * Renamed many options to cleanup conventions a little. Now all
4248 are lowercase, and only underscores where needed. Also in the code
4266 are lowercase, and only underscores where needed. Also in the code
4249 option name tables are clearer.
4267 option name tables are clearer.
4250
4268
4251 * Changed prompts a little. Now input is 'In [n]:' instead of
4269 * Changed prompts a little. Now input is 'In [n]:' instead of
4252 'In[n]:='. This allows it the numbers to be aligned with the
4270 'In[n]:='. This allows it the numbers to be aligned with the
4253 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4271 Out[n] numbers, and removes usage of ':=' which doesn't exist in
4254 Python (it was a Mathematica thing). The '...' continuation prompt
4272 Python (it was a Mathematica thing). The '...' continuation prompt
4255 was also changed a little to align better.
4273 was also changed a little to align better.
4256
4274
4257 * Fixed bug when flushing output cache. Not all _p<n> variables
4275 * Fixed bug when flushing output cache. Not all _p<n> variables
4258 exist, so their deletion needs to be wrapped in a try:
4276 exist, so their deletion needs to be wrapped in a try:
4259
4277
4260 * Figured out how to properly use inspect.formatargspec() (it
4278 * Figured out how to properly use inspect.formatargspec() (it
4261 requires the args preceded by *). So I removed all the code from
4279 requires the args preceded by *). So I removed all the code from
4262 _get_pdef in Magic, which was just replicating that.
4280 _get_pdef in Magic, which was just replicating that.
4263
4281
4264 * Added test to prefilter to allow redefining magic function names
4282 * Added test to prefilter to allow redefining magic function names
4265 as variables. This is ok, since the @ form is always available,
4283 as variables. This is ok, since the @ form is always available,
4266 but whe should allow the user to define a variable called 'ls' if
4284 but whe should allow the user to define a variable called 'ls' if
4267 he needs it.
4285 he needs it.
4268
4286
4269 * Moved the ToDo information from README into a separate ToDo.
4287 * Moved the ToDo information from README into a separate ToDo.
4270
4288
4271 * General code cleanup and small bugfixes. I think it's close to a
4289 * General code cleanup and small bugfixes. I think it's close to a
4272 state where it can be released, obviously with a big 'beta'
4290 state where it can be released, obviously with a big 'beta'
4273 warning on it.
4291 warning on it.
4274
4292
4275 * Got the magic function split to work. Now all magics are defined
4293 * Got the magic function split to work. Now all magics are defined
4276 in a separate class. It just organizes things a bit, and now
4294 in a separate class. It just organizes things a bit, and now
4277 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4295 Xemacs behaves nicer (it was choking on InteractiveShell b/c it
4278 was too long).
4296 was too long).
4279
4297
4280 * Changed @clear to @reset to avoid potential confusions with
4298 * Changed @clear to @reset to avoid potential confusions with
4281 the shell command clear. Also renamed @cl to @clear, which does
4299 the shell command clear. Also renamed @cl to @clear, which does
4282 exactly what people expect it to from their shell experience.
4300 exactly what people expect it to from their shell experience.
4283
4301
4284 Added a check to the @reset command (since it's so
4302 Added a check to the @reset command (since it's so
4285 destructive, it's probably a good idea to ask for confirmation).
4303 destructive, it's probably a good idea to ask for confirmation).
4286 But now reset only works for full namespace resetting. Since the
4304 But now reset only works for full namespace resetting. Since the
4287 del keyword is already there for deleting a few specific
4305 del keyword is already there for deleting a few specific
4288 variables, I don't see the point of having a redundant magic
4306 variables, I don't see the point of having a redundant magic
4289 function for the same task.
4307 function for the same task.
4290
4308
4291 2001-11-24 Fernando Perez <fperez@colorado.edu>
4309 2001-11-24 Fernando Perez <fperez@colorado.edu>
4292
4310
4293 * Updated the builtin docs (esp. the ? ones).
4311 * Updated the builtin docs (esp. the ? ones).
4294
4312
4295 * Ran all the code through pychecker. Not terribly impressed with
4313 * Ran all the code through pychecker. Not terribly impressed with
4296 it: lots of spurious warnings and didn't really find anything of
4314 it: lots of spurious warnings and didn't really find anything of
4297 substance (just a few modules being imported and not used).
4315 substance (just a few modules being imported and not used).
4298
4316
4299 * Implemented the new ultraTB functionality into IPython. New
4317 * Implemented the new ultraTB functionality into IPython. New
4300 option: xcolors. This chooses color scheme. xmode now only selects
4318 option: xcolors. This chooses color scheme. xmode now only selects
4301 between Plain and Verbose. Better orthogonality.
4319 between Plain and Verbose. Better orthogonality.
4302
4320
4303 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4321 * Large rewrite of ultraTB. Much cleaner now, with a separation of
4304 mode and color scheme for the exception handlers. Now it's
4322 mode and color scheme for the exception handlers. Now it's
4305 possible to have the verbose traceback with no coloring.
4323 possible to have the verbose traceback with no coloring.
4306
4324
4307 2001-11-23 Fernando Perez <fperez@colorado.edu>
4325 2001-11-23 Fernando Perez <fperez@colorado.edu>
4308
4326
4309 * Version 0.1.12 released, 0.1.13 opened.
4327 * Version 0.1.12 released, 0.1.13 opened.
4310
4328
4311 * Removed option to set auto-quote and auto-paren escapes by
4329 * Removed option to set auto-quote and auto-paren escapes by
4312 user. The chances of breaking valid syntax are just too high. If
4330 user. The chances of breaking valid syntax are just too high. If
4313 someone *really* wants, they can always dig into the code.
4331 someone *really* wants, they can always dig into the code.
4314
4332
4315 * Made prompt separators configurable.
4333 * Made prompt separators configurable.
4316
4334
4317 2001-11-22 Fernando Perez <fperez@colorado.edu>
4335 2001-11-22 Fernando Perez <fperez@colorado.edu>
4318
4336
4319 * Small bugfixes in many places.
4337 * Small bugfixes in many places.
4320
4338
4321 * Removed the MyCompleter class from ipplib. It seemed redundant
4339 * Removed the MyCompleter class from ipplib. It seemed redundant
4322 with the C-p,C-n history search functionality. Less code to
4340 with the C-p,C-n history search functionality. Less code to
4323 maintain.
4341 maintain.
4324
4342
4325 * Moved all the original ipython.py code into ipythonlib.py. Right
4343 * Moved all the original ipython.py code into ipythonlib.py. Right
4326 now it's just one big dump into a function called make_IPython, so
4344 now it's just one big dump into a function called make_IPython, so
4327 no real modularity has been gained. But at least it makes the
4345 no real modularity has been gained. But at least it makes the
4328 wrapper script tiny, and since ipythonlib is a module, it gets
4346 wrapper script tiny, and since ipythonlib is a module, it gets
4329 compiled and startup is much faster.
4347 compiled and startup is much faster.
4330
4348
4331 This is a reasobably 'deep' change, so we should test it for a
4349 This is a reasobably 'deep' change, so we should test it for a
4332 while without messing too much more with the code.
4350 while without messing too much more with the code.
4333
4351
4334 2001-11-21 Fernando Perez <fperez@colorado.edu>
4352 2001-11-21 Fernando Perez <fperez@colorado.edu>
4335
4353
4336 * Version 0.1.11 released, 0.1.12 opened for further work.
4354 * Version 0.1.11 released, 0.1.12 opened for further work.
4337
4355
4338 * Removed dependency on Itpl. It was only needed in one place. It
4356 * Removed dependency on Itpl. It was only needed in one place. It
4339 would be nice if this became part of python, though. It makes life
4357 would be nice if this became part of python, though. It makes life
4340 *a lot* easier in some cases.
4358 *a lot* easier in some cases.
4341
4359
4342 * Simplified the prefilter code a bit. Now all handlers are
4360 * Simplified the prefilter code a bit. Now all handlers are
4343 expected to explicitly return a value (at least a blank string).
4361 expected to explicitly return a value (at least a blank string).
4344
4362
4345 * Heavy edits in ipplib. Removed the help system altogether. Now
4363 * Heavy edits in ipplib. Removed the help system altogether. Now
4346 obj?/?? is used for inspecting objects, a magic @doc prints
4364 obj?/?? is used for inspecting objects, a magic @doc prints
4347 docstrings, and full-blown Python help is accessed via the 'help'
4365 docstrings, and full-blown Python help is accessed via the 'help'
4348 keyword. This cleans up a lot of code (less to maintain) and does
4366 keyword. This cleans up a lot of code (less to maintain) and does
4349 the job. Since 'help' is now a standard Python component, might as
4367 the job. Since 'help' is now a standard Python component, might as
4350 well use it and remove duplicate functionality.
4368 well use it and remove duplicate functionality.
4351
4369
4352 Also removed the option to use ipplib as a standalone program. By
4370 Also removed the option to use ipplib as a standalone program. By
4353 now it's too dependent on other parts of IPython to function alone.
4371 now it's too dependent on other parts of IPython to function alone.
4354
4372
4355 * Fixed bug in genutils.pager. It would crash if the pager was
4373 * Fixed bug in genutils.pager. It would crash if the pager was
4356 exited immediately after opening (broken pipe).
4374 exited immediately after opening (broken pipe).
4357
4375
4358 * Trimmed down the VerboseTB reporting a little. The header is
4376 * Trimmed down the VerboseTB reporting a little. The header is
4359 much shorter now and the repeated exception arguments at the end
4377 much shorter now and the repeated exception arguments at the end
4360 have been removed. For interactive use the old header seemed a bit
4378 have been removed. For interactive use the old header seemed a bit
4361 excessive.
4379 excessive.
4362
4380
4363 * Fixed small bug in output of @whos for variables with multi-word
4381 * Fixed small bug in output of @whos for variables with multi-word
4364 types (only first word was displayed).
4382 types (only first word was displayed).
4365
4383
4366 2001-11-17 Fernando Perez <fperez@colorado.edu>
4384 2001-11-17 Fernando Perez <fperez@colorado.edu>
4367
4385
4368 * Version 0.1.10 released, 0.1.11 opened for further work.
4386 * Version 0.1.10 released, 0.1.11 opened for further work.
4369
4387
4370 * Modified dirs and friends. dirs now *returns* the stack (not
4388 * Modified dirs and friends. dirs now *returns* the stack (not
4371 prints), so one can manipulate it as a variable. Convenient to
4389 prints), so one can manipulate it as a variable. Convenient to
4372 travel along many directories.
4390 travel along many directories.
4373
4391
4374 * Fixed bug in magic_pdef: would only work with functions with
4392 * Fixed bug in magic_pdef: would only work with functions with
4375 arguments with default values.
4393 arguments with default values.
4376
4394
4377 2001-11-14 Fernando Perez <fperez@colorado.edu>
4395 2001-11-14 Fernando Perez <fperez@colorado.edu>
4378
4396
4379 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4397 * Added the PhysicsInput stuff to dot_ipython so it ships as an
4380 example with IPython. Various other minor fixes and cleanups.
4398 example with IPython. Various other minor fixes and cleanups.
4381
4399
4382 * Version 0.1.9 released, 0.1.10 opened for further work.
4400 * Version 0.1.9 released, 0.1.10 opened for further work.
4383
4401
4384 * Added sys.path to the list of directories searched in the
4402 * Added sys.path to the list of directories searched in the
4385 execfile= option. It used to be the current directory and the
4403 execfile= option. It used to be the current directory and the
4386 user's IPYTHONDIR only.
4404 user's IPYTHONDIR only.
4387
4405
4388 2001-11-13 Fernando Perez <fperez@colorado.edu>
4406 2001-11-13 Fernando Perez <fperez@colorado.edu>
4389
4407
4390 * Reinstated the raw_input/prefilter separation that Janko had
4408 * Reinstated the raw_input/prefilter separation that Janko had
4391 initially. This gives a more convenient setup for extending the
4409 initially. This gives a more convenient setup for extending the
4392 pre-processor from the outside: raw_input always gets a string,
4410 pre-processor from the outside: raw_input always gets a string,
4393 and prefilter has to process it. We can then redefine prefilter
4411 and prefilter has to process it. We can then redefine prefilter
4394 from the outside and implement extensions for special
4412 from the outside and implement extensions for special
4395 purposes.
4413 purposes.
4396
4414
4397 Today I got one for inputting PhysicalQuantity objects
4415 Today I got one for inputting PhysicalQuantity objects
4398 (from Scientific) without needing any function calls at
4416 (from Scientific) without needing any function calls at
4399 all. Extremely convenient, and it's all done as a user-level
4417 all. Extremely convenient, and it's all done as a user-level
4400 extension (no IPython code was touched). Now instead of:
4418 extension (no IPython code was touched). Now instead of:
4401 a = PhysicalQuantity(4.2,'m/s**2')
4419 a = PhysicalQuantity(4.2,'m/s**2')
4402 one can simply say
4420 one can simply say
4403 a = 4.2 m/s**2
4421 a = 4.2 m/s**2
4404 or even
4422 or even
4405 a = 4.2 m/s^2
4423 a = 4.2 m/s^2
4406
4424
4407 I use this, but it's also a proof of concept: IPython really is
4425 I use this, but it's also a proof of concept: IPython really is
4408 fully user-extensible, even at the level of the parsing of the
4426 fully user-extensible, even at the level of the parsing of the
4409 command line. It's not trivial, but it's perfectly doable.
4427 command line. It's not trivial, but it's perfectly doable.
4410
4428
4411 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4429 * Added 'add_flip' method to inclusion conflict resolver. Fixes
4412 the problem of modules being loaded in the inverse order in which
4430 the problem of modules being loaded in the inverse order in which
4413 they were defined in
4431 they were defined in
4414
4432
4415 * Version 0.1.8 released, 0.1.9 opened for further work.
4433 * Version 0.1.8 released, 0.1.9 opened for further work.
4416
4434
4417 * Added magics pdef, source and file. They respectively show the
4435 * Added magics pdef, source and file. They respectively show the
4418 definition line ('prototype' in C), source code and full python
4436 definition line ('prototype' in C), source code and full python
4419 file for any callable object. The object inspector oinfo uses
4437 file for any callable object. The object inspector oinfo uses
4420 these to show the same information.
4438 these to show the same information.
4421
4439
4422 * Version 0.1.7 released, 0.1.8 opened for further work.
4440 * Version 0.1.7 released, 0.1.8 opened for further work.
4423
4441
4424 * Separated all the magic functions into a class called Magic. The
4442 * Separated all the magic functions into a class called Magic. The
4425 InteractiveShell class was becoming too big for Xemacs to handle
4443 InteractiveShell class was becoming too big for Xemacs to handle
4426 (de-indenting a line would lock it up for 10 seconds while it
4444 (de-indenting a line would lock it up for 10 seconds while it
4427 backtracked on the whole class!)
4445 backtracked on the whole class!)
4428
4446
4429 FIXME: didn't work. It can be done, but right now namespaces are
4447 FIXME: didn't work. It can be done, but right now namespaces are
4430 all messed up. Do it later (reverted it for now, so at least
4448 all messed up. Do it later (reverted it for now, so at least
4431 everything works as before).
4449 everything works as before).
4432
4450
4433 * Got the object introspection system (magic_oinfo) working! I
4451 * Got the object introspection system (magic_oinfo) working! I
4434 think this is pretty much ready for release to Janko, so he can
4452 think this is pretty much ready for release to Janko, so he can
4435 test it for a while and then announce it. Pretty much 100% of what
4453 test it for a while and then announce it. Pretty much 100% of what
4436 I wanted for the 'phase 1' release is ready. Happy, tired.
4454 I wanted for the 'phase 1' release is ready. Happy, tired.
4437
4455
4438 2001-11-12 Fernando Perez <fperez@colorado.edu>
4456 2001-11-12 Fernando Perez <fperez@colorado.edu>
4439
4457
4440 * Version 0.1.6 released, 0.1.7 opened for further work.
4458 * Version 0.1.6 released, 0.1.7 opened for further work.
4441
4459
4442 * Fixed bug in printing: it used to test for truth before
4460 * Fixed bug in printing: it used to test for truth before
4443 printing, so 0 wouldn't print. Now checks for None.
4461 printing, so 0 wouldn't print. Now checks for None.
4444
4462
4445 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4463 * Fixed bug where auto-execs increase the prompt counter by 2 (b/c
4446 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4464 they have to call len(str(sys.ps1)) ). But the fix is ugly, it
4447 reaches by hand into the outputcache. Think of a better way to do
4465 reaches by hand into the outputcache. Think of a better way to do
4448 this later.
4466 this later.
4449
4467
4450 * Various small fixes thanks to Nathan's comments.
4468 * Various small fixes thanks to Nathan's comments.
4451
4469
4452 * Changed magic_pprint to magic_Pprint. This way it doesn't
4470 * Changed magic_pprint to magic_Pprint. This way it doesn't
4453 collide with pprint() and the name is consistent with the command
4471 collide with pprint() and the name is consistent with the command
4454 line option.
4472 line option.
4455
4473
4456 * Changed prompt counter behavior to be fully like
4474 * Changed prompt counter behavior to be fully like
4457 Mathematica's. That is, even input that doesn't return a result
4475 Mathematica's. That is, even input that doesn't return a result
4458 raises the prompt counter. The old behavior was kind of confusing
4476 raises the prompt counter. The old behavior was kind of confusing
4459 (getting the same prompt number several times if the operation
4477 (getting the same prompt number several times if the operation
4460 didn't return a result).
4478 didn't return a result).
4461
4479
4462 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4480 * Fixed Nathan's last name in a couple of places (Gray, not Graham).
4463
4481
4464 * Fixed -Classic mode (wasn't working anymore).
4482 * Fixed -Classic mode (wasn't working anymore).
4465
4483
4466 * Added colored prompts using Nathan's new code. Colors are
4484 * Added colored prompts using Nathan's new code. Colors are
4467 currently hardwired, they can be user-configurable. For
4485 currently hardwired, they can be user-configurable. For
4468 developers, they can be chosen in file ipythonlib.py, at the
4486 developers, they can be chosen in file ipythonlib.py, at the
4469 beginning of the CachedOutput class def.
4487 beginning of the CachedOutput class def.
4470
4488
4471 2001-11-11 Fernando Perez <fperez@colorado.edu>
4489 2001-11-11 Fernando Perez <fperez@colorado.edu>
4472
4490
4473 * Version 0.1.5 released, 0.1.6 opened for further work.
4491 * Version 0.1.5 released, 0.1.6 opened for further work.
4474
4492
4475 * Changed magic_env to *return* the environment as a dict (not to
4493 * Changed magic_env to *return* the environment as a dict (not to
4476 print it). This way it prints, but it can also be processed.
4494 print it). This way it prints, but it can also be processed.
4477
4495
4478 * Added Verbose exception reporting to interactive
4496 * Added Verbose exception reporting to interactive
4479 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4497 exceptions. Very nice, now even 1/0 at the prompt gives a verbose
4480 traceback. Had to make some changes to the ultraTB file. This is
4498 traceback. Had to make some changes to the ultraTB file. This is
4481 probably the last 'big' thing in my mental todo list. This ties
4499 probably the last 'big' thing in my mental todo list. This ties
4482 in with the next entry:
4500 in with the next entry:
4483
4501
4484 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4502 * Changed -Xi and -Xf to a single -xmode option. Now all the user
4485 has to specify is Plain, Color or Verbose for all exception
4503 has to specify is Plain, Color or Verbose for all exception
4486 handling.
4504 handling.
4487
4505
4488 * Removed ShellServices option. All this can really be done via
4506 * Removed ShellServices option. All this can really be done via
4489 the magic system. It's easier to extend, cleaner and has automatic
4507 the magic system. It's easier to extend, cleaner and has automatic
4490 namespace protection and documentation.
4508 namespace protection and documentation.
4491
4509
4492 2001-11-09 Fernando Perez <fperez@colorado.edu>
4510 2001-11-09 Fernando Perez <fperez@colorado.edu>
4493
4511
4494 * Fixed bug in output cache flushing (missing parameter to
4512 * Fixed bug in output cache flushing (missing parameter to
4495 __init__). Other small bugs fixed (found using pychecker).
4513 __init__). Other small bugs fixed (found using pychecker).
4496
4514
4497 * Version 0.1.4 opened for bugfixing.
4515 * Version 0.1.4 opened for bugfixing.
4498
4516
4499 2001-11-07 Fernando Perez <fperez@colorado.edu>
4517 2001-11-07 Fernando Perez <fperez@colorado.edu>
4500
4518
4501 * Version 0.1.3 released, mainly because of the raw_input bug.
4519 * Version 0.1.3 released, mainly because of the raw_input bug.
4502
4520
4503 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4521 * Fixed NASTY bug in raw_input: input line wasn't properly parsed
4504 and when testing for whether things were callable, a call could
4522 and when testing for whether things were callable, a call could
4505 actually be made to certain functions. They would get called again
4523 actually be made to certain functions. They would get called again
4506 once 'really' executed, with a resulting double call. A disaster
4524 once 'really' executed, with a resulting double call. A disaster
4507 in many cases (list.reverse() would never work!).
4525 in many cases (list.reverse() would never work!).
4508
4526
4509 * Removed prefilter() function, moved its code to raw_input (which
4527 * Removed prefilter() function, moved its code to raw_input (which
4510 after all was just a near-empty caller for prefilter). This saves
4528 after all was just a near-empty caller for prefilter). This saves
4511 a function call on every prompt, and simplifies the class a tiny bit.
4529 a function call on every prompt, and simplifies the class a tiny bit.
4512
4530
4513 * Fix _ip to __ip name in magic example file.
4531 * Fix _ip to __ip name in magic example file.
4514
4532
4515 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4533 * Changed 'tar -x -f' to 'tar xvf' in auto-installer. This should
4516 work with non-gnu versions of tar.
4534 work with non-gnu versions of tar.
4517
4535
4518 2001-11-06 Fernando Perez <fperez@colorado.edu>
4536 2001-11-06 Fernando Perez <fperez@colorado.edu>
4519
4537
4520 * Version 0.1.2. Just to keep track of the recent changes.
4538 * Version 0.1.2. Just to keep track of the recent changes.
4521
4539
4522 * Fixed nasty bug in output prompt routine. It used to check 'if
4540 * Fixed nasty bug in output prompt routine. It used to check 'if
4523 arg != None...'. Problem is, this fails if arg implements a
4541 arg != None...'. Problem is, this fails if arg implements a
4524 special comparison (__cmp__) which disallows comparing to
4542 special comparison (__cmp__) which disallows comparing to
4525 None. Found it when trying to use the PhysicalQuantity module from
4543 None. Found it when trying to use the PhysicalQuantity module from
4526 ScientificPython.
4544 ScientificPython.
4527
4545
4528 2001-11-05 Fernando Perez <fperez@colorado.edu>
4546 2001-11-05 Fernando Perez <fperez@colorado.edu>
4529
4547
4530 * Also added dirs. Now the pushd/popd/dirs family functions
4548 * Also added dirs. Now the pushd/popd/dirs family functions
4531 basically like the shell, with the added convenience of going home
4549 basically like the shell, with the added convenience of going home
4532 when called with no args.
4550 when called with no args.
4533
4551
4534 * pushd/popd slightly modified to mimic shell behavior more
4552 * pushd/popd slightly modified to mimic shell behavior more
4535 closely.
4553 closely.
4536
4554
4537 * Added env,pushd,popd from ShellServices as magic functions. I
4555 * Added env,pushd,popd from ShellServices as magic functions. I
4538 think the cleanest will be to port all desired functions from
4556 think the cleanest will be to port all desired functions from
4539 ShellServices as magics and remove ShellServices altogether. This
4557 ShellServices as magics and remove ShellServices altogether. This
4540 will provide a single, clean way of adding functionality
4558 will provide a single, clean way of adding functionality
4541 (shell-type or otherwise) to IP.
4559 (shell-type or otherwise) to IP.
4542
4560
4543 2001-11-04 Fernando Perez <fperez@colorado.edu>
4561 2001-11-04 Fernando Perez <fperez@colorado.edu>
4544
4562
4545 * Added .ipython/ directory to sys.path. This way users can keep
4563 * Added .ipython/ directory to sys.path. This way users can keep
4546 customizations there and access them via import.
4564 customizations there and access them via import.
4547
4565
4548 2001-11-03 Fernando Perez <fperez@colorado.edu>
4566 2001-11-03 Fernando Perez <fperez@colorado.edu>
4549
4567
4550 * Opened version 0.1.1 for new changes.
4568 * Opened version 0.1.1 for new changes.
4551
4569
4552 * Changed version number to 0.1.0: first 'public' release, sent to
4570 * Changed version number to 0.1.0: first 'public' release, sent to
4553 Nathan and Janko.
4571 Nathan and Janko.
4554
4572
4555 * Lots of small fixes and tweaks.
4573 * Lots of small fixes and tweaks.
4556
4574
4557 * Minor changes to whos format. Now strings are shown, snipped if
4575 * Minor changes to whos format. Now strings are shown, snipped if
4558 too long.
4576 too long.
4559
4577
4560 * Changed ShellServices to work on __main__ so they show up in @who
4578 * Changed ShellServices to work on __main__ so they show up in @who
4561
4579
4562 * Help also works with ? at the end of a line:
4580 * Help also works with ? at the end of a line:
4563 ?sin and sin?
4581 ?sin and sin?
4564 both produce the same effect. This is nice, as often I use the
4582 both produce the same effect. This is nice, as often I use the
4565 tab-complete to find the name of a method, but I used to then have
4583 tab-complete to find the name of a method, but I used to then have
4566 to go to the beginning of the line to put a ? if I wanted more
4584 to go to the beginning of the line to put a ? if I wanted more
4567 info. Now I can just add the ? and hit return. Convenient.
4585 info. Now I can just add the ? and hit return. Convenient.
4568
4586
4569 2001-11-02 Fernando Perez <fperez@colorado.edu>
4587 2001-11-02 Fernando Perez <fperez@colorado.edu>
4570
4588
4571 * Python version check (>=2.1) added.
4589 * Python version check (>=2.1) added.
4572
4590
4573 * Added LazyPython documentation. At this point the docs are quite
4591 * Added LazyPython documentation. At this point the docs are quite
4574 a mess. A cleanup is in order.
4592 a mess. A cleanup is in order.
4575
4593
4576 * Auto-installer created. For some bizarre reason, the zipfiles
4594 * Auto-installer created. For some bizarre reason, the zipfiles
4577 module isn't working on my system. So I made a tar version
4595 module isn't working on my system. So I made a tar version
4578 (hopefully the command line options in various systems won't kill
4596 (hopefully the command line options in various systems won't kill
4579 me).
4597 me).
4580
4598
4581 * Fixes to Struct in genutils. Now all dictionary-like methods are
4599 * Fixes to Struct in genutils. Now all dictionary-like methods are
4582 protected (reasonably).
4600 protected (reasonably).
4583
4601
4584 * Added pager function to genutils and changed ? to print usage
4602 * Added pager function to genutils and changed ? to print usage
4585 note through it (it was too long).
4603 note through it (it was too long).
4586
4604
4587 * Added the LazyPython functionality. Works great! I changed the
4605 * Added the LazyPython functionality. Works great! I changed the
4588 auto-quote escape to ';', it's on home row and next to '. But
4606 auto-quote escape to ';', it's on home row and next to '. But
4589 both auto-quote and auto-paren (still /) escapes are command-line
4607 both auto-quote and auto-paren (still /) escapes are command-line
4590 parameters.
4608 parameters.
4591
4609
4592
4610
4593 2001-11-01 Fernando Perez <fperez@colorado.edu>
4611 2001-11-01 Fernando Perez <fperez@colorado.edu>
4594
4612
4595 * Version changed to 0.0.7. Fairly large change: configuration now
4613 * Version changed to 0.0.7. Fairly large change: configuration now
4596 is all stored in a directory, by default .ipython. There, all
4614 is all stored in a directory, by default .ipython. There, all
4597 config files have normal looking names (not .names)
4615 config files have normal looking names (not .names)
4598
4616
4599 * Version 0.0.6 Released first to Lucas and Archie as a test
4617 * Version 0.0.6 Released first to Lucas and Archie as a test
4600 run. Since it's the first 'semi-public' release, change version to
4618 run. Since it's the first 'semi-public' release, change version to
4601 > 0.0.6 for any changes now.
4619 > 0.0.6 for any changes now.
4602
4620
4603 * Stuff I had put in the ipplib.py changelog:
4621 * Stuff I had put in the ipplib.py changelog:
4604
4622
4605 Changes to InteractiveShell:
4623 Changes to InteractiveShell:
4606
4624
4607 - Made the usage message a parameter.
4625 - Made the usage message a parameter.
4608
4626
4609 - Require the name of the shell variable to be given. It's a bit
4627 - Require the name of the shell variable to be given. It's a bit
4610 of a hack, but allows the name 'shell' not to be hardwire in the
4628 of a hack, but allows the name 'shell' not to be hardwire in the
4611 magic (@) handler, which is problematic b/c it requires
4629 magic (@) handler, which is problematic b/c it requires
4612 polluting the global namespace with 'shell'. This in turn is
4630 polluting the global namespace with 'shell'. This in turn is
4613 fragile: if a user redefines a variable called shell, things
4631 fragile: if a user redefines a variable called shell, things
4614 break.
4632 break.
4615
4633
4616 - magic @: all functions available through @ need to be defined
4634 - magic @: all functions available through @ need to be defined
4617 as magic_<name>, even though they can be called simply as
4635 as magic_<name>, even though they can be called simply as
4618 @<name>. This allows the special command @magic to gather
4636 @<name>. This allows the special command @magic to gather
4619 information automatically about all existing magic functions,
4637 information automatically about all existing magic functions,
4620 even if they are run-time user extensions, by parsing the shell
4638 even if they are run-time user extensions, by parsing the shell
4621 instance __dict__ looking for special magic_ names.
4639 instance __dict__ looking for special magic_ names.
4622
4640
4623 - mainloop: added *two* local namespace parameters. This allows
4641 - mainloop: added *two* local namespace parameters. This allows
4624 the class to differentiate between parameters which were there
4642 the class to differentiate between parameters which were there
4625 before and after command line initialization was processed. This
4643 before and after command line initialization was processed. This
4626 way, later @who can show things loaded at startup by the
4644 way, later @who can show things loaded at startup by the
4627 user. This trick was necessary to make session saving/reloading
4645 user. This trick was necessary to make session saving/reloading
4628 really work: ideally after saving/exiting/reloading a session,
4646 really work: ideally after saving/exiting/reloading a session,
4629 *everythin* should look the same, including the output of @who. I
4647 *everythin* should look the same, including the output of @who. I
4630 was only able to make this work with this double namespace
4648 was only able to make this work with this double namespace
4631 trick.
4649 trick.
4632
4650
4633 - added a header to the logfile which allows (almost) full
4651 - added a header to the logfile which allows (almost) full
4634 session restoring.
4652 session restoring.
4635
4653
4636 - prepend lines beginning with @ or !, with a and log
4654 - prepend lines beginning with @ or !, with a and log
4637 them. Why? !lines: may be useful to know what you did @lines:
4655 them. Why? !lines: may be useful to know what you did @lines:
4638 they may affect session state. So when restoring a session, at
4656 they may affect session state. So when restoring a session, at
4639 least inform the user of their presence. I couldn't quite get
4657 least inform the user of their presence. I couldn't quite get
4640 them to properly re-execute, but at least the user is warned.
4658 them to properly re-execute, but at least the user is warned.
4641
4659
4642 * Started ChangeLog.
4660 * Started ChangeLog.
General Comments 0
You need to be logged in to leave comments. Login now